From c4b0e8efe0e7f1d5cba9ea7a17ca9c8deb886769 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:35:50 +0200 Subject: [PATCH 01/43] Horizon extras: zoom, FPS counter and keystroke overlay, off by default An Extras section in Horizon's Options holds optional additions saved in horizon-extras.txt beside options.txt. Zoom divides the field-of-view target vanilla's Camera.tickFov eases toward (the spyglass path), with a wheel-adjustable level and lower mouse sensitivity; scoping keeps the spyglass view. The FPS counter (with minimum and 1% low) and the keystroke overlay (WASD, space, mouse buttons with clicks per second) draw in the HUD layer, hidden with F1. docs/extras.md describes all the extras. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/extras.rs | 603 +++++++++++++++++++ crates/horizon-client/src/extras_hud.rs | 193 ++++++ crates/horizon-client/src/game.rs | 14 +- crates/horizon-client/src/game/extras.rs | 152 +++++ crates/horizon-client/src/game/fov.rs | 6 +- crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/options_horizon.rs | 51 ++ crates/horizon-client/src/options_ui.rs | 6 +- crates/horizon-client/src/settings.rs | 11 + crates/horizon-client/src/ui_theme.rs | 7 +- docs/README.md | 1 + docs/extras.md | 101 ++++ 12 files changed, 1142 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/extras.rs create mode 100644 crates/horizon-client/src/extras_hud.rs create mode 100644 crates/horizon-client/src/game/extras.rs create mode 100644 docs/extras.md diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs new file mode 100644 index 000000000..551bcb27e --- /dev/null +++ b/crates/horizon-client/src/extras.rs @@ -0,0 +1,603 @@ +//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their +//! settings, kept in `horizon-extras.txt` next to `options.txt` so that file +//! stays exactly vanilla's, and the logic behind them. Every extra is off by +//! default; see `docs/extras.md`. +use std::{collections::VecDeque, fs, path::Path}; + +pub const FILE: &str = "horizon-extras.txt"; +/// The name the options screen uses while the zoom key waits for a key. +pub const ZOOM_KEY: &str = "horizon.zoom"; +/// Zoom levels the default cycles through, and the wheel's limits. +pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10]; +pub const ZOOM_MIN: f32 = 1.25; +/// `Camera.tickFov` keeps the field-of-view modifier at 0.1 or more. +pub const ZOOM_MAX: f32 = 10.0; +/// Each wheel step multiplies the zoom by this. +const ZOOM_STEP: f32 = 1.25; + +/// A screen corner for an overlay. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Corner { + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} +impl Corner { + pub const ALL: [Corner; 4] = [ + Corner::TopLeft, + Corner::TopRight, + Corner::BottomLeft, + Corner::BottomRight, + ]; + pub fn name(self) -> &'static str { + match self { + Corner::TopLeft => "top_left", + Corner::TopRight => "top_right", + Corner::BottomLeft => "bottom_left", + Corner::BottomRight => "bottom_right", + } + } + pub fn label(self) -> &'static str { + match self { + Corner::TopLeft => "Top left", + Corner::TopRight => "Top right", + Corner::BottomLeft => "Bottom left", + Corner::BottomRight => "Bottom right", + } + } + fn parse(s: &str, default: Corner) -> Corner { + Self::ALL + .into_iter() + .find(|c| c.name() == s) + .unwrap_or(default) + } + pub fn top(self) -> bool { + matches!(self, Corner::TopLeft | Corner::TopRight) + } + pub fn left(self) -> bool { + matches!(self, Corner::TopLeft | Corner::BottomLeft) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Extras { + pub zoom: bool, + /// A vanilla key name (`key.keyboard.z`). + pub zoom_key: String, + /// The zoom the key starts at. + pub zoom_level: u8, + /// Ease through vanilla's FOV easing (as the spyglass does). + pub zoom_smooth: bool, + /// Divide mouse turning by the zoom. + pub zoom_sensitivity: bool, + pub fps: bool, + pub fps_corner: Corner, + /// Also show the minimum and 1% low. + pub fps_lows: bool, + pub keystrokes: bool, + pub keystrokes_corner: Corner, + /// Clicks per second under the mouse buttons. + pub keystrokes_cps: bool, +} +impl Default for Extras { + fn default() -> Self { + Self { + zoom: false, + zoom_key: "key.keyboard.z".into(), + zoom_level: 4, + zoom_smooth: true, + zoom_sensitivity: true, + fps: false, + fps_corner: Corner::TopLeft, + fps_lows: false, + keystrokes: false, + keystrokes_corner: Corner::TopLeft, + keystrokes_cps: true, + } + } +} +fn bool_text(v: bool) -> &'static str { + if v { "true" } else { "false" } +} +impl Extras { + pub fn load(dir: &Path) -> Self { + fs::read_to_string(dir.join(FILE)) + .map(|t| Self::parse(&t)) + .unwrap_or_default() + } + pub fn parse(text: &str) -> Self { + let mut e = Self::default(); + for line in text.lines() { + let Some((key, value)) = line.split_once(':') else { + continue; + }; + let value = value.trim(); + let flag = |d: bool| match value { + "true" => true, + "false" => false, + _ => d, + }; + match key.trim() { + "zoom" => e.zoom = flag(e.zoom), + "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), + "zoomLevel" => { + if let Ok(v) = value.parse::() { + e.zoom_level = v.clamp(2, ZOOM_MAX as u8); + } + } + "zoomSmooth" => e.zoom_smooth = flag(e.zoom_smooth), + "zoomSensitivity" => e.zoom_sensitivity = flag(e.zoom_sensitivity), + "fps" => e.fps = flag(e.fps), + "fpsCorner" => e.fps_corner = Corner::parse(value, e.fps_corner), + "fpsLows" => e.fps_lows = flag(e.fps_lows), + "keystrokes" => e.keystrokes = flag(e.keystrokes), + "keystrokesCorner" => { + e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner) + } + "keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps), + _ => {} + } + } + e + } + pub fn serialize(&self) -> String { + format!( + "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\n", + bool_text(self.zoom), + self.zoom_key, + self.zoom_level, + bool_text(self.zoom_smooth), + bool_text(self.zoom_sensitivity), + bool_text(self.fps), + self.fps_corner.name(), + bool_text(self.fps_lows), + bool_text(self.keystrokes), + self.keystrokes_corner.name(), + bool_text(self.keystrokes_cps), + ) + } + /// Written only once something differs from the defaults, so a vanilla + /// setup gains no file. + pub fn save(&self, dir: &Path) { + let path = dir.join(FILE); + if *self == Self::default() && !path.exists() { + return; + } + let _ = fs::write(path, self.serialize()); + } +} + +/// The zoom key's state: held or not, and the zoom the wheel has set. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Zoom { + held: bool, + factor: f32, +} +impl Default for Zoom { + fn default() -> Self { + Self { + held: false, + factor: 1.0, + } + } +} +impl Zoom { + /// The key went down: start at the default level. + pub fn press(&mut self, level: u8) { + self.held = true; + self.factor = f32::from(level).clamp(ZOOM_MIN, ZOOM_MAX); + } + pub fn release(&mut self) { + self.held = false; + } + pub fn held(&self) -> bool { + self.held + } + /// Wheel steps while held (positive zooms in); false when not zooming. + pub fn scroll(&mut self, steps: f32) -> bool { + if !self.held { + return false; + } + self.factor = (self.factor * ZOOM_STEP.powf(steps)).clamp(ZOOM_MIN, ZOOM_MAX); + true + } + /// The zoom in effect: 1 when the key is up or the spyglass is in use + /// (scoping keeps vanilla's spyglass view). + pub fn factor(&self, scoping: bool) -> f32 { + if self.held && !scoping { + self.factor + } else { + 1.0 + } + } +} +/// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's +/// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is. +pub fn fov_target(vanilla: f32, zoom: f32) -> f32 { + if zoom == 1.0 { vanilla } else { vanilla / zoom } +} +/// The mouse turning scale while zoomed. +pub fn turn_scale(zoom: f32, lower_sensitivity: bool) -> f64 { + if lower_sensitivity && zoom > 1.0 { + 1.0 / f64::from(zoom) + } else { + 1.0 + } +} + +/// Frame times over the last few seconds: frames per second, the minimum +/// and the 1% low, recomputed twice a second. +pub struct FpsCounter { + /// (end time in seconds, frame milliseconds), oldest first. + frames: VecDeque<(f64, f32)>, + shown: FpsReading, + computed_at: f64, +} +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FpsReading { + pub fps: u32, + pub min: u32, + pub low: u32, +} +/// Seconds the minimum and 1% low look back. +const LOW_WINDOW: f64 = 5.0; +impl Default for FpsCounter { + fn default() -> Self { + Self { + frames: VecDeque::new(), + shown: FpsReading::default(), + computed_at: f64::NEG_INFINITY, + } + } +} +impl FpsCounter { + /// A frame that ended at `now` (seconds) and took `ms`. + pub fn record(&mut self, now: f64, ms: f32) { + self.frames.push_back((now, ms)); + while self + .frames + .front() + .is_some_and(|&(t, _)| now - t > LOW_WINDOW) + { + self.frames.pop_front(); + } + if now - self.computed_at >= 0.5 { + self.computed_at = now; + self.shown = self.compute(now); + } + } + fn compute(&self, now: f64) -> FpsReading { + let fps = self.frames.iter().filter(|&&(t, _)| now - t < 1.0).count() as u32; + let mut times: Vec = self.frames.iter().map(|f| f.1).collect(); + if times.is_empty() { + return FpsReading::default(); + } + times.sort_by(|a, b| b.total_cmp(a)); + let to_fps = |ms: f32| (1000.0 / ms.max(0.001)).round() as u32; + // The 1% low: the frame rate of the 99th percentile frame time. + let low = times[(times.len() - 1) / 100]; + FpsReading { + fps, + min: to_fps(times[0]), + low: to_fps(low), + } + } + pub fn reading(&self) -> FpsReading { + self.shown + } + pub fn clear(&mut self) { + *self = Self::default(); + } +} + +/// Clicks of one button in the last second. +#[derive(Default)] +pub struct Cps { + clicks: VecDeque, +} +impl Cps { + pub fn click(&mut self, now: f64) { + self.clicks.push_back(now); + self.forget(now); + } + fn forget(&mut self, now: f64) { + while self.clicks.front().is_some_and(|&t| now - t >= 1.0) { + self.clicks.pop_front(); + } + } + pub fn per_second(&mut self, now: f64) -> usize { + self.forget(now); + self.clicks.len() + } +} + +/// The settings the Extras page shows, one per row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Item { + Zoom, + ZoomKey, + ZoomLevel, + ZoomSmooth, + ZoomSensitivity, + Fps, + FpsCorner, + FpsLows, + Keystrokes, + KeystrokesCorner, + KeystrokesCps, +} +/// The Extras page: headers and items. +pub fn rows() -> Vec> { + use Item::*; + vec![ + Err("Zoom"), + Ok(Zoom), + Ok(ZoomKey), + Ok(ZoomLevel), + Ok(ZoomSmooth), + Ok(ZoomSensitivity), + Err("FPS counter"), + Ok(Fps), + Ok(FpsCorner), + Ok(FpsLows), + Err("Keystrokes"), + Ok(Keystrokes), + Ok(KeystrokesCorner), + Ok(KeystrokesCps), + ] +} +fn next(all: &[T], current: T, back: bool) -> T { + let i = all.iter().position(|v| *v == current).unwrap_or(0); + let n = all.len(); + all[if back { (i + n - 1) % n } else { (i + 1) % n }] +} +impl Item { + pub fn caption(self) -> &'static str { + match self { + Item::Zoom => "Zoom", + Item::ZoomKey => "Zoom key", + Item::ZoomLevel => "Starting zoom", + Item::ZoomSmooth => "Smooth zoom", + Item::ZoomSensitivity => "Lower sensitivity while zoomed", + Item::Fps => "FPS counter", + Item::FpsCorner | Item::KeystrokesCorner => "Corner", + Item::FpsLows => "Minimum and 1% low", + Item::Keystrokes => "Keystrokes", + Item::KeystrokesCps => "Clicks per second", + } + } + /// What the row says under its caption. + pub fn description(self) -> &'static str { + match self { + Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", + Item::ZoomKey => "Click, then press a key. Escape unbinds it.", + Item::ZoomLevel => "The zoom the key starts at.", + Item::ZoomSmooth => "Eases in and out like the spyglass.", + Item::ZoomSensitivity => "Turns slower the more you zoom in.", + Item::Fps => "Frames per second in a corner of the screen.", + Item::FpsCorner | Item::KeystrokesCorner => "Overlays in one corner stack.", + Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.", + Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", + Item::KeystrokesCps => "Clicks in the last second under each mouse button.", + } + } + /// The frame-time cost the main switch of an extra shows. + pub fn cost(self) -> Option { + use crate::graphics_style::Cost; + match self { + Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), + _ => None, + } + } + /// On/off items and their value. + pub fn switch(self, e: &Extras) -> Option { + Some(match self { + Item::Zoom => e.zoom, + Item::ZoomSmooth => e.zoom_smooth, + Item::ZoomSensitivity => e.zoom_sensitivity, + Item::Fps => e.fps, + Item::FpsLows => e.fps_lows, + Item::Keystrokes => e.keystrokes, + Item::KeystrokesCps => e.keystrokes_cps, + _ => return None, + }) + } + /// The value of the other items, as their button shows it. + pub fn value(self, e: &Extras) -> String { + match self { + Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(), + Item::ZoomLevel => format!("{}x", e.zoom_level), + Item::FpsCorner => e.fps_corner.label().into(), + Item::KeystrokesCorner => e.keystrokes_corner.label().into(), + other => match other.switch(e) { + Some(true) => "On".into(), + _ => "Off".into(), + }, + } + } + /// A click (`back` for the right button). The zoom key binds instead. + pub fn cycle(self, e: &mut Extras, back: bool) { + match self { + Item::Zoom => e.zoom = !e.zoom, + Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, + Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, + Item::Fps => e.fps = !e.fps, + Item::FpsLows => e.fps_lows = !e.fps_lows, + Item::Keystrokes => e.keystrokes = !e.keystrokes, + Item::KeystrokesCps => e.keystrokes_cps = !e.keystrokes_cps, + Item::ZoomLevel => e.zoom_level = next(&ZOOM_LEVELS, e.zoom_level, back), + Item::FpsCorner => e.fps_corner = next(&Corner::ALL, e.fps_corner, back), + Item::KeystrokesCorner => { + e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back) + } + Item::ZoomKey => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn everything_is_off_by_default_and_round_trips() { + let d = Extras::default(); + assert!(!d.zoom && !d.fps && !d.keystrokes); + assert_eq!(Extras::parse(""), d); + assert_eq!(Extras::parse(&d.serialize()), d); + let mut e = d.clone(); + e.zoom = true; + e.zoom_key = "key.keyboard.c".into(); + e.zoom_level = 6; + e.fps_corner = Corner::BottomRight; + e.keystrokes = true; + e.keystrokes_cps = false; + assert_eq!(Extras::parse(&e.serialize()), e); + } + + #[test] + fn bad_lines_keep_defaults() { + let e = Extras::parse("zoom:maybe\nzoomLevel:99\nfpsCorner:middle\nzoomKey:z\nnoise"); + assert!(!e.zoom); + assert_eq!(e.zoom_level, 10); + assert_eq!(e.fps_corner, Corner::TopLeft); + assert_eq!(e.zoom_key, "key.keyboard.z"); + } + + #[test] + fn default_zoom_key_is_free_in_vanilla() { + let key = Extras::default().zoom_key; + assert!(crate::keybinds::key_code(&key).is_some()); + assert!( + crate::keybinds::MAPPINGS.iter().all(|m| m.1 != key), + "{key} is a vanilla binding" + ); + } + + #[test] + fn zoom_is_vanilla_unless_held_and_not_scoping() { + let mut z = Zoom::default(); + assert_eq!(z.factor(false), 1.0); + assert_eq!(fov_target(1.1, z.factor(false)), 1.1); + assert!(!z.scroll(1.0), "the wheel is the hotbar's when not zooming"); + z.press(4); + assert_eq!(z.factor(false), 4.0); + assert_eq!(z.factor(true), 1.0, "the spyglass wins"); + assert!((fov_target(1.0, 4.0) - 0.25).abs() < 1e-6); + assert!(z.scroll(1.0)); + assert!((z.factor(false) - 5.0).abs() < 1e-5); + for _ in 0..40 { + z.scroll(1.0); + } + assert_eq!(z.factor(false), ZOOM_MAX); + for _ in 0..80 { + z.scroll(-1.0); + } + assert_eq!(z.factor(false), ZOOM_MIN); + z.release(); + assert_eq!(z.factor(false), 1.0); + z.press(2); + assert_eq!(z.factor(false), 2.0, "each press starts at the default"); + } + + #[test] + fn zoom_target_eases_like_the_spyglass() { + // Camera.tickFov halves the distance to the target each tick. + let mut camera = crate::camera::Camera::default(); + camera.tick(None, 1.0); + for _ in 0..30 { + camera.tick(None, 1.0); + } + let target = fov_target(1.0, 4.0); + camera.tick(None, target); + let first = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((first - 70.0 * 0.625).abs() < 1e-3, "{first}"); + for _ in 0..30 { + camera.tick(None, target); + } + let settled = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((settled - 70.0 / 4.0).abs() < 1e-3, "{settled}"); + // Deeper than the 0.1 floor stops there, as vanilla clamps. + for _ in 0..30 { + camera.tick(None, fov_target(1.0, 20.0)); + } + let floor = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false); + assert!((floor - 7.0).abs() < 1e-3, "{floor}"); + } + + #[test] + fn sensitivity_scales_with_zoom() { + assert_eq!(turn_scale(1.0, true), 1.0); + assert_eq!(turn_scale(4.0, false), 1.0); + assert_eq!(turn_scale(4.0, true), 0.25); + } + + #[test] + fn fps_counter_reports_rate_minimum_and_low() { + let mut c = FpsCounter::default(); + let mut t = 0.0; + // Two seconds at 100 fps with one 50 ms hitch. + for i in 0..200 { + let ms = if i == 150 { 50.0 } else { 10.0 }; + t += f64::from(ms) / 1000.0; + c.record(t, ms); + } + c.computed_at = f64::NEG_INFINITY; + c.record(t + 0.01, 10.0); + let r = c.reading(); + assert!((95..=101).contains(&r.fps), "{r:?}"); + assert_eq!(r.min, 20); + assert_eq!(r.low, 100, "one frame in 200 is under the 1% mark"); + // Hitches beyond 1% of frames pull the 1% low down. + let mut c = FpsCounter::default(); + let mut t = 0.0; + for i in 0..100 { + let ms = if i % 25 == 0 { 40.0 } else { 10.0 }; + t += f64::from(ms) / 1000.0; + c.record(t, ms); + } + c.computed_at = f64::NEG_INFINITY; + c.record(t, 10.0); + assert_eq!(c.reading().low, 25); + } + + #[test] + fn old_frames_leave_the_window() { + let mut c = FpsCounter::default(); + c.record(0.0, 100.0); + for i in 1..=700 { + c.record(f64::from(i) / 100.0, 10.0); + } + assert_eq!(c.reading().min, 100, "the 100 ms frame is 7 s old"); + } + + #[test] + fn cps_counts_the_last_second() { + let mut cps = Cps::default(); + for i in 0..10 { + cps.click(f64::from(i) * 0.1); + } + assert_eq!(cps.per_second(0.95), 10); + assert_eq!(cps.per_second(1.25), 7); + assert_eq!(cps.per_second(3.0), 0); + } + + #[test] + fn items_cycle_through_their_values() { + let mut e = Extras::default(); + Item::ZoomLevel.cycle(&mut e, false); + assert_eq!(e.zoom_level, 6); + Item::ZoomLevel.cycle(&mut e, true); + Item::ZoomLevel.cycle(&mut e, true); + assert_eq!(e.zoom_level, 3); + Item::FpsCorner.cycle(&mut e, true); + assert_eq!(e.fps_corner, Corner::BottomRight); + Item::Zoom.cycle(&mut e, false); + assert_eq!(Item::Zoom.switch(&e), Some(true)); + assert_eq!(Item::ZoomKey.value(&e), "Z"); + for item in rows().into_iter().flatten() { + assert!(!item.caption().is_empty() && !item.description().is_empty()); + } + } +} diff --git a/crates/horizon-client/src/extras_hud.rs b/crates/horizon-client/src/extras_hud.rs new file mode 100644 index 000000000..6d015f5df --- /dev/null +++ b/crates/horizon-client/src/extras_hud.rs @@ -0,0 +1,193 @@ +//! The extras' HUD overlays (FPS counter, keystrokes): small boxes in the +//! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`). +use crate::{ + extras::{Corner, FpsReading}, + hud::{HudAtlas, HudBatch, rgba}, +}; + +/// The gap between an overlay and the screen edge or the next overlay. +const MARGIN: f32 = 2.0; +const BACKGROUND: u32 = 0x7800_0000; + +/// Where the next overlay goes in each corner. +pub struct Corners { + width: f32, + height: f32, + /// Distance from the corner's top or bottom edge, per `Corner::ALL`. + used: [f32; 4], +} +impl Corners { + /// `top_right` reserves the status effect icons' rows. + pub fn new(width: f32, height: f32, top_right: f32) -> Self { + Self { + width, + height, + used: [0.0, top_right, 0.0, 0.0], + } + } + /// The top-left position of a `w` x `h` box in `corner`, below (or + /// above) what the corner already holds. + pub fn place(&mut self, corner: Corner, w: f32, h: f32) -> (f32, f32) { + let i = Corner::ALL.iter().position(|c| *c == corner).unwrap_or(0); + let edge = self.used[i] + MARGIN; + self.used[i] = edge + h; + let x = if corner.left() { + MARGIN + } else { + self.width - MARGIN - w + }; + let y = if corner.top() { + edge + } else { + self.height - edge - h + }; + (x, y) + } +} + +/// The FPS counter's text. +pub fn fps_text(r: FpsReading, lows: bool) -> String { + if lows { + format!("{} fps min {} 1% {}", r.fps, r.min, r.low) + } else { + format!("{} fps", r.fps) + } +} +pub fn draw_fps( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + corner: Corner, + reading: FpsReading, + lows: bool, +) { + let text = fps_text(reading, lows); + let w = HudBatch::text_width(atlas, &text) + 4.0; + let (x, y) = corners.place(corner, w, 12.0); + batch.fill(atlas, x, y, w, 12.0, BACKGROUND); + batch.text( + atlas, + &text, + x + 2.0, + y + 2.0, + rgba(255, 255, 255, 255), + true, + ); +} + +/// What the keystroke overlay shows. +pub struct Keystrokes { + /// Forward, left, back, right: held, and the bound key's name. + pub moves: [(bool, String); 4], + pub jump: bool, + pub attack: bool, + pub use_: bool, + /// Clicks per second of the left and right buttons, when shown. + pub cps: Option<(usize, usize)>, +} +const KEY: f32 = 22.0; +const GAP: f32 = 2.0; +/// The overlay's size. +pub fn keystrokes_size() -> (f32, f32) { + (3.0 * KEY + 2.0 * GAP, 3.0 * KEY + 3.0 * GAP + 10.0) +} +fn key_box(batch: &mut HudBatch, atlas: &HudAtlas, rect: [f32; 4], held: bool, lines: &[&str]) { + let [x, y, w, h] = rect; + let (fill, ink) = if held { + (rgba(255, 255, 255, 176), rgba(20, 20, 20, 255)) + } else { + (BACKGROUND, rgba(255, 255, 255, 255)) + }; + batch.fill(atlas, x, y, w, h, fill); + let total = lines.len() as f32 * 9.0 - 1.0; + for (i, line) in lines.iter().enumerate() { + let tw = HudBatch::text_width(atlas, line); + let tx = (x + (w - tw) / 2.0).round(); + let ty = (y + (h - total) / 2.0).round() + i as f32 * 9.0; + batch.text(atlas, line, tx, ty, ink, !held); + } +} +pub fn draw_keystrokes( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + corner: Corner, + k: &Keystrokes, +) { + let (w, h) = keystrokes_size(); + let (x, y) = corners.place(corner, w, h); + let step = KEY + GAP; + let [forward, left, back, right] = &k.moves; + key_box( + batch, + atlas, + [x + step, y, KEY, KEY], + forward.0, + &[&forward.1], + ); + for (i, key) in [left, back, right].into_iter().enumerate() { + key_box( + batch, + atlas, + [x + i as f32 * step, y + step, KEY, KEY], + key.0, + &[&key.1], + ); + } + let mw = (w - GAP) / 2.0; + let my = y + 2.0 * step; + for (i, (held, label, cps)) in [ + (k.attack, "LMB", k.cps.map(|c| c.0)), + (k.use_, "RMB", k.cps.map(|c| c.1)), + ] + .into_iter() + .enumerate() + { + let rate = cps.map(|n| format!("{n} CPS")); + let lines: Vec<&str> = std::iter::once(label).chain(rate.as_deref()).collect(); + key_box( + batch, + atlas, + [x + i as f32 * (mw + GAP), my, mw, KEY], + held, + &lines, + ); + } + // The space bar: a line in a short key. + let sy = my + step; + key_box(batch, atlas, [x, sy, w, 10.0], k.jump, &[]); + let ink = if k.jump { + rgba(20, 20, 20, 255) + } else { + rgba(255, 255, 255, 255) + }; + batch.fill(atlas, x + w / 2.0 - 12.0, sy + 4.0, 24.0, 2.0, ink); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corners_stack_away_from_their_edge() { + let mut c = Corners::new(400.0, 300.0, 26.0); + assert_eq!(c.place(Corner::TopLeft, 50.0, 12.0), (2.0, 2.0)); + assert_eq!(c.place(Corner::TopLeft, 70.0, 20.0), (2.0, 16.0)); + // Top right starts under the effect icons. + assert_eq!(c.place(Corner::TopRight, 50.0, 12.0), (348.0, 28.0)); + assert_eq!(c.place(Corner::BottomRight, 50.0, 12.0), (348.0, 286.0)); + assert_eq!(c.place(Corner::BottomRight, 50.0, 10.0), (348.0, 274.0)); + assert_eq!(c.place(Corner::BottomLeft, 10.0, 10.0), (2.0, 288.0)); + } + + #[test] + fn fps_text_with_and_without_lows() { + let r = FpsReading { + fps: 144, + min: 61, + low: 98, + }; + assert_eq!(fps_text(r, false), "144 fps"); + assert_eq!(fps_text(r, true), "144 fps min 61 1% 98"); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c5fea0539..fbd2daff6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod dragon; mod enchant_effects; mod end; mod explosion; +mod extras; mod fangs; mod fireworks; mod fishing; @@ -860,6 +861,8 @@ struct Game<'a> { pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, /// Recent frame times for the performance overlay. frame_graph: horizon_client::perf_overlay::FrameGraph, + /// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`. + extras: extras::ExtrasState, /// Meshed sections waiting for an upload budget (Horizon settings). pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>, /// This frame's view frustum, for culling entities and block entities. @@ -3090,7 +3093,8 @@ impl Game<'_> { x_rot_o: self.pitch, y_rot_o: self.yaw, }; - rotation.turn(xo, yo); + let zoom = self.zoom_turn_scale(); + rotation.turn(xo * zoom, yo * zoom); self.yaw = rotation.y_rot; self.pitch = rotation.x_rot; } @@ -3244,6 +3248,7 @@ impl Game<'_> { self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). self.draw_boss_bars(&mut batch); + self.draw_extras(&mut batch); } // Hud.extractSleepOverlay, under the sidebar, titles and chat. if let Some((_, ticks)) = self.sleeping { @@ -8263,6 +8268,7 @@ impl ApplicationHandler for Game<'_> { let d = scaled(raw_y) as f32; if self.screen == Screen::Playing && self.player.is_some() + && !self.extras_scroll(d) && let Some((wheel, _)) = self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) @@ -8366,6 +8372,7 @@ impl ApplicationHandler for Game<'_> { self.capture(true); return Ok(()); } + self.extras_mouse(button, pressed); match self.settings.keys.translate_mouse(button) { Some(Err(b)) => self.play_mouse(b, pressed)?, Some(Ok(k)) if pressed => { @@ -8523,6 +8530,9 @@ impl ApplicationHandler for Game<'_> { let PhysicalKey::Code(key) = event.physical_key else { return Ok(()); }; + if self.extras_key(key, event.state == ElementState::Pressed, event.repeat) { + return Ok(()); + } // key.smoothCamera toggles the cinematic camera. if self.screen == Screen::Playing && event.state == ElementState::Pressed @@ -8587,6 +8597,7 @@ impl ApplicationHandler for Game<'_> { self.sprint_report(&report); } } + self.extras_frame(elapsed); self.apply_mouse_look(); self.pad_look(elapsed.as_secs_f32()); self.advance_flight(); @@ -9089,6 +9100,7 @@ pub fn run() -> Result<()> { view_frustum: None, pending_uploads: Vec::new(), frame_graph: Default::default(), + extras: Default::default(), sky_darken_memo: Default::default(), persist: Default::default(), remote: None, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs new file mode 100644 index 000000000..7197725f7 --- /dev/null +++ b/crates/horizon-client/src/game/extras.rs @@ -0,0 +1,152 @@ +//! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel, +//! clicks for the keystroke overlay, frame times for the FPS counter, and +//! their HUD. Each hook does nothing while its extra is off. +use super::{Game, Screen}; +use horizon_client::{ + extras::{Cps, FpsCounter, Zoom, fov_target, turn_scale}, + extras_hud::{self, Corners, Keystrokes}, + hud::HudBatch, + keybinds, +}; +use std::time::Duration; +use winit::{event::MouseButton, keyboard::KeyCode}; + +#[derive(Default)] +pub(super) struct ExtrasState { + zoom: Zoom, + fps: FpsCounter, + /// Left and right mouse buttons: held, and their clicks. + mouse: [bool; 2], + cps: [Cps; 2], +} + +impl Game<'_> { + fn extras_now(&self) -> f64 { + self.started.elapsed().as_secs_f64() + } + fn zoom_key(&self) -> Option { + let e = &self.settings.extras; + e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten() + } + /// A key press or release while playing; true when the zoom key took it. + pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) -> bool { + if self.zoom_key() != Some(key) { + return false; + } + if !pressed { + self.extras.zoom.release(); + } else if !repeat && self.screen == Screen::Playing && self.title.is_none() { + self.extras.zoom.press(self.settings.extras.zoom_level); + } + true + } + /// Wheel steps while playing; true when zooming took them from the hotbar. + pub(super) fn extras_scroll(&mut self, steps: f32) -> bool { + self.settings.extras.zoom && self.extras.zoom.scroll(steps) + } + /// Mouse buttons while playing, for the keystroke overlay. + pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) { + let i = match button { + MouseButton::Left => 0, + MouseButton::Right => 1, + _ => return, + }; + self.extras.mouse[i] = pressed; + if pressed && self.settings.extras.keystrokes { + let now = self.extras_now(); + self.extras.cps[i].click(now); + } + } + /// Once per frame: the frame's time, and keys let go behind screens. + pub(super) fn extras_frame(&mut self, elapsed: Duration) { + let playing = self.screen == Screen::Playing && self.title.is_none() && self.focused; + if !playing || !self.settings.extras.zoom { + self.extras.zoom.release(); + } + if !playing { + self.extras.mouse = [false; 2]; + } + if self.settings.extras.fps { + let now = self.extras_now(); + self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0); + } else { + self.extras.fps.clear(); + } + } + /// The zoom in effect (1 unless the key is held). + fn zoom_factor(&self) -> f32 { + self.extras.zoom.factor(self.scoping()) + } + /// The field-of-view modifier target, divided by a smooth zoom. + pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 { + if self.settings.extras.zoom_smooth { + fov_target(vanilla, self.zoom_factor()) + } else { + vanilla + } + } + /// The field of view in degrees, divided by an instant zoom. + pub(super) fn zoomed_fov_degrees(&self, fov: f32) -> f32 { + if self.settings.extras.zoom_smooth { + fov + } else { + fov / self.zoom_factor() + } + } + /// Mouse turning while zoomed. + pub(super) fn zoom_turn_scale(&self) -> f64 { + turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity) + } + /// The FPS counter and keystrokes, in the HUD layer (hidden with F1 by + /// the caller). The top left corner gives way to the debug screen. + pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { + let e = &self.settings.extras; + if !e.fps && !e.keystrokes { + return; + } + let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows); + let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps); + let visible = |corner| !(self.debug && corner == horizon_client::extras::Corner::TopLeft); + let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); + let atlas = &self.res.atlas; + if fps_on && visible(fps_corner) { + let reading = self.extras.fps.reading(); + extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows); + } + if keys_on && visible(keys_corner) { + let now = self.extras_now(); + let cps = cps_on.then(|| { + let [l, r] = &mut self.extras.cps; + (l.per_second(now), r.per_second(now)) + }); + let held = |k| self.keys.contains(&k); + let label = |name| keybinds::display_name(self.settings.keys.get(name)).plain(); + let k = Keystrokes { + moves: [ + (held(KeyCode::KeyW), label("key.forward")), + (held(KeyCode::KeyA), label("key.left")), + (held(KeyCode::KeyS), label("key.back")), + (held(KeyCode::KeyD), label("key.right")), + ], + jump: held(KeyCode::Space), + attack: self.extras.mouse[0], + use_: self.extras.mouse[1], + cps, + }; + extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); + } + } + /// The height the status effect icons take at the top right + /// (`Hud.extractEffects`: beneficial at y 1, harmful at y 26). + fn effect_rows_height(&self) -> f32 { + let effects = &self.potions.effects.list; + if effects.is_empty() || self.screen != Screen::Playing { + return 0.0; + } + let harmful = effects.iter().any(|e| { + horizon_client::brewing::effect(e.id) + .is_some_and(|d| d.category != horizon_client::brewing::Category::Beneficial) + }); + if harmful { 50.0 } else { 25.0 } + } +} diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 4f715d697..102248861 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -54,6 +54,7 @@ impl Game<'_> { let target = self .fov_player() .map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect)); + let target = self.zoomed_fov_target(target); let eye = self.player.as_ref().map(|p| p.dimensions.eye_height); self.view.tick(eye, target); } @@ -77,14 +78,15 @@ impl Game<'_> { } /// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`. pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { - self.view.calculate_fov( + let fov = self.view.calculate_fov( partial, self.settings.fov as i32, self.fov_effect_scale(), self.death_time(), self.camera_fluid(camera), false, - ) + ); + self.zoomed_fov_degrees(fov) } /// `Camera.calculateHudFov`: the first-person hand's field of view. pub(super) fn hud_fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index eae7dc596..f3b1db78d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -46,6 +46,8 @@ pub mod enchant; pub mod entities; pub mod entity_nbt; pub mod environment; +pub mod extras; +pub mod extras_hud; pub mod fast_hash; pub mod fastutil_order; pub mod first_person; diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index ac731fb4c..fcac82be3 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -10,6 +10,7 @@ //! of control belong in `ui_theme` so the launcher-matching look stays in one //! place. Everything else (sliders dragging, scrolling, Done) is handled here. use crate::{ + extras, graphics_style::Cost, graphics_ui::{self, Item, Level}, hud::{HudAtlas, HudBatch}, @@ -34,6 +35,8 @@ pub enum HRow { Level, /// A graphics setting with its frame-time cost and description. Graphics(Item, Cost, &'static str), + /// One of Horizon's extras (`extras`), off by default. + Extra(extras::Item), } /// A sidebar section: name, description, rows. pub struct Section { @@ -172,6 +175,16 @@ pub const SECTIONS: &[Section] = &[ ] }, }, + Section { + name: "Extras", + blurb: "Optional additions, all off by default: the game stays vanilla until you turn one on.", + rows: |_| { + extras::rows() + .into_iter() + .map(|r| r.map_or_else(HRow::Header, HRow::Extra)) + .collect() + }, + }, ]; const NAV: u64 = id("options.nav", 0); @@ -402,6 +415,33 @@ impl OptionsUi { ); } } + HRow::Extra(item) => { + let cy = y + ROW_H / 2.0; + let id = ROW + i as u64; + let cost = item.cost().map_or((0, ""), |c| (c as u8, c.label())); + let (caption, text) = (item.caption(), item.description()); + if let Some(on) = item.switch(&s.extras) { + ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0); + ui.switch(id, control_x, cy, on); + } else { + let value = if item == extras::Item::ZoomKey + && self.selected_key == Some(extras::ZOOM_KEY) + { + "Press a key".to_owned() + } else { + item.value(&s.extras) + }; + let bw = ui.button_width(&value, false).max(96.0); + ui.described_row(x, y, caption, "", 0.0, cost, text, cw - bw - 24.0); + ui.button( + id, + [control_x - bw, y + 12.0, bw, CONTROL], + &value, + Button::Secondary, + true, + ); + } + } HRow::Style => { ui.row(x, y, "Menu style", "", 0.0); let labels = ["Horizon", "Classic"]; @@ -513,6 +553,10 @@ impl OptionsUi { } return events; } + // A click anywhere stops waiting for the zoom key. + if self.selected_key == Some(extras::ZOOM_KEY) { + self.selected_key = None; + } match self.horizon_target(s, atlas, x, y) { Some(Target::Nav(i)) => { self.section = i; @@ -554,6 +598,13 @@ impl OptionsUi { events.push(Event::Changed); } Some(HRow::Page(_, _, page)) => self.open_page(*page), + Some(HRow::Extra(extras::Item::ZoomKey)) => { + self.selected_key = Some(extras::ZOOM_KEY); + } + Some(HRow::Extra(item)) => { + item.cycle(&mut s.extras, right); + events.push(Event::Changed); + } _ => {} } } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 88196f453..d5d508361 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1930,7 +1930,11 @@ impl OptionsUi { .unwrap_or("key.keyboard.unknown") .to_owned() }; - s.keys.set(name, &value); + if name == crate::extras::ZOOM_KEY { + s.extras.zoom_key = value; + } else { + s.keys.set(name, &value); + } return vec![Event::Changed]; } if key == K::Escape { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 9a3c5fa45..1cc58b472 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -179,6 +179,8 @@ pub struct Settings { pub horizon: crate::graphics::Graphics, /// Controller settings (`horizon-controller.txt`, Horizon's own). pub controller: crate::gamepad::PadSettings, + /// Horizon's optional extras (`horizon-extras.txt`), all off by default. + pub extras: crate::extras::Extras, } impl Default for Settings { fn default() -> Self { @@ -249,6 +251,7 @@ impl Default for Settings { sprint_window: 7, horizon: Default::default(), controller: Default::default(), + extras: Default::default(), } } } @@ -287,15 +290,21 @@ impl Settings { .parent() .map(crate::gamepad::PadSettings::load) .unwrap_or_default(); + let extras = path + .parent() + .map(crate::extras::Extras::load) + .unwrap_or_default(); let settings = match fs::read(path) { Ok(bytes) => Self { horizon, controller, + extras, ..Self::parse(&String::from_utf8_lossy(&bytes)) }, Err(_) => Self { horizon, controller, + extras, ..Self::default() }, }; @@ -395,6 +404,7 @@ impl Settings { sprint_window: f.int("sprintWindow"), horizon: Default::default(), controller: Default::default(), + extras: Default::default(), auto_jump: f.bool("autoJump"), language: f.string("lang"), force_unicode: f.bool("forceUnicodeFont"), @@ -528,6 +538,7 @@ impl Settings { if let Some(dir) = path.parent() { self.horizon.save(dir); self.controller.save(dir); + self.extras.save(dir); } } /// Volume of a sound source (master excluded). diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 9d0851b00..39c6555d3 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -1070,7 +1070,12 @@ impl<'a> Ui<'a> { let tint = [0.0, 0.2, 0.55, 1.0][usize::from(cost.0.min(3))]; let cost_color = color::mix(color::FAINT, color::DANGER, tint); self.text(Face::Medium, SMALL, x, dy, cost_color, cost.1); - let used = self.measure(Face::Medium, SMALL, cost.1); + // No cost label: the description starts at the row's edge. + let used = if cost.1.is_empty() { + -8.0 + } else { + self.measure(Face::Medium, SMALL, cost.1) + }; let rest = self.fit( Face::Regular, SMALL, diff --git a/docs/README.md b/docs/README.md index 1a4e47969..54e8187b8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. +- [Extras](extras.md): optional zoom, minimap, FPS and keystroke overlays and auto-reconnect, all off by default. - [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it. - Menus: the title, world list, create world, multiplayer, options and pause screens share the launcher's design tokens and fonts (`crates/horizon-theme`), drawn by `ui_theme` over a live frozen backdrop (`game/backdrop.rs`, blurred and graded by `post.rs`). Options → Interface → Menu style switches to vanilla's screens (Classic, kept in `horizon.txt`; `HORIZON_MENU_STYLE=horizon|classic` overrides it, and scripted runs default to Classic). [Title](media/menu-title.png) ([webm](media/menu-title.webm)), [worlds](media/menu-worlds.png), [options](media/menu-options.png), [pause](media/menu-pause.png). diff --git a/docs/extras.md b/docs/extras.md new file mode 100644 index 000000000..13e267f6b --- /dev/null +++ b/docs/extras.md @@ -0,0 +1,101 @@ +# Horizon extras + +Optional conveniences built into the client: zoom, a minimap, an FPS counter, a +keystroke overlay and auto-reconnect. **Every one is off by default**: a fresh +install looks and behaves exactly like vanilla 26.3, and turning an extra off +again restores vanilla's behaviour completely. + +## Where they live + +| Part | Code | +|---|---| +| Settings, parsing and saving | `crates/horizon-client/src/extras.rs` | +| Zoom curve, FPS and click counters | `extras.rs` (pure logic, unit tested) | +| HUD drawing (FPS, keystrokes, minimap frame) | `crates/horizon-client/src/extras_hud.rs` | +| Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` | +| Reconnect policy and backoff | `crates/horizon-client/src/reconnect.rs` | +| Game glue (input hooks, per-frame update) | `crates/horizon-client/src/game/extras.rs` | +| The settings page | `options_horizon.rs`: the **Extras** section of Horizon's Options | + +`game.rs` only gets one-line hooks (key, wheel, mouse, frame, HUD), so the +extras stay out of the way of other input and options work. + +## Options storage + +`horizon-extras.txt` beside `options.txt`, in the same `key:value` format as +`horizon-graphics.txt`. `options.txt` is untouched, so a vanilla client can share +the folder. Unknown or broken lines fall back to the defaults. + +The zoom key is a Horizon setting stored in that file (`zoomKey:key.keyboard.z`) +and bound on the Extras page, not in vanilla's Key Binds screen: Horizon has no +Horizon category in Controls, and adding one would put a non-vanilla mapping into +`options.txt`. + +## The extras + +### Zoom (`zoom`, default off) +- Hold the zoom key (default **Z**, unused by every vanilla 26.3 key mapping; C + is `key.saveToolbarActivator`) to zoom. The key does nothing while zoom is off. +- Starts at the default level (4x, settable 2x to 10x); the scroll wheel changes + it while the key is held (and does not move the hotbar then). +- **Smooth** (default on) goes through vanilla's own FOV easing: the zoom divides + the field-of-view modifier target `Camera.tickFov` eases toward, the path the + spyglass uses (`AbstractClientPlayer.getFieldOfViewModifier` returns 0.1 while + scoping). The modifier keeps vanilla's 0.1 floor, so 10x is the deepest zoom. + Off applies the zoom to the final FOV with no easing. +- While scoping with a spyglass the zoom does nothing: the spyglass view and its + overlay stay exactly vanilla's. +- **Lower sensitivity** (default on) divides mouse turning by the zoom factor. +- With zoom off (or the key up) the FOV target and mouse are vanilla's, bit for + bit; the FOV harness covers this. + +### FPS counter (`fps`, default off) +- A small "N fps" line in a corner (default top left), optionally followed by + the minimum and the 1% low over the last 5 seconds. +- Separate from the Advanced graphics "Overlay" (the frame-time graph). + +### Keystrokes (`keystrokes`, default off) +- W A S D, Space, LMB and RMB keys that light up while held, with clicks per + second under the mouse buttons (clicks in the last second). The letters follow + the bound keys. + +### Minimap (`minimap`, default off) +- A corner map (top right by default), square or round, small/medium/large, + zoom 0.5 to 4 blocks per pixel, rotating with the player or north up, with the + player arrow (vanilla's map decoration sprite). +- Colours are vanilla's `MapColor` per block, as map items use, with the map + item's height shading and water-depth dithering. +- Underground, in the Nether and under any roof, it maps the floor around the + player's height instead of the top block, so caves read sensibly. +- Cost: one cached 16x16 tile per loaded chunk (packed map colour and height). + Tiles are filled nearest first and refreshed when blocks change, within a time + budget of 0.3 ms a frame; composing the 128x128 image is a few thousand + lookups, done only when the view moved or a tile changed, and uploaded into a + dedicated atlas slot. With the minimap off nothing runs. + +### Auto-reconnect (`autoReconnect`, default off) +- On the "Connection lost" screen after a multiplayer connection drops, a + countdown "Reconnecting in N s" with a Cancel button, then a new connection + to the same address. +- Backoff 5, 10, 20, 40, 60 s; at most 5 attempts, then it stops. The count + only resets after staying connected for a minute, so a server that drops + players at once never causes an endless loop. +- Never after a kick, a ban, a whitelist or version refusal, a duplicate login + or an online-mode refusal: only lost connections (errors, time-outs, refused + connections while the server restarts) and the server's own "Server closed" + shutdown reason. + +## Shared rules + +- All extras are hidden with F1 and drawn in the HUD layer: under screens, over + the world, like vanilla's HUD. Extras in the top left corner give way to the + debug screen (F3), which shows the FPS anyway. +- Corners stack: extras placed in the same corner stack downward (top corners) + or upward (bottom corners) in the order minimap, FPS, keystrokes. The top + right corner starts below the status effect icons. + +## Perf budget + +Off: a flag check per frame per extra (no allocations, no world access). +On: FPS and keystrokes are a few quads; the minimap stays under 0.3 ms of CPU +per frame (tile budget) plus a 64 KiB texture upload when its image changes. From a08577e301c8b83b414fed0c120f55dfabde64a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:53:38 +0200 Subject: [PATCH 02/43] Extras: horizon-ctl key and mouse reach the zoom key and keystrokes Agents press keys and buttons through the control socket, which skipped the keyboard and mouse hooks; under control the window may also lack focus without pausing, so the zoom no longer lets go then. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/control.rs | 22 ++++++++++++++++++++-- crates/horizon-client/src/game/extras.rs | 4 +++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index bc584990d..e7fe21260 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -163,6 +163,16 @@ impl Game<'_> { self.debug_key(key, KeyAction::Release); } } + // The zoom extra's key, as the keyboard hook sees it. + if self.screen == Screen::Playing { + let action = arg(2)?; + if self.extras_key(physical, action != "up", false) { + if action == "tap" { + self.extras_key(physical, false, false); + } + return ok(); + } + } // Text screens consume raw presses; releases follow key binds. let typing = matches!(self.screen, Screen::Chat | Screen::Options); let key = if typing && arg(2)? != "up" { @@ -228,9 +238,17 @@ impl Game<'_> { .into()); } match arg(2)? { - "down" => self.play_mouse(button, true)?, - "up" => self.play_mouse(button, false)?, + "down" => { + self.extras_mouse(button, true); + self.play_mouse(button, true)? + } + "up" => { + self.extras_mouse(button, false); + self.play_mouse(button, false)? + } "click" => { + self.extras_mouse(button, true); + self.extras_mouse(button, false); self.play_mouse(button, true)?; self.play_mouse(button, false)?; } diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 7197725f7..284871fd6 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -59,7 +59,9 @@ impl Game<'_> { } /// Once per frame: the frame's time, and keys let go behind screens. pub(super) fn extras_frame(&mut self, elapsed: Duration) { - let playing = self.screen == Screen::Playing && self.title.is_none() && self.focused; + // Under agent control the window may lack focus without pausing. + let focused = self.focused || self.control.is_some(); + let playing = self.screen == Screen::Playing && self.title.is_none() && focused; if !playing || !self.settings.extras.zoom { self.extras.zoom.release(); } From 365d35f53ad2e7969679d8ba2111581c8fecf764 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:41:01 +0200 Subject: [PATCH 03/43] Extras: the zoom key zooms only while playing and never takes keys The zoom key went to the zoom on every screen, so with zoom on, Z could not be typed in screens with text fields that share the game's key handler. Now it zooms only while playing with no sign or book open, lets go when a screen opens, and always passes the key on, like a vanilla key mapping. A vanilla mapping bound to the same key still acts; the Extras page marks the zoom key "Also bound" and names it. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/extras.rs | 65 ++++++++++++++++++++ crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/control.rs | 14 ++--- crates/horizon-client/src/game/extras.rs | 20 +++--- crates/horizon-client/src/options_horizon.rs | 14 ++++- docs/extras.md | 5 ++ 6 files changed, 99 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 551bcb27e..e35f94cd2 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -191,6 +191,16 @@ impl Zoom { pub fn release(&mut self) { self.held = false; } + /// A press or release of the zoom key. Only a press while `playing` (no + /// screen or text field open) zooms; anywhere else the key belongs to + /// the screen, and the zoom lets go. + pub fn key(&mut self, pressed: bool, repeat: bool, playing: bool, level: u8) { + if !pressed || !playing { + self.release(); + } else if !repeat { + self.press(level); + } + } pub fn held(&self) -> bool { self.held } @@ -212,6 +222,19 @@ impl Zoom { } } } +/// Vanilla key mappings bound to the zoom key. The key still reaches them +/// (a key bound twice triggers both, as vanilla's do), so the Extras page +/// says so. +pub fn zoom_key_conflicts(e: &Extras, keys: &crate::keybinds::KeyBinds) -> Vec<&'static str> { + if e.zoom_key == "key.keyboard.unknown" { + return Vec::new(); + } + crate::keybinds::MAPPINGS + .iter() + .map(|m| m.0) + .filter(|name| keys.get(name) == e.zoom_key) + .collect() +} /// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's /// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is. pub fn fov_target(vanilla: f32, zoom: f32) -> f32 { @@ -526,6 +549,48 @@ mod tests { assert!((floor - 7.0).abs() < 1e-3, "{floor}"); } + #[test] + fn the_zoom_key_only_zooms_while_playing() { + let mut z = Zoom::default(); + // In chat, a sign, a text field or any screen: no zoom. + z.key(true, false, false, 4); + assert!(!z.held()); + z.key(true, false, true, 4); + assert!(z.held()); + // A screen opening while held lets go (its key presses are the screen's). + z.key(true, true, false, 4); + assert!(!z.held()); + // Key repeats do not restart a zoom the wheel changed. + z.key(true, false, true, 4); + z.scroll(1.0); + z.key(true, true, true, 4); + assert!((z.factor(false) - 5.0).abs() < 1e-5); + z.key(false, false, true, 4); + assert!(!z.held()); + } + + #[test] + fn zoom_key_conflicts_name_the_vanilla_mappings() { + let mut e = Extras::default(); + let mut keys = crate::keybinds::KeyBinds::default(); + assert!(zoom_key_conflicts(&e, &keys).is_empty()); + e.zoom_key = "key.keyboard.c".into(); + assert_eq!( + zoom_key_conflicts(&e, &keys), + [ + "key.saveToolbarActivator", + "key.debug.crash", + "key.debug.copyLocation" + ] + ); + keys.set("key.drop", "key.keyboard.z"); + e.zoom_key = "key.keyboard.z".into(); + assert_eq!(zoom_key_conflicts(&e, &keys), ["key.drop"]); + e.zoom_key = "key.keyboard.unknown".into(); + keys.set("key.smoothCamera", "key.keyboard.unknown"); + assert!(zoom_key_conflicts(&e, &keys).is_empty()); + } + #[test] fn sensitivity_scales_with_zoom() { assert_eq!(turn_scale(1.0, true), 1.0); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fbd2daff6..6114ef09a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8530,9 +8530,7 @@ impl ApplicationHandler for Game<'_> { let PhysicalKey::Code(key) = event.physical_key else { return Ok(()); }; - if self.extras_key(key, event.state == ElementState::Pressed, event.repeat) { - return Ok(()); - } + self.extras_key(key, event.state == ElementState::Pressed, event.repeat); // key.smoothCamera toggles the cinematic camera. if self.screen == Screen::Playing && event.state == ElementState::Pressed diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index e7fe21260..567dd3a72 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -163,15 +163,11 @@ impl Game<'_> { self.debug_key(key, KeyAction::Release); } } - // The zoom extra's key, as the keyboard hook sees it. - if self.screen == Screen::Playing { - let action = arg(2)?; - if self.extras_key(physical, action != "up", false) { - if action == "tap" { - self.extras_key(physical, false, false); - } - return ok(); - } + // The zoom extra sees the key as the keyboard hook does. + let action = arg(2)?; + self.extras_key(physical, action != "up", false); + if action == "tap" { + self.extras_key(physical, false, false); } // Text screens consume raw presses; releases follow key binds. let typing = matches!(self.screen, Screen::Chat | Screen::Options); diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 284871fd6..4f4e3061e 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -28,17 +28,19 @@ impl Game<'_> { let e = &self.settings.extras; e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten() } - /// A key press or release while playing; true when the zoom key took it. - pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) -> bool { + /// A key press or release. The zoom key zooms only while playing with + /// no text open; the key itself always goes on to the screen and the key + /// binds, as a vanilla key mapping's would. + pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) { if self.zoom_key() != Some(key) { - return false; + return; } - if !pressed { - self.extras.zoom.release(); - } else if !repeat && self.screen == Screen::Playing && self.title.is_none() { - self.extras.zoom.press(self.settings.extras.zoom_level); - } - true + let playing = self.screen == Screen::Playing + && self.title.is_none() + && self.sign_edit.is_none() + && self.book.is_none(); + let level = self.settings.extras.zoom_level; + self.extras.zoom.key(pressed, repeat, playing, level); } /// Wheel steps while playing; true when zooming took them from the hotbar. pub(super) fn extras_scroll(&mut self, steps: f32) -> bool { diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index fcac82be3..095547ed2 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -418,8 +418,18 @@ impl OptionsUi { HRow::Extra(item) => { let cy = y + ROW_H / 2.0; let id = ROW + i as u64; - let cost = item.cost().map_or((0, ""), |c| (c as u8, c.label())); - let (caption, text) = (item.caption(), item.description()); + let mut cost = item.cost().map_or((0, ""), |c| (c as u8, c.label())); + let (caption, mut text) = (item.caption(), item.description().to_owned()); + // A vanilla mapping on the same key: both act on it, like + // the binds list's duplicates; say which. + let conflicts = extras::zoom_key_conflicts(&s.extras, &s.keys); + if item == extras::Item::ZoomKey && !conflicts.is_empty() { + let names: Vec = + conflicts.iter().map(|c| crate::lang::get(c)).collect(); + cost = (3, "Also bound"); + text = format!("{} uses this key too; both act on it.", names.join(", ")); + } + let text = text.as_str(); if let Some(on) = item.switch(&s.extras) { ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0); ui.switch(id, control_x, cy, on); diff --git a/docs/extras.md b/docs/extras.md index 13e267f6b..9ace6e593 100644 --- a/docs/extras.md +++ b/docs/extras.md @@ -36,6 +36,11 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int ### Zoom (`zoom`, default off) - Hold the zoom key (default **Z**, unused by every vanilla 26.3 key mapping; C is `key.saveToolbarActivator`) to zoom. The key does nothing while zoom is off. +- It zooms only while playing: in chat, signs, books, text fields and every + other screen the key is typed or handled as usual. The key is never taken + from vanilla's mappings: one bound to the same key still acts (a key bound + twice triggers both, as vanilla's do), and the Extras page marks the zoom key + "Also bound" and names the mapping. - Starts at the default level (4x, settable 2x to 10x); the scroll wheel changes it while the key is held (and does not move the hotbar then). - **Smooth** (default on) goes through vanilla's own FOV easing: the zoom divides From 663f61c8c3f068423e048c32988c3e9d99d32e95 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:40:56 +0200 Subject: [PATCH 04/43] Horizon extras: a minimap, off by default A corner map of the loaded chunks in vanilla's map colours with the map item's height and water shading: square or round, three sizes, four zooms, north up or turning with the player, with the player arrow. In the Nether, underground and under a roof it maps the floor at the player's height and cuts walls. Each loaded chunk keeps a 16x16 tile, filled nearest first within 0.3 ms a frame and rescanned after block changes; the image is recomposed only when the view or a tile changed and uploaded into its own atlas slot. Nothing runs while it is off. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/extras.rs | 120 +++- crates/horizon-client/src/extras_hud.rs | 56 +- crates/horizon-client/src/game/extras.rs | 108 +++- crates/horizon-client/src/hud.rs | 9 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/minimap.rs | 679 +++++++++++++++++++++++ 6 files changed, 961 insertions(+), 12 deletions(-) create mode 100644 crates/horizon-client/src/minimap.rs diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index e35f94cd2..33854e67d 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -15,6 +15,10 @@ pub const ZOOM_MAX: f32 = 10.0; /// Each wheel step multiplies the zoom by this. const ZOOM_STEP: f32 = 1.25; +/// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel. +pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")]; +pub const MINIMAP_ZOOMS: [f32; 4] = [0.5, 1.0, 2.0, 4.0]; + /// A screen corner for an overlay. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Corner { @@ -79,6 +83,15 @@ pub struct Extras { pub keystrokes_corner: Corner, /// Clicks per second under the mouse buttons. pub keystrokes_cps: bool, + pub minimap: bool, + pub minimap_corner: Corner, + /// Side in GUI pixels (`MINIMAP_SIZES`). + pub minimap_size: u8, + pub minimap_round: bool, + /// Blocks per pixel (`MINIMAP_ZOOMS`). + pub minimap_zoom: f32, + /// Turn with the player (forward up) instead of north up. + pub minimap_rotate: bool, } impl Default for Extras { fn default() -> Self { @@ -94,6 +107,12 @@ impl Default for Extras { keystrokes: false, keystrokes_corner: Corner::TopLeft, keystrokes_cps: true, + minimap: false, + minimap_corner: Corner::TopRight, + minimap_size: 96, + minimap_round: false, + minimap_zoom: 1.0, + minimap_rotate: false, } } } @@ -136,6 +155,20 @@ impl Extras { e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner) } "keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps), + "minimap" => e.minimap = flag(e.minimap), + "minimapCorner" => e.minimap_corner = Corner::parse(value, e.minimap_corner), + "minimapSize" => { + if let Some(&(v, _)) = MINIMAP_SIZES.iter().find(|s| s.0.to_string() == value) { + e.minimap_size = v; + } + } + "minimapShape" => e.minimap_round = value == "round", + "minimapZoom" => { + if let Some(&z) = MINIMAP_ZOOMS.iter().find(|z| z.to_string() == value) { + e.minimap_zoom = z; + } + } + "minimapRotate" => e.minimap_rotate = flag(e.minimap_rotate), _ => {} } } @@ -143,7 +176,7 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\n", + "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\n", bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -155,6 +188,16 @@ impl Extras { bool_text(self.keystrokes), self.keystrokes_corner.name(), bool_text(self.keystrokes_cps), + bool_text(self.minimap), + self.minimap_corner.name(), + self.minimap_size, + if self.minimap_round { + "round" + } else { + "square" + }, + self.minimap_zoom, + bool_text(self.minimap_rotate), ) } /// Written only once something differs from the defaults, so a vanilla @@ -349,6 +392,12 @@ pub enum Item { Keystrokes, KeystrokesCorner, KeystrokesCps, + Minimap, + MinimapCorner, + MinimapSize, + MinimapShape, + MinimapZoom, + MinimapRotate, } /// The Extras page: headers and items. pub fn rows() -> Vec> { @@ -360,6 +409,13 @@ pub fn rows() -> Vec> { Ok(ZoomLevel), Ok(ZoomSmooth), Ok(ZoomSensitivity), + Err("Minimap"), + Ok(Minimap), + Ok(MinimapCorner), + Ok(MinimapSize), + Ok(MinimapShape), + Ok(MinimapZoom), + Ok(MinimapRotate), Err("FPS counter"), Ok(Fps), Ok(FpsCorner), @@ -370,6 +426,16 @@ pub fn rows() -> Vec> { Ok(KeystrokesCps), ] } +/// "1 block", "2 blocks", "½ block". +fn block_count(n: f32) -> String { + if n < 1.0 { + "½ block".into() + } else if n == 1.0 { + "1 block".into() + } else { + format!("{n} blocks") + } +} fn next(all: &[T], current: T, back: bool) -> T { let i = all.iter().position(|v| *v == current).unwrap_or(0); let n = all.len(); @@ -384,7 +450,12 @@ impl Item { Item::ZoomSmooth => "Smooth zoom", Item::ZoomSensitivity => "Lower sensitivity while zoomed", Item::Fps => "FPS counter", - Item::FpsCorner | Item::KeystrokesCorner => "Corner", + Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner", + Item::Minimap => "Minimap", + Item::MinimapSize => "Size", + Item::MinimapShape => "Shape", + Item::MinimapZoom => "Zoom", + Item::MinimapRotate => "Turn with the player", Item::FpsLows => "Minimum and 1% low", Item::Keystrokes => "Keystrokes", Item::KeystrokesCps => "Clicks per second", @@ -399,7 +470,14 @@ impl Item { Item::ZoomSmooth => "Eases in and out like the spyglass.", Item::ZoomSensitivity => "Turns slower the more you zoom in.", Item::Fps => "Frames per second in a corner of the screen.", - Item::FpsCorner | Item::KeystrokesCorner => "Overlays in one corner stack.", + Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => { + "Overlays in one corner stack." + } + Item::Minimap => "A map of the loaded terrain around you, in map colours.", + Item::MinimapSize => "How big the map is on screen.", + Item::MinimapShape => "Square or round.", + Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.", + Item::MinimapRotate => "Forward is up; off keeps north up.", Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.", Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", Item::KeystrokesCps => "Clicks in the last second under each mouse button.", @@ -410,6 +488,7 @@ impl Item { use crate::graphics_style::Cost; match self { Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), + Item::Minimap => Some(Cost::Low), _ => None, } } @@ -423,6 +502,8 @@ impl Item { Item::FpsLows => e.fps_lows, Item::Keystrokes => e.keystrokes, Item::KeystrokesCps => e.keystrokes_cps, + Item::Minimap => e.minimap, + Item::MinimapRotate => e.minimap_rotate, _ => return None, }) } @@ -433,6 +514,14 @@ impl Item { Item::ZoomLevel => format!("{}x", e.zoom_level), Item::FpsCorner => e.fps_corner.label().into(), Item::KeystrokesCorner => e.keystrokes_corner.label().into(), + Item::MinimapCorner => e.minimap_corner.label().into(), + Item::MinimapSize => MINIMAP_SIZES + .iter() + .find(|s| s.0 == e.minimap_size) + .map_or("Medium", |s| s.1) + .into(), + Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(), + Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)), other => match other.switch(e) { Some(true) => "On".into(), _ => "Off".into(), @@ -454,6 +543,15 @@ impl Item { Item::KeystrokesCorner => { e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back) } + Item::Minimap => e.minimap = !e.minimap, + Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate, + Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back), + Item::MinimapSize => { + let sizes: Vec = MINIMAP_SIZES.iter().map(|s| s.0).collect(); + e.minimap_size = next(&sizes, e.minimap_size, back); + } + Item::MinimapShape => e.minimap_round = !e.minimap_round, + Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back), Item::ZoomKey => {} } } @@ -466,7 +564,7 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); - assert!(!d.zoom && !d.fps && !d.keystrokes); + assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap); assert_eq!(Extras::parse(""), d); assert_eq!(Extras::parse(&d.serialize()), d); let mut e = d.clone(); @@ -476,6 +574,12 @@ mod tests { e.fps_corner = Corner::BottomRight; e.keystrokes = true; e.keystrokes_cps = false; + e.minimap = true; + e.minimap_size = 128; + e.minimap_round = true; + e.minimap_zoom = 0.5; + e.minimap_rotate = true; + e.minimap_corner = Corner::BottomLeft; assert_eq!(Extras::parse(&e.serialize()), e); } @@ -661,6 +765,14 @@ mod tests { Item::Zoom.cycle(&mut e, false); assert_eq!(Item::Zoom.switch(&e), Some(true)); assert_eq!(Item::ZoomKey.value(&e), "Z"); + Item::MinimapZoom.cycle(&mut e, true); + assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel"); + Item::MinimapSize.cycle(&mut e, false); + assert_eq!(Item::MinimapSize.value(&e), "Large"); + assert_eq!( + Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom, + 1.0 + ); for item in rows().into_iter().flatten() { assert!(!item.caption().is_empty() && !item.description().is_empty()); } diff --git a/crates/horizon-client/src/extras_hud.rs b/crates/horizon-client/src/extras_hud.rs index 6d015f5df..df23b533f 100644 --- a/crates/horizon-client/src/extras_hud.rs +++ b/crates/horizon-client/src/extras_hud.rs @@ -2,7 +2,7 @@ //! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`). use crate::{ extras::{Corner, FpsReading}, - hud::{HudAtlas, HudBatch, rgba}, + hud::{HudAtlas, HudBatch, Rect, rgba}, }; /// The gap between an overlay and the screen edge or the next overlay. @@ -45,6 +45,60 @@ impl Corners { } } +/// How the minimap shows: its corner and side in GUI pixels, its image (an +/// atlas rect), the player arrow (the map item's decoration sprite) turned +/// `arrow` degrees clockwise from up, and the rim's N toward `north` when the +/// map turns. +pub struct MinimapLook { + pub corner: Corner, + pub size: f32, + pub image: Rect, + pub arrow: f32, + pub north: Option<(f32, f32)>, +} +pub fn draw_minimap( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + look: &MinimapLook, +) { + let MinimapLook { + corner, + size, + image, + arrow, + north, + } = *look; + let (x, y) = corners.place(corner, size, size); + batch.rect_uv(x, y, size, size, image, u32::MAX); + let (cx, cy) = (x + size / 2.0, y + size / 2.0); + if let Some(r) = atlas.sprites.get("map/decorations/player").copied() { + // MapRenderer's decorations draw the sprite flipped: its arrow + // points down the texture, so up on screen is half a turn. + let (s, c) = (arrow + 180.0).to_radians().sin_cos(); + let p = |dx: f32, dy: f32| [cx + dx * c - dy * s, cy + dx * s + dy * c]; + let h = 4.0; + batch.quad( + [p(-h, h), p(h, h), p(h, -h), p(-h, -h)], + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], + u32::MAX, + ); + } + if let Some((nx, ny)) = north { + let reach = size / 2.0 - 6.0; + let tw = HudBatch::text_width(atlas, "N"); + let (tx, ty) = (cx + nx * reach - tw / 2.0, cy + ny * reach - 4.0); + batch.text( + atlas, + "N", + tx.round(), + ty.round(), + rgba(255, 255, 255, 255), + true, + ); + } +} + /// The FPS counter's text. pub fn fps_text(r: FpsReading, lows: bool) -> String { if lows { diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 4f4e3061e..721dc0280 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -1,12 +1,14 @@ //! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel, -//! clicks for the keystroke overlay, frame times for the FPS counter, and -//! their HUD. Each hook does nothing while its extra is off. -use super::{Game, Screen}; +//! clicks for the keystroke overlay, frame times for the FPS counter, the +//! minimap's tiles and image, and their HUD. Each hook does nothing while its +//! extra is off. +use super::{Dim, Game, Screen}; use horizon_client::{ - extras::{Cps, FpsCounter, Zoom, fov_target, turn_scale}, + extras::{Corner, Cps, FpsCounter, Zoom, fov_target, turn_scale}, extras_hud::{self, Corners, Keystrokes}, - hud::HudBatch, + hud::{HudBatch, MINIMAP_SPRITE}, keybinds, + minimap::{self, Layer, Minimap, View}, }; use std::time::Duration; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -18,7 +20,12 @@ pub(super) struct ExtrasState { /// Left and right mouse buttons: held, and their clicks. mouse: [bool; 2], cps: [Cps; 2], + minimap: Minimap, + /// The dimension the minimap's tiles belong to. + minimap_dim: Option, } +/// CPU time the minimap's tiles may take per frame. +const MINIMAP_BUDGET: Duration = Duration::from_micros(300); impl Game<'_> { fn extras_now(&self) -> f64 { @@ -70,6 +77,7 @@ impl Game<'_> { if !playing { self.extras.mouse = [false; 2]; } + self.update_minimap(); if self.settings.extras.fps { let now = self.extras_now(); self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0); @@ -77,6 +85,72 @@ impl Game<'_> { self.extras.fps.clear(); } } + /// The minimap's view of the player, if it shows. + fn minimap_view(&self) -> Option { + let e = &self.settings.extras; + let p = self.player.as_ref()?; + let shown = e.minimap && self.title.is_none() && !self.ui.hide_gui; + shown.then_some(View { + x: p.position.x, + z: p.position.z, + yaw: self.yaw, + rotate: e.minimap_rotate, + blocks_per_pixel: e.minimap_zoom, + round: e.minimap_round, + }) + } + /// Refresh the minimap's tiles within the frame budget, recompose its + /// image when the view or a tile changed, and queue the upload. + fn update_minimap(&mut self) { + let Some(view) = self.minimap_view() else { + if !self.settings.extras.minimap || self.player.is_none() { + self.extras.minimap.clear(); + self.extras.minimap_dim = None; + } + return; + }; + if self.extras.minimap_dim != Some(self.dim) { + self.extras.minimap.clear(); + self.extras.minimap_dim = Some(self.dim); + } + let Some(p) = self.player.as_ref() else { + return; + }; + let head = (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32; + let (bx, bz) = (view.x.floor() as i32, view.z.floor() as i32); + // Underground, under a roof or in the Nether: the floor around the player. + let covered = self.world.light(bx, head, bz) >> 4 == 0; + let layer = if self.dim == Dim::Nether || covered { + Layer::Below(head) + } else { + Layer::Surface + }; + // The chunks the image can reach (its corners when it turns). + let reach = minimap::SIZE as f32 / 2.0 * view.blocks_per_pixel * std::f32::consts::SQRT_2; + let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2)); + self.extras.minimap.update( + &self.world, + &self.res.facts, + (bx >> 4, bz >> 4), + radius, + layer, + MINIMAP_BUDGET, + ); + if !self.extras.minimap.compose(view) { + return; + } + let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + return; + }; + let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + self.map_patches.push(horizon_client::font::Patch { + x: (rect.u0 * w).round() as u32, + y: (rect.v0 * h).round() as u32, + width: minimap::SIZE as u32, + height: minimap::SIZE as u32, + rgba: self.extras.minimap.image.clone(), + }); + } /// The zoom in effect (1 unless the key is held). fn zoom_factor(&self) -> f32 { self.extras.zoom.factor(self.scoping()) @@ -105,14 +179,34 @@ impl Game<'_> { /// the caller). The top left corner gives way to the debug screen. pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { let e = &self.settings.extras; - if !e.fps && !e.keystrokes { + if !e.fps && !e.keystrokes && !e.minimap { return; } let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows); let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps); - let visible = |corner| !(self.debug && corner == horizon_client::extras::Corner::TopLeft); + let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); + let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); let atlas = &self.res.atlas; + if let Some(view) = self.minimap_view() + && visible(map_corner) + && !self.extras.minimap.image.is_empty() + && let Some(image) = atlas.sprites.get(MINIMAP_SPRITE).copied() + { + let (arrow, north) = if view.rotate { + (0.0, Some(view.north())) + } else { + (180.0 + view.yaw, None) + }; + let look = extras_hud::MinimapLook { + corner: map_corner, + size: map_size, + image, + arrow, + north, + }; + extras_hud::draw_minimap(batch, atlas, &mut corners, &look); + } if fps_on && visible(fps_corner) { let reading = self.extras.fps.reading(); extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 6161160dd..71db32199 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -31,6 +31,8 @@ pub struct HudAtlas { pub const GLYPH_ROWS: u32 = 512; /// 128x128 atlas slots for map textures. pub const MAP_SLOTS: usize = 16; +/// The atlas slot the minimap extra draws into. +pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. pub const SKIN_SLOTS: usize = 32; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { @@ -200,6 +202,13 @@ impl HudAtlas { for i in 0..MAP_SLOTS { images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4])); } + // The minimap extra's image (game/extras.rs). + images.push(( + MINIMAP_SPRITE.into(), + crate::minimap::SIZE as u32, + crate::minimap::SIZE as u32, + vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4], + )); // Downloaded skins (game/scoreboard.rs) likewise. for i in 0..SKIN_SLOTS { images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f3b1db78d..5b21d45ae 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -86,6 +86,7 @@ pub mod logging; pub mod menu; pub mod merchant; pub mod mesher; +pub mod minimap; pub mod mobs; pub mod models; pub mod motion; diff --git a/crates/horizon-client/src/minimap.rs b/crates/horizon-client/src/minimap.rs new file mode 100644 index 000000000..8015e2ab2 --- /dev/null +++ b/crates/horizon-client/src/minimap.rs @@ -0,0 +1,679 @@ +//! The minimap extra (`docs/extras.md`): a 16x16 tile per loaded chunk with +//! each column's vanilla map colour (`MapColor`, as `MapItem.update` picks +//! it), height and water depth, and a 128x128 image composed from the tiles +//! around the player with the map item's height and water shading. +//! +//! Tiles are filled nearest first within a time budget and rescanned after +//! block changes; the image is recomposed only when the view moved or a tile +//! changed. +use crate::{ + blocks::{BlockFacts, Fluid, MAP_COLORS}, + chunk::{Chunk, MIN_Y, SECTIONS}, + fast_hash::FxHashMap, + world::World, +}; +use std::time::{Duration, Instant}; + +/// The image's side in texels. +pub const SIZE: usize = 128; +/// Marks a column the map cuts through (a wall at the player's height). +const WALL: u8 = 0x80; +/// Water's and lava's map colours (`MapColor.WATER`, `FIRE`). +const WATER: u8 = 12; +const LAVA: u8 = 4; +/// A tile whose chunk changed is rescanned at most this often. +const RESCAN: Duration = Duration::from_secs(1); + +/// What the map shows of each column. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layer { + /// The top block, as map items show it. + Surface, + /// Underground, in the Nether or under a roof: the floor below this + /// height (the player's head), and walls cut at it. + Below(i32), +} + +/// What the scan needs of each block state. +pub struct Palette { + /// Map colour id, 0 for none. + color: Vec, + /// 0 none, 1 water, 2 lava; | 4 for air; | 8 when sturdy on top. + flags: Vec, +} +const FLUID: u8 = 3; +const AIR: u8 = 4; +const STURDY_TOP: u8 = 8; +impl Palette { + pub fn new(facts: &BlockFacts) -> Self { + let mut color = Vec::with_capacity(facts.states.len()); + let mut flags = Vec::with_capacity(facts.states.len()); + for (i, f) in facts.states.iter().enumerate() { + color.push(f.map_color); + let mut b = match f.fluid { + Fluid::None => 0, + Fluid::Water => 1, + Fluid::Lava => 2, + }; + if facts.is_air(horizon_world::registry::BlockStateId(i as u32)) { + b |= AIR; + } + // isFaceSturdy(UP, FULL): Direction.UP's ordinal is 1. + if f.sturdy_full >> 1 & 1 != 0 { + b |= STURDY_TOP; + } + flags.push(b); + } + Self { color, flags } + } + /// A palette from (colour, flags) per state id (tests). + #[cfg(test)] + fn from_parts(parts: &[(u8, u8)]) -> Self { + Self { + color: parts.iter().map(|p| p.0).collect(), + flags: parts.iter().map(|p| p.1).collect(), + } + } + #[inline] + fn get(&self, id: u16) -> (u8, u8) { + let i = usize::from(id); + ( + self.color.get(i).copied().unwrap_or(0), + self.flags.get(i).copied().unwrap_or(AIR), + ) + } +} + +#[derive(Clone)] +struct Tile { + /// Map colour id per column (`z * 16 + x`), `| WALL` for cut walls. + color: [u8; 256], + height: [i16; 256], + /// Water depth below the surface, for the map's water shading. + depth: [u8; 256], + revision: u64, + layer: Layer, + scanned: Instant, +} +/// `MapItem.update` for one column: the first block with a map colour +/// going down, the fluid's colour over a fluid unless the block is sturdy on +/// top (`getCorrectStateForFluidBlock`), and the fluid's depth. +fn scan_column( + chunk: &Chunk, + palette: &Palette, + x: i32, + z: i32, + top: i32, + layer: Layer, +) -> (u8, i16, u8) { + let mut y = top; + if let Layer::Below(head) = layer { + let (color, flags) = palette.get(chunk.get(x, head, z)); + if flags & AIR == 0 && color != 0 && flags & FLUID == 0 { + return (color | WALL, head as i16, 0); + } + } + while y > MIN_Y { + let (mut color, flags) = palette.get(chunk.get(x, y, z)); + if color == 0 { + y -= 1; + continue; + } + let mut depth = 0u8; + let fluid = flags & FLUID; + if fluid != 0 { + let mut below = y - 1; + while below > MIN_Y && palette.get(chunk.get(x, below, z)).1 & FLUID != 0 { + depth = depth.saturating_add(1); + below -= 1; + } + depth = depth.saturating_add(1); + if flags & STURDY_TOP == 0 { + color = if fluid == 2 { LAVA } else { WATER }; + } + } + return (color, y as i16, depth); + } + (0, MIN_Y as i16, 0) +} +/// The highest block of a chunk worth scanning from. +fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { + let surface = (0..SECTIONS) + .rev() + .find(|&s| { + chunk + .sections + .get(s) + .is_some_and(|sec| !sec.is_uniform(air)) + }) + .map_or(MIN_Y, |s| MIN_Y + s as i32 * 16 + 15); + match layer { + Layer::Surface => surface, + Layer::Below(head) => surface.min(head), + } +} +fn scan_tile(chunk: &Chunk, palette: &Palette, air: u16, layer: Layer, revision: u64) -> Tile { + let top = top_of(chunk, air, layer); + let mut tile = Tile { + color: [0; 256], + height: [MIN_Y as i16; 256], + depth: [0; 256], + revision, + layer, + scanned: Instant::now(), + }; + for z in 0..16 { + for x in 0..16 { + let (c, h, d) = scan_column(chunk, palette, x, z, top, layer); + let i = (z * 16 + x) as usize; + tile.color[i] = c; + tile.height[i] = h; + tile.depth[i] = d; + } + } + tile +} + +/// Where the map looks from and how. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct View { + pub x: f64, + pub z: f64, + /// The player's yaw in degrees (0 faces south). + pub yaw: f32, + /// The map turns with the player (forward is up), or north is up. + pub rotate: bool, + pub blocks_per_pixel: f32, + pub round: bool, +} +impl View { + /// Whether the image for `self` would look different from `other`'s. + fn differs(&self, other: &View) -> bool { + let moved = ((self.x - other.x).abs().max((self.z - other.z).abs()) as f32) + >= self.blocks_per_pixel / 4.0; + let turned = self.rotate && (self.yaw - other.yaw).abs() >= 0.5; + moved + || turned + || self.rotate != other.rotate + || self.round != other.round + || self.blocks_per_pixel != other.blocks_per_pixel + } + /// The world's right and forward directions as the map's x and up. + fn axes(&self) -> ([f64; 2], [f64; 2]) { + if !self.rotate { + return ([1.0, 0.0], [0.0, -1.0]); + } + let (s, c) = f64::from(self.yaw).to_radians().sin_cos(); + ([-c, -s], [-s, c]) + } + /// Where north is on the map's rim, as a unit direction (x right, y down). + pub fn north(&self) -> (f32, f32) { + let (r, f) = self.axes(); + // The direction (0, -1) in the map's (right, -forward) basis. + (-r[1] as f32, f[1] as f32) + } +} + +/// `MapColor.getColorFromPackedId` as RGBA. +fn packed_rgba(id: u8, brightness: u8) -> [u8; 4] { + let id = usize::from(id); + if id == 0 || id >= MAP_COLORS.len() { + return [0; 4]; + } + let modifier = [180u32, 220, 255, 135][usize::from(brightness & 3)]; + let col = MAP_COLORS[id]; + let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8; + [ch(16), ch(8), ch(0), 255] +} +/// The map item's shading at scale 1: brighter facing a lower north +/// neighbour, darker facing a higher one, dithered; water by depth. +fn brightness(color: u8, height: i16, north: Option, depth: u8, parity: i32) -> u8 { + if color & WALL != 0 { + return 3; + } + let parity = f64::from(parity & 1); + if color == WATER { + let diff = f64::from(depth) * 0.1 + parity * 0.2; + return if diff < 0.5 { + 2 + } else if diff > 0.9 { + 0 + } else { + 1 + }; + } + let north = north.unwrap_or(height); + let diff = f64::from(height - north) * 4.0 / 5.0 + (parity - 0.5) * 0.4; + if diff > 0.6 { + 2 + } else if diff < -0.6 { + 0 + } else { + 1 + } +} +const UNKNOWN: [u8; 4] = [20, 20, 20, 200]; +const BORDER: [u8; 4] = [10, 10, 10, 230]; + +#[derive(Default)] +pub struct Minimap { + tiles: FxHashMap<(i32, i32), Tile>, + palette: Option, + composed: Option, + /// Tiles changed since the image was composed. + changed: bool, + /// The composed image, `SIZE` x `SIZE` RGBA. + pub image: Vec, +} +impl Minimap { + /// Forget everything (a new world or dimension, or the minimap turned off). + pub fn clear(&mut self) { + let palette = self.palette.take(); + *self = Self { + palette, + ..Self::default() + }; + } + /// Fill and refresh tiles around chunk `center` within `radius` chunks, + /// nearest first, until `budget` is spent. Returns the tiles scanned. + pub fn update( + &mut self, + world: &World, + facts: &BlockFacts, + center: (i32, i32), + radius: i32, + layer: Layer, + budget: Duration, + ) -> usize { + let palette = self.palette.get_or_insert_with(|| Palette::new(facts)); + let started = Instant::now(); + let air = world.air.0 as u16; + // Tiles of unloaded or distant chunks go. + self.tiles.retain(|k, _| { + (k.0 - center.0).abs() <= radius + 2 + && (k.1 - center.1).abs() <= radius + 2 + && world.chunks.contains_key(k) + }); + let mut scanned = 0; + for ring in 0..=radius { + for (dx, dz) in ring_offsets(ring) { + let key = (center.0 + dx, center.1 + dz); + let Some(chunk) = world.chunks.get(&key) else { + continue; + }; + let stale = match self.tiles.get(&key) { + None => true, + Some(t) if t.layer != layer => true, + Some(t) => t.revision != world.revision && t.scanned.elapsed() >= RESCAN, + }; + if !stale { + continue; + } + let tile = scan_tile(chunk, palette, air, layer, world.revision); + if self.tiles.get(&key).is_none_or(|t| { + t.color != tile.color || t.height != tile.height || t.depth != tile.depth + }) { + self.changed = true; + } + self.tiles.insert(key, tile); + scanned += 1; + if started.elapsed() >= budget { + return scanned; + } + } + } + scanned + } + /// Recompose the image if the view or the tiles changed; true when it did. + pub fn compose(&mut self, view: View) -> bool { + if !self.changed + && self.composed.is_some_and(|c| !view.differs(&c)) + && !self.image.is_empty() + { + return false; + } + self.changed = false; + self.composed = Some(view); + self.image.resize(SIZE * SIZE * 4, 0); + let (r, f) = view.axes(); + let bpp = f64::from(view.blocks_per_pixel); + let half = SIZE as f64 / 2.0; + let mut cached: Option<((i32, i32), &Tile)> = None; + let mut column = |x: i32, z: i32| -> Option<(u8, i16, u8)> { + let key = (x >> 4, z >> 4); + let tile = match cached { + Some((k, t)) if k == key => t, + _ => { + let t = self.tiles.get(&key)?; + cached = Some((key, t)); + t + } + }; + let i = ((z & 15) * 16 + (x & 15)) as usize; + Some((tile.color[i], tile.height[i], tile.depth[i])) + }; + for j in 0..SIZE { + for i in 0..SIZE { + let (u, v) = (i as f64 + 0.5 - half, j as f64 + 0.5 - half); + let o = (j * SIZE + i) * 4; + let edge = if view.round { + let d = (u * u + v * v).sqrt(); + if d > half { + self.image[o..o + 4].copy_from_slice(&[0; 4]); + continue; + } + d > half - 1.5 + } else { + i == 0 || j == 0 || i == SIZE - 1 || j == SIZE - 1 + }; + if edge { + self.image[o..o + 4].copy_from_slice(&BORDER); + continue; + } + let wx = view.x + bpp * (u * r[0] - v * f[0]); + let wz = view.z + bpp * (u * r[1] - v * f[1]); + let (x, z) = (wx.floor() as i32, wz.floor() as i32); + let rgba = match column(x, z) { + Some((color, height, depth)) if color & !WALL != 0 => { + let north = column(x, z - 1).filter(|c| c.0 & !WALL != 0).map(|c| c.1); + let b = brightness(color, height, north, depth, x + z); + packed_rgba(color & !WALL, b) + } + _ => UNKNOWN, + }; + self.image[o..o + 4].copy_from_slice(&rgba); + } + } + true + } + pub fn tile_count(&self) -> usize { + self.tiles.len() + } +} +/// Chunk offsets at Chebyshev distance `ring`. +fn ring_offsets(ring: i32) -> impl Iterator { + (-ring..=ring).flat_map(move |dz| { + (-ring..=ring) + .filter(move |&dx| dx.abs() == ring || dz.abs() == ring) + .map(move |dx| (dx, dz)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + // States: 0 air, 1 grass (colour 1), 2 stone (11), 3 water, 4 glass (no + // colour), 5 waterlogged slab (sturdy on top? no), 6 lava. + fn palette() -> Palette { + Palette::from_parts(&[ + (0, AIR), + (1, STURDY_TOP), + (11, STURDY_TOP), + (WATER, 1), + (0, 0), + (11, 1), + (LAVA, 2), + ]) + } + fn chunk(columns: &[(i32, i32, &[(i32, u16)])]) -> Chunk { + let mut c = Chunk::empty(0, 0); + for &(x, z, blocks) in columns { + for &(y, id) in blocks { + c.set(x, y, z, id); + } + } + c + } + + #[test] + fn columns_take_the_first_coloured_block_and_fluids_over_it() { + let p = palette(); + let c = chunk(&[ + (0, 0, &[(60, 2), (61, 1)]), + // Glass has no map colour: the grass under it shows. + (1, 0, &[(61, 1), (62, 4)]), + // Three water over stone. + (2, 0, &[(60, 2), (61, 3), (62, 3), (63, 3)]), + (3, 0, &[(70, 6)]), + ]); + let top = top_of(&c, 0, Layer::Surface); + assert_eq!(top, 79); + assert_eq!(scan_column(&c, &p, 0, 0, top, Layer::Surface), (1, 61, 0)); + assert_eq!(scan_column(&c, &p, 1, 0, top, Layer::Surface), (1, 61, 0)); + assert_eq!( + scan_column(&c, &p, 2, 0, top, Layer::Surface), + (WATER, 63, 3) + ); + assert_eq!( + scan_column(&c, &p, 3, 0, top, Layer::Surface), + (LAVA, 70, 1) + ); + assert_eq!(scan_column(&c, &p, 4, 0, top, Layer::Surface).0, 0); + } + + #[test] + fn a_waterlogged_block_not_sturdy_on_top_shows_water() { + let p = palette(); + let c = chunk(&[(0, 0, &[(60, 2), (61, 5)])]); + assert_eq!( + scan_column(&c, &p, 0, 0, 70, Layer::Surface), + (WATER, 61, 1) + ); + } + + #[test] + fn below_a_height_shows_the_floor_and_cuts_walls() { + let p = palette(); + // A cave: stone everywhere from 0 to 20, air at 10 and 11 in column 0. + let mut blocks: Vec<(i32, u16)> = (0..=20).map(|y| (y, 2)).collect(); + let solid = blocks.clone(); + blocks.retain(|&(y, _)| y != 10 && y != 11); + let c = chunk(&[(0, 0, &blocks), (1, 0, &solid)]); + let layer = Layer::Below(11); + let top = top_of(&c, 0, layer); + assert_eq!(top, 11); + assert_eq!(scan_column(&c, &p, 0, 0, top, layer), (11, 9, 0)); + assert_eq!(scan_column(&c, &p, 1, 0, top, layer), (11 | WALL, 11, 0)); + // The surface view sees the roof. + assert_eq!(scan_column(&c, &p, 0, 0, 31, Layer::Surface), (11, 20, 0)); + } + + #[test] + fn shading_follows_the_map_item() { + // Higher than the north neighbour: bright; lower: dark; level: normal. + assert_eq!(brightness(1, 65, Some(64), 0, 0), 2); + assert_eq!(brightness(1, 63, Some(64), 0, 1), 0); + assert_eq!(brightness(1, 64, Some(64), 0, 0), 1); + assert_eq!(brightness(1, 64, Some(64), 0, 1), 1); + // Shallow water is bright, deep water dark. + assert_eq!(brightness(WATER, 62, None, 1, 0), 2); + assert_eq!(brightness(WATER, 62, None, 10, 0), 0); + assert_eq!(brightness(1 | WALL, 0, None, 0, 0), 3); + assert_eq!(packed_rgba(1, 2), [127, 178, 56, 255]); + assert_eq!(packed_rgba(0, 2), [0; 4]); + } + + fn world_with(chunks: Vec) -> World { + let mut w = World::new(horizon_world::registry::BlockStateId(0), 0); + for c in chunks { + w.chunks.insert((c.x, c.z), Arc::new(c)); + } + w + } + fn grass_chunk(x: i32, z: i32) -> Chunk { + let mut c = Chunk::empty(x, z); + for bz in 0..16 { + for bx in 0..16 { + c.set(bx, 64, bz, 1); + } + } + c + } + + #[test] + fn tiles_fill_nearest_first_and_follow_changes() { + let mut map = Minimap { + palette: Some(palette()), + ..Default::default() + }; + let facts = BlockFacts { + states: Vec::new(), + air: horizon_world::registry::BlockStateId(0), + }; + let mut world = world_with( + (-2..=2) + .flat_map(|x| (-2..=2).map(move |z| grass_chunk(x, z))) + .collect(), + ); + // A zero budget still scans one tile: the player's own chunk. + assert_eq!( + map.update(&world, &facts, (0, 0), 2, Layer::Surface, Duration::ZERO), + 1 + ); + assert!(map.tiles.contains_key(&(0, 0))); + let n = map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1), + ); + assert_eq!(n, 24); + assert_eq!(map.tile_count(), 25); + // Nothing changed: nothing to scan. + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 0 + ); + // A changed world is rescanned once the tiles are old enough. + world + .set(0, 70, 0, horizon_world::registry::BlockStateId(2)) + .unwrap(); + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 0 + ); + for t in map.tiles.values_mut() { + t.scanned -= RESCAN; + } + assert_eq!( + map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Surface, + Duration::from_secs(1) + ), + 25 + ); + assert_eq!(map.tiles[&(0, 0)].color[0], 11); + // A new layer rescans everything; unloaded chunks drop out. + world.chunks.remove(&(2, 2)); + let n = map.update( + &world, + &facts, + (0, 0), + 2, + Layer::Below(70), + Duration::from_secs(1), + ); + assert_eq!(n, 24); + assert!(!map.tiles.contains_key(&(2, 2))); + } + + #[test] + fn the_image_is_north_up_or_turns_with_the_player() { + let mut map = Minimap { + palette: Some(palette()), + ..Default::default() + }; + let facts = BlockFacts { + states: Vec::new(), + air: horizon_world::registry::BlockStateId(0), + }; + // Grass everywhere, one stone block 10 blocks north of the player. + let mut world = world_with( + (-4..=4) + .flat_map(|x| (-4..=4).map(move |z| grass_chunk(x, z))) + .collect(), + ); + world + .set(0, 64, -10, horizon_world::registry::BlockStateId(2)) + .unwrap(); + map.update( + &world, + &facts, + (0, 0), + 4, + Layer::Surface, + Duration::from_secs(1), + ); + let pixel = |map: &Minimap, i: usize, j: usize| { + let o = (j * SIZE + i) * 4; + [map.image[o], map.image[o + 1], map.image[o + 2]] + }; + let stone = [96, 96, 96]; + let mut view = View { + x: 0.0, + z: 0.0, + yaw: 0.0, + rotate: false, + blocks_per_pixel: 1.0, + round: false, + }; + assert!(map.compose(view)); + assert!(!map.compose(view), "the same view is not recomposed"); + // North up: the stone is 10 pixels above the centre. + assert_eq!(pixel(&map, 64, 54), stone); + // Turning with the player facing east (yaw -90): north is to the left. + view.rotate = true; + view.yaw = -90.0; + assert!(map.compose(view)); + assert_eq!(pixel(&map, 54, 63), stone); + let (nx, ny) = view.north(); + assert!((nx + 1.0).abs() < 1e-5 && ny.abs() < 1e-5, "{nx} {ny}"); + // Facing north, north is up. + view.yaw = 180.0; + map.compose(view); + assert_eq!(pixel(&map, 64, 54), stone); + // Round maps are transparent in the corners, framed at the edge. + view.round = true; + map.compose(view); + assert_eq!(map.image[3], 0); + assert_eq!(&map.image[(64 * SIZE) * 4..(64 * SIZE) * 4 + 4], &BORDER); + // A small move recomposes only once it is visible. + view.x += 0.1; + assert!(!map.compose(view)); + view.x += 0.2; + assert!(map.compose(view)); + } + + #[test] + fn rings_cover_each_offset_once() { + let mut seen = std::collections::HashSet::new(); + for r in 0..=3 { + for o in ring_offsets(r) { + assert!(seen.insert(o)); + } + } + assert_eq!(seen.len(), 49); + } +} From eebf5621bf5c937e585639a17fb9e900b854b250 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:54:51 +0100 Subject: [PATCH 05/43] Fix classic menu panorama resource preparation --- crates/horizon-prepare/src/lib.rs | 15 +++- crates/horizon-prepare/src/main.rs | 22 ++++-- crates/horizon-prepare/src/sounds.rs | 109 +++++++++++++++++++++++++-- docs/native-client.md | 7 +- 4 files changed, 137 insertions(+), 16 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 246cb4d51..534abfc8a 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -17,7 +17,7 @@ pub mod pyjson; mod sounds; mod survival; -pub use sounds::sounds; +pub use sounds::{panorama, sounds}; use pyjson::Value; use sha2::Digest; @@ -452,7 +452,7 @@ pub fn prepare(options: &Options, log: Log) -> Result { origin, log, }; - steps(&run, &lock, &oracle)?; + steps(&run, &lock, &oracle, options.minecraft_dir.as_deref())?; log(&format!( "Prepared Horizon native-client resources: {}", resources.display() @@ -464,7 +464,12 @@ fn arg(path: &Path) -> String { path.display().to_string() } -fn steps(run: &Run, lock: &artifacts::Lock, oracle: &Path) -> Result<(), String> { +fn steps( + run: &Run, + lock: &artifacts::Lock, + oracle: &Path, + minecraft: Option<&Path>, +) -> Result<(), String> { let root = &run.resources; let repo = &run.root; let server_cp = run.server_classpath.as_str(); @@ -678,6 +683,10 @@ fn steps(run: &Run, lock: &artifacts::Lock, oracle: &Path) -> Result<(), String> count += 1; } + // The JAR holds only gray 1x1 panorama placeholders. Import the indexed + // textures afterwards, including on reruns that just extracted the JAR again. + panorama(repo, minecraft, run.log)?; + // One file each, exported again when the exporter or the jar it reads changed. let single = |what: &str, file: &str, diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 1ef1387ad..4be86f525 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -10,6 +10,7 @@ horizon-prepare: prepare Horizon's resources from your own Minecraft Java Editio Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH] horizon-prepare sounds [--minecraft-dir PATH] [--root PATH] + horizon-prepare panorama [--minecraft-dir PATH] [--root PATH] --prepare Import the pinned game files from your own copy first --server-jar PATH The pinned server jar you downloaded yourself @@ -23,6 +24,9 @@ Needs Minecraft played once from the official launcher, and Java (a JDK) of the research-lock.json pins: JAVA_HOME, else javac and java on the PATH. The resources go to /.local/horizon-client/; pass that to horizon-client --resources. +horizon-prepare panorama repairs the classic menu background in existing resources without Java. +Full preparation also imports these textures after extracting the client JAR's placeholders. + horizon-prepare sounds copies the pinned version's sounds (about 380 MB) from the official launcher's asset store into the same folder, checking every file. It is optional: without it the game is silent. Nothing is downloaded; it needs the version played once from the official launcher. @@ -52,7 +56,7 @@ fn main() -> ExitCode { }; let mut root = None; let mut args = std::env::args_os().skip(1).peekable(); - let sounds = args.next_if(|a| a == "sounds").is_some(); + let assets = args.next_if(|a| a == "sounds" || a == "panorama"); while let Some(arg) = args.next() { let text = arg.to_string_lossy().into_owned(); let (flag, inline) = match text.split_once('=') { @@ -71,8 +75,8 @@ fn main() -> ExitCode { } }; let parsed = match flag.as_str() { - "--prepare" | "--server-jar" if sounds => { - Err(format!("{flag} is for preparing, not for sounds")) + "--prepare" | "--server-jar" if assets.is_some() => { + Err(format!("{flag} is for preparing, not for asset copying")) } "--prepare" if inline.is_none() => { options.import = true; @@ -108,10 +112,14 @@ fn main() -> ExitCode { let _ = writeln!(out, "{line}"); let _ = out.flush(); }; - let result = if sounds { - horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log) - } else { - horizon_prepare::prepare(&options, &log) + let result = match assets.as_deref().and_then(|a| a.to_str()) { + Some("sounds") => { + horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log) + } + Some("panorama") => { + horizon_prepare::panorama(&options.root, options.minecraft_dir.as_deref(), &log) + } + _ => horizon_prepare::prepare(&options, &log), }; match result { Ok(_) => ExitCode::SUCCESS, diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index 75ed221a4..e0787656d 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -1,4 +1,4 @@ -//! The pinned version's sounds (sounds.json and the .ogg files) from the player's own official +//! The pinned version's sounds and title panorama from the player's own official //! launcher install, each object checked against the asset index's SHA-1, copied into //! `.local/horizon-client//assets` where the game reads them (tools/fetch_sounds.py and //! the tools/lab.py functions it called). Nothing is downloaded. @@ -76,6 +76,37 @@ fn is_sound(name: &str) -> bool { /// `.local/horizon-client/`; returns that folder. Files already there with the right /// SHA-1 are kept. pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + copy_assets(root, minecraft, log, is_sound, "Sound", &[]) +} + +/// Replaces the client JAR's 1x1 title placeholders with the full panorama from the +/// launcher's asset store. Also usable on already-prepared resources without Java. +pub fn panorama(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + copy_assets(root, minecraft, log, is_panorama, "Panorama", &PANORAMA) +} + +const PANORAMA: [&str; 7] = [ + "minecraft/textures/gui/title/background/panorama_0.png", + "minecraft/textures/gui/title/background/panorama_1.png", + "minecraft/textures/gui/title/background/panorama_2.png", + "minecraft/textures/gui/title/background/panorama_3.png", + "minecraft/textures/gui/title/background/panorama_4.png", + "minecraft/textures/gui/title/background/panorama_5.png", + "minecraft/textures/gui/title/background/panorama_overlay.png", +]; + +fn is_panorama(name: &str) -> bool { + PANORAMA.contains(&name) +} + +fn copy_assets( + root: &Path, + minecraft: Option<&Path>, + log: Log, + wanted_asset: fn(&str) -> bool, + label: &str, + required: &[&str], +) -> Result { let lock = Lock::read(root)?; let minecraft = artifacts::minecraft_dir(minecraft); let manifest = artifacts::import_manifest(&lock, &minecraft)?; @@ -95,12 +126,17 @@ pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result = Vec::new(); - for (name, info) in objects.iter().filter(|(name, _)| is_sound(name)) { + for (name, info) in objects.iter().filter(|(name, _)| wanted_asset(name)) { match wanted.iter_mut().find(|(n, _)| n == name) { Some(entry) => entry.1 = info, None => wanted.push((name, info)), } } + for name in required { + if !wanted.iter().any(|(n, _)| n == name) { + return Err(format!("{name} is missing from the asset index")); + } + } let mut total: u64 = 0; for (name, info) in &wanted { let hash = info @@ -125,7 +161,7 @@ pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result Fixture { + Self::with_panorama(name, &PANORAMA) + } + + fn with_panorama(name: &str, panorama: &[&'static str]) -> Fixture { let dir = std::env::temp_dir().join(format!( "horizon-prepare-sounds-{name}-{}", std::process::id() @@ -159,12 +199,16 @@ mod tests { let _ = fs::remove_dir_all(&dir); let root = dir.join("horizon"); let minecraft = dir.join("minecraft"); - let objects: Vec<(&'static str, Vec)> = vec![ + let mut objects: Vec<(&'static str, Vec)> = vec![ ("minecraft/sounds.json", b"{\"a\": {}}".to_vec()), ("minecraft/sounds/ambient/cave1.ogg", b"OggS cave".to_vec()), ("minecraft/sounds/dig/stone1.ogg", b"OggS stone".to_vec()), ("minecraft/lang/fr_fr.json", b"{}".to_vec()), ]; + for &name in panorama { + // Distinct object bytes let the test catch swapped faces too. + objects.push((name, name.as_bytes().to_vec())); + } let mut index = String::from("{\"objects\": {"); for (i, (name, data)) in objects.iter().enumerate() { let hash = sha1_hex(data); @@ -243,6 +287,7 @@ mod tests { assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); } assert!(!target.join("assets/minecraft/lang").exists()); + assert!(!target.join("assets/minecraft/textures").exists()); assert_eq!( fs::read(target.join("asset-index.json")).unwrap(), fs::read(f.minecraft.join("assets/indexes/7.json")).unwrap() @@ -267,6 +312,60 @@ mod tests { assert!(f.run().unwrap_err().starts_with("Missing asset object")); } + #[test] + fn panorama_replaces_jar_placeholders_and_repairs_repeated_preparations() { + let f = Fixture::new("panorama"); + let target = f.root.join(".local/horizon-client/9.9"); + for _ in 0..2 { + // Full preparation extracts the JAR before importing the asset store. + for (name, _) in &f.objects[4..] { + let path = target.join("assets").join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"1x1 gray placeholder").unwrap(); + } + assert_eq!( + panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap(), + target + ); + for (name, data) in &f.objects[4..] { + assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); + } + } + assert!(!target.join("assets/minecraft/sounds.json").exists()); + assert!(!target.join("assets/minecraft/lang").exists()); + } + + #[test] + fn panorama_objects_are_verified_before_replacing_placeholders() { + let f = Fixture::new("panorama-corrupt"); + fs::write(f.object(4), b"corrupt panorama").unwrap(); + let path = f + .root + .join(".local/horizon-client/9.9/assets") + .join(f.objects[4].0); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"placeholder").unwrap(); + assert!(panorama(&f.root, Some(&f.minecraft), &|_| {}) + .unwrap_err() + .starts_with("Corrupt asset object")); + assert_eq!(fs::read(path).unwrap(), b"placeholder"); + fs::remove_file(f.object(4)).unwrap(); + assert!(panorama(&f.root, Some(&f.minecraft), &|_| {}) + .unwrap_err() + .starts_with("Missing asset object")); + } + + #[test] + fn panorama_requires_every_face_and_the_overlay_in_the_index() { + let f = Fixture::with_panorama("panorama-incomplete", &PANORAMA[..6]); + let error = panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap_err(); + assert_eq!( + error, + format!("{} is missing from the asset index", PANORAMA[6]) + ); + assert!(!f.root.join(".local/horizon-client/9.9/assets").exists()); + } + #[test] fn the_index_must_be_the_pinned_one() { let f = Fixture::new("index"); diff --git a/docs/native-client.md b/docs/native-client.md index 3081bac7c..f05199ba7 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -23,7 +23,12 @@ verifies it against the pinned checksums, runs vanilla's data generator and smal exporters against those jars, and extracts the jar's assets and data into ignored `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your launcher's asset store by `horizon-prepare sounds`, each file checked against the asset -index's SHA-1. Prepared resources are private; never commit them. +index's SHA-1. Preparation also replaces the JAR's gray 1×1 title panorama placeholders +with the full textures from that asset store. To repair an existing classic menu background +without rerunning the Java exporters, run `horizon-prepare panorama` (or +`cargo run --release -p horizon-prepare -- panorama` in a checkout). Pass +`--minecraft-dir PATH` when using a different Minecraft installation. +Prepared resources are private; never commit them. Preparation is `horizon-prepare` (`crates/horizon-prepare`, Rust): it needs no Python, only the JDK, for the small exporters that call Mojang's own code. Release folders ship it beside From c6634830d319da65d43c92c1861074949a95d793 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:19:51 +0200 Subject: [PATCH 06/43] WIP: Microsoft account design note and RSA (not wired yet) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/src/rsa.rs | 278 +++++++++++++++++++++++++++++ docs/microsoft-account.md | 177 ++++++++++++++++++ 2 files changed, 455 insertions(+) create mode 100644 crates/horizon-protocol/src/rsa.rs create mode 100644 docs/microsoft-account.md diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs new file mode 100644 index 000000000..fd07db851 --- /dev/null +++ b/crates/horizon-protocol/src/rsa.rs @@ -0,0 +1,278 @@ +//! RSA for the online-mode login: the server's X.509 public key +//! (Crypt.byteToPublicKey) and PKCS#1 v1.5 encryption of the shared secret +//! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher = +//! RSA/ECB/PKCS1Padding). Modular exponentiation uses Montgomery +//! multiplication on 32-bit limbs; RSA moduli are always odd. +use crate::{Error, Result}; + +/// A non-negative integer, little-endian 32-bit limbs. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Big(Vec); + +impl Big { + fn from_be_bytes(bytes: &[u8], limbs: usize) -> Self { + let mut v = vec![0u32; limbs]; + for (i, b) in bytes.iter().rev().enumerate() { + if *b != 0 { + v[i / 4] |= u32::from(*b) << (8 * (i % 4)); + } + } + Self(v) + } + fn to_be_bytes(&self, len: usize) -> Vec { + let mut out = vec![0u8; len]; + for i in 0..len.min(self.0.len() * 4) { + out[len - 1 - i] = (self.0[i / 4] >> (8 * (i % 4))) as u8; + } + out + } + fn bits(&self) -> usize { + self.0 + .iter() + .rposition(|&l| l != 0) + .map_or(0, |i| i * 32 + 32 - self.0[i].leading_zeros() as usize) + } + fn bit(&self, i: usize) -> bool { + self.0[i / 32] >> (i % 32) & 1 == 1 + } + fn ge(&self, other: &Self) -> bool { + for (a, b) in self.0.iter().rev().zip(other.0.iter().rev()) { + if a != b { + return a > b; + } + } + true + } + fn sub_assign(&mut self, other: &Self) { + let mut borrow = 0i64; + for (a, b) in self.0.iter_mut().zip(&other.0) { + let d = i64::from(*a) - i64::from(*b) - borrow; + borrow = i64::from(d < 0); + *a = d.rem_euclid(1 << 32) as u32; + } + } +} + +/// Montgomery arithmetic modulo an odd `n`. +struct Mont { + n: Big, + /// -n⁻¹ mod 2³². + n0: u32, + /// R² mod n, R = 2^(32·limbs). + r2: Big, +} + +impl Mont { + fn new(n: Big) -> Self { + let k = n.0.len(); + // Newton's iteration for n⁻¹ mod 2³². + let mut inv = 1u32; + for _ in 0..5 { + inv = inv.wrapping_mul(2u32.wrapping_sub(n.0[0].wrapping_mul(inv))); + } + // R² mod n by doubling 1 2·32·k times. + let mut r2 = Big(vec![0; k]); + r2.0[0] = 1; + for _ in 0..64 * k { + let carry = r2.0[k - 1] >> 31; + for i in (1..k).rev() { + r2.0[i] = r2.0[i] << 1 | r2.0[i - 1] >> 31; + } + r2.0[0] <<= 1; + if carry == 1 || r2.ge(&n) { + r2.sub_assign(&n); + } + } + Self { + n0: inv.wrapping_neg(), + n, + r2, + } + } + /// a·b·R⁻¹ mod n (CIOS). + fn mul(&self, a: &Big, b: &Big) -> Big { + let k = self.n.0.len(); + let mut t = vec![0u32; k + 2]; + for i in 0..k { + let mut carry = 0u64; + for j in 0..k { + let s = u64::from(t[j]) + u64::from(a.0[j]) * u64::from(b.0[i]) + carry; + t[j] = s as u32; + carry = s >> 32; + } + let s = u64::from(t[k]) + carry; + t[k] = s as u32; + t[k + 1] = (s >> 32) as u32; + let m = t[0].wrapping_mul(self.n0); + let mut carry = (u64::from(t[0]) + u64::from(m) * u64::from(self.n.0[0])) >> 32; + for j in 1..k { + let s = u64::from(t[j]) + u64::from(m) * u64::from(self.n.0[j]) + carry; + t[j - 1] = s as u32; + carry = s >> 32; + } + let s = u64::from(t[k]) + carry; + t[k - 1] = s as u32; + t[k] = t[k + 1] + (s >> 32) as u32; + } + let overflow = t[k] != 0; + let mut r = Big(t[..k].to_vec()); + if overflow || r.ge(&self.n) { + r.sub_assign(&self.n); + } + r + } + /// base^exp mod n, base < n. + fn pow(&self, base: &Big, exp: &Big) -> Big { + let k = self.n.0.len(); + let mut one = Big(vec![0; k]); + one.0[0] = 1; + let b = self.mul(base, &self.r2); + let mut x = self.mul(&one, &self.r2); + for i in (0..exp.bits()).rev() { + x = self.mul(&x, &x); + if exp.bit(i) { + x = self.mul(&x, &b); + } + } + self.mul(&x, &one) + } +} + +/// A minimal DER reader: (tag, contents) of the element at the front. +fn der(input: &[u8]) -> Result<(u8, &[u8], &[u8])> { + let bad = || Error::new("Malformed public key"); + let (&tag, rest) = input.split_first().ok_or_else(bad)?; + let (&first, mut rest) = rest.split_first().ok_or_else(bad)?; + let len = if first < 0x80 { + usize::from(first) + } else { + let n = usize::from(first & 0x7f); + if n == 0 || n > 4 || rest.len() < n { + return Err(bad()); + } + let len = rest[..n].iter().fold(0usize, |l, b| l << 8 | usize::from(*b)); + rest = &rest[n..]; + len + }; + if rest.len() < len { + return Err(bad()); + } + Ok((tag, &rest[..len], &rest[len..])) +} + +/// The DER of OID 1.2.840.113549.1.1.1 (rsaEncryption). +const RSA_ENCRYPTION: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaPublicKey { + /// Modulus and exponent, big-endian without leading zeros. + pub modulus: Vec, + pub exponent: Vec, +} + +fn strip(int: &[u8]) -> Vec { + let start = int.iter().position(|&b| b != 0).unwrap_or(int.len()); + int[start..].to_vec() +} + +impl RsaPublicKey { + /// X509EncodedKeySpec: SubjectPublicKeyInfo { AlgorithmIdentifier, BIT STRING RSAPublicKey }. + pub fn from_der(spki: &[u8]) -> Result { + let bad = || Error::new("Malformed public key"); + let (tag, body, _) = der(spki)?; + if tag != 0x30 { + return Err(bad()); + } + let (tag, algorithm, rest) = der(body)?; + let (oid_tag, oid, _) = der(algorithm)?; + if tag != 0x30 || oid_tag != 0x06 || oid != RSA_ENCRYPTION { + return Err(Error::new("Not an RSA public key")); + } + let (tag, bits, _) = der(rest)?; + if tag != 0x03 || bits.first() != Some(&0) { + return Err(bad()); + } + let (tag, key, _) = der(&bits[1..])?; + if tag != 0x30 { + return Err(bad()); + } + let (n_tag, n, rest) = der(key)?; + let (e_tag, e, _) = der(rest)?; + if n_tag != 0x02 || e_tag != 0x02 { + return Err(bad()); + } + let key = Self { + modulus: strip(n), + exponent: strip(e), + }; + if key.modulus.len() < 64 || key.modulus.last().is_none_or(|b| b & 1 == 0) { + return Err(bad()); + } + Ok(key) + } + /// Length of the modulus in bytes (and of every ciphertext). + pub fn size(&self) -> usize { + self.modulus.len() + } + /// The raw RSA operation m^e mod n on a `size()`-byte block. + fn apply(&self, block: &[u8], exponent: &[u8]) -> Vec { + let limbs = self.size().div_ceil(4); + let mont = Mont::new(Big::from_be_bytes(&self.modulus, limbs)); + let m = Big::from_be_bytes(block, limbs); + mont.pow(&m, &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4)))) + .to_be_bytes(self.size()) + } + /// RSAES-PKCS1-v1_5 (RFC 8017 7.2.1) with random non-zero padding. + pub fn encrypt(&self, message: &[u8]) -> Result> { + let k = self.size(); + if message.len() + 11 > k { + return Err(Error::new("Message too long for the RSA key")); + } + let mut block = vec![0u8; k]; + block[1] = 2; + let padding = &mut block[2..k - message.len() - 1]; + crate::crypto::random_bytes(padding)?; + for b in padding.iter_mut() { + while *b == 0 { + let mut one = [0u8]; + crate::crypto::random_bytes(&mut one)?; + *b = one[0]; + } + } + block[k - message.len()..].copy_from_slice(message); + Ok(self.apply(&block, &self.exponent)) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub fn hex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + } + + /// A 1024-bit test key made with `openssl genrsa 1024`. + pub const TEST_SPKI: &str = "30819f300d06092a864886f70d010101050003818d0030818902818100ab026074f92450a8f726f3895bb11176ca8f065f3100cd4143bac4f7d3674edcff95b41a0525d2365a549c106ec6685881b392177420fd31ff5c144ff11ba24311e751cd2c6b5d1817b6af6686a43c95d61243613005e6945b6093cd95223cec5e8856826da9d2ee1b323362ac1cebeab3659cbc45319a9b540dda816a4798ff0203010001"; + pub const TEST_N: &str = "ab026074f92450a8f726f3895bb11176ca8f065f3100cd4143bac4f7d3674edcff95b41a0525d2365a549c106ec6685881b392177420fd31ff5c144ff11ba24311e751cd2c6b5d1817b6af6686a43c95d61243613005e6945b6093cd95223cec5e8856826da9d2ee1b323362ac1cebeab3659cbc45319a9b540dda816a4798ff"; + pub const TEST_D: &str = "172bcb460e3c0d71d78b3f946d082105a78c99a06c535f7c6860f62f5e45b139e0a7b82f8e630188bbd49b10def1a351dac12a1a6371d4dce16ce893ac67c2247b9ee13e3a840abaf9ea685304558f1a93c4f354193f5713c3e53bd10dd275300db36e764fc081549afbd30cd00c31e6eb726720337a963913d96b50e4d8fd1"; + /// SHA256withRSA signature of "hello" with the test key (openssl pkeyutl), for chat signing. + pub const TEST_SIG_HELLO: &str = "0bc8716622e44f9bf72432045e91bf1b40a96aae3c402fa86262b83758db1c90d2ed16b9fa86f29af175f2e6eedb864bf8da2667a7ada2bf5433fba36c1951af0c356e45bd5f90fb905b9a08f33a0666c4968ccffbf32fda643d736deec66f82c75fe4a8075c7f2b8a6c0ca630e0ffe4805a1f1d672506b82fc188510fb4ef80"; + + #[test] + fn montgomery_matches_small_numbers() { + // 4^13 mod 497 = 445 (the classic example), on one limb. + let mont = Mont::new(Big(vec![497])); + assert_eq!(mont.pow(&Big(vec![4]), &Big(vec![13])), Big(vec![445])); + // Two limbs: (2^40 + 5)^3 mod (2^61 - 1). + let n = (1u128 << 61) - 1; + let m = Mont::new(Big(vec![n as u32, (n >> 32) as u32])); + let b = (1u128 << 40) + 5; + let expected = b * b % n * b % n; + let r = m.pow(&Big(vec![b as u32, (b >> 32) as u32]), &Big(vec![3, 0])); + assert_eq!(u128::from(r.0[0]) | u128::from(r.0[1]) << 32, expected); + } +} diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md new file mode 100644 index 000000000..c992cd25f --- /dev/null +++ b/docs/microsoft-account.md @@ -0,0 +1,177 @@ +# Microsoft account sign-in and online-mode play + +Horizon signs players in with their Microsoft account in the launcher and joins online-mode +(authenticated) servers like vanilla 26.3 does. Offline profiles and offline/LAN play stay exactly as +they are. This note is the design, the status of each part and what Ludovic has to register. + +## What Ludovic registers (needs his accounts) + +Nothing below can be done by an agent: the app registrations belong to Ludovic. Until the client ID +is set, the launcher's sign-in shows "Microsoft sign-in is not configured yet" and everything else +works as before. + +1. **Azure app registration** (https://portal.azure.com → Microsoft Entra ID → App registrations → + New registration): + - Name: `Horizon` (shown to players on the Microsoft consent page). + - Supported account types: **Personal Microsoft accounts only** (Minecraft accounts are + consumer accounts; the launcher uses the `consumers` tenant). + - Redirect URI: none needed for the device-code flow. If the form insists, add a + "Mobile and desktop applications" redirect `https://login.microsoftonline.com/common/oauth2/nativeclient`. + - After creating it: Authentication → Advanced settings → **Allow public client flows: Yes** + (this enables the device-code flow; there is no client secret, Horizon is a public client). + - API permissions: none to add. The launcher requests the scopes `XboxLive.signin offline_access` + at sign-in time; `offline_access` gives the refresh token. + - Copy the **Application (client) ID** (a GUID). +2. **Minecraft API access** (Mojang): new Azure apps are refused by + `api.minecraftservices.com/authentication/login_with_xbox` (HTTP 403, "Invalid app registration") + until Mojang approves them. Apply with the form linked from https://aka.ms/mce-reviewappid + (Minecraft Java "App ID review"), giving the client ID above, the app name, the project URL + (https://github.com/ludovic111/horizon) and a short description ("open-source Minecraft Java + Edition client written in Rust; signs players in to join online-mode servers"). Approval takes + days to weeks; sign-in fails at the Minecraft step with "This app is not approved by Mojang yet" + until then. +3. **Where the ID goes**: + - Release builds: the GitHub repository variable (not a secret: client IDs are public) + `HORIZON_MSA_CLIENT_ID`; the launcher's build reads it with `option_env!` at compile time. + - Any build, at run time: the environment variable `HORIZON_MSA_CLIENT_ID` overrides the built-in + value (empty or unset = not configured). + +Never use another application's client ID (the official launcher's or another launcher's). + +## Flow (launcher) + +All requests use HTTPS and JSON except the two OAuth calls (form-encoded): + +1. **Device code**: `POST https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode` + (`client_id`, `scope=XboxLive.signin offline_access`). The launcher shows the `user_code` and + `verification_uri` (https://www.microsoft.com/link) with a copy button and opens the browser. +2. **Poll** `POST …/consumers/oauth2/v2.0/token` (`grant_type=urn:ietf:params:oauth:grant-type:device_code`) + every `interval` seconds; `authorization_pending` waits, `slow_down` adds 5 s, `authorization_declined`, + `expired_token` and `bad_verification_code` end the sign-in with a message. Result: the Microsoft + access token and refresh token. +3. **Xbox Live**: `POST https://user.auth.xboxlive.com/user/authenticate` with + `AuthMethod=RPS, SiteName=user.auth.xboxlive.com, RpsTicket=d=`, + `RelyingParty=http://auth.xboxlive.com`. Result: the XBL token and the user hash (`uhs`). +4. **XSTS**: `POST https://xsts.auth.xboxlive.com/xsts/authorize` with the XBL token, + `SandboxId=RETAIL`, `RelyingParty=rp://api.minecraftservices.com/`. The `XErr` codes become + messages: 2148916233 no Xbox profile yet, 2148916235 Xbox Live not available in the country, + 2148916236/2148916237 adult verification (South Korea), 2148916238 child account (needs a family). +5. **Minecraft**: `POST https://api.minecraftservices.com/authentication/login_with_xbox` + (`identityToken = "XBL3.0 x=;"`), the endpoint taken from the services discovery + document (authentication/loginXbox) like authlib does. Result: the Minecraft access token (24 h). +6. **Entitlements**: `GET https://api.minecraftservices.com/entitlements/mcstore`: the account must + own `game_minecraft` or `product_minecraft` (Game Pass included), else "This account doesn't own + Minecraft Java Edition". +7. **Profile**: `GET https://api.minecraftservices.com/minecraft/profile`: UUID, name, skins, capes. + 404 = owns the game but has no profile yet ("Create your Minecraft profile on minecraft.net first"). + +Refresh: the Minecraft token is renewed from the Microsoft refresh token (steps 2-5 with +`grant_type=refresh_token`) when it has less than an hour left, before every launch. A refused +refresh token (`invalid_grant`) asks the player to sign in again. Several accounts can be signed in; +one is selected. "Sign out" deletes the account's secrets from the keychain. + +## Token storage + +- Secrets (the Microsoft refresh token, the Minecraft access token and its expiry) go to the OS + keychain, one item per account: Keychain on macOS, Credential Manager on Windows, the Secret + Service (GNOME Keyring, KWallet) on Linux. Service name `dev.playhorizon.launcher`, account = the + Minecraft UUID. +- `accounts.json` in the launcher's data folder keeps only public data: UUID, name, skin URL, which + account is selected. Never a token. +- No keychain available (a Linux box without a Secret Service, a locked keychain): sign-in still + works for the session but nothing is saved, and the launcher says "No keychain available: you will + have to sign in again next time" (it never falls back to a plain file). +- Tokens never appear in logs, errors, `horizon-launcher` CLI output, MCP results or crash reports. + Requests are logged by endpoint name only. + +## Handing the session to the game + +Vanilla's launcher passes `--accessToken ` on the command line, where every user of the +machine can read it in the process list. Horizon keeps it out of argv: + +- The launcher writes `session-.json` (mode 0600 on Unix, created new, in the game home's + `sessions/` folder) with `{"name", "uuid", "access_token", "user_type": "msa", "xuid"}` and starts + the game with `--session-file PATH`. +- The game reads the file at start and deletes it at once; the token lives only in the game's memory. + A file older than two minutes is refused (and deleted), so a stale file can't be replayed. +- Without a session file the game is offline as today (`--name`, offline UUID). +- `HORIZON_SESSION_FILE` is the same as `--session-file` (development and harnesses). + +## Online-mode login (game) + +Vanilla's `ClientHandshakePacketListenerImpl.handleHello`, `Crypt` and authlib's +`MinecraftServicesSessionService.joinServer`: + +1. `ClientboundHelloPacket` (server id, X.509 RSA public key, challenge, should_authenticate). +2. Generate a random 16-byte AES key (the shared secret). +3. Server hash: SHA-1 over `serverId` (ISO-8859-1), the shared secret, the encoded public key; + `new BigInteger(digest).toString(16)` (signed two's complement hex, e.g. "Notch" → + `4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48`, "jeb_" → `-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1`). +4. If `should_authenticate`: `POST` the session service's `join` endpoint + `{"accessToken", "selectedProfile" (undashed UUID), "serverId": hash}`, the URL taken from the + services discovery document (`https://discovery.minecraftservices.com/minecraft/client`, fetched + once per game). Errors map like authlib's `MinecraftClientHttpException`: + `ForbiddenOperationException` or 401 → "Failed to log in: Invalid session (Try restarting your + game and the launcher)", `InsufficientPrivilegesException` → "Multiplayer is disabled…", + `multiplayer.access.banned` / `FORCED_USERNAME_CHANGE` → "You are banned from playing online", + 5xx or no network → "The authentication servers are currently not reachable…". Without a session + the game says "This server is in online mode. Sign in with your Microsoft account in the Horizon + launcher to join it." On a LAN server a failure is only logged (vanilla does the same). +5. Send `ServerboundKeyPacket` (the secret and the challenge, each RSA PKCS#1 v1.5 encrypted with + the server key), then AES/CFB8 (key = IV = the secret) both ways. + +`HORIZON_API_DISCOVERY` overrides the discovery URL, the counterpart of authlib's +`-Dminecraft.api.discovery.host`; it is how the harness points both the vanilla server and Horizon at +a local mock. + +## Skins and capes (part b) + +Profile properties (`textures`, base64 JSON) arrive in `ClientboundPlayerInfoUpdatePacket` for every +player and in the login profile for ourselves. Like authlib's `unpackTextures`, only URLs under the +discovery document's `profiles/getTexture` `validUris` (textures.minecraft.net) are fetched; skins +(classic/slim from the `metadata.model`), capes and elytra textures are downloaded over HTTPS on a +worker thread, cached on disk by texture hash (`assets/skins/xx/hash`, like vanilla's +`SkinManager`), converted from legacy 64×32 the way `SkinTextureDownloader` does and given to the +player renderer. Until a skin arrives the default skin for the UUID shows (as today). + +## Chat signing (part d) + +26.3's dedicated servers default to `enforce-secure-profile=true`. A client without a chat session +can join and play, but every chat message and signed command argument is refused with "Chat +disabled due to missing profile public key. Please try reconnecting." (`SignedMessageChain.Decoder.unsigned`). +To chat on such servers the game will: + +- fetch the profile key pair from the services `player/getCertificates` endpoint (Minecraft token); +- send `ServerboundChatSessionUpdatePacket` (random session UUID, key expiry, public key, Mojang's + key signature) after joining; +- sign each chat message and signable command argument with SHA256withRSA over vanilla's + `SignedMessageBody` layout and keep the last-seen message tracker and acknowledgements. + +Until part d lands, Horizon joins online servers but chat works only where +`enforce-secure-profile=false` (or the server can't validate keys). + +## Harnesses + +`tools/test_online_mode_parity.py` (dev only, needs no account): a local mock of the Minecraft +services (discovery document, `join`, `hasJoined`/`verify`, empty public keys) and a vanilla 26.3 +dedicated server in online mode started with `-Dminecraft.api.discovery.host=`. Horizon's +headless client (`HORIZON_NET_REPORT`) joins with a session file holding a mock token: the server +verifies the join through the mock with the hash it computed itself (so the RSA wrapping, the hash +and AES/CFB8 are all checked against vanilla's code), the player spawns, chats and runs `/list`. +Negative cases: a token the mock rejects (the client must show vanilla's "Invalid session" message) +and a client that skips the join (the server must say "Failed to verify username!"). + +Rust unit tests: server hash vectors (Notch, jeb_, simon), RSA wrapping round trip with a test key, +X.509 key parsing, AES/CFB8 vectors (already in `horizon-protocol`), the session file (permissions, +age, deletion), the error mapping. Launcher: the whole token chain against a local mock of the +Microsoft, Xbox and Minecraft endpoints, and the keychain abstraction with an in-memory backend. + +## PR plan + +- (a) Game: online-mode handshake, encryption, session join, session file, harness. *(this PR)* +- (c) Launcher: device-code sign-in, token chain, keychain, accounts UI, CLI/MCP (`account list`, + `account sign-in`, `account sign-out`, never tokens), session file handoff. +- (b) Game: skins and capes over HTTPS, the real names and skins in game. +- (d) Game: chat signing (profile keys, chat session, signed messages and commands). + +Each part ships on its own: online mode needs a session, which only (c) creates. From c8629f3378fec01fe30c0e32e01e93942f4dcbc5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:35:18 +0200 Subject: [PATCH 07/43] Protocol: RSA public keys and PKCS#1 encryption, server hash, secrets Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/Cargo.toml | 3 ++ crates/horizon-protocol/src/crypto.rs | 74 ++++++++++++++++++++++++++- crates/horizon-protocol/src/lib.rs | 1 + crates/horizon-protocol/src/rsa.rs | 43 ++++++++++++++++ 4 files changed, 119 insertions(+), 2 deletions(-) diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index 04bb00d5b..fad282080 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -10,6 +10,9 @@ description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 7 horizon-world = { path = "../horizon-world" } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } serde_json = "1.0.151" +# The shared secret and RSA padding (OS randomness) and the server hash. +getrandom = "0.3" +sha1 = "0.10" [lints] workspace = true diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs index c55b003b5..b5b6fa447 100644 --- a/crates/horizon-protocol/src/crypto.rs +++ b/crates/horizon-protocol/src/crypto.rs @@ -1,7 +1,9 @@ //! Connection encryption (Crypt.getCipher: AES/CFB8/NoPadding with the shared //! secret as key and IV) and MD5 name-based UUIDs for offline-mode profiles -//! (UUIDUtil.createOfflinePlayerUUID). Only the AES forward cipher is needed: -//! CFB8 encrypts the shift register in both directions. +//! (UUIDUtil.createOfflinePlayerUUID), the online-mode server hash +//! (Crypt.digestData) and the shared secret. Only the AES forward cipher is +//! needed: CFB8 encrypts the shift register in both directions. +use sha1::{Digest, Sha1}; const SBOX: [u8; 256] = { // Generated from the AES field inverse and affine transform at compile time. @@ -138,6 +140,54 @@ impl Cfb8 { } } +/// Fill `out` with the operating system's cryptographic randomness. +pub fn random_bytes(out: &mut [u8]) -> crate::Result<()> { + getrandom::fill(out).map_err(|e| crate::Error::new(format!("No secure random source: {e}"))) +} + +/// Crypt.generateSecretKey: a random AES-128 key, the connection's shared secret. +pub fn generate_secret() -> crate::Result<[u8; 16]> { + let mut key = [0u8; 16]; + random_bytes(&mut key)?; + Ok(key) +} + +/// `new BigInteger(digest).toString(16)`: the digest read as a signed +/// two's-complement number, in lowercase hex without leading zeros. +pub fn java_hex_digest(digest: &[u8]) -> String { + let negative = digest.first().is_some_and(|b| b & 0x80 != 0); + let mut magnitude = digest.to_vec(); + if negative { + // Two's complement: invert and add one. + let mut carry = true; + for b in magnitude.iter_mut().rev() { + *b = !*b; + if carry { + let (v, c) = b.overflowing_add(1); + *b = v; + carry = c; + } + } + } + let hex: String = magnitude.iter().map(|b| format!("{b:02x}")).collect(); + let hex = hex.trim_start_matches('0'); + let hex = if hex.is_empty() { "0" } else { hex }; + if negative { format!("-{hex}") } else { hex.to_owned() } +} + +/// The server id sent to the session service when joining an online-mode +/// server: SHA-1 over the server id (ISO-8859-1), the shared secret and the +/// server's encoded public key, as a signed hex number. +pub fn server_hash(server_id: &str, secret: &[u8], public_key: &[u8]) -> String { + let mut sha = Sha1::new(); + // ISO-8859-1: characters above U+00FF become '?' like String.getBytes. + let latin1: Vec = server_id.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect(); + sha.update(&latin1); + sha.update(secret); + sha.update(public_key); + java_hex_digest(&sha.finalize()) +} + /// MD5 (RFC 1321). pub fn md5(input: &[u8]) -> [u8; 16] { const S: [u32; 64] = [ @@ -256,6 +306,26 @@ mod tests { assert_eq!(data, plain); } + /// The digests of single names published with the protocol docs. + #[test] + fn server_hash_vectors() { + let hash = |name: &str| java_hex_digest(&Sha1::digest(name.as_bytes())); + assert_eq!(hash("Notch"), "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48"); + assert_eq!(hash("jeb_"), "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1"); + assert_eq!(hash("simon"), "88e16a1019277b15d58faf0541e11910eb756f6"); + // The three inputs are hashed in order: one update equals three. + assert_eq!(server_hash("", b"Not", b"ch"), hash("Notch")); + assert_eq!(java_hex_digest(&[0; 4]), "0"); + assert_eq!(java_hex_digest(&[0xff; 2]), "-1"); + assert_eq!(java_hex_digest(&[0x80, 0]), "-8000"); + } + + #[test] + fn secrets_are_random() { + let (a, b) = (generate_secret().unwrap(), generate_secret().unwrap()); + assert_ne!(a, b); + } + #[test] fn md5_and_offline_uuids() { assert_eq!(md5(b"").to_vec(), hex("d41d8cd98f00b204e9800998ecf8427e")); diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index 1f29637dd..e49031b77 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -12,6 +12,7 @@ pub mod ids; pub mod item; pub mod packets; pub mod registry; +pub mod rsa; pub mod servers; pub mod text; diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index fd07db851..cbc256c06 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -249,6 +249,7 @@ pub(crate) mod tests { use super::*; pub fn hex(s: &str) -> Vec { + let s = if s.len() % 2 == 1 { format!("0{s}") } else { s.to_owned() }; (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) @@ -275,4 +276,46 @@ pub(crate) mod tests { let r = m.pow(&Big(vec![b as u32, (b >> 32) as u32]), &Big(vec![3, 0])); assert_eq!(u128::from(r.0[0]) | u128::from(r.0[1]) << 32, expected); } + + #[test] + fn parses_x509_public_keys() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + assert_eq!(key.modulus, hex(TEST_N)); + assert_eq!(key.exponent, vec![1, 0, 1]); + assert_eq!(key.size(), 128); + assert!(RsaPublicKey::from_der(&hex(TEST_SPKI)[..100]).is_err()); + assert!(RsaPublicKey::from_der(b"not a key").is_err()); + } + + /// Encrypted with the public key, decrypted with the private exponent: + /// a PKCS#1 v1.5 type 2 block with non-zero padding around the message. + #[test] + fn pkcs1_round_trip() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let secret = [0x5au8; 16]; + let a = key.encrypt(&secret).unwrap(); + let b = key.encrypt(&secret).unwrap(); + assert_eq!(a.len(), 128); + assert_ne!(a, b, "padding is random"); + for c in [a, b] { + let block = key.apply(&c, &hex(TEST_D)); + assert_eq!(&block[..2], &[0, 2]); + let zero = 2 + block[2..].iter().position(|&b| b == 0).unwrap(); + assert_eq!(zero, 128 - 16 - 1); + assert_eq!(&block[zero + 1..], &secret); + } + assert!(key.encrypt(&[0; 118]).is_err()); + } + + /// An OpenSSL signature checked with the public exponent: the block ends + /// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's. + #[test] + fn verifies_an_openssl_signature() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let block = key.apply(&hex(TEST_SIG_HELLO), &key.exponent); + assert_eq!(&block[..2], &[0, 1]); + assert!(block.ends_with(&hex( + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" + ))); + } } From 89b2ca64a9da151ab8876c28d095a5416658f5ed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:39:16 +0200 Subject: [PATCH 08/43] Join online-mode servers with the launcher's account Read the signed-in account from a session file (--session-file, deleted on read), answer ClientboundHelloPacket like vanilla: shared secret, server hash, session join through the services discovery document (authlib's error mapping and messages), RSA-wrapped key packet, AES/CFB8 both ways. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 382 ++++++++++++++++++ crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/auth.rs | 343 ++++++++++++++++ crates/horizon-client/src/game.rs | 15 +- crates/horizon-client/src/game/net_harness.rs | 7 +- crates/horizon-client/src/game/remote.rs | 5 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/net.rs | 74 +++- 8 files changed, 812 insertions(+), 17 deletions(-) create mode 100644 crates/horizon-client/src/auth.rs diff --git a/Cargo.lock b/Cargo.lock index 1e3919458..4694fb718 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -174,6 +174,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bit-set" version = "0.10.0" @@ -693,6 +699,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -737,6 +752,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -894,6 +920,7 @@ dependencies = [ "pollster", "serde_json", "symphonia", + "ureq", "wgpu", "winit", ] @@ -920,8 +947,10 @@ name = "horizon-protocol" version = "0.1.0" dependencies = [ "flate2", + "getrandom 0.3.4", "horizon-world", "serde_json", + "sha1", ] [[package]] @@ -964,6 +993,110 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1157,6 +1290,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "litrs" version = "1.0.0" @@ -1880,6 +2019,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "presser" version = "0.3.1" @@ -2020,6 +2168,20 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -2061,6 +2223,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2254,6 +2451,12 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" @@ -2266,6 +2469,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "symphonia" version = "0.5.5" @@ -2359,6 +2568,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -2424,6 +2644,16 @@ dependencies = [ "strict-num", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tokio" version = "1.53.2" @@ -2520,6 +2750,45 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.28.0" @@ -2556,6 +2825,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -2750,6 +3025,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "wgpu" version = "30.0.1" @@ -3289,6 +3582,12 @@ dependencies = [ "wayland-protocols-wlr", ] +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "x11-dl" version = "2.21.0" @@ -3356,6 +3655,29 @@ version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.60" @@ -3376,6 +3698,66 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "zip" version = "2.4.2" diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index b54424966..42841eecb 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -30,6 +30,8 @@ horizon-theme = { path = "../horizon-theme" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). gilrs = "0.11" +# HTTPS to the Minecraft services (online-mode session join). +ureq = { version = "2", default-features = false, features = ["tls"] } [features] # Records the call sites of mob random draws (`mob_ai_probe` traces). diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs new file mode 100644 index 000000000..27339259f --- /dev/null +++ b/crates/horizon-client/src/auth.rs @@ -0,0 +1,343 @@ +//! The Microsoft account the launcher signed in, handed over in a session +//! file (docs/microsoft-account.md), and the Minecraft services call +//! online-mode servers need: authlib's MinecraftServicesSessionService.joinServer +//! through the services discovery document. The access token stays in this +//! process's memory: it is never logged, printed or written anywhere. +use std::{ + path::Path, + sync::{Arc, Mutex, OnceLock}, + time::{Duration, SystemTime}, +}; + +/// MinecraftServicesEnvironment.PROD. +pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client"; +/// A session file older than this is refused: it can't be replayed later. +const MAX_SESSION_FILE_AGE: Duration = Duration::from_secs(120); + +/// A signed-in account (vanilla's User with type msa). +pub struct AuthSession { + pub name: String, + pub uuid: u128, + pub xuid: Option, + access_token: String, +} +impl std::fmt::Debug for AuthSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthSession") + .field("name", &self.name) + .field("uuid", &horizon_protocol::crypto::uuid_string(self.uuid)) + .field("access_token", &"") + .finish() + } +} + +/// A UUID with or without dashes. +pub fn parse_uuid(text: &str) -> Option { + let hex: String = text.chars().filter(|c| *c != '-').collect(); + (hex.len() == 32) + .then(|| u128::from_str_radix(&hex, 16).ok()) + .flatten() +} + +impl AuthSession { + /// For tests and harnesses. + pub fn new(name: &str, uuid: u128, access_token: &str) -> Self { + Self { + name: name.to_owned(), + uuid, + xuid: None, + access_token: access_token.to_owned(), + } + } + /// The session file's JSON: {"name", "uuid", "access_token", "user_type": "msa", "xuid"}. + pub fn parse(text: &str) -> Result { + let v: serde_json::Value = + serde_json::from_str(text).map_err(|_| "the session file is not valid JSON")?; + let field = |k: &str| v.get(k).and_then(|s| s.as_str()); + let name = field("name").ok_or("the session file has no name")?; + if name.is_empty() || name.chars().count() > 16 { + return Err("the session file's name is not a valid player name".into()); + } + let uuid = field("uuid") + .and_then(parse_uuid) + .ok_or("the session file has no valid uuid")?; + let access_token = field("access_token") + .filter(|t| !t.is_empty()) + .ok_or("the session file has no access token")?; + if field("user_type").is_some_and(|t| t != "msa") { + return Err("the session file is not a Microsoft account session".into()); + } + Ok(Self { + name: name.to_owned(), + uuid, + xuid: field("xuid").map(str::to_owned), + access_token: access_token.to_owned(), + }) + } + /// Read the session file the launcher wrote and delete it at once. It + /// must be fresh and, on Unix, readable by its owner only. + pub fn load(path: &Path) -> Result { + let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + let refuse = |why: &str| { + let _ = std::fs::remove_file(path); + Err(format!("{}: {why}", path.display())) + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if meta.permissions().mode() & 0o077 != 0 { + return refuse("other users can read it"); + } + } + let age = meta + .modified() + .ok() + .and_then(|m| SystemTime::now().duration_since(m).ok()) + .unwrap_or_default(); + if age > MAX_SESSION_FILE_AGE { + return refuse("it is too old (start the game from the launcher)"); + } + let text = std::fs::read_to_string(path); + let _ = std::fs::remove_file(path); + Self::parse(&text.map_err(|e| format!("{}: {e}", path.display()))?) + } +} + +static CURRENT: OnceLock> = OnceLock::new(); + +/// The account this game was started with (set once at start). +pub fn set_current(session: AuthSession) { + let _ = CURRENT.set(Arc::new(session)); +} +pub fn current() -> Option> { + CURRENT.get().cloned() +} + +/// Why joining a server through the session service failed, like the +/// AuthenticationException subclasses authlib throws. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JoinError { + /// No answer, or a 5xx (AuthenticationUnavailableException). + Unavailable, + /// 401 or ForbiddenOperationException (InvalidCredentialsException). + InvalidSession, + /// InsufficientPrivilegesException: multiplayer is off for the account. + InsufficientPrivileges, + /// multiplayer.access.banned or FORCED_USERNAME_CHANGE. + Banned, + /// Anything else, with the service's message. + Other(String), +} +impl JoinError { + /// MinecraftClientHttpException.toAuthenticationException. + pub fn from_response(status: u16, body: &str) -> Self { + let v: serde_json::Value = serde_json::from_str(body).unwrap_or_default(); + let error = v.get("error").and_then(|e| e.as_str()).unwrap_or(""); + match error { + "ForbiddenOperationException" => return Self::InvalidSession, + "multiplayer.access.banned" | "FORCED_USERNAME_CHANGE" => return Self::Banned, + "InsufficientPrivilegesException" => return Self::InsufficientPrivileges, + _ => {} + } + match status { + 401 => Self::InvalidSession, + 500.. => Self::Unavailable, + _ => Self::Other( + v.get("errorMessage") + .and_then(|m| m.as_str()) + .map_or_else(|| format!("Status: {status}"), str::to_owned), + ), + } + } + /// ClientHandshakePacketListenerImpl.authenticateServer's message: the + /// key of the reason inside "disconnect.loginFailedInfo", or its text. + pub fn reason(&self) -> Result<&'static str, &str> { + match self { + Self::Unavailable => Ok("disconnect.loginFailedInfo.serversUnavailable"), + Self::InvalidSession => Ok("disconnect.loginFailedInfo.invalidSession"), + Self::InsufficientPrivileges => Ok("disconnect.loginFailedInfo.insufficientPrivileges"), + Self::Banned => Ok("disconnect.loginFailedInfo.userBanned"), + Self::Other(message) => Err(message), + } + } +} + +/// The services discovery document URL: `HORIZON_API_DISCOVERY` overrides +/// it like authlib's `-Dminecraft.api.discovery.host`. +pub fn discovery_url() -> String { + std::env::var("HORIZON_API_DISCOVERY") + .ok() + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned()) +} + +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build() +} + +/// The discovery document, fetched once per game (a failure is retried next time). +fn discovery() -> Result, JoinError> { + static CACHE: Mutex>> = Mutex::new(None); + if let Some(d) = CACHE.lock().unwrap().clone() { + return Ok(d); + } + let doc: serde_json::Value = agent() + .get(&discovery_url()) + .call() + .ok() + .and_then(|r| r.into_string().ok()) + .and_then(|t| serde_json::from_str(&t).ok()) + .ok_or(JoinError::Unavailable)?; + let doc = Arc::new(doc); + *CACHE.lock().unwrap() = Some(doc.clone()); + Ok(doc) +} + +/// MinecraftServicesDiscoveryService.getUrl(service, endpoint). +pub fn endpoint(doc: &serde_json::Value, service: &str, name: &str) -> Option { + doc.pointer(&format!("/discovery/{service}/endpoints/{name}/uri")) + .and_then(|u| u.as_str()) + .map(str::to_owned) +} + +/// The JoinMinecraftServerRequest body; `selectedProfile` is the undashed UUID. +pub fn join_request(session: &AuthSession, server_hash: &str) -> String { + serde_json::json!({ + "accessToken": session.access_token, + "selectedProfile": format!("{:032x}", session.uuid), + "serverId": server_hash, + }) + .to_string() +} + +/// MinecraftServicesSessionService.joinServer: tell the session service this +/// account is joining the server whose hash is `server_hash`. +pub fn join_server(session: &AuthSession, server_hash: &str) -> Result<(), JoinError> { + let doc = discovery()?; + let url = endpoint(&doc, "session", "join").ok_or(JoinError::Unavailable)?; + match agent() + .post(&url) + .set("Content-Type", "application/json; charset=utf-8") + .send_string(&join_request(session, server_hash)) + { + Ok(_) => Ok(()), + Err(ureq::Error::Status(status, response)) => Err(JoinError::from_response( + status, + &response.into_string().unwrap_or_default(), + )), + Err(ureq::Error::Transport(_)) => Err(JoinError::Unavailable), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const UUID: u128 = 0x069a79f444e94726a5befca90e38aaf5; + + fn write(dir: &Path, text: &str, mode: u32) -> std::path::PathBuf { + let path = dir.join("session.json"); + std::fs::write(&path, text).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + } + let _ = mode; + path + } + + #[test] + fn session_files_are_read_once_and_must_be_private() { + let dir = std::env::temp_dir().join(format!("horizon-auth-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let text = r#"{"name":"Notch","uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","access_token":"mock-token","user_type":"msa"}"#; + let path = write(&dir, text, 0o600); + let s = AuthSession::load(&path).unwrap(); + assert_eq!((s.name.as_str(), s.uuid), ("Notch", UUID)); + assert!(!path.exists(), "deleted after reading"); + assert!(!format!("{s:?}").contains("mock-token")); + #[cfg(unix)] + { + let path = write(&dir, text, 0o644); + assert!( + AuthSession::load(&path) + .unwrap_err() + .contains("other users") + ); + assert!(!path.exists()); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn session_file_fields() { + assert!( + AuthSession::parse(r#"{"name":"Notch","uuid":"069a79f444e94726a5befca90e38aaf5"}"#) + .is_err() + ); + assert!( + AuthSession::parse( + r#"{"name":"","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t"}"# + ) + .is_err() + ); + assert!(AuthSession::parse(r#"{"name":"A","uuid":"nope","access_token":"t"}"#).is_err()); + assert!(AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","user_type":"legacy"}"#).is_err()); + let s = AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","xuid":"25"}"#).unwrap(); + assert_eq!(s.xuid.as_deref(), Some("25")); + } + + #[test] + fn join_request_like_authlib() { + let s = AuthSession::new("Notch", UUID, "tok"); + let v: serde_json::Value = serde_json::from_str(&join_request(&s, "-7c9d")).unwrap(); + assert_eq!( + v, + serde_json::json!({"accessToken": "tok", "selectedProfile": "069a79f444e94726a5befca90e38aaf5", "serverId": "-7c9d"}) + ); + } + + #[test] + fn errors_map_like_authlib() { + let e = |status, body| JoinError::from_response(status, body); + assert_eq!( + e( + 403, + r#"{"error":"ForbiddenOperationException","errorMessage":"Invalid token"}"# + ), + JoinError::InvalidSession + ); + assert_eq!(e(401, ""), JoinError::InvalidSession); + assert_eq!( + e(403, r#"{"error":"InsufficientPrivilegesException"}"#), + JoinError::InsufficientPrivileges + ); + assert_eq!( + e(403, r#"{"error":"multiplayer.access.banned"}"#), + JoinError::Banned + ); + assert_eq!(e(503, "down"), JoinError::Unavailable); + assert_eq!( + e(429, r#"{"errorMessage":"Too many"}"#), + JoinError::Other("Too many".into()) + ); + assert_eq!( + JoinError::InvalidSession.reason(), + Ok("disconnect.loginFailedInfo.invalidSession") + ); + } + + #[test] + fn discovery_endpoints() { + let doc = serde_json::json!({"discovery": {"session": {"endpoints": {"join": {"uri": "https://s/join"}}}}}); + assert_eq!( + endpoint(&doc, "session", "join").as_deref(), + Some("https://s/join") + ); + assert_eq!(endpoint(&doc, "session", "verify"), None); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..d9fbf97cc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -246,12 +246,13 @@ impl Options { player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), dedicated: None, }; + let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -295,6 +296,7 @@ impl Options { "--world" => o.world = Some(value), "--server" => o.server = Some(value), "--name" => o.player_name = value, + "--session-file" => session_file = Some(value), "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), "--weather" => o.weather = Some(value), @@ -314,6 +316,17 @@ impl Options { } } } + // The launcher's account: online-mode servers need it. A bad file + // only leaves the game offline. + if let Some(path) = session_file.filter(|p| !p.is_empty()) { + match horizon_client::auth::AuthSession::load(path.as_ref()) { + Ok(session) => { + o.player_name = session.name.clone(); + horizon_client::auth::set_current(session); + } + Err(e) => eprintln!("Horizon: not signed in: {e}"), + } + } Ok(Some(o)) } } diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index d9bb6a74b..681a950b0 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -28,7 +28,12 @@ impl Game<'_> { while Instant::now() < deadline { self.update_world(); if self.remote.is_none() { - error = Some("disconnected".to_owned()); + error = Some(match self.title.as_ref().map(|t| &t.mode) { + Some(horizon_client::title::Mode::Multiplayer( + horizon_client::multiplayer::Screen::Disconnected { reason }, + )) => format!("disconnected: {reason}"), + _ => "disconnected".to_owned(), + }); break; } if Instant::now() >= next { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 73edbaca6..ae6b810d4 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -158,7 +158,10 @@ impl Game<'_> { 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()); + // A signed-in account always plays under its own name. + let auth = horizon_client::auth::current(); + let name = auth.as_ref().map_or(name, |a| a.name.as_str()); + let session = Session::connect(address, name, auth.clone(), view, lang.clone()); let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index eae7dc596..d71d5c19f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -9,6 +9,7 @@ pub mod atlas_sources; pub mod attack_strength; pub mod attribute_updates; pub mod audio; +pub mod auth; pub mod auto_jump; pub mod banner; pub mod biome; diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 94bc7c701..2e733c9ba 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -1,17 +1,20 @@ -//! Multiplayer session: a network thread that connects to a server, logs in -//! (offline mode only), runs the configuration phase and then forwards decoded -//! play packets to the game thread. Keep-alives and pings are answered on the -//! network thread like vanilla's connection handlers so a busy frame never -//! times the client out. Online-mode (authenticated) servers are refused: -//! Horizon never handles Microsoft credentials. +//! Multiplayer session: a network thread that connects to a server, logs in, +//! runs the configuration phase and then forwards decoded play packets to the +//! game thread. Keep-alives and pings are answered on the network thread like +//! vanilla's connection handlers so a busy frame never times the client out. +//! Online-mode servers need the Microsoft account the launcher signed in +//! (crate::auth): the login joins the server through the session service and +//! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello). +use crate::auth::AuthSession; use horizon_protocol::{ PROTOCOL_VERSION, connection::{ConnReader, ConnWriter, Connection, Counters}, - crypto::offline_uuid, + crypto::{generate_secret, offline_uuid, server_hash}, packets::{Empty, configuration as cfg, handshake, login, play}, registry::Dynamic, + rsa::RsaPublicKey, servers::parse_address, - text::{Language, plain}, + text::{Language, plain, translatable}, }; use std::{ sync::{ @@ -51,8 +54,14 @@ pub struct Session { debug: bool, } impl Session { - /// Start connecting in the background. - pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc) -> Self { + /// Start connecting in the background, as `auth`'s account when there is one. + pub fn connect( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + ) -> Self { let (send, events) = channel(); let writer = Arc::new(Mutex::new(None)); let counters = Arc::new(Mutex::new(None)); @@ -64,6 +73,7 @@ impl Session { let reason = match run( &address_owned, &name_owned, + auth.as_deref(), view_distance, &lang, &send, @@ -131,10 +141,19 @@ fn status(send: &Sender, text: &str) { let _ = send.send(Event::Status(text.to_owned())); } +/// Shown when an online-mode server asks a client without an account to authenticate. +pub const NOT_SIGNED_IN: &str = "This server is in online mode. Sign in with your Microsoft account in the Horizon launcher to join it."; + +/// A translation, or the key itself (Language.getOrDefault). +fn tr(lang: &Language, key: &str) -> String { + lang.get(key).cloned().unwrap_or_else(|| key.to_owned()) +} + /// The whole connection; returns the disconnect reason. fn run( address: &str, name: &str, + auth: Option<&AuthSession>, view_distance: i8, lang: &Language, send: &Sender, @@ -158,8 +177,8 @@ fn run( .encode(), ) .map_err(e)?; - status(send, "Logging in..."); - let uuid = offline_uuid(name); + // Vanilla's login sends the account's profile id, or the offline one. + let uuid = auth.map_or_else(|| offline_uuid(name), |a| a.uuid); c.send( &login::Serverbound::Hello(login::ServerHello { name: name.to_owned(), @@ -183,8 +202,35 @@ fn run( .unwrap_or(p.reason_json); return Err(reason); } - login::Clientbound::Hello(_) => { - return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into()); + login::Clientbound::Hello(hello) => { + status(send, &tr(lang, "connect.authorizing")); + let key = RsaPublicKey::from_der(&hello.public_key) + .map_err(|err| format!("Protocol error: {err}"))?; + let secret = generate_secret().map_err(e)?; + if hello.should_authenticate { + let account = auth.ok_or_else(|| NOT_SIGNED_IN.to_owned())?; + let hash = server_hash(&hello.server_id, &secret, &hello.public_key); + if let Err(err) = crate::auth::join_server(account, &hash) { + let reason = match err.reason() { + Ok(key) => tr(lang, key), + Err(message) => message.to_owned(), + }; + return Err(plain( + &translatable("disconnect.loginFailedInfo", &[&reason]), + lang, + )); + } + } + status(send, &tr(lang, "connect.encrypting")); + c.send( + &login::Serverbound::Key(login::Key { + key: key.encrypt(&secret).map_err(e)?, + challenge: key.encrypt(&hello.challenge).map_err(e)?, + }) + .encode(), + ) + .map_err(e)?; + c.enable_encryption(&secret); } login::Clientbound::CustomQuery(q) => { c.send( From ac97e9c0b9be8f3368a1a645a15a369d827c5204 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:44:50 +0200 Subject: [PATCH 09/43] Harness: online-mode login against vanilla's server and a mock session service Co-Authored-By: Claude Opus 5.5 --- docs/microsoft-account.md | 19 ++- tools/test_online_mode_parity.py | 269 +++++++++++++++++++++++++++++++ 2 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 tools/test_online_mode_parity.py diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index c992cd25f..41c73c594 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -116,10 +116,18 @@ Vanilla's `ClientHandshakePacketListenerImpl.handleHello`, `Crypt` and authlib's `multiplayer.access.banned` / `FORCED_USERNAME_CHANGE` → "You are banned from playing online", 5xx or no network → "The authentication servers are currently not reachable…". Without a session the game says "This server is in online mode. Sign in with your Microsoft account in the Horizon - launcher to join it." On a LAN server a failure is only logged (vanilla does the same). + launcher to join it." (Vanilla goes on after a failed join on LAN-discovered servers, which then + refuse the player anyway; Horizon stops at once.) 5. Send `ServerboundKeyPacket` (the secret and the challenge, each RSA PKCS#1 v1.5 encrypted with the server key), then AES/CFB8 (key = IV = the secret) both ways. +The connecting screen follows vanilla's states: "Connecting to the server..." until the encryption +request, "Logging in..." while joining the session service, "Encrypting...", then "Joining world...". +Code: `horizon-protocol` (`rsa.rs`, `crypto::server_hash`), `horizon-client` (`auth.rs`, `net.rs`). + +Horizon's own dedicated and LAN servers stay offline-mode (they don't verify players with the +session service); that is separate work. + `HORIZON_API_DISCOVERY` overrides the discovery URL, the counterpart of authlib's `-Dminecraft.api.discovery.host`; it is how the harness points both the vanilla server and Horizon at a local mock. @@ -153,8 +161,10 @@ Until part d lands, Horizon joins online servers but chat works only where ## Harnesses `tools/test_online_mode_parity.py` (dev only, needs no account): a local mock of the Minecraft -services (discovery document, `join`, `hasJoined`/`verify`, empty public keys) and a vanilla 26.3 -dedicated server in online mode started with `-Dminecraft.api.discovery.host=`. Horizon's +services (discovery document, `join`, `hasJoined`/`verify`, no public keys) and a vanilla 26.3 +dedicated server in online mode started with `-Dminecraft.api.discovery.host=` (authlib +10.0.77's only override: it replaces the whole discovery URL; the old `minecraft.api.session.host` +style properties are gone). Horizon's headless client (`HORIZON_NET_REPORT`) joins with a session file holding a mock token: the server verifies the join through the mock with the hash it computed itself (so the RSA wrapping, the hash and AES/CFB8 are all checked against vanilla's code), the player spawns, chats and runs `/list`. @@ -168,7 +178,8 @@ Microsoft, Xbox and Minecraft endpoints, and the keychain abstraction with an in ## PR plan -- (a) Game: online-mode handshake, encryption, session join, session file, harness. *(this PR)* +- (a) Game: online-mode handshake, encryption, session join, session file, harness (15/15 checks + against vanilla 26.3 on macOS). - (c) Launcher: device-code sign-in, token chain, keychain, accounts UI, CLI/MCP (`account list`, `account sign-in`, `account sign-out`, never tokens), session file handoff. - (b) Game: skins and capes over HTTPS, the real names and skins in game. diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py new file mode 100644 index 000000000..45b4b3ac6 --- /dev/null +++ b/tools/test_online_mode_parity.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Horizon's client joins vanilla's online-mode server, with no real account. + +A small mock of the Minecraft services (dev only: the discovery document and +the session service's join and hasJoined endpoints) stands in for Mojang's. +The pinned vanilla 26.3 dedicated server runs in online mode and finds the +mock through authlib's own override, `-Dminecraft.api.discovery.host`; +Horizon's client finds it through `HORIZON_API_DISCOVERY` and signs in with a +session file holding a mock token, as the launcher hands it over. + +The client must answer the server's encryption request: generate the shared +secret, hash the server id with it and the server's public key, join through +the mock, RSA-wrap the secret and the challenge for the server, then encrypt +the connection with AES/CFB8. The server decrypts the secret with its private +key, computes the hash itself and asks the mock whether the player joined +with that hash: so vanilla's own code checks the hash, the RSA wrapping and +the cipher. Then the client plays as in the dedicated-server harness (stands +in the world with its chunks, chats, runs /list, leaves). + +Also checked, with vanilla's messages: +- a token the session service rejects ("Failed to log in: Invalid session"); +- a join the session service forgets (the server: "Failed to verify username!"); +- no account at all (the client refuses before joining). + +Chat is unsigned here: the mock serves no Mojang public keys, so the server +can't validate profile keys and doesn't enforce secure chat. +""" +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import threading +import urllib.parse + +try: + from . import lab, oracle_harness as oh, test_rust_parity as base + from .test_dedicated_server_parity import Server, free_port +except ImportError: + import lab + import oracle_harness as oh + import test_rust_parity as base + from test_dedicated_server_parity import Server, free_port + +NAME = 'online-mode-parity' +PLAYER = 'Tester' +PLAYER_UUID = '5f3c1e6a2b9d4c7e8a1f0b2c3d4e5f60' +GOOD, FORGET, BAD = 'mock-token-good', 'mock-token-forget', 'mock-token-rejected' +PROPERTIES = { + 'online-mode': 'true', + 'white-list': 'false', + 'level-seed': '12345', + 'view-distance': '4', + 'simulation-distance': '4', + 'spawn-protection': '0', + 'max-players': '5', + 'pause-when-empty-seconds': '-1', +} + + +def dashed(u): + return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' + + +class Services: + """The mock session service. Records what was asked, never the tokens.""" + + def __init__(self): + self.joined = {} + self.log = [] + self.lock = threading.Lock() + services = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def reply(self, status, body=None): + data = b'' if body is None else json.dumps(body).encode() + self.send_response(status) + if body is not None: + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + url = urllib.parse.urlparse(self.path) + query = dict(urllib.parse.parse_qsl(url.query)) + if url.path == '/minecraft/client': + return self.reply(200, services.discovery()) + if url.path == '/session/minecraft/hasJoined': + with services.lock: + ok = services.joined.get(query.get('username')) == query.get('serverId') + services.log.append(('verify', query.get('username'), query.get('serverId'), ok)) + if ok: + return self.reply(200, {'id': PLAYER_UUID, 'name': query['username'], 'properties': []}) + return self.reply(204) + self.reply(404, {'error': 'NotFound', 'path': url.path}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}') + if self.path != '/session/minecraft/join': + return self.reply(404, {'error': 'NotFound'}) + token, profile, server_id = body.get('accessToken'), body.get('selectedProfile'), body.get('serverId') + accepted = token in (GOOD, FORGET) and profile == PLAYER_UUID + with services.lock: + services.log.append(('join', profile, server_id, accepted)) + if token == GOOD and accepted: + services.joined[PLAYER] = server_id + if not accepted: + return self.reply(403, {'error': 'ForbiddenOperationException', 'errorMessage': 'Invalid token'}) + self.reply(204) + + self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.server.server_address[1]}' + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def discovery(self): + def endpoints(**names): + return {'endpoints': {k: {'uri': self.url + v} for k, v in names.items()}} + return {'environment': 'mock', 'product': 'minecraft', 'discovery': { + 'authentication': endpoints(getPublicKeys='/publickeys'), + 'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined', + getProfileById='/session/minecraft/profile/{profileId}'), + 'player': {'endpoints': {}}, + 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}}}, + 'telemetry': {'endpoints': {}}, + }} + + def take_log(self): + with self.lock: + log, self.log = self.log, [] + return log + + def stop(self): + self.server.shutdown() + + +def session_file(directory, token): + """What the launcher writes: owner-only, read once by the game.""" + path = directory / 'session.json' + path.unlink(missing_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as f: + json.dump({'name': PLAYER, 'uuid': dashed(PLAYER_UUID), 'access_token': token, 'user_type': 'msa'}, f) + return path + + +def run_client(binary, build, port, label, token, discovery): + directory = build / f'client-{label}' + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir() + report = directory / 'report.json' + env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery) + command = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--render-distance', 2, + '--server', f'127.0.0.1:{port}', '--name', PLAYER] + if token: + command += ['--session-file', session_file(directory, token)] + with (build / f'client-{label}.log').open('w') as log: + subprocess.run([str(c) for c in command], cwd=directory, env=env, stdout=log, stderr=subprocess.STDOUT, + timeout=300, check=True) + got = json.loads(report.read_text()) + got['session file left'] = (directory / 'session.json').exists() + return got + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + + services = Services() + discovery = services.url + '/minecraft/client' + port = free_port() + directory = build / 'server' + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir() + props = dict(PROPERTIES, **{'server-port': str(port)}) + (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) + (directory / 'eula.txt').write_text('eula=true\n') + command = ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', + '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + server = Server(command, directory, 'vanilla-online') + checks = [] + + def check(label, actual, expected): + checks.append(f'{label}: ' + ('ok' if actual == expected else f'expected {expected!r}, got {actual!r}')) + + try: + server.wait_for(r'Done \(', timeout=600) + services.take_log() + + # 1. Signed in: the full encrypted handshake, then play. + got = run_client(binary, build, port, 'signed-in', GOOD, discovery) + server.wait_for(r'Tester left the game', timeout=30) + log = services.take_log() + joins = [e for e in log if e[0] == 'join'] + verifies = [e for e in log if e[0] == 'verify'] + check('signed-in: connected throughout', got['error'], None) + check('signed-in: joined the session service once', [(e[1], e[3]) for e in joins], [(PLAYER_UUID, True)]) + check('signed-in: server verified the same hash', + [(e[1], e[2], e[3]) for e in verifies], [(PLAYER, joins[0][2] if joins else None, True)]) + check('signed-in: own chat shown', any(' hello from the horizon client' in c for c in got['chat']), True) + check('signed-in: /list reply shown', + any('There are 1 of a max of 5 players online: Tester' in c for c in got['chat']), True) + check('signed-in: chunks received', got['chunks'] > 0, True) + check('signed-in: session file deleted', got['session file left'], False) + lines = '\n'.join(server.lines) + check('signed-in: server log', [k for k in [f'UUID of player Tester is {dashed(PLAYER_UUID)}', + 'Tester joined the game', + ' hello from the horizon client', + 'Tester left the game'] if k in lines], [ + f'UUID of player Tester is {dashed(PLAYER_UUID)}', 'Tester joined the game', + ' hello from the horizon client', 'Tester left the game']) + + # 2. A token the session service rejects: vanilla's message, no key sent. + mark = len(server.lines) + got = run_client(binary, build, port, 'rejected', BAD, discovery) + check('rejected token: client message', got['error'], + 'disconnected: Failed to log in: Invalid session (Try restarting your game and the launcher)') + check('rejected token: no verification', [e[0] for e in services.take_log()], ['join']) + + # 3. The session service forgets the join: the server refuses the player. + got = run_client(binary, build, port, 'forgotten', FORGET, discovery) + server.wait_for(r'Failed to verify username', timeout=30) + check('forgotten join: client message', got['error'], 'disconnected: Failed to verify username!') + check('forgotten join: server verified and refused', + [(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', False)]) + + # 4. No account: refused by the client before anything is sent to the services. + got = run_client(binary, build, port, 'no-account', None, discovery) + check('no account: client message', got['error'] or '', 'disconnected: This server is in online mode. ' + 'Sign in with your Microsoft account in the Horizon launcher to join it.') + check('no account: no service calls', services.take_log(), []) + check('no player joined after the first', 'joined the game' in '\n'.join(server.lines[mark:]), False) + finally: + server.stop() + services.stop() + + for line in checks: + print(line) + failed = [c for c in checks if not c.endswith(': ok')] + if failed: + raise AssertionError(f'{len(failed)} of {len(checks)} checks failed (logs in {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks), + scope='Online-mode login against vanilla\'s dedicated server and a mock session service: server hash, ' + 'RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten join, no account.')) + print(f'online mode: {len(checks)} checks ok') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From 6957d74742637cbf10e399b64218973b87378f7e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:48:05 +0200 Subject: [PATCH 10/43] docs: Minecraft login endpoint Co-Authored-By: Claude Opus 5.5 --- docs/microsoft-account.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 41c73c594..61b402211 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -57,8 +57,7 @@ All requests use HTTPS and JSON except the two OAuth calls (form-encoded): messages: 2148916233 no Xbox profile yet, 2148916235 Xbox Live not available in the country, 2148916236/2148916237 adult verification (South Korea), 2148916238 child account (needs a family). 5. **Minecraft**: `POST https://api.minecraftservices.com/authentication/login_with_xbox` - (`identityToken = "XBL3.0 x=;"`), the endpoint taken from the services discovery - document (authentication/loginXbox) like authlib does. Result: the Minecraft access token (24 h). + (`identityToken = "XBL3.0 x=;"`). Result: the Minecraft access token (24 h). 6. **Entitlements**: `GET https://api.minecraftservices.com/entitlements/mcstore`: the account must own `game_minecraft` or `product_minecraft` (Game Pass included), else "This account doesn't own Minecraft Java Edition". From 0acd686720c6a02c9c916533856357cd0f7c1e1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:55:56 +0200 Subject: [PATCH 11/43] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/src/crypto.rs | 11 +++++++++-- crates/horizon-protocol/src/rsa.rs | 17 +++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs index b5b6fa447..bd0244b07 100644 --- a/crates/horizon-protocol/src/crypto.rs +++ b/crates/horizon-protocol/src/crypto.rs @@ -172,7 +172,11 @@ pub fn java_hex_digest(digest: &[u8]) -> String { let hex: String = magnitude.iter().map(|b| format!("{b:02x}")).collect(); let hex = hex.trim_start_matches('0'); let hex = if hex.is_empty() { "0" } else { hex }; - if negative { format!("-{hex}") } else { hex.to_owned() } + if negative { + format!("-{hex}") + } else { + hex.to_owned() + } } /// The server id sent to the session service when joining an online-mode @@ -181,7 +185,10 @@ pub fn java_hex_digest(digest: &[u8]) -> String { pub fn server_hash(server_id: &str, secret: &[u8], public_key: &[u8]) -> String { let mut sha = Sha1::new(); // ISO-8859-1: characters above U+00FF become '?' like String.getBytes. - let latin1: Vec = server_id.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect(); + let latin1: Vec = server_id + .chars() + .map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')) + .collect(); sha.update(&latin1); sha.update(secret); sha.update(public_key); diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index cbc256c06..57443e4fd 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -150,7 +150,9 @@ fn der(input: &[u8]) -> Result<(u8, &[u8], &[u8])> { if n == 0 || n > 4 || rest.len() < n { return Err(bad()); } - let len = rest[..n].iter().fold(0usize, |l, b| l << 8 | usize::from(*b)); + let len = rest[..n] + .iter() + .fold(0usize, |l, b| l << 8 | usize::from(*b)); rest = &rest[n..]; len }; @@ -219,8 +221,11 @@ impl RsaPublicKey { let limbs = self.size().div_ceil(4); let mont = Mont::new(Big::from_be_bytes(&self.modulus, limbs)); let m = Big::from_be_bytes(block, limbs); - mont.pow(&m, &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4)))) - .to_be_bytes(self.size()) + mont.pow( + &m, + &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4))), + ) + .to_be_bytes(self.size()) } /// RSAES-PKCS1-v1_5 (RFC 8017 7.2.1) with random non-zero padding. pub fn encrypt(&self, message: &[u8]) -> Result> { @@ -249,7 +254,11 @@ pub(crate) mod tests { use super::*; pub fn hex(s: &str) -> Vec { - let s = if s.len() % 2 == 1 { format!("0{s}") } else { s.to_owned() }; + let s = if s.len() % 2 == 1 { + format!("0{s}") + } else { + s.to_owned() + }; (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) From f38e8cc393214658641672f62d0a3797fd4008b9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:57:34 +0200 Subject: [PATCH 12/43] Skins over HTTPS: fetch textures with ureq (rustls) Players' skins on online servers come from https://textures.minecraft.net; the old plain-HTTP fetch left everyone with their default skin. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/skins.rs | 96 +++++++++++++++--------------- 1 file changed, 47 insertions(+), 49 deletions(-) diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index ef8d575c3..c47c9d47f 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -246,9 +246,8 @@ pub fn process_legacy_skin(width: u32, height: u32, rgba: &[u8]) -> Option/<2 hex>/`) or over HTTP, keeping each one -/// by kind and hash as vanilla's `TextureCache`s do. Plain HTTP only: an -/// `https` texture that isn't cached fails, and the player keeps their -/// default skin. +/// by kind and hash as vanilla's `TextureCache`s do. A texture that can't +/// be fetched fails, and the player keeps their default skin. pub struct Downloader { root: std::path::PathBuf, states: std::collections::HashMap<(Kind, String), Download>, @@ -318,53 +317,23 @@ impl Downloader { } } -/// A plain HTTP/1.1 GET; the body of a 2xx answer. +/// A GET over HTTP or HTTPS (textures.minecraft.net serves both; vanilla +/// uses https): the body of a 2xx answer, 16 MiB at most, after redirects. fn http_get(url: &str) -> Option> { - use std::io::{Read, Write}; - let rest = url.strip_prefix("http://")?; - let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); - let path = if path.is_empty() { "/" } else { path }; - let path = &path[..path.find('#').unwrap_or(path.len())]; - let host = authority.split(':').next()?; - let address = if authority.contains(':') { - authority.to_owned() - } else { - format!("{authority}:80") - }; - let timeout = std::time::Duration::from_secs(15); - let addr = std::net::ToSocketAddrs::to_socket_addrs(&address) - .ok()? - .next()?; - let mut stream = std::net::TcpStream::connect_timeout(&addr, timeout).ok()?; - stream.set_read_timeout(Some(timeout)).ok()?; - write!( - stream, - "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: Java\r\n\r\n" - ) - .ok()?; - let mut response = Vec::new(); - stream.take(16 << 20).read_to_end(&mut response).ok()?; - let split = response.windows(4).position(|w| w == b"\r\n\r\n")?; - let head = String::from_utf8_lossy(&response[..split]).to_ascii_lowercase(); - let mut body = response[split + 4..].to_vec(); - let status: u32 = head.split_whitespace().nth(1)?.parse().ok()?; - if status / 100 != 2 { - return None; - } - if head.contains("transfer-encoding: chunked") { - let (mut out, mut at) = (Vec::new(), 0); - loop { - let end = at + body[at..].windows(2).position(|w| w == b"\r\n")?; - let line = String::from_utf8_lossy(&body[at..end]); - let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?; - if size == 0 { - break; - } - out.extend_from_slice(body.get(end + 2..end + 2 + size)?); - at = end + 4 + size; - } - body = out; - } + use std::io::Read; + let response = ureq::AgentBuilder::new() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("Java") + .build() + .get(url) + .call() + .ok()?; + let mut body = Vec::new(); + response + .into_reader() + .take(16 << 20) + .read_to_end(&mut body) + .ok()?; Some(body) } @@ -424,6 +393,35 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + /// Textures come over plain HTTP too (a local server here; https is the + /// same request through rustls), and only 2xx answers count. + #[test] + fn http_get_reads_2xx_bodies() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for stream in listener.incoming().take(2) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + reader.read_line(&mut line).unwrap(); + while reader.read_line(&mut String::new()).unwrap() > 2 {} + let reply: &[u8] = if line.contains("/texture/abc") { + b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nPNG!" + } else { + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + }; + stream.write_all(reply).unwrap(); + } + }); + assert_eq!( + http_get(&format!("{base}/texture/abc")), + Some(b"PNG!".to_vec()) + ); + assert_eq!(http_get(&format!("{base}/texture/missing")), None); + } + use super::*; #[test] From 82bee83dc5176ad01bd941cf8731e345e1ca9adf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:54:48 +0200 Subject: [PATCH 13/43] Launcher: Microsoft account sign-in, keychain and the game's session Device-code OAuth, Xbox Live, XSTS, Minecraft login, ownership and profile; secrets in the OS keychain (oo7 on Linux, keyring on macOS/Windows), accounts.json without tokens; Settings account rows, 'Playing as' on the Play page; CLI 'account' and MCP account tools; the game gets a 0600 session file it deletes. Client ID is configuration (HORIZON_MSA_CLIENT_ID), empty = not configured. Co-Authored-By: Claude Opus 5.5 --- launcher/Cargo.lock | 42 +- launcher/Cargo.toml | 12 + launcher/src/account.rs | 815 ++++++++++++++++++++++++++++++++++ launcher/src/account/tests.rs | 410 +++++++++++++++++ launcher/src/backend.rs | 12 +- launcher/src/cli.rs | 97 ++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 263 ++++++++++- launcher/src/mcp.rs | 73 +++ 9 files changed, 1717 insertions(+), 8 deletions(-) create mode 100644 launcher/src/account.rs create mode 100644 launcher/src/account/tests.rs diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 8d80f615c..39972745d 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2570,10 +2570,14 @@ dependencies = [ "clap", "dirs 5.0.1", "flate2", + "futures-lite 2.6.1", + "getrandom 0.3.4", "gpui", "horizon-prepare", "horizon-theme", "image", + "keyring", + "oo7", "pulldown-cmark", "self-replace", "serde", @@ -2992,6 +2996,20 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "log", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4645,7 +4663,7 @@ dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework", + "security-framework 3.7.0", ] [[package]] @@ -4810,6 +4828,19 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -6665,6 +6696,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index ef74e59a0..1d2e259df 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -22,6 +22,18 @@ image = { version = "0.25", default-features = false, features = ["jpeg"] } clap = { version = "4", features = ["derive"] } horizon-theme = { path = "../crates/horizon-theme" } horizon-prepare = { path = "../crates/horizon-prepare" } +# The session file's random name. +getrandom = "0.3" + +# Microsoft account secrets in the OS keychain: the Secret Service on Linux through oo7 (the same +# build gpui uses), Keychain and Credential Manager through keyring. +[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies] +oo7 = { version = "0.5", default-features = false, features = ["async-std", "native_crypto"] } +futures-lite = "2" +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { version = "3", features = ["apple-native"] } +[target.'cfg(target_os = "windows")'.dependencies] +keyring = { version = "3", features = ["windows-native"] } [profile.release] strip = true diff --git a/launcher/src/account.rs b/launcher/src/account.rs new file mode 100644 index 000000000..e64141646 --- /dev/null +++ b/launcher/src/account.rs @@ -0,0 +1,815 @@ +//! Microsoft account sign-in (docs/microsoft-account.md): the OAuth device-code flow, then Xbox +//! Live, XSTS and the Minecraft services, the game ownership check and the profile. Secrets (the +//! Microsoft refresh token, the Minecraft access token) live in the OS keychain; accounts.json +//! keeps only names and UUIDs. The game gets the session in a file it reads once +//! (`--session-file`), never on its command line. Tokens never reach logs, errors or output. +//! +//! The Azure app (client ID) is Horizon's own and is configuration: `HORIZON_MSA_CLIENT_ID` at +//! build time, or at run time to override it. Without one, sign-in says it is not configured. +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// The keychain service name every secret is stored under. +pub const SERVICE: &str = "dev.playhorizon.launcher"; +const SCOPE: &str = "XboxLive.signin offline_access"; +pub const NOT_CONFIGURED: &str = + "Microsoft sign-in is not configured yet in this build of the launcher (no client ID)."; +const SIGN_IN_AGAIN: &str = "Your Microsoft sign-in expired. Sign in again."; +/// The Minecraft token is renewed when it has less than this left. +const RENEW_BEFORE: u64 = 3600; + +/// The configured Azure app, if any: the run-time variable wins over the build-time one, and an +/// empty value means none. +pub fn client_id() -> Option { + std::env::var("HORIZON_MSA_CLIENT_ID") + .ok() + .or_else(|| option_env!("HORIZON_MSA_CLIENT_ID").map(str::to_owned)) + .map(|id| id.trim().to_owned()) + .filter(|id| !id.is_empty()) +} + +/// Where the requests go: the real services, or a mock in tests. +#[derive(Clone, Debug)] +pub struct Endpoints { + /// The OAuth 2.0 v2 endpoints for personal accounts (`…/devicecode`, `…/token`). + pub microsoft: String, + pub xbox_user: String, + pub xsts: String, + /// api.minecraftservices.com. + pub minecraft: String, +} + +impl Endpoints { + pub fn live() -> Self { + Self { + microsoft: "https://login.microsoftonline.com/consumers/oauth2/v2.0".into(), + xbox_user: "https://user.auth.xboxlive.com/user/authenticate".into(), + xsts: "https://xsts.auth.xboxlive.com/xsts/authorize".into(), + minecraft: "https://api.minecraftservices.com".into(), + } + } +} + +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout(Duration::from_secs(20)) + .user_agent(concat!("horizon-launcher/", env!("CARGO_PKG_VERSION"))) + .build() +} + +/// One request's result: the status and the JSON body (empty when there is none). Transport +/// errors name the service, never the URL's query or the request. +fn send(request: ureq::Request, body: Option, service: &str) -> Result<(u16, Value), String> { + let result = match body { + None => request.call(), + Some(Body::Form(fields)) => request.send_form(&fields), + Some(Body::Json(value)) => request.set("Accept", "application/json").send_json(value), + }; + let response = match result { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(ureq::Error::Transport(_)) => { + return Err(format!( + "Could not reach {service}. Check your internet connection." + )) + } + }; + let status = response.status(); + let text = response.into_string().unwrap_or_default(); + Ok((status, serde_json::from_str(&text).unwrap_or(Value::Null))) +} + +enum Body<'a> { + Form(Vec<(&'a str, &'a str)>), + Json(Value), +} + +fn str_field(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_str).map(str::to_owned) +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +// ----- The device-code flow ---------------------------------------------------------------------- + +/// What the player types at the verification page. +#[derive(Clone)] +pub struct DeviceCode { + pub user_code: String, + pub verification_uri: String, + pub interval: u64, + pub expires_at: u64, + device_code: String, +} + +impl std::fmt::Debug for DeviceCode { + // The device code can be traded for tokens once the player approves: never shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DeviceCode") + .field("user_code", &self.user_code) + .field("verification_uri", &self.verification_uri) + .finish_non_exhaustive() + } +} + +/// The Microsoft tokens; the access token only lasts for the Xbox step. +pub struct MsTokens { + access: String, + refresh: String, +} + +impl std::fmt::Debug for MsTokens { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("MsTokens()") + } +} + +pub enum Poll { + Pending, + /// The server asked to poll less often: wait 5 s more. + SlowDown, + Done(MsTokens), +} + +pub fn device_code(ep: &Endpoints, client_id: &str) -> Result { + let (status, v) = send( + agent().post(&format!("{}/devicecode", ep.microsoft)), + Some(Body::Form(vec![("client_id", client_id), ("scope", SCOPE)])), + "Microsoft", + )?; + match ( + status, + str_field(&v, "user_code"), + str_field(&v, "device_code"), + ) { + (200, Some(user_code), Some(device_code)) => Ok(DeviceCode { + user_code, + verification_uri: str_field(&v, "verification_uri") + .unwrap_or_else(|| "https://www.microsoft.com/link".into()), + interval: v + .get("interval") + .and_then(Value::as_u64) + .unwrap_or(5) + .max(1), + expires_at: now() + v.get("expires_in").and_then(Value::as_u64).unwrap_or(900), + device_code, + }), + _ => Err(oauth_error(&v)), + } +} + +/// The OAuth error codes as messages for the player. +fn oauth_error(v: &Value) -> String { + match v.get("error").and_then(Value::as_str) { + Some("authorization_declined") => "Sign-in was declined in the browser.".into(), + Some("expired_token") => "The sign-in code expired. Start again.".into(), + Some("bad_verification_code") => "The sign-in code was not recognised. Start again.".into(), + Some("invalid_grant") => SIGN_IN_AGAIN.into(), + Some("invalid_client" | "unauthorized_client") => { + "Microsoft refused this launcher's app registration (client ID).".into() + } + Some(other) => format!("Microsoft sign-in failed ({other})."), + None => "Microsoft sign-in failed.".into(), + } +} + +/// One poll of the token endpoint while the player signs in. +pub fn poll(ep: &Endpoints, client_id: &str, code: &DeviceCode) -> Result { + let (status, v) = send( + agent().post(&format!("{}/token", ep.microsoft)), + Some(Body::Form(vec![ + ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), + ("client_id", client_id), + ("device_code", &code.device_code), + ])), + "Microsoft", + )?; + match v.get("error").and_then(Value::as_str) { + Some("authorization_pending") => return Ok(Poll::Pending), + Some("slow_down") => return Ok(Poll::SlowDown), + _ => {} + } + ms_tokens(status, &v).map(Poll::Done) +} + +fn ms_tokens(status: u16, v: &Value) -> Result { + match ( + status, + str_field(v, "access_token"), + str_field(v, "refresh_token"), + ) { + (200, Some(access), Some(refresh)) => Ok(MsTokens { access, refresh }), + _ => Err(oauth_error(v)), + } +} + +/// Wait for the player to finish in the browser, polling as asked, until the code expires or +/// `cancelled` says stop. +pub fn wait_for_sign_in( + ep: &Endpoints, + client_id: &str, + code: &DeviceCode, + cancelled: &dyn Fn() -> bool, +) -> Result { + let mut interval = code.interval; + loop { + let until = std::time::Instant::now() + Duration::from_secs(interval); + while std::time::Instant::now() < until { + if cancelled() { + return Err("Sign-in cancelled.".into()); + } + std::thread::sleep(Duration::from_millis(100)); + } + if now() > code.expires_at { + return Err("The sign-in code expired. Start again.".into()); + } + match poll(ep, client_id, code)? { + Poll::Pending => {} + Poll::SlowDown => interval += 5, + Poll::Done(tokens) => return Ok(tokens), + } + } +} + +fn refresh_ms(ep: &Endpoints, client_id: &str, refresh: &str) -> Result { + let (status, v) = send( + agent().post(&format!("{}/token", ep.microsoft)), + Some(Body::Form(vec![ + ("grant_type", "refresh_token"), + ("client_id", client_id), + ("refresh_token", refresh), + ("scope", SCOPE), + ])), + "Microsoft", + )?; + ms_tokens(status, &v) +} + +// ----- Xbox Live, XSTS, Minecraft ---------------------------------------------------------------- + +/// The XSTS `XErr` codes, as the official launcher explains them. +fn xsts_error(code: u64) -> String { + match code { + 2148916233 => "This Microsoft account has no Xbox profile yet. Sign in once at xbox.com to create one, then try again.".into(), + 2148916235 => "Xbox Live is not available in your country or region.".into(), + 2148916236 | 2148916237 => "This account needs adult verification on xbox.com before it can play.".into(), + 2148916238 => "This is a child account: an adult has to add it to a Microsoft family first.".into(), + other => format!("Xbox Live refused the sign-in (error {other})."), + } +} + +/// The Minecraft access token from the Microsoft one, through Xbox Live and XSTS. +struct Minecraft { + token: String, + expires_at: u64, + xuid: Option, +} + +fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result { + let (status, xbl) = send( + agent().post(&ep.xbox_user), + Some(Body::Json(json!({ + "Properties": { + "AuthMethod": "RPS", + "SiteName": "user.auth.xboxlive.com", + "RpsTicket": format!("d={ms_access}"), + }, + "RelyingParty": "http://auth.xboxlive.com", + "TokenType": "JWT", + }))), + "Xbox Live", + )?; + let xbl_token = str_field(&xbl, "Token") + .filter(|_| status == 200) + .ok_or("Xbox Live refused the sign-in.")?; + let (status, xsts) = send( + agent().post(&ep.xsts), + Some(Body::Json(json!({ + "Properties": { "SandboxId": "RETAIL", "UserTokens": [xbl_token] }, + "RelyingParty": "rp://api.minecraftservices.com/", + "TokenType": "JWT", + }))), + "Xbox Live", + )?; + if let Some(code) = xsts.get("XErr").and_then(Value::as_u64) { + return Err(xsts_error(code)); + } + let claims = xsts.pointer("/DisplayClaims/xui/0"); + let (Some(xsts_token), Some(uhs)) = ( + str_field(&xsts, "Token").filter(|_| status == 200), + claims.and_then(|c| str_field(c, "uhs")), + ) else { + return Err("Xbox Live refused the sign-in.".into()); + }; + let xuid = claims.and_then(|c| str_field(c, "xid")); + let (status, mc) = send( + agent().post(&format!("{}/authentication/login_with_xbox", ep.minecraft)), + Some(Body::Json( + json!({ "identityToken": format!("XBL3.0 x={uhs};{xsts_token}") }), + )), + "the Minecraft services", + )?; + match (status, str_field(&mc, "access_token")) { + (200, Some(token)) => Ok(Minecraft { + token, + expires_at: now() + + mc.get("expires_in") + .and_then(Value::as_u64) + .unwrap_or(86400), + xuid, + }), + // New Azure apps are refused until Mojang approves them (Minecraft API access). + (403, _) => Err( + "The Minecraft services refused this launcher: its app is not approved by Mojang yet." + .into(), + ), + (429, _) => Err("Too many sign-ins in a short time. Wait a minute and try again.".into()), + _ => Err("The Minecraft services refused the sign-in.".into()), + } +} + +fn bearer(request: ureq::Request, token: &str) -> ureq::Request { + request.set("Authorization", &format!("Bearer {token}")) +} + +/// Whether the account owns Minecraft: Java Edition (Game Pass included). +fn owns_game(ep: &Endpoints, token: &str) -> Result { + let (status, v) = send( + bearer( + agent().get(&format!("{}/entitlements/mcstore", ep.minecraft)), + token, + ), + None, + "the Minecraft services", + )?; + if status != 200 { + return Err("Could not check which games this account owns.".into()); + } + Ok(v.get("items") + .and_then(Value::as_array) + .is_some_and(|items| { + items.iter().any(|i| { + matches!( + i.get("name").and_then(Value::as_str), + Some("game_minecraft" | "product_minecraft") + ) + }) + })) +} + +/// A Minecraft profile, as the launcher shows and remembers it (no secrets). +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Account { + /// The profile UUID without dashes. + pub uuid: String, + pub name: String, + /// The active skin's URL (textures.minecraft.net) and model ("classic" or "slim"). + #[serde(default)] + pub skin: Option<(String, String)>, + #[serde(default)] + pub cape: Option, +} + +fn profile(ep: &Endpoints, token: &str) -> Result { + let (status, v) = send( + bearer( + agent().get(&format!("{}/minecraft/profile", ep.minecraft)), + token, + ), + None, + "the Minecraft services", + )?; + if status == 404 { + return Err("This account has no Minecraft profile yet. Create one at minecraft.net, then sign in again.".into()); + } + let (Some(uuid), Some(name)) = (str_field(&v, "id"), str_field(&v, "name")) else { + return Err("Could not read the Minecraft profile.".into()); + }; + let active = |key: &str| { + v.get(key) + .and_then(Value::as_array) + .and_then(|list| { + list.iter() + .find(|s| s.get("state").and_then(Value::as_str) == Some("ACTIVE")) + }) + .cloned() + }; + Ok(Account { + uuid: uuid.replace('-', "").to_lowercase(), + name, + skin: active("skins").and_then(|s| { + Some(( + str_field(&s, "url")?, + str_field(&s, "variant") + .unwrap_or_else(|| "CLASSIC".into()) + .to_lowercase(), + )) + }), + cape: active("capes").and_then(|c| str_field(&c, "url")), + }) +} + +/// What the keychain keeps for one account. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub struct Secrets { + refresh_token: String, + minecraft_token: String, + minecraft_expires_at: u64, + #[serde(default)] + xuid: Option, +} +impl std::fmt::Debug for Secrets { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secrets()") + } +} + +/// From Microsoft tokens to a ready account: Xbox, XSTS, Minecraft, ownership, profile. +pub fn finish_sign_in(ep: &Endpoints, ms: MsTokens) -> Result<(Account, Secrets), String> { + let mc = minecraft_login(ep, &ms.access)?; + if !owns_game(ep, &mc.token)? { + return Err("This account doesn't own Minecraft: Java Edition.".into()); + } + let account = profile(ep, &mc.token)?; + Ok(( + account, + Secrets { + refresh_token: ms.refresh, + minecraft_token: mc.token, + minecraft_expires_at: mc.expires_at, + xuid: mc.xuid, + }, + )) +} + +/// A Minecraft token with at least an hour left, renewed through the refresh token if needed. +/// The profile is read again on renewal (the name may have changed). +pub fn fresh( + ep: &Endpoints, + client_id: &str, + account: &Account, + secrets: Secrets, +) -> Result<(Account, Secrets), String> { + if secrets.minecraft_expires_at > now() + RENEW_BEFORE { + return Ok((account.clone(), secrets)); + } + let ms = refresh_ms(ep, client_id, &secrets.refresh_token)?; + let (renewed, secrets) = finish_sign_in(ep, ms)?; + if renewed.uuid != account.uuid { + return Err( + "The Microsoft account now has another Minecraft profile. Sign in again.".into(), + ); + } + Ok((renewed, secrets)) +} + +// ----- The keychain -------------------------------------------------------------------------------- + +/// Where secrets are kept: the OS keychain, or memory in tests and when there is none. +pub trait SecretStore: Send + Sync { + fn get(&self, key: &str) -> Result, String>; + fn set(&self, key: &str, secret: &str) -> Result<(), String>; + fn delete(&self, key: &str) -> Result<(), String>; + /// False for memory: secrets are gone when the launcher closes. + fn persistent(&self) -> bool; +} + +#[derive(Default)] +pub struct MemoryStore(Mutex>); +impl SecretStore for MemoryStore { + fn get(&self, key: &str) -> Result, String> { + Ok(self.0.lock().unwrap().get(key).cloned()) + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + self.0.lock().unwrap().insert(key.into(), secret.into()); + Ok(()) + } + fn delete(&self, key: &str) -> Result<(), String> { + self.0.lock().unwrap().remove(key); + Ok(()) + } + fn persistent(&self) -> bool { + false + } +} + +/// The Secret Service (GNOME Keyring, KWallet) through oo7, as gpui itself uses it. +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +pub struct SystemStore; +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +impl SystemStore { + fn keyring() -> Result { + futures_lite::future::block_on(async { + let keyring = oo7::Keyring::new().await.map_err(|e| e.to_string())?; + keyring.unlock().await.map_err(|e| e.to_string())?; + Ok(keyring) + }) + } +} +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +impl SecretStore for SystemStore { + fn get(&self, key: &str) -> Result, String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + let items = keyring + .search_items(&attributes) + .await + .map_err(|e| e.to_string())?; + let Some(item) = items.into_iter().next() else { + return Ok(None); + }; + item.unlock().await.map_err(|e| e.to_string())?; + let secret = item.secret().await.map_err(|e| e.to_string())?; + Ok(String::from_utf8(secret.to_vec()).ok()) + }) + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + keyring + .create_item( + "Horizon launcher: Minecraft account", + &attributes, + secret.as_bytes(), + true, + ) + .await + .map_err(|e| e.to_string()) + }) + } + fn delete(&self, key: &str) -> Result<(), String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + keyring.delete(&attributes).await.map_err(|e| e.to_string()) + }) + } + fn persistent(&self) -> bool { + true + } +} + +/// Keychain on macOS, Credential Manager on Windows (the keyring crate). +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub struct SystemStore; +#[cfg(any(target_os = "macos", target_os = "windows"))] +impl SecretStore for SystemStore { + fn get(&self, key: &str) -> Result, String> { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.get_password()) { + Ok(secret) => Ok(Some(secret)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(e.to_string()), + } + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + keyring::Entry::new(SERVICE, key) + .and_then(|e| e.set_password(secret)) + .map_err(|e| e.to_string()) + } + fn delete(&self, key: &str) -> Result<(), String> { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.delete_credential()) { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(e.to_string()), + } + } + fn persistent(&self) -> bool { + true + } +} + +pub const NO_KEYCHAIN: &str = "No keychain available: you are signed in until the launcher closes, then you will have to sign in again."; + +/// The keychain if it answers, else memory for this run (said once in the UI with NO_KEYCHAIN). +pub fn store() -> &'static dyn SecretStore { + static STORE: OnceLock> = OnceLock::new(); + STORE + .get_or_init(|| { + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "macos", + target_os = "windows" + ))] + if std::env::var_os("HORIZON_NO_KEYCHAIN").is_none() && SystemStore.get("probe").is_ok() + { + return Box::new(SystemStore); + } + Box::::default() + }) + .as_ref() +} + +// ----- Accounts ------------------------------------------------------------------------------------ + +/// accounts.json: the signed-in accounts and the one that plays. Never a token. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Accounts { + pub accounts: Vec, + /// The UUID of the account the game starts with; none plays offline. + pub selected: Option, +} + +impl Accounts { + fn path() -> PathBuf { + crate::backend::data_dir().join("accounts.json") + } + pub fn load() -> Self { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + pub fn save(&self) -> Result<(), String> { + let path = Self::path(); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + std::fs::write(path, text + "\n").map_err(|e| e.to_string()) + } + pub fn selected(&self) -> Option<&Account> { + let uuid = self.selected.as_ref()?; + self.accounts.iter().find(|a| &a.uuid == uuid) + } + /// Find an account by name (any case) or UUID (with or without dashes). + pub fn find(&self, who: &str) -> Option<&Account> { + let undashed = who.replace('-', "").to_lowercase(); + self.accounts + .iter() + .find(|a| a.name.eq_ignore_ascii_case(who) || a.uuid == undashed) + } + /// Keep a new or renewed account, its secrets in the store, and select it. + pub fn add( + &mut self, + store: &dyn SecretStore, + account: Account, + secrets: &Secrets, + ) -> Result<(), String> { + store.set( + &account.uuid, + &serde_json::to_string(secrets).map_err(|e| e.to_string())?, + )?; + self.selected = Some(account.uuid.clone()); + match self.accounts.iter_mut().find(|a| a.uuid == account.uuid) { + Some(a) => *a = account, + None => self.accounts.push(account), + } + Ok(()) + } + /// Sign out: the secrets leave the keychain, the account the list. + pub fn remove(&mut self, store: &dyn SecretStore, uuid: &str) -> Result<(), String> { + store.delete(uuid)?; + self.accounts.retain(|a| a.uuid != uuid); + if self.selected.as_deref() == Some(uuid) { + self.selected = None; + } + Ok(()) + } +} + +/// The selected account with a token good for this game, renewed and saved if needed. +pub fn session_for_launch( + ep: &Endpoints, + store: &dyn SecretStore, + accounts: &mut Accounts, +) -> Result, String> { + let Some(account) = accounts.selected().cloned() else { + return Ok(None); + }; + let secrets: Secrets = store + .get(&account.uuid)? + .and_then(|s| serde_json::from_str(&s).ok()) + .ok_or_else(|| { + format!( + "{} is no longer signed in on this computer. Sign in again.", + account.name + ) + })?; + let client_id = client_id().ok_or(NOT_CONFIGURED)?; + let before = secrets.minecraft_token.clone(); + let (renewed, secrets) = fresh(ep, &client_id, &account, secrets)?; + if renewed != account || secrets.minecraft_token != before { + accounts.add(store, renewed.clone(), &secrets)?; + accounts.save()?; + } + Ok(Some((renewed, secrets))) +} + +/// Write the session for the game, readable by this user only, in a fresh file it deletes +/// when it reads it. +pub fn write_session_file( + dir: &Path, + account: &Account, + secrets: &Secrets, +) -> Result { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + // Leftovers of games that never started (refused by the game after two minutes anyway). + if let Ok(entries) = std::fs::read_dir(dir) { + for e in entries.flatten() { + let old = e + .metadata() + .and_then(|m| m.modified()) + .is_ok_and(|m| m.elapsed().is_ok_and(|age| age > Duration::from_secs(120))); + if old { + let _ = std::fs::remove_file(e.path()); + } + } + } + let mut name = [0u8; 12]; + getrandom::fill(&mut name).map_err(|e| e.to_string())?; + let path = dir.join(format!( + "session-{}.json", + name.iter().map(|b| format!("{b:02x}")).collect::() + )); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path).map_err(|e| e.to_string())?; + let body = json!({ + "name": account.name, + "uuid": account.uuid, + "access_token": secrets.minecraft_token, + "user_type": "msa", + "xuid": secrets.xuid, + }); + std::io::Write::write_all(&mut file, body.to_string().as_bytes()).map_err(|e| e.to_string())?; + Ok(path) +} + +/// Where a background sign-in is (the window and the MCP server show it). +#[derive(Clone, Debug)] +pub enum SignInState { + Starting, + /// Waiting for the player at `verification_uri` with `user_code`. + Code(DeviceCode), + Done(Result), +} + +/// A sign-in on its own thread, from the code to the saved account. +pub struct SignIn { + state: std::sync::Arc>, + cancel: std::sync::Arc, +} + +impl SignIn { + pub fn start() -> Self { + use std::sync::atomic::Ordering; + let state = std::sync::Arc::new(Mutex::new(SignInState::Starting)); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (thread_state, thread_cancel) = (state.clone(), cancel.clone()); + std::thread::spawn(move || { + let set = |s| *thread_state.lock().unwrap() = s; + let result = (|| { + let ep = Endpoints::live(); + let client_id = client_id().ok_or(NOT_CONFIGURED)?; + let code = device_code(&ep, &client_id)?; + set(SignInState::Code(code.clone())); + let ms = wait_for_sign_in(&ep, &client_id, &code, &|| { + thread_cancel.load(Ordering::Relaxed) + })?; + let (account, secrets) = finish_sign_in(&ep, ms)?; + let mut accounts = Accounts::load(); + accounts.add(store(), account.clone(), &secrets)?; + accounts.save()?; + Ok(account) + })(); + set(SignInState::Done(result)); + }); + Self { state, cancel } + } + pub fn state(&self) -> SignInState { + self.state.lock().unwrap().clone() + } + pub fn cancel(&self) { + self.cancel + .store(true, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Give the game the selected account's session, when there is one. +pub fn attach_session( + cmd: &mut std::process::Command, + game_home: &Path, +) -> Result, String> { + let mut accounts = Accounts::load(); + let Some((account, secrets)) = session_for_launch(&Endpoints::live(), store(), &mut accounts)? + else { + return Ok(None); + }; + let file = write_session_file(&game_home.join("sessions"), &account, &secrets)?; + cmd.arg("--session-file").arg(file); + Ok(Some(account)) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs new file mode 100644 index 000000000..925b78195 --- /dev/null +++ b/launcher/src/account/tests.rs @@ -0,0 +1,410 @@ +//! The sign-in chain against a local mock of the Microsoft, Xbox Live and Minecraft endpoints +//! (recorded response shapes, mock tokens only), and the keychain abstraction in memory. +use super::*; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::sync::Arc; + +const UUID: &str = "069a79f444e94726a5befca90e38aaf5"; + +/// What the mock answers and what it was asked. +#[derive(Default)] +struct Mock { + /// Polls left before the token endpoint stops saying authorization_pending. + pending: usize, + xerr: Option, + owns_game: bool, + no_profile: bool, + /// Every request: method, path and body. + log: Vec<(String, String, String)>, +} + +fn reply(status: u16, body: Value) -> (u16, String) { + (status, body.to_string()) +} + +fn route(mock: &mut Mock, method: &str, path: &str, auth: &str, body: &str) -> (u16, String) { + let form = |key: &str| { + body.split('&') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v.replace('+', " ").replace("%3A", ":").replace("%20", " ")) + }; + match (method, path) { + ("POST", "/ms/devicecode") => { + assert_eq!(form("client_id").as_deref(), Some("test-client")); + assert_eq!(form("scope").as_deref(), Some(SCOPE)); + reply( + 200, + json!({"user_code": "ABCD-EFGH", "device_code": "dev-1", "verification_uri": "https://www.microsoft.com/link", "expires_in": 900, "interval": 1}), + ) + } + ("POST", "/ms/token") => match form("grant_type").as_deref() { + Some("urn:ietf:params:oauth:grant-type:device_code") if mock.pending > 0 => { + mock.pending -= 1; + reply(400, json!({"error": "authorization_pending"})) + } + Some("urn:ietf:params:oauth:grant-type:device_code") => { + assert_eq!(form("device_code").as_deref(), Some("dev-1")); + reply( + 200, + json!({"access_token": "ms-access-1", "refresh_token": "ms-refresh-1", "expires_in": 3600}), + ) + } + Some("refresh_token") if form("refresh_token").as_deref() == Some("ms-refresh-1") => { + reply( + 200, + json!({"access_token": "ms-access-2", "refresh_token": "ms-refresh-2"}), + ) + } + _ => reply(400, json!({"error": "invalid_grant"})), + }, + ("POST", "/xbl") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert!(v["Properties"]["RpsTicket"] + .as_str() + .unwrap() + .starts_with("d=ms-access-")); + assert_eq!(v["RelyingParty"], "http://auth.xboxlive.com"); + reply( + 200, + json!({"Token": "xbl-token", "DisplayClaims": {"xui": [{"uhs": "uhs-1"}]}}), + ) + } + ("POST", "/xsts") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["Properties"]["UserTokens"][0], "xbl-token"); + assert_eq!(v["RelyingParty"], "rp://api.minecraftservices.com/"); + match mock.xerr { + Some(code) => reply(401, json!({"Identity": "0", "XErr": code, "Message": ""})), + None => reply( + 200, + json!({"Token": "xsts-token", "DisplayClaims": {"xui": [{"uhs": "uhs-1", "xid": "2535400000000000"}]}}), + ), + } + } + ("POST", "/mc/authentication/login_with_xbox") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["identityToken"], "XBL3.0 x=uhs-1;xsts-token"); + reply( + 200, + json!({"username": "mock", "access_token": "mc-token", "token_type": "Bearer", "expires_in": 86400}), + ) + } + ("GET", "/mc/entitlements/mcstore") => { + assert_eq!(auth, "Bearer mc-token"); + let items = if mock.owns_game { + json!([{"name": "product_minecraft", "signature": "x"}, {"name": "game_minecraft", "signature": "x"}]) + } else { + json!([]) + }; + reply(200, json!({"items": items, "signature": "x", "keyId": "1"})) + } + ("GET", "/mc/minecraft/profile") if mock.no_profile => reply( + 404, + json!({"path": "/minecraft/profile", "errorType": "NOT_FOUND", "error": "NOT_FOUND"}), + ), + ("GET", "/mc/minecraft/profile") => reply( + 200, + json!({ + "id": UUID, "name": "Notch", + "skins": [{"id": "s1", "state": "ACTIVE", "url": "http://textures.minecraft.net/texture/abc", "variant": "SLIM"}], + "capes": [{"id": "c1", "state": "INACTIVE", "url": "http://textures.minecraft.net/texture/cape1", "alias": "Migrator"}, + {"id": "c2", "state": "ACTIVE", "url": "http://textures.minecraft.net/texture/cape2", "alias": "Vanilla"}], + }), + ), + _ => reply(404, json!({"error": "NotFound"})), + } +} + +/// A one-thread HTTP/1.1 server: one request per connection. +fn serve(mock: Arc>) -> Endpoints { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + if reader.read_line(&mut line).is_err() { + continue; + } + let mut parts = line.split_whitespace(); + let (method, path) = ( + parts.next().unwrap_or("").to_owned(), + parts.next().unwrap_or("").to_owned(), + ); + let (mut length, mut auth) = (0, String::new()); + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + let header = header.trim_end(); + if header.is_empty() { + break; + } + let (k, v) = header.split_once(':').unwrap(); + match k.to_ascii_lowercase().as_str() { + "content-length" => length = v.trim().parse().unwrap(), + "authorization" => auth = v.trim().to_owned(), + _ => {} + } + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let body = String::from_utf8(body).unwrap(); + let (status, text) = { + let mut m = mock.lock().unwrap(); + m.log.push((method.clone(), path.clone(), body.clone())); + route(&mut m, &method, &path, &auth, &body) + }; + let _ = write!( + stream, + "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}", + text.len() + ); + } + }); + Endpoints { + microsoft: format!("{base}/ms"), + xbox_user: format!("{base}/xbl"), + xsts: format!("{base}/xsts"), + minecraft: format!("{base}/mc"), + } +} + +fn mock(f: impl FnOnce(&mut Mock)) -> (Arc>, Endpoints) { + let mut m = Mock { + owns_game: true, + ..Default::default() + }; + f(&mut m); + let m = Arc::new(Mutex::new(m)); + let ep = serve(m.clone()); + (m, ep) +} + +#[test] +fn the_whole_chain() { + let (m, ep) = mock(|m| m.pending = 2); + let code = device_code(&ep, "test-client").unwrap(); + assert_eq!( + (code.user_code.as_str(), code.verification_uri.as_str()), + ("ABCD-EFGH", "https://www.microsoft.com/link") + ); + let ms = wait_for_sign_in(&ep, "test-client", &code, &|| false).unwrap(); + let (account, secrets) = finish_sign_in(&ep, ms).unwrap(); + assert_eq!( + account, + Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: Some(( + "http://textures.minecraft.net/texture/abc".into(), + "slim".into() + )), + cape: Some("http://textures.minecraft.net/texture/cape2".into()), + } + ); + assert_eq!(secrets.minecraft_token, "mc-token"); + assert_eq!(secrets.xuid.as_deref(), Some("2535400000000000")); + assert!(secrets.minecraft_expires_at > now() + 80000); + // Two pending polls, then the token; then Xbox, XSTS, Minecraft, entitlements, profile. + let paths: Vec = m + .lock() + .unwrap() + .log + .iter() + .map(|(_, p, _)| p.clone()) + .collect(); + assert_eq!( + paths, + [ + "/ms/devicecode", + "/ms/token", + "/ms/token", + "/ms/token", + "/xbl", + "/xsts", + "/mc/authentication/login_with_xbox", + "/mc/entitlements/mcstore", + "/mc/minecraft/profile" + ] + ); + assert!(!format!("{secrets:?}").contains("mc-token")); +} + +#[test] +fn refresh_only_when_the_token_runs_out() { + let (m, ep) = mock(|_| {}); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let good = Secrets { + refresh_token: "ms-refresh-1".into(), + minecraft_token: "old".into(), + minecraft_expires_at: now() + 7200, + xuid: None, + }; + let (_, kept) = fresh(&ep, "test-client", &account, good).unwrap(); + assert_eq!(kept.minecraft_token, "old"); + assert!(m.lock().unwrap().log.is_empty()); + let stale = Secrets { + minecraft_expires_at: now() + 60, + ..kept.clone() + }; + let (renewed_account, renewed) = fresh(&ep, "test-client", &account, stale).unwrap(); + assert_eq!( + ( + renewed.refresh_token.as_str(), + renewed.minecraft_token.as_str() + ), + ("ms-refresh-2", "mc-token") + ); + assert!(renewed_account.skin.is_some()); + let revoked = Secrets { + refresh_token: "revoked".into(), + minecraft_expires_at: 0, + ..kept + }; + assert_eq!( + fresh(&ep, "test-client", &account, revoked).unwrap_err(), + SIGN_IN_AGAIN + ); +} + +#[test] +fn refusals_have_messages() { + let tokens = || MsTokens { + access: "ms-access-1".into(), + refresh: "r".into(), + }; + let (_, ep) = mock(|m| m.xerr = Some(2148916233)); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("no Xbox profile")); + let (_, ep) = mock(|m| m.xerr = Some(2148916238)); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("child account")); + let (_, ep) = mock(|m| m.owns_game = false); + assert_eq!( + finish_sign_in(&ep, tokens()).unwrap_err(), + "This account doesn't own Minecraft: Java Edition." + ); + let (_, ep) = mock(|m| m.no_profile = true); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("no Minecraft profile")); + assert_eq!( + oauth_error(&json!({"error": "authorization_declined"})), + "Sign-in was declined in the browser." + ); + // Nothing listening: a message, not a URL. + let dead = Endpoints { + microsoft: "http://127.0.0.1:9/ms".into(), + ..Endpoints::live() + }; + assert_eq!( + device_code(&dead, "x").unwrap_err(), + "Could not reach Microsoft. Check your internet connection." + ); +} + +#[test] +fn cancelling_stops_the_wait() { + let (_, ep) = mock(|m| m.pending = 100); + let code = device_code(&ep, "test-client").unwrap(); + assert_eq!( + wait_for_sign_in(&ep, "test-client", &code, &|| true).unwrap_err(), + "Sign-in cancelled." + ); +} + +#[test] +fn accounts_keep_secrets_in_the_store_only() { + let store = MemoryStore::default(); + let mut accounts = Accounts::default(); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let secrets = Secrets { + refresh_token: "r".into(), + minecraft_token: "mc-secret".into(), + minecraft_expires_at: 1, + xuid: None, + }; + accounts.add(&store, account.clone(), &secrets).unwrap(); + assert_eq!(accounts.selected(), Some(&account)); + assert_eq!(accounts.find("notch"), Some(&account)); + assert_eq!( + accounts.find("069a79f4-44e9-4726-a5be-fca90e38aaf5"), + Some(&account) + ); + let saved = serde_json::to_string(&accounts).unwrap(); + assert!(!saved.contains("mc-secret") && !saved.contains("\"r\"")); + assert!(store.get(UUID).unwrap().unwrap().contains("mc-secret")); + accounts.remove(&store, UUID).unwrap(); + assert_eq!( + (accounts.selected(), store.get(UUID).unwrap()), + (None, None) + ); + assert!(!store.persistent()); +} + +#[test] +fn session_files_are_private_and_complete() { + let dir = std::env::temp_dir().join(format!("horizon-launcher-session-{}", std::process::id())); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let secrets = Secrets { + refresh_token: "r".into(), + minecraft_token: "mc-token".into(), + minecraft_expires_at: 1, + xuid: Some("25".into()), + }; + let path = write_session_file(&dir, &account, &secrets).unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!( + v, + json!({"name": "Notch", "uuid": UUID, "access_token": "mc-token", "user_type": "msa", "xuid": "25"}) + ); + // The refresh token never leaves the keychain. + assert!(!v.to_string().contains("\"r\"")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + let other = write_session_file(&dir, &account, &secrets).unwrap(); + assert_ne!(path, other); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn client_id_is_configuration() { + // The run-time variable overrides; empty means not configured. + std::env::set_var("HORIZON_MSA_CLIENT_ID", " "); + assert_eq!(client_id(), None); + std::env::set_var( + "HORIZON_MSA_CLIENT_ID", + "00000000-1111-2222-3333-444444444444", + ); + assert_eq!( + client_id().as_deref(), + Some("00000000-1111-2222-3333-444444444444") + ); + std::env::remove_var("HORIZON_MSA_CLIENT_ID"); +} diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 354837d2c..152aa3f69 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -996,7 +996,12 @@ fn need_prepared(tag: &str) -> Result<(), String> { /// The client's command, once its resources are prepared. pub fn client(tag: &str) -> Result { need_prepared(tag)?; - Ok(client_command(tag)) + let mut cmd = client_command(tag); + // A sign-in that can't be renewed (no network, expired) still lets the game start, offline. + if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { + eprintln!("Playing offline: {e}"); + } + Ok(cmd) } /// The dedicated server's command in `folder`, once prepared and the EULA is agreed to. @@ -1387,6 +1392,11 @@ pub enum Msg { LauncherUpdated(Result<(), String>), /// `reuse_prepared_everywhere` prepared these versions. Reused(Vec<(String, String)>), + /// Whether secrets are kept in the OS keychain (else only until the launcher closes). + Keychain(bool), + /// The selected account's session file for the game about to start (none = offline), or + /// why it could not be renewed. + Session(Result, String>), } /// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`. diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index b624b2259..46827ca85 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -1,6 +1,7 @@ //! `horizon-launcher `: the same steps as the window, from a terminal. Every //! command goes through `backend`; this file only parses arguments and prints. use clap::{Parser, Subcommand}; +use horizon_launcher::account::{self, Accounts}; use horizon_launcher::backend::{self, Release}; use std::io::{IsTerminal, Write}; use std::path::PathBuf; @@ -20,6 +21,23 @@ struct Cli { command: Option, } +#[derive(Subcommand)] +enum AccountCmd { + /// The signed-in accounts and which one plays + List, + /// Sign in with a Microsoft account in your browser (device code) + SignIn, + /// Sign out: the account's tokens leave the keychain + SignOut { + /// Its name or UUID + who: String, + }, + /// Play as this account + Select { who: String }, + /// Play offline, without an account + Offline, +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -61,6 +79,11 @@ enum Cmd { Notes { tag: Option }, /// Show the Discord, sponsor and website links Links, + /// Microsoft accounts: list them (the default), sign in, sign out, or pick the one that plays + Account { + #[command(subcommand)] + action: Option, + }, /// Show or set the game's menu style (classic is vanilla's own screens) MenuStyle { /// Omit to show the current style @@ -254,6 +277,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { ); } } + Cmd::Account { action } => account_command(action.unwrap_or(AccountCmd::List), as_json)?, Cmd::Links => { let links = backend::links(); if as_json { @@ -331,3 +355,76 @@ fn update(check: bool, as_json: bool) -> Result<(), String> { } Ok(()) } + +/// `account …`: names and UUIDs only; tokens are never printed. +fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { + let mut accounts = Accounts::load(); + let find = |accounts: &Accounts, who: &str| { + accounts + .find(who) + .cloned() + .ok_or_else(|| format!("No signed-in account {who}. See `horizon-launcher account`.")) + }; + match action { + AccountCmd::List => { + if as_json { + json(serde_json::json!({ + "accounts": accounts.accounts.iter().map(|a| serde_json::json!({ + "name": a.name, "uuid": a.uuid, + "selected": accounts.selected.as_ref() == Some(&a.uuid), + })).collect::>(), + "sign_in_configured": account::client_id().is_some(), + })); + } else if accounts.accounts.is_empty() { + println!("No Microsoft account signed in: the game plays offline."); + } else { + for a in &accounts.accounts { + let mark = if accounts.selected.as_ref() == Some(&a.uuid) { + "*" + } else { + " " + }; + println!("{mark} {} {}", a.name, a.uuid); + } + if accounts.selected().is_none() { + println!("Playing offline (`account select NAME` to play as one)."); + } + } + } + AccountCmd::SignIn => { + let client_id = account::client_id().ok_or(account::NOT_CONFIGURED)?; + let ep = account::Endpoints::live(); + let code = account::device_code(&ep, &client_id)?; + eprintln!( + "To sign in, open {} in a browser and enter the code {}", + code.verification_uri, code.user_code + ); + let ms = account::wait_for_sign_in(&ep, &client_id, &code, &|| false)?; + let (signed_in, secrets) = account::finish_sign_in(&ep, ms)?; + accounts.add(account::store(), signed_in.clone(), &secrets)?; + accounts.save()?; + println!("Signed in as {}.", signed_in.name); + if !account::store().persistent() { + eprintln!("{}", account::NO_KEYCHAIN); + } + } + AccountCmd::SignOut { who } => { + let a = find(&accounts, &who)?; + accounts.remove(account::store(), &a.uuid)?; + accounts.save()?; + println!("Signed out {}.", a.name); + } + AccountCmd::Select { who } => { + let a = find(&accounts, &who)?; + accounts.selected = Some(a.uuid); + accounts.save()?; + println!("The game plays as {}.", a.name); + } + AccountCmd::Offline => { + accounts.selected = None; + accounts.save()?; + println!("The game plays offline."); + } + } + Ok(()) +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 64766a00c..cac481c4a 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -1,2 +1,3 @@ //! The launcher's core, shared by the GUI, the CLI and the MCP server. +pub mod account; pub mod backend; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index be556226f..b3fade865 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -13,6 +13,7 @@ use gpui::{ RenderImage, ScrollHandle, SharedString, Stateful, Subscription, TitlebarOptions, Window, WindowBounds, WindowOptions, }; +use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; use std::borrow::Cow; use std::collections::VecDeque; @@ -147,6 +148,13 @@ struct Launcher { client_started: Option, crash: Option, server: Option, + /// Microsoft accounts (accounts.json), the sign-in under way and what it last showed. + accounts: Accounts, + sign_in: Option, + sign_in_state: Option, + keychain: bool, + /// The game is waiting for its session (a token renewal) before it starts. + starting_client: Option, server_log: VecDeque, server_error: Option, input: String, @@ -228,6 +236,11 @@ impl Launcher { client_started: None, crash: None, server: None, + accounts: Accounts::load(), + sign_in: None, + sign_in_state: None, + keychain: true, + starting_client: None, server_log: VecDeque::new(), server_error: None, input: String::new(), @@ -239,6 +252,11 @@ impl Launcher { _appearance: appearance, }; let tx = this.tx.clone(); + let keychain_tx = this.tx.clone(); + // Asking the keychain can block (D-Bus), so not on this thread. + std::thread::spawn(move || { + let _ = keychain_tx.send(Msg::Keychain(account::store().persistent())); + }); std::thread::spawn(move || { let reused = backend::reuse_prepared_everywhere(); if !reused.is_empty() { @@ -331,6 +349,25 @@ impl Launcher { Msg::Links(links) => self.links = links, // The page reads is_prepared when drawn; `changed` redraws it. Msg::Reused(_) => self.installed = backend::installed(), + Msg::Keychain(persistent) => self.keychain = persistent, + Msg::Session(session) => { + if let Some(tag) = self.starting_client.take() { + let mut cmd = backend::client_command(&tag); + match session { + Ok(Some(file)) => { + cmd.arg("--session-file").arg(file); + } + Ok(None) => {} + // Still play, offline, and say why. + Err(e) => self.client_error = Some(format!("Playing offline: {e}")), + } + self.accounts = Accounts::load(); + match backend::spawn(Job::Client, cmd, self.tx.clone()) { + Ok(r) => self.client = Some(r), + Err(e) => self.client_error = Some(e), + } + } + } Msg::Progress(tag, p) => { self.bar = (self.bar.1, p); self.installing = Some((tag, p)); @@ -454,6 +491,17 @@ impl Launcher { } } } + if let Some(sign_in) = &self.sign_in { + let state = sign_in.state(); + let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); + if changed_state { + if let SignInState::Done(Ok(_)) = state { + self.accounts = Accounts::load(); + } + self.sign_in_state = Some(state); + changed = true; + } + } if self.checked.is_some_and(|at| at.elapsed() > CHECK_EVERY) { self.check_updates(); } @@ -545,7 +593,7 @@ impl Launcher { }; match self.mode { Mode::Client => { - if self.client.is_some() { + if self.client.is_some() || self.starting_client.is_some() { return; } self.client_error = None; @@ -554,10 +602,30 @@ impl Launcher { // A little earlier than the spawn: file times can be coarse. self.client_started = Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); - match backend::spawn(Job::Client, backend::client_command(&tag), self.tx.clone()) { - Ok(r) => self.client = Some(r), - Err(e) => self.client_error = Some(e), - } + // The session (a network round trip when the token needs renewing) comes first; + // `drain` starts the game when it arrives. + self.starting_client = Some(tag); + let tx = self.tx.clone(); + std::thread::spawn(move || { + let session = (|| { + let mut accounts = Accounts::load(); + let Some((a, secrets)) = account::session_for_launch( + &account::Endpoints::live(), + account::store(), + &mut accounts, + )? + else { + return Ok(None); + }; + account::write_session_file( + &backend::game_home().join("sessions"), + &a, + &secrets, + ) + .map(Some) + })(); + let _ = tx.send(Msg::Session(session)); + }); } Mode::Server => { if let Some(server) = &mut self.server { @@ -1163,7 +1231,7 @@ impl Launcher { let version = backend::game_version(&tag); let hero = self.hero(&tag, &version, prepared, cx); let running = match self.mode { - Mode::Client => self.client.is_some(), + Mode::Client => self.client.is_some() || self.starting_client.is_some(), Mode::Server => self.server.is_some(), }; let play_label = match (self.mode, running) { @@ -1263,6 +1331,27 @@ impl Launcher { )), &t, )); + if self.mode == Mode::Client { + let who = match self.accounts.selected() { + Some(a) => div().child(format!("{} (Microsoft account)", a.name)), + None => div() + .text_color(t.muted) + .child("Offline: online servers need a Microsoft account."), + }; + rows = rows.child(divider(&t)).child(row( + "Playing as", + who, + Some( + button("accounts", "Accounts…", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.go(Page::Settings); + cx.notify(); + }, + )), + ), + &t, + )); + } if self.mode == Mode::Server { let folder = self .settings @@ -1761,6 +1850,7 @@ impl Launcher { div() .flex() .flex_col() + .child(self.account_rows(cx)) .child(divider(&t)) .child(row("Updates", auto, Some(toggle), &t)) .child(divider(&t)) @@ -1808,6 +1898,167 @@ impl Launcher { .child(agents) } + /// Settings' Microsoft accounts: who is signed in and plays, the sign-in with its code. + fn account_rows(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + let mut rows = div().flex().flex_col(); + let selected = self.accounts.selected.clone(); + for (i, a) in self.accounts.accounts.clone().into_iter().enumerate() { + let plays = selected.as_ref() == Some(&a.uuid); + let value = div() + .flex() + .flex_col() + .gap(px(2.)) + .child(a.name.clone()) + .child( + div() + .text_size(px(theme::SMALL)) + .text_color(t.muted) + .child(if plays { "Plays" } else { "Signed in" }), + ); + let uuid = a.uuid.clone(); + let mut actions = div().flex().gap(px(4.)); + if plays { + actions = actions.child( + button(format!("offline-{i}"), "Play offline", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.accounts.selected = None; + let _ = this.accounts.save(); + cx.notify(); + }), + ), + ); + } else { + let uuid = uuid.clone(); + actions = actions.child( + button(format!("select-{i}"), "Play as", Kind::Secondary, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.accounts.selected = Some(uuid.clone()); + let _ = this.accounts.save(); + cx.notify(); + }), + ), + ); + } + actions = actions.child( + button(format!("sign-out-{i}"), "Sign out", Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + let store = account::store(); + if let Err(e) = this.accounts.remove(store, &uuid) { + this.sign_in_state = Some(SignInState::Done(Err(e))); + } + let _ = this.accounts.save(); + cx.notify(); + }, + )), + ); + let label = if i == 0 { "Accounts" } else { "" }; + rows = rows.child(divider(&t)).child(row( + label, + value, + Some(actions.id(SharedString::from(format!("account-{i}")))), + &t, + )); + } + let configured = account::client_id().is_some(); + let busy = matches!( + self.sign_in_state, + Some(SignInState::Starting | SignInState::Code(_)) + ); + let value = match &self.sign_in_state { + _ if !configured => div().text_color(t.muted).child(account::NOT_CONFIGURED), + Some(SignInState::Starting) => div().text_color(t.muted).child("Asking Microsoft…"), + Some(SignInState::Code(code)) => div() + .flex() + .flex_col() + .gap(px(4.)) + .child(format!( + "Open {} in your browser and enter this code:", + code.verification_uri + )) + .child( + div() + .font_family(theme::MONO) + .text_size(px(theme::LARGE)) + .font_weight(FontWeight::MEDIUM) + .child(code.user_code.clone()), + ), + Some(SignInState::Done(Ok(a))) => div().child(format!("Signed in as {}.", a.name)), + Some(SignInState::Done(Err(e))) => div().text_color(t.danger).child(e.clone()), + None if self.accounts.accounts.is_empty() => div().text_color(t.muted).child( + "Sign in to play on online servers with your name and skin. Without an account the game plays offline.", + ), + None => div().text_color(t.muted).child("Add another account."), + }; + let value = if self.keychain || self.accounts.accounts.is_empty() { + value + } else { + div().flex().flex_col().gap(px(4.)).child(value).child( + div() + .text_size(px(theme::SMALL)) + .text_color(t.muted) + .child(account::NO_KEYCHAIN), + ) + }; + let action = if !configured { + None + } else if let Some(SignInState::Code(code)) = &self.sign_in_state { + let (uri, user_code) = (code.verification_uri.clone(), code.user_code.clone()); + Some( + div() + .flex() + .gap(px(4.)) + .child( + button("sign-in-copy", "Copy code", Kind::Secondary, &t).on_click( + move |_, _, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + user_code.clone(), + )) + }, + ), + ) + .child( + button("sign-in-open", "Open link", Kind::Secondary, &t) + .on_click(move |_, _, cx| cx.open_url(&uri)), + ) + .child( + button("sign-in-cancel", "Cancel", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(s) = this.sign_in.take() { + s.cancel(); + } + this.sign_in_state = None; + cx.notify(); + }, + )), + ), + ) + } else if busy { + None + } else { + Some(div().child( + button("sign-in", "Sign in with Microsoft", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.sign_in = Some(SignIn::start()); + this.sign_in_state = Some(SignInState::Starting); + cx.notify(); + }), + ), + )) + }; + let label = if self.accounts.accounts.is_empty() { + "Account" + } else { + "" + }; + rows.child(divider(&t)).child(row( + label, + value, + action.map(|a| a.id("sign-in-actions")), + &t, + )) + } + fn console(&self, cx: &mut Context) -> Div { let t = self.theme; let running = self.server.is_some(); diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index a8fd6de9a..d842ade2e 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -1,6 +1,7 @@ //! `horizon-launcher mcp`: the Model Context Protocol over stdin and stdout (JSON-RPC 2.0, one //! message per line), so AI agents can install, prepare and run Horizon. Every tool goes through //! `backend`. A server started here lives as long as the session. +use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Logged}; use serde_json::{json, Value}; use std::io::{BufRead, Write}; @@ -12,6 +13,7 @@ const PROTOCOL: &str = "2025-06-18"; struct Session { server: Option, client: Option, + sign_in: Option, } fn tools() -> Value { @@ -42,6 +44,12 @@ fn tools() -> Value { "inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } }, { "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.", "inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "How many lines of latest.log (default 100)." }, "crash": { "type": "boolean", "description": "Return the newest crash report instead." } } } }, + { "name": "accounts", "description": "The Microsoft accounts signed in to the launcher (names and UUIDs, never tokens), which one the game plays as (none = offline), and how a sign-in started with sign_in is going.", "inputSchema": none }, + { "name": "sign_in", "description": "Start signing in a Microsoft account: returns a link and a code the player enters in their browser. The sign-in finishes in the background; check it with accounts. Only when the player asks to sign in.", "inputSchema": none }, + { "name": "sign_out", "description": "Sign an account out of the launcher (its tokens leave the keychain).", + "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "Its name or UUID." } }, "required": ["account"] } }, + { "name": "select_account", "description": "Choose the account the game plays as, or \"offline\" to play without one.", + "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "A name or UUID, or \"offline\"." } }, "required": ["account"] } }, { "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none }, ]) } @@ -242,6 +250,70 @@ impl Session { })) .unwrap()) } + "accounts" => { + let accounts = Accounts::load(); + let sign_in = self.sign_in.as_ref().map(|s| match s.state() { + SignInState::Starting => json!({ "state": "starting" }), + SignInState::Code(c) => json!({ "state": "waiting for the player", "link": c.verification_uri, "code": c.user_code }), + SignInState::Done(Ok(a)) => json!({ "state": "signed in", "name": a.name }), + SignInState::Done(Err(e)) => json!({ "state": "failed", "error": e }), + }); + Ok(serde_json::to_string_pretty(&json!({ + "accounts": accounts.accounts.iter().map(|a| json!({ "name": a.name, "uuid": a.uuid })).collect::>(), + "plays_as": accounts.selected().map(|a| a.name.clone()), + "sign_in_configured": account::client_id().is_some(), + "keychain": account::store().persistent(), + "sign_in": sign_in, + })) + .unwrap()) + } + "sign_in" => { + account::client_id().ok_or(account::NOT_CONFIGURED)?; + if let Some(s) = self.sign_in.take() { + s.cancel(); + } + let sign_in = SignIn::start(); + let deadline = std::time::Instant::now() + Duration::from_secs(30); + let state = loop { + match sign_in.state() { + SignInState::Starting if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(100)) + } + state => break state, + } + }; + self.sign_in = Some(sign_in); + match state { + SignInState::Code(c) => Ok(format!( + "Ask the player to open {} and enter the code {}. Then check accounts.", + c.verification_uri, c.user_code + )), + SignInState::Done(Err(e)) => Err(e), + _ => Err("Microsoft did not answer. Try again.".into()), + } + } + "sign_out" | "select_account" => { + let who = arg_str(args, "account").ok_or("account is required")?; + let mut accounts = Accounts::load(); + if name == "select_account" && who.eq_ignore_ascii_case("offline") { + accounts.selected = None; + accounts.save()?; + return Ok("The game plays offline.".into()); + } + let a = accounts + .find(who) + .cloned() + .ok_or_else(|| format!("No signed-in account {who}."))?; + if name == "sign_out" { + accounts.remove(account::store(), &a.uuid)?; + accounts.save()?; + Ok(format!("Signed out {}.", a.name)) + } else { + accounts.selected = Some(a.uuid); + accounts.save()?; + Ok(format!("The game plays as {}.", a.name)) + } + } _ => Err(format!("Unknown tool {name}")), } } @@ -292,6 +364,7 @@ pub fn serve() -> Result<(), String> { let mut session = Session { server: None, client: None, + sign_in: None, }; let stdin = std::io::stdin(); let mut stdout = std::io::stdout(); From 324eb2836c588fc40412e463845c92070b5d02de Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:58:02 +0200 Subject: [PATCH 14/43] Launcher README: Microsoft accounts Co-Authored-By: Claude Opus 5.5 --- launcher/README.md | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/launcher/README.md b/launcher/README.md index f77d345d2..b70b4be82 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -70,9 +70,14 @@ The same binary is a command-line tool; without a subcommand it opens the window 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 + horizon-launcher account [list] the Microsoft accounts signed in (* = plays) + horizon-launcher account sign-in sign in in your browser with a code + horizon-launcher account sign-out + horizon-launcher account select play as this account + horizon-launcher account offline play without an account `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`, `logs`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `update --check`, `logs`, `account`). 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). @@ -84,13 +89,29 @@ 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`, `logs` and -`check_updates`. +`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs`, +`check_updates`, `accounts`, `sign_in` (returns the link and code for the player; the sign-in +finishes in the background), `sign_out` and `select_account`. 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`. +## Microsoft accounts + +Settings → Accounts signs in a Microsoft account to play on online-mode servers under your own +name and skin: the launcher shows a code, you enter it at microsoft.com/link, and the launcher +checks that the account owns Minecraft: Java Edition. The Play page says who plays ("Playing as"); +without an account the game plays offline, as before. Tokens live in the system keychain (Keychain, +Credential Manager, or the Secret Service on Linux), never in a file, a log or the command line; +`accounts.json` in the data folder keeps only names and UUIDs. Without a keychain you stay signed +in until the launcher closes. When the game starts, it gets the session in a private file it +deletes as soon as it has read it. Sign out removes the tokens. + +Sign-in needs Horizon's own Azure app registration: its client ID is built in from +`HORIZON_MSA_CLIENT_ID` (and `HORIZON_MSA_CLIENT_ID` at run time overrides it; empty = not +configured). How it works: [docs/microsoft-account.md](../docs/microsoft-account.md). + ## Logs and crash reports The game writes its log to `logs/latest.log` in the game folder (`HORIZON_HOME`, else From 6bed9b92caac62e29a1e462b9123d6ac321cf024 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:58:17 +0200 Subject: [PATCH 15/43] launcher.yml: build in HORIZON_MSA_CLIENT_ID from the repository variable Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index db8c5fac6..50a9ca9ca 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -33,6 +33,9 @@ jobs: runs-on: ${{ matrix.os }} env: RUSTFLAGS: ${{ matrix.rustflags }} + # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository + # variable, not a secret. Unset, the launcher says sign-in is not configured. + HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} defaults: run: working-directory: launcher From d4e0dc49177a10d28bbddc4f79720ade32fdfe24 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:07:47 +0200 Subject: [PATCH 16/43] Settings subtitle mentions accounts Co-Authored-By: Claude Opus 5.5 --- launcher/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/src/main.rs b/launcher/src/main.rs index b3fade865..c81256b18 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1843,7 +1843,7 @@ impl Launcher { .gap(px(24.)) .child(page_header( "Settings", - "Updates, menus, and the launcher itself.", + "Accounts, updates, menus, and the launcher itself.", &t, )) .child( From 8987369b07db03fd98e825b40071c3aed663775c Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:09:42 +0100 Subject: [PATCH 17/43] Fix inventory banner face depth ordering --- crates/horizon-client/src/item_render/gui.rs | 138 ++++++++++++++---- .../src/item_render/gui/depth.rs | 119 +++++++++++++++ 2 files changed, 229 insertions(+), 28 deletions(-) create mode 100644 crates/horizon-client/src/item_render/gui/depth.rs diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index bbdb2cb02..9456b26e4 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -10,6 +10,8 @@ use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; use std::{collections::HashMap, f32::consts::PI}; +mod depth; + /// `Lighting.DIFFUSE_LIGHT_0` and `DIFFUSE_LIGHT_1`. fn diffuse_lights() -> (Vec3, Vec3) { ( @@ -177,35 +179,19 @@ fn draw_quads( rect: [f32; 4], time: f32, ) { - // Back-face culling: front faces wind counter-clockwise on screen with y up. - let mut visible: Vec<(f32, usize)> = quads - .iter() - .enumerate() - .filter(|(_, q)| { - let p = q.pos.map(|v| Vec2::new(v.x, -v.y)); - let area: f32 = (0..4) - .map(|i| { - let (a, b) = (p[i], p[(i + 1) % 4]); - a.x * b.y - b.x * a.y - }) - .sum(); - area > 0.0 - }) - .map(|(i, q)| (q.pos.iter().map(|v| v.z).sum::() / 4.0, i)) - .collect(); - // Far to near; the depth buffer of the item atlas, approximated per quad. - visible.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, i) in visible { - let q = &quads[i]; - let points: [Point; 4] = std::array::from_fn(|k| Point { - p: Vec2::new(q.pos[k].x, q.pos[k].y), - uv: q.uv[k], - }); + for face in depth::sort(quads) { + let q = &quads[face.quad]; + let points: Vec<_> = face + .corners + .iter() + .map(|v| Point { + p: v.pos.truncate(), + uv: v.uv, + }) + .collect(); let color = lit_color(q, lights); - for tri in [ - [points[0], points[1], points[2]], - [points[0], points[2], points[3]], - ] { + for i in 1..points.len().saturating_sub(1) { + let tri = [points[0], points[i], points[i + 1]]; let fan = clip_triangle(tri, rect); if fan.len() < 3 { continue; @@ -275,6 +261,102 @@ pub fn draw_banner_result( mod tests { use super::*; + fn face(y0: f32, y1: f32, z: impl Fn(f32) -> f32, color: u32) -> ItemQuad { + ItemQuad { + pos: [(0.0, y0), (0.0, y1), (8.0, y1), (8.0, y0)].map(|(x, y)| Vec3::new(x, y, z(y))), + uv: [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], + normal: Vec3::Z, + color, + foil: Foil::None, + light_emission: 0, + } + } + + // Sample the emitted triangles in draw order, using opaque test faces. + fn color_at(batch: &HudBatch, p: Vec2) -> Option { + batch.vertices.chunks_exact(3).rev().find_map(|tri| { + let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos)); + let area = (b - a).perp_dot(c - a); + if area.abs() < 1e-6 { + return None; + } + let u = (b - p).perp_dot(c - p) / area; + let v = (c - p).perp_dot(a - p) / area; + let w = 1.0 - u - v; + (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color) + }) + } + + #[test] + fn banner_cloth_occludes_the_support_at_the_top_edge() { + // The cloth is nearer where it overlaps the bar, although its + // average depth is farther away because it slopes along its height. + let bar = face(0.0, 1.0, |_| 0.0, 0xFF80_4000); + let cloth = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF); + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &[bar, cloth], + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + assert_eq!(color_at(&batch, Vec2::new(4.0, 0.5)), Some(u32::MAX)); + } + + #[test] + fn intersecting_faces_change_draw_order_at_their_intersection() { + let flat = face(0.0, 8.0, |_| 0.0, 0xFFFF_0000); + let tilted = face(0.0, 8.0, |y| y - 4.0, 0xFF00_00FF); + for quads in [[flat, tilted], [tilted, flat]] { + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &quads, + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + assert_eq!( + color_at(&batch, Vec2::new(4.0, 2.0)), + Some(lit_color(&flat, (Vec3::Z, Vec3::Z))) + ); + assert_eq!( + color_at(&batch, Vec2::new(4.0, 6.0)), + Some(lit_color(&tilted, (Vec3::Z, Vec3::Z))) + ); + // The cut must interpolate the texture along with the position. + for v in &batch.vertices { + assert!((v.uv[0] - v.pos[0] / 8.0).abs() < 1e-6); + assert!((v.uv[1] - v.pos[1] / 8.0).abs() < 1e-6); + } + } + } + + #[test] + fn coplanar_pattern_layers_keep_submission_order() { + let base = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF); + let pattern = ItemQuad { + color: 0xFF00_00FF, + ..base + }; + let quads = [face(0.0, 1.0, |_| 0.0, 0xFF80_4000), base, pattern]; + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &quads, + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + for y in [0.5, 6.0] { + assert_eq!( + color_at(&batch, Vec2::new(4.0, y)), + Some(lit_color(&quads[2], (Vec3::Z, Vec3::Z))) + ); + } + } + #[test] fn flat_lights_match_joml() { // new Matrix4f().rotationY(-PI/8).rotateX(3PI/4).transformDirection(L0). diff --git a/crates/horizon-client/src/item_render/gui/depth.rs b/crates/horizon-client/src/item_render/gui/depth.rs new file mode 100644 index 000000000..9fecfdee7 --- /dev/null +++ b/crates/horizon-client/src/item_render/gui/depth.rs @@ -0,0 +1,119 @@ +//! Back-to-front ordering for the orthographic GUI item view (near is +Z). +//! Whole-face average depths fail when a long, tilted face overlaps a short +//! one, such as a banner's cloth and support. Partition faces by their planes +//! instead, splitting intersecting faces with their UVs. Coplanar faces keep +//! submission order so banner/shield pattern layers still paint bottom first. +use super::super::ItemQuad; +use glam::{Vec3, Vec4}; + +#[derive(Clone, Copy)] +pub(super) struct Corner { + pub pos: Vec3, + pub uv: [f32; 2], +} + +pub(super) struct Face { + pub quad: usize, + pub corners: Vec, +} + +const EPSILON: f32 = 1e-4; + +fn split(face: Face, distances: &[f32]) -> (Face, Face) { + let mut back = Vec::new(); + let mut front = Vec::new(); + for i in 0..face.corners.len() { + let a = face.corners[i]; + let b = face.corners[(i + 1) % face.corners.len()]; + let da = distances[i]; + let db = distances[(i + 1) % face.corners.len()]; + if da <= EPSILON { + back.push(a); + } + if da >= -EPSILON { + front.push(a); + } + if (da < -EPSILON && db > EPSILON) || (da > EPSILON && db < -EPSILON) { + let t = da / (da - db); + let corner = Corner { + pos: a.pos.lerp(b.pos, t), + uv: std::array::from_fn(|k| a.uv[k] + (b.uv[k] - a.uv[k]) * t), + }; + back.push(corner); + front.push(corner); + } + } + ( + Face { + quad: face.quad, + corners: back, + }, + Face { + quad: face.quad, + corners: front, + }, + ) +} + +pub(super) fn sort(quads: &[ItemQuad]) -> Vec { + let mut planes = vec![Vec4::ZERO; quads.len()]; + let faces: Vec<_> = quads + .iter() + .enumerate() + .filter_map(|(i, q)| { + let normal = (q.pos[2] - q.pos[0]).cross(q.pos[3] - q.pos[1]); + // Front faces wind counter-clockwise on screen with Y up. + if normal.z >= 0.0 { + return None; + } + let normal = -normal.normalize(); + planes[i] = normal.extend(-normal.dot(q.pos[0])); + Some(Face { + quad: i, + corners: std::array::from_fn::<_, 4, _>(|k| Corner { + pos: q.pos[k], + uv: q.uv[k], + }) + .to_vec(), + }) + }) + .collect(); + let mut out = Vec::new(); + // An explicit stack avoids recursion for models with many parallel faces. + let mut pending = vec![(faces, false)]; + while let Some((faces, emit)) = pending.pop() { + if emit { + out.extend(faces); + continue; + } + let mut faces = faces.into_iter(); + let Some(first) = faces.next() else { continue }; + let plane = planes[first.quad]; + let mut coplanar = vec![first]; + let mut back = Vec::new(); + let mut front = Vec::new(); + for face in faces { + let distances: Vec<_> = face + .corners + .iter() + .map(|c| plane.dot(c.pos.extend(1.0))) + .collect(); + let behind = distances.iter().any(|d| *d < -EPSILON); + let ahead = distances.iter().any(|d| *d > EPSILON); + match (behind, ahead) { + (false, false) => coplanar.push(face), + (true, false) => back.push(face), + (false, true) => front.push(face), + (true, true) => { + let (b, f) = split(face, &distances); + back.push(b); + front.push(f); + } + } + } + pending.push((front, false)); + pending.push((coplanar, true)); + pending.push((back, false)); + } + out +} From aab88753b6825e83d88f12b21895a681b2964e5d Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:15:16 +0100 Subject: [PATCH 18/43] Keep title panorama optional during full resource preparation --- crates/horizon-prepare/src/lib.rs | 3 +- crates/horizon-prepare/src/sounds.rs | 59 ++++++++++++++++++++++++---- docs/native-client.md | 7 ++-- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 534abfc8a..e1c165e8e 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -685,7 +685,8 @@ fn steps( // The JAR holds only gray 1x1 panorama placeholders. Import the indexed // textures afterwards, including on reruns that just extracted the JAR again. - panorama(repo, minecraft, run.log)?; + // Cosmetic assets are optional when preparing from already-imported JARs. + sounds::optional_panorama(repo, minecraft, run.log); // One file each, exported again when the exporter or the jar it reads changed. let single = |what: &str, diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index e0787656d..b18ed3426 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -85,6 +85,15 @@ pub fn panorama(root: &Path, minecraft: Option<&Path>, log: Log) -> Result, log: Log) { + if let Err(error) = panorama(root, minecraft, log) { + log(&format!( + "Title panorama not imported: {error}; run horizon-prepare panorama later" + )); + } +} + const PANORAMA: [&str; 7] = [ "minecraft/textures/gui/title/background/panorama_0.png", "minecraft/textures/gui/title/background/panorama_1.png", @@ -138,6 +147,7 @@ fn copy_assets( } } let mut total: u64 = 0; + let mut copies = Vec::with_capacity(wanted.len()); for (name, info) in &wanted { let hash = info .get("hash") @@ -151,15 +161,14 @@ fn copy_assets( let relative = artifacts::safe_relative(name) .ok_or_else(|| format!("Unsafe asset name {name:?} in the asset index"))?; let source = launcher_object(&store, hash)?; - artifacts::import_copy( - &source, - &target.join("assets").join(relative), - hash, - "sha1", - "", - )?; + copies.push((source, target.join("assets").join(relative), hash)); total += size; } + // Check the entire set before replacing any placeholders: a missing late face + // must not leave a mixture of real textures and gray faces in either entry point. + for (source, destination, hash) in copies { + artifacts::import_copy(&source, &destination, hash, "sha1", "")?; + } log(&format!( "{label} assets ready: {} files, {:.1} MB", wanted.len(), @@ -366,6 +375,42 @@ mod tests { assert!(!f.root.join(".local/horizon-client/9.9/assets").exists()); } + #[test] + fn full_preparation_keeps_placeholders_when_panorama_is_unavailable() { + for missing in ["store", "install", "last-object"] { + let f = Fixture::new(&format!("optional-panorama-{missing}")); + // The JARs and manifest were imported earlier; the launcher need not remain. + artifacts::import_manifest(&Lock::read(&f.root).unwrap(), &f.minecraft).unwrap(); + let target = f.root.join(".local/horizon-client/9.9/assets"); + for name in PANORAMA { + let path = target.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"jar placeholder").unwrap(); + } + match missing { + "store" => fs::remove_dir_all(f.minecraft.join("assets")).unwrap(), + "install" => fs::remove_dir_all(&f.minecraft).unwrap(), + _ => fs::remove_file(f.object(f.objects.len() - 1)).unwrap(), + } + // The repair subcommand remains strict, even for a missing final object. + let error = panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap_err(); + let lines = std::cell::RefCell::new(Vec::new()); + // This is the optional import step used by full preparation after extraction. + optional_panorama(&f.root, Some(&f.minecraft), &|line| { + lines.borrow_mut().push(line.to_string()) + }); + assert_eq!( + *lines.borrow(), + [format!( + "Title panorama not imported: {error}; run horizon-prepare panorama later" + )] + ); + for name in PANORAMA { + assert_eq!(fs::read(target.join(name)).unwrap(), b"jar placeholder"); + } + } + } + #[test] fn the_index_must_be_the_pinned_one() { let f = Fixture::new("index"); diff --git a/docs/native-client.md b/docs/native-client.md index f05199ba7..e51bd8e40 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -23,9 +23,10 @@ verifies it against the pinned checksums, runs vanilla's data generator and smal exporters against those jars, and extracts the jar's assets and data into ignored `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your launcher's asset store by `horizon-prepare sounds`, each file checked against the asset -index's SHA-1. Preparation also replaces the JAR's gray 1×1 title panorama placeholders -with the full textures from that asset store. To repair an existing classic menu background -without rerunning the Java exporters, run `horizon-prepare panorama` (or +index's SHA-1. Preparation also tries to replace the JAR's gray 1×1 title panorama +placeholders with the full textures from that asset store. If the store is missing or +incomplete, preparation logs a warning and keeps the placeholders. To import the panorama +later without rerunning the Java exporters, run `horizon-prepare panorama` (or `cargo run --release -p horizon-prepare -- panorama` in a checkout). Pass `--minecraft-dir PATH` when using a different Minecraft installation. Prepared resources are private; never commit them. From 1596210bba2e71fc117aed34190a2ea0dcca83da Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:19:57 +0200 Subject: [PATCH 19/43] Respawn anchors charge, set the respawn point, explode outside the Nether A right click with glowstone on a respawn anchor did nothing and a charged anchor never became the respawn point: the block reported the use and the game dropped it. RespawnAnchorBlock is now played out (game/respawn_anchor.rs): useItemOn charges with glowstone (the block change, block.respawn_anchor.charge, the used item and the charge_respawn_anchor criterion), passing to the off hand's glowstone; useWithoutItem sets the respawn point in the Nether (block.minecraft.set_spawn once, respawn_anchor.set_spawn) and elsewhere explodes: the anchor goes, then a power 5 fiery BLOCK explosion with the bad_respawn_point damage source whose centre resists like water when water would flow into it. Dying with an anchor as the respawn point travels to its dimension and respawns at findStandUpPosition (DismountHelper's safe and unsafe passes, facing the anchor with calculateLookAtYaw), using a charge and playing respawn_anchor.deplete; a missing or empty anchor falls back to the world spawn with block.minecraft.spawn.not_valid. The point is saved in the player's respawn compound with its dimension; a bed or /spawnpoint replaces it. Dying in the Nether without one now respawns in the Overworld. Explosions gained what these need: a damage type, a block resistance override, BaseFireBlock.getState for their fire, the explosion radius in the block loot context (survives_explosion and explosion_decay drawing from the table's random sequence) and TntBlock.wasExploded without a game event. tools/test_use_item_on_parity.py now charges, uses and blows up anchors in both dimensions through vanilla's real ServerExplosion on the stand-in level, and respawns at anchors among blocks through ServerPlayer.findRespawnAndUseSpawnBlock. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 81 ++- crates/horizon-client/src/game/commands.rs | 1 + .../src/game/dispense_fixture.rs | 52 +- crates/horizon-client/src/game/end.rs | 6 +- crates/horizon-client/src/game/explosion.rs | 79 ++- .../horizon-client/src/game/respawn_anchor.rs | 542 ++++++++++++++++++ crates/horizon-client/src/game/screens.rs | 10 + crates/horizon-client/src/items.rs | 42 +- crates/horizon-client/src/save.rs | 31 +- .../parity/VanillaBlockUpdateOracle.java | 22 + .../parity/VanillaDispenserOracle.java | 47 +- tools/test_use_item_on_parity.py | 113 +++- 12 files changed, 974 insertions(+), 52 deletions(-) create mode 100644 crates/horizon-client/src/game/respawn_anchor.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..71610bfb7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -88,6 +88,7 @@ mod recipe_book; mod remote; mod render_control; mod render_tick; +mod respawn_anchor; mod scoreboard; mod screens; mod sculk; @@ -791,6 +792,11 @@ struct Game<'a> { portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). end_travel: bool, + /// The respawn point when it is not the world spawn or a bed: a respawn + /// anchor (`game/respawn_anchor.rs`). + respawn_config: Option, + /// A respawn travelling to its anchor's dimension and chunks. + respawn_travel: Option, /// The next enter_dimension call comes from an End portal. end_portal_travel: bool, end: end::EndState, @@ -1725,7 +1731,10 @@ impl Game<'_> { food.saturation = (food.saturation + 0.4).min(food.food as f32); } } - PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} + PlayerEffect::RespawnAnchor => { + self.respawn_anchor_used([pos.x, pos.y, pos.z])? + } + PlayerEffect::InteractLoot(_) => {} }, LevelEvent::PrimeTnt { pos, rot } => self.add_primed_tnt(pos, rot, 80), LevelEvent::BlockEvent { @@ -2119,6 +2128,7 @@ impl Game<'_> { return Ok(()); } let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + let mut anchor_passed = None; // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. if !(sneaking && self.held().is_some()) && let Some(hit) = self.pick() @@ -2136,6 +2146,15 @@ impl Game<'_> { self.swing_arm(); return Ok(()); } + match self.use_respawn_anchor(hit.pos, held.as_ref())? { + respawn_anchor::AnchorUse::Charged => { + self.swing_arm(); + return Ok(()); + } + // The main hand passes; its item is used, then the off hand's glowstone. + respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos), + respawn_anchor::AnchorUse::Other => {} + } let face = match hit.face { [0, 1, 0] => Direction::Up, [0, -1, 0] => Direction::Down, @@ -2157,17 +2176,21 @@ impl Game<'_> { }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); let item = held.as_ref().map(|s| s.item.to_string()); - let result = self.with_level(|b, level, ticks| { - b.use_item_on( - level, - ticks, - BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), - face, - at, - player, - item.as_deref(), - ) - }); + let result = if anchor_passed.is_some() { + horizon_world::level::InteractionResult::Pass + } else { + self.with_level(|b, level, ticks| { + b.use_item_on( + level, + ticks, + BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + at, + player, + item.as_deref(), + ) + }) + }; self.process_level_events()?; if result.consumes_action() { self.swing_arm(); @@ -2175,6 +2198,12 @@ impl Game<'_> { } } let Some(stack) = self.held().cloned() else { + // Minecraft.startUseItem goes on to the off hand. + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); }; @@ -2239,6 +2268,11 @@ impl Game<'_> { return Ok(()); }; if info.block.is_none() { + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); } @@ -2585,7 +2619,10 @@ impl Game<'_> { self.streaming.center = (cx, cz); if (-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { let (player, target) = self.travelling.take().ok_or("travel")?; - if self.end_travel { + if let Some(config) = self.respawn_travel.take() { + drop(player); + self.place_respawned(config)?; + } else if self.end_travel { self.place_after_end_travel(player, target)?; } else { self.place_after_travel(player, target)?; @@ -5649,6 +5686,17 @@ impl Game<'_> { self.travelling = None; self.player = None; self.spawn = None; + self.respawn_travel = None; + self.respawn_config = + self.level + .respawn_elsewhere + .as_ref() + .map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig { + dim: Dim::from_id(dim), + pos: *pos, + yaw: *yaw, + forced: *forced, + }); self.spawn_search = 0; self.spawn_origin = None; self.spawn_spiral = Default::default(); @@ -7097,6 +7145,8 @@ impl Game<'_> { f64::from(head[1]) + 0.6, f64::from(head[2]) + 0.5, )); + // The bed replaces a respawn anchor. + self.respawn_config = None; self.level.spawn = Some([ f64::from(head[0]), f64::from(head[1]) + 1.0, @@ -7474,6 +7524,9 @@ impl Game<'_> { level.weather = self.world.weather; level.day_time = self.world.day_time; level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); + level.respawn_elsewhere = self + .respawn_config + .map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced)); level.rotation = [self.yaw, self.pitch]; level.xp_level = self.experience.level; level.xp_progress = self.experience.progress; @@ -9050,6 +9103,8 @@ pub fn run() -> Result<()> { travelling: None, portals: Default::default(), end_travel: false, + respawn_config: None, + respawn_travel: None, end_portal_travel: false, end: Default::default(), block_ticks: Ticks::new(0), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index aff5ad2a1..15d43c80b 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2010,6 +2010,7 @@ impl Game<'_> { f64::from(pos[1]), f64::from(pos[2]) + 0.5, )); + self.respawn_config = None; let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); let mut args = vec![ diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index ab6a79961..6e10b53b1 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -137,6 +137,8 @@ impl Game<'_> { // Hopper cooldowns of an earlier case. self.hoppers.clear(); self.ui.rules = Default::default(); + self.dim = super::Dim::Overworld; + self.respawn_config = None; // The oracle level plays on normal difficulty. self.ui.difficulty = 2; // The oracle level has world seed 0 and fresh random sequences. @@ -162,6 +164,9 @@ impl Game<'_> { } } self.world.game_time = case["time"].as_i64().unwrap_or(0); + if case["dim"].as_str() == Some("nether") { + self.dim = super::Dim::Nether; + } // The oracle level's clock stands at day time 6000. self.world.day_time = 6000; if let Some(rules) = case["rules"].as_object() { @@ -272,6 +277,26 @@ impl Game<'_> { used = self.fixture_use(origin, op)?; } else if let Some(op) = case.get("use_item") { used = self.fixture_use_item(origin, op)?; + } else if let Some(op) = case.get("respawn_at") { + // ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin. + let config = super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos: [origin.x, origin.y, origin.z], + yaw: 0.0, + forced: op["forced"].as_bool().unwrap_or(false), + }; + let found = + self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?; + used.push(match found { + Some((p, yaw)) => format!( + "respawn {} {} {} {}", + num(p.x), + num(p.y), + num(p.z), + yaw.to_bits() as i32 + ), + None => "respawn none".to_owned(), + }); } else if case.get("hopper").is_some() { // HopperBlockEntity.pushItemsTick, once. self.hopper_try_move_items((origin.x, origin.y, origin.z)); @@ -447,14 +472,24 @@ impl Game<'_> { GameMode::Survival }; self.creative = self.mode == GameMode::Creative; + let distance = op["distance"].as_f64().unwrap_or(3.0); let mut player = PlayerMotion::new( self.motion, horizon_core::geometry::Vec3::new( f64::from(pos.x) + 0.5, f64::from(pos.y) + 1.0, - f64::from(pos.z) + 3.5, + f64::from(pos.z) + 0.5 + distance, ), )?; + if let Some(r) = op["respawn"].as_array() { + let p = |i: usize| r.get(i).and_then(Value::as_i64).unwrap_or(0) as i32; + self.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos: [p(0), p(1), p(2)], + yaw: 0.0, + forced: false, + }); + } player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32; self.player = Some(player); self.yaw = 0.0; @@ -488,7 +523,10 @@ impl Game<'_> { let key = m.component()["translate"] .as_str() .map_or_else(|| m.plain(), str::to_owned); - out.push(format!("msg {key}")); + // The oracle player's advancements are not tracked. + if !key.starts_with("chat.type.advancement") { + out.push(format!("msg {key}")); + } } if let Some(s) = &stack { let used = self.stats.get("used", &s.item) - used_before; @@ -504,6 +542,16 @@ impl Game<'_> { "held {} using {using}", canon_stack(self.inventory[self.selected].as_ref()) )); + out.push(match self.respawn_config { + Some(c) => format!( + "respawn {} {},{},{}", + c.dim.id(), + c.pos[0], + c.pos[1], + c.pos[2] + ), + None => "respawn -".to_owned(), + }); self.player = None; self.using = None; Ok(out) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e6be63093..126bd322b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -494,14 +494,16 @@ impl Game<'_> { Ok(()) } - /// Dying in the End respawns in the Overworld. + /// Dying away from the Overworld respawns at the world spawn there. pub(super) fn respawn_out_of_end(&mut self) -> Result<()> { - if self.dim != Dim::End || self.player.is_none() { + if self.dim == Dim::Overworld || self.player.is_none() { return Ok(()); } self.end_portal_travel = true; let result = self.enter_dimension(Dim::Overworld); self.end_portal_travel = false; + // The arrival places a fresh player at the spawn. + self.end_travel = true; result } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 1332ad51d..c03b99609 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -109,8 +109,14 @@ impl Game<'_> { } hits as f32 / count as f32 } - /// `ServerExplosion.calculateExplodedPositions`. - fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { + /// `ServerExplosion.calculateExplodedPositions`; `resists` overrides one + /// block's resistance (`ExplosionDamageCalculator.getBlockExplosionResistance`). + fn exploded_positions( + &mut self, + center: [f64; 3], + radius: f32, + resists: Option<([i32; 3], f32)>, + ) -> Vec<[i32; 3]> { let (min_y, max_y) = self.with_level(|_, level, _| { use horizon_world::level::LevelAccess; (level.min_y(), level.max_y()) @@ -147,8 +153,14 @@ impl Game<'_> { } else { 0.0 }; - if !self.res.facts.is_air(state) || f.fluid != Fluid::None { - power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + match resists { + Some((at, resistance)) if at == pos => { + power -= (resistance + 0.3) * 0.3; + } + _ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => { + power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + } + _ => {} } if power > 0.0 { set.put(Key(pos), ()); @@ -163,8 +175,9 @@ impl Game<'_> { } set.entries().map(|(k, _)| k.0).collect() } - /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT). - fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) { + /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); + /// the player takes `damage_type`. + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; } @@ -223,7 +236,7 @@ impl Game<'_> { let mut hurt = false; let creative = self.creative; if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id("minecraft:explosion") + && let Some(id) = self.motion.health.damage.id(damage_type) { // Creative players are invulnerable to explosions. if !creative && player_hurtable { @@ -334,6 +347,26 @@ impl Game<'_> { radius: f32, interaction: BlockInteraction, fire: bool, + ) -> Result<()> { + self.server_explode_as( + center, + radius, + interaction, + fire, + "minecraft:explosion", + None, + ) + } + /// `server_explode` with the damage type the player takes and a block + /// whose explosion resistance the damage calculator overrides. + pub(super) fn server_explode_as( + &mut self, + center: [f64; 3], + radius: f32, + interaction: BlockInteraction, + fire: bool, + damage_type: &str, + resists: Option<([i32; 3], f32)>, ) -> Result<()> { if let Some(p) = &self.player { let d = [ @@ -344,11 +377,11 @@ impl Game<'_> { let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius }); } - let mut targets = self.exploded_positions(center, radius); // Explosion.explode: the blast is heard. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); - self.explosion_hurt_entities(center, radius); + let mut targets = self.exploded_positions(center, radius, resists); + self.explosion_hurt_entities(center, radius, damage_type); if interaction != BlockInteraction::Keep { // Util.shuffle(list, level.random) for i in (2..=targets.len()).rev() { @@ -375,8 +408,12 @@ impl Game<'_> { .facts .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .solid_render - && let Some(fire) = self.res.assets.registry.default_state("minecraft:fire") { + // BaseFireBlock.getState: soul fire on its base blocks, + // fire shaped by its neighbours elsewhere. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + let fire = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); self.level_set(pos, fire)?; } } @@ -420,32 +457,36 @@ impl Game<'_> { } if !is_tnt { let dynamic = self.pending.dynamic(pos); - let drops = self.res.items.block_drops_full( + // LootContextParams.EXPLOSION_RADIUS under DESTROY_WITH_DECAY: the + // tables' survives_explosion and explosion_decay draw from their + // random sequence. + let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); + let drops = self.res.items.block_drops_exploded( self.res.assets.registry, state, None, &dynamic, &mut self.world.random, Some((&mut self.rand_sequences, self.level.seed)), + decay, ); for mut stack in drops { if &*stack.item == "minecraft:air" || stack.count == 0 { continue; } self.pending.attach(pos, &mut stack); - // survives_explosion / explosion_decay: 1 / radius per stack. - if interaction == BlockInteraction::DestroyWithDecay - && self.world.random.next_float() > 1.0 / radius - { - continue; - } add_or_append_stack(stacks, stack, pos); } } self.pending.clear(pos); self.level_set(pos, self.world.air)?; - if is_tnt { - self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true); + // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then + // getRandomShortFuse(80); no game event. + if is_tnt && self.ui.rules.bool("tnt_explodes") { + let r = &mut self.world.random; + let rot = r.next_double() * f64::from(std::f32::consts::TAU); + let fuse = r.next_int_bound(20).unwrap_or(0) + 10; + self.add_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), rot, fuse); } Ok(()) } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs new file mode 100644 index 000000000..b1b9e18fe --- /dev/null +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -0,0 +1,542 @@ +//! `RespawnAnchorBlock` in the game: glowstone charges it (`useItemOn`), a +//! right click on a charged anchor sets the respawn point in the Nether and +//! blows it up anywhere else (`useWithoutItem`), and respawning goes to it +//! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`), +//! using a charge. +use super::{Dim, Game}; +use horizon_client::{ + Result, + blocks::Fluid, + collisions::{SceneCollisions, no_collision_empty}, + items::ItemStack, + mobs::Who, + motion::PlayerMotion, + text::Text, +}; +use horizon_core::{ + geometry::{Aabb, Axis, Vec3, VoxelShape}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{collision_context::CollisionContext, registry::BlockStateId}; + +/// `ServerPlayer.RespawnConfig`: a respawn point other than the world spawn +/// that the game resolves through its block (a respawn anchor). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct RespawnConfig { + pub dim: Dim, + pub pos: [i32; 3], + pub yaw: f32, + pub forced: bool, +} + +/// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block +/// below, a block above, and straight above. +const HORIZONTAL: [[i32; 3]; 8] = [ + [0, 0, -1], + [-1, 0, 0], + [0, 0, 1], + [1, 0, 0], + [-1, 0, -1], + [1, 0, -1], + [-1, 0, 1], + [1, 0, 1], +]; +fn respawn_offsets() -> impl Iterator { + HORIZONTAL + .into_iter() + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y - 1, z])) + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y + 1, z])) + .chain(std::iter::once([0, 1, 0])) +} + +/// What a right click with an item does to an anchor before `useWithoutItem`. +pub(super) enum AnchorUse { + /// Glowstone charged it. + Charged, + /// `PASS`: the off hand's glowstone charges it instead. + Pass, + /// `TRY_WITH_EMPTY_HAND`, or not an anchor. + Other, +} + +impl Game<'_> { + fn is_anchor(&self, state: BlockStateId) -> bool { + &*self.res.facts.get(state).name == "minecraft:respawn_anchor" + } + fn anchor_charges(&self, state: BlockStateId) -> i32 { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("charges")) + .and_then(|c| c.parse().ok()) + .unwrap_or(0) + } + fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + s.properties.insert("charges".into(), charges.to_string()); + self.res.assets.registry.resolve(&s).ok() + } + /// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute + /// (only the Nether's dimension type sets it). + pub(super) fn anchor_works(&self) -> bool { + self.dim == Dim::Nether + } + /// `RespawnAnchorBlock.charge`: one more charge, the block change and the sound. + fn charge_anchor( + &mut self, + pos: [i32; 3], + state: BlockStateId, + who: Option, + ) -> Result<()> { + let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) + 1) else { + return Ok(()); + }; + self.level_set(pos, next)?; + self.post_block_game_event("minecraft:block_change", pos, who, Some(next)); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0); + Ok(()) + } + /// `RespawnAnchorBlock.useItemOn` with `held` in the main hand. + pub(super) fn use_respawn_anchor( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.is_anchor(state) { + return Ok(AnchorUse::Other); + } + let fuel = |s: Option<&ItemStack>| s.is_some_and(|s| &*s.item == "minecraft:glowstone"); + let chargeable = self.anchor_charges(state) < 4; + if fuel(held) && chargeable { + let used = held.cloned(); + self.charge_anchor(pos, state, Some(Who::Player))?; + // itemStack.consume(1, player); the criterion sees the stack as used. + self.consume_held(); + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + return Ok(AnchorUse::Charged); + } + if fuel(self.offhand.as_ref()) && chargeable { + return Ok(AnchorUse::Pass); + } + Ok(AnchorUse::Other) + } + /// The off hand's glowstone on an anchor the main hand passed on. + pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + let fuel = self + .offhand + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:glowstone"); + if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 { + return Ok(false); + } + let used = self.offhand.clone(); + self.charge_anchor(pos, state, Some(Who::Player))?; + if !self.creative + && let Some(s) = self.offhand.as_mut() + { + s.count -= 1; + if s.count == 0 { + self.offhand = None; + } + } + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + self.swing_arm(); + Ok(true) + } + /// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the + /// Nether it explodes; inside, it becomes the respawn point. + pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.anchor_works() { + return self.explode_anchor(pos, state); + } + let config = RespawnConfig { + dim: self.dim, + pos, + yaw: 0.0, + forced: false, + }; + // RespawnConfig.isSamePosition: dimension and block. + let same = self + .respawn_config + .is_some_and(|c| c.dim == config.dim && c.pos == config.pos); + if !same { + // setRespawnPosition(config, true): the message, the point; the + // anchor replaces a bed. + self.system_message(Text::translate("block.minecraft.set_spawn", &[])); + self.respawn_config = Some(config); + if let Some([x, y, z]) = self.level.world_spawn { + self.spawn = Some(Vec3::new( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + )); + } + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + "minecraft:block.respawn_anchor.set_spawn", + Some(at), + 1.0, + 1.0, + ); + } + Ok(()) + } + /// `RespawnAnchorBlock.isWaterThatWouldFlow`. + fn water_would_flow(&self, p: [i32; 3]) -> bool { + let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + if f.fluid != Fluid::Water { + return false; + } + if f.fluid_level == 8 && !f.fluid_falling { + return true; + } + if f.fluid_level < 2 { + return false; + } + self.res + .facts + .get(self.world.block(p[0], p[1] - 1, p[2])) + .fluid + != Fluid::Water + } + /// `RespawnAnchorBlock.explode`: the anchor goes, then a power 5 fiery + /// explosion (`badRespawnPointExplosion`, `ExplosionInteraction.BLOCK`) + /// whose centre resists like water when water would flow into it. + fn explode_anchor(&mut self, pos: [i32; 3], _state: BlockStateId) -> Result<()> { + self.level_set(pos, self.world.air)?; + let horizontal = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]] + .into_iter() + .any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]])); + let above = self + .res + .facts + .get(self.world.block(pos[0], pos[1] + 1, pos[2])) + .fluid + == Fluid::Water; + let in_water = horizontal || above; + let center = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.block_explosion(center, in_water.then_some(pos)) + } + /// `Level.explode(null, badRespawnPointExplosion(center), calculator, + /// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors): + /// `water_at` is the block that resists like water. + pub(super) fn block_explosion( + &mut self, + center: [f64; 3], + water_at: Option<[i32; 3]>, + ) -> Result<()> { + let interaction = if self.ui.rules.bool("block_explosion_drop_decay") { + super::explosion::BlockInteraction::DestroyWithDecay + } else { + super::explosion::BlockInteraction::Destroy + }; + self.server_explode_as( + center, + 5.0, + interaction, + true, + "minecraft:bad_respawn_point", + water_at.map(|p| (p, 100.0)), + ) + } + + // ---- respawning ------------------------------------------------------- + + /// `DismountHelper.nonClimbableShape`: the collision shape, empty for + /// climbable blocks and open trapdoors. + fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape { + let state = self.world.block(p[0], p[1], p[2]); + let name = &self.res.facts.get(state).name; + let open_trapdoor = name.ends_with("_trapdoor") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("open")) + .is_some_and(|v| v == "true"); + if self.block_in_tag("minecraft:climbable", name) || open_trapdoor { + return VoxelShape::empty(); + } + let binding = self.collision; + let mut scene = SceneCollisions { + world: &self.world, + binding, + subject: None, + }; + binding + .collision_shape_with_context( + &mut scene, + state, + BlockPos::new(p[0], p[1], p[2]), + &CollisionContext::empty(false), + ) + .unwrap_or_else(|_| VoxelShape::empty()) + } + fn block_in_tag(&self, tag: &str, block: &str) -> bool { + self.res + .items + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + /// `EntityType.isBlockDangerous` for the player. + fn dangerous_for_player(&self, p: [i32; 3]) -> bool { + let state = self.world.block(p[0], p[1], p[2]); + let name = &*self.res.facts.get(state).name; + let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + // NodeEvaluator.isBurningBlock, then the hurting plants and snow. + self.block_in_tag("minecraft:fire", name) + || matches!( + name, + "minecraft:lava" + | "minecraft:magma_block" + | "minecraft:lava_cauldron" + | "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ) + || lit_campfire + } + /// `DismountHelper.findSafeDismountLocation` for a standing player. + fn safe_dismount_location(&self, p: [i32; 3], check_dangerous: bool) -> Option { + if check_dangerous && self.dangerous_for_player(p) { + return None; + } + let shape = self.non_climbable_shape(p); + let below = self.non_climbable_shape([p[0], p[1] - 1, p[2]]); + let floor = horizon_core::geometry::block_floor_height(&shape, || &below); + // DismountHelper.isBlockFloorValid. + if floor.is_infinite() || floor >= 1.0 { + return None; + } + if check_dangerous && floor <= 0.0 && self.dangerous_for_player([p[0], p[1] - 1, p[2]]) { + return None; + } + let position = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + floor, + f64::from(p[2]) + 0.5, + ); + // EntityDimensions.makeBoundingBox for 0.6 by 1.8 (the half width is a float). + let half = f64::from(0.6f32 / 2.0); + let bounds = Aabb::new( + Vec3::new(position.x - half, position.y, position.z - half), + Vec3::new( + position.x + half, + position.y + f64::from(1.8f32), + position.z + half, + ), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + if !no_collision_empty(&mut scene, bounds) { + return None; + } + let name = |q: [i32; 3]| { + self.res + .facts + .get(self.world.block(q[0], q[1], q[2])) + .name + .clone() + }; + if self.block_in_tag("minecraft:invalid_spawn_inside", &name(p)) + || self.block_in_tag( + "minecraft:invalid_spawn_inside", + &name([p[0], p[1] + 1, p[2]]), + ) + { + return None; + } + // WorldBorder.isWithinBounds(box). + let (lo, hi) = (bounds.min(Axis::X), bounds.max(Axis::X) - 1.0e-5); + let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5); + (self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position) + } + /// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the + /// anchor, else any spot. + pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option { + for check in [true, false] { + for d in respawn_offsets() { + let p = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + if let Some(at) = self.safe_dismount_location(p, check) { + return Some(at); + } + } + } + None + } + /// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the + /// loaded dimension: the position and yaw, using a charge. + pub(super) fn find_respawn_and_use( + &mut self, + c: RespawnConfig, + consume: bool, + ) -> Result> { + let state = self.world.block(c.pos[0], c.pos[1], c.pos[2]); + if !(self.is_anchor(state) + && (c.forced || self.anchor_charges(state) > 0) + && self.anchor_works()) + { + return Ok(None); + } + let stand = self.anchor_stand_up(c.pos); + if !c.forced + && consume + && stand.is_some() + && let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) - 1) + { + self.level_set(c.pos, next)?; + } + Ok(stand.map(|p| (p, look_at_yaw(p, c.pos)))) + } + /// The death screen's respawn with an anchor as the respawn point: travel + /// to its dimension and wait for its chunks (`travelling`), then resolve + /// it in [`Game::place_respawned`]. + pub(super) fn begin_anchor_respawn(&mut self) -> Result { + let Some(config) = self.respawn_config else { + return Ok(false); + }; + if self.player.is_none() { + return Ok(false); + } + if self.dim != config.dim { + self.end_portal_travel = false; + self.enter_dimension(config.dim)?; + } else { + let player = self.player.take().ok_or("player")?; + self.travelling = Some((player, Vec3::ZERO)); + } + let target = Vec3::new( + f64::from(config.pos[0]) + 0.5, + f64::from(config.pos[1]), + f64::from(config.pos[2]) + 0.5, + ); + if let Some((_, t)) = self.travelling.as_mut() { + *t = target; + } + self.end_travel = false; + self.respawn_travel = Some(config); + Ok(true) + } + /// `PlayerList.respawn` at an anchor once its dimension is loaded around + /// it: a fresh player at the stand-up position facing the anchor and the + /// deplete sound, or, with no anchor left, the world spawn and + /// `block.minecraft.spawn.not_valid`. + pub(super) fn place_respawned(&mut self, config: RespawnConfig) -> Result<()> { + match self.find_respawn_and_use(config, true)? { + Some((position, yaw)) => { + let mut player = PlayerMotion::new(self.motion, position)?; + player.yaw = yaw; + player.head_yaw = yaw; + self.yaw = yaw; + self.pitch = 0.0; + player.pitch = 0.0; + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + self.previous_position = position; + self.player = Some(player); + self.sway = Default::default(); + self.apply_equipment(); + // ClientboundSoundPacket at the block's corner, seeded from the level random. + let state = self + .world + .block(config.pos[0], config.pos[1], config.pos[2]); + if self.is_anchor(state) { + let _seed = self.world.random.next_long(); + let at = [ + f64::from(config.pos[0]), + f64::from(config.pos[1]), + f64::from(config.pos[2]), + ]; + self.audio + .play("minecraft:block.respawn_anchor.deplete", Some(at), 1.0, 1.0); + } + Ok(()) + } + None => { + // TeleportTransition.missingRespawnBlock: the world spawn, and + // the point is forgotten. + self.respawn_config = None; + self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[])); + let dead = PlayerMotion::new(self.motion, Vec3::ZERO)?; + if self.dim != Dim::Overworld { + // A dead stand-in travels; the arrival makes a fresh player. + let mut dead = dead; + dead.set_health(0.0, false)?; + self.player = Some(dead); + self.end_portal_travel = true; + let result = self.enter_dimension(Dim::Overworld); + self.end_portal_travel = false; + self.end_travel = true; + return result; + } + self.player = None; + self.spawn_player() + } + } + } +} + +/// `RespawnPosAngle.calculateLookAtYaw`: the yaw from the position to the +/// bottom centre of the block. +fn look_at_yaw(position: Vec3, block: [i32; 3]) -> f32 { + let d = Vec3::new( + f64::from(block[0]) + 0.5 - position.x, + f64::from(block[1]) - position.y, + f64::from(block[2]) + 0.5 - position.z, + ) + .normalize(); + // Mth.atan2(z, x) * 180.0F / (float) Math.PI - 90.0: the compiled code + // multiplies by the folded float constant widened to double. + let degrees = horizon_core::geometry::trig::atan2(d.z, d.x) + * f64::from(horizon_core::geometry::trig::RAD_TO_DEG) + - 90.0; + wrap_degrees(degrees) as f32 +} +/// `Mth.wrapDegrees(double)`. +fn wrap_degrees(degrees: f64) -> f64 { + let mut d = degrees % 360.0; + if d >= 180.0 { + d -= 360.0; + } + if d < -180.0 { + d += 360.0; + } + d +} diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 96a4dc6c4..1de93e862 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -261,6 +261,16 @@ impl Game<'_> { self.toggles.respawn(); self.remote_respawn(); } + Some(0) if self.respawn_config.is_some() => { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + // PlayerList.respawn at the respawn anchor, once it is loaded. + self.begin_anchor_respawn()?; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } Some(0) => { // LocalPlayer.respawn: KeyMapping.resetToggleKeys. self.toggles.respawn(); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 9892243fc..f336d432e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -601,6 +601,7 @@ impl Items { properties: &empty, held: None, killed_by_player: false, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -662,7 +663,22 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { - let drops = self.block_drops_raw(registry, state, held, random, sequences); + self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None) + } + /// `block_drops_full` for a block an explosion destroys: `explosion` + /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`). + #[allow(clippy::too_many_arguments)] + pub fn block_drops_exploded( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion: Option, + ) -> Vec { + let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } @@ -684,6 +700,7 @@ impl Items { held: Option<&ItemStack>, random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion_radius: Option, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -713,6 +730,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; return ctx.evaluate(table, random); } @@ -722,6 +740,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; ctx.evaluate(table, random) } @@ -744,6 +763,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -775,6 +795,7 @@ impl Items { properties: &block.properties, held: None, killed_by_player: false, + explosion_radius: None, }; match table.get("random_sequence").and_then(Value::as_str) { Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), @@ -799,6 +820,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -820,6 +842,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -859,6 +882,8 @@ struct LootContext<'a> { properties: &'a BTreeMap, held: Option<&'a ItemStack>, killed_by_player: bool, + /// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops. + explosion_radius: Option, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. @@ -920,7 +945,10 @@ impl LootContext<'_> { _ => return true, }; match kind { - "minecraft:survives_explosion" => true, + // ExplosionCondition: 1 / radius under a decaying explosion. + "minecraft:survives_explosion" => self + .explosion_radius + .is_none_or(|r| random.next_float() <= 1.0 / r), "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), @@ -1205,6 +1233,15 @@ impl LootContext<'_> { } } } + // ApplyExplosionDecay: each item survives with 1 / radius. + "minecraft:explosion_decay" => { + if let Some(radius) = self.explosion_radius { + let probability = 1.0 / radius; + stack.count = (0..stack.count) + .filter(|_| random.next_float() <= probability) + .count() as u32; + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1238,6 +1275,7 @@ mod tests { properties: props, held, killed_by_player: block.is_empty(), + explosion_radius: None, } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 94b60f3b0..7a90871c2 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1732,6 +1732,9 @@ pub struct Level { pub day_time: i64, /// The player's respawn point (bed, or the world spawn). pub spawn: Option<[f64; 3]>, + /// A respawn point in another dimension than the Overworld (a respawn + /// anchor): dimension, block, yaw and `forced`. + pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, @@ -1924,7 +1927,18 @@ impl Level { && let Some(Tag::IntArray(pos)) = respawn.get("pos") && pos.len() == 3 { - self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + let dimension = + text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into()); + if dimension == "minecraft:overworld" { + self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + } else { + let yaw = match respawn.get("yaw") { + Some(Tag::Float(b)) => f32::from_bits(*b), + _ => 0.0, + }; + let forced = number(respawn.get("forced")).is_some_and(|v| v != 0); + self.respawn_elsewhere = Some((dimension, [pos[0], pos[1], pos[2]], yaw, forced)); + } } let mut inventory = Vec::new(); let mut inventory_components = HashMap::new(); @@ -2116,8 +2130,19 @@ impl Level { if let Some(pos) = self.position { entries.push(("Pos", doubles(&pos))); } - // A respawn point other than the world spawn (a bed). - if let Some(s) = self.spawn { + // A respawn point other than the world spawn: an anchor elsewhere, or a bed. + if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere { + let mut respawn = vec![ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(block.to_vec())), + ("yaw", Tag::Float(yaw.to_bits())), + ("pitch", Tag::Float(0f32.to_bits())), + ]; + if *forced { + respawn.push(("forced", Tag::Byte(1))); + } + entries.push(("respawn", Tag::compound(respawn))); + } else if let Some(s) = self.spawn { let block = [ s[0].floor() as i32, s[1].floor() as i32, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 4093c0538..077a6dbff 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -351,6 +351,28 @@ public final class VanillaBlockUpdateOracle { return attributes; } @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return type != null ? type : OVERWORLD_TYPE; } + /** + * ServerLevel.explode without the players to send the packet to: the + * ServerExplosion runs, then the explosion sound the client plays at + * the centre is logged. + */ + @Override public void explode(Entity source, net.minecraft.world.damagesource.DamageSource damageSource, + net.minecraft.world.level.ExplosionDamageCalculator calculator, double x, double y, double z, float r, boolean fire, + net.minecraft.world.level.Level.ExplosionInteraction type, net.minecraft.core.particles.ParticleOptions small, + net.minecraft.core.particles.ParticleOptions large, net.minecraft.util.random.WeightedList blockParticles, + net.minecraft.core.Holder sound) { + java.util.function.Function, net.minecraft.world.level.Explosion.BlockInteraction> destroy = + rule -> rules.get(rule) ? net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY : net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; + var interaction = switch (type) { + case NONE -> net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case BLOCK -> destroy.apply(GameRules.BLOCK_EXPLOSION_DROP_DECAY); + case MOB -> rules.get(GameRules.MOB_GRIEFING) ? destroy.apply(GameRules.MOB_EXPLOSION_DROP_DECAY) : net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case TNT -> destroy.apply(GameRules.TNT_EXPLOSION_DROP_DECAY); + case TRIGGER -> net.minecraft.world.level.Explosion.BlockInteraction.TRIGGER_BLOCK; + }; + new net.minecraft.world.level.ServerExplosion(this, source, damageSource, calculator, new Vec3(x, y, z), r, fire, interaction).explode(); + if (source == null || !source.isSilent()) emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location()); + } /** The overworld (fire in an obsidian frame lights a portal here). */ @Override public net.minecraft.resources.ResourceKey dimension() { return dimensionKey != null ? dimensionKey : net.minecraft.world.level.Level.OVERWORLD; } @Override public long getOverworldClockTime() { return DAY.totalTicks(); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index abbd13dc4..e1c3ff4e8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -247,10 +247,18 @@ public final class VanillaDispenserOracle { w.registries = ParityData.access; w.server.loot.delegate = ParityData.loot; VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access)); + if (f.has("dim") && f.get("dim").getAsString().equals("nether")) { + // The Nether's dimension type and attributes (respawn anchors work, beds explode). + if (NETHER == null) NETHER = VanillaBlockUpdateOracle.loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER); + w.type = NETHER; + w.dimensionKey = Level.NETHER; + w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(NETHER.attributes()).build(); + } if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null); if (rule.getKey().equals("spawner_blocks_work")) w.rules.set(GameRules.SPAWNER_BLOCKS_WORK, rule.getValue().getAsBoolean(), null); + if (rule.getKey().equals("block_explosion_drop_decay")) w.rules.set(GameRules.BLOCK_EXPLOSION_DROP_DECAY, rule.getValue().getAsBoolean(), null); } } if (f.has("items")) { @@ -302,6 +310,8 @@ public final class VanillaDispenserOracle { used = use(w, origin, f.getAsJsonObject("use")); } else if (f.has("use_item")) { used = useItem(w, origin, f.getAsJsonObject("use_item")); + } else if (f.has("respawn_at")) { + used = respawnAt(w, origin, f.getAsJsonObject("respawn_at")); } else if (f.has("hopper")) { // HopperBlockEntity.pushItemsTick, once. var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); @@ -379,6 +389,8 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } + static net.minecraft.world.level.dimension.DimensionType NETHER; + /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ static final class User extends net.minecraft.server.level.ServerPlayer { VanillaBlockUpdateOracle.World world; @@ -506,8 +518,15 @@ public final class VanillaDispenserOracle { var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); - // Standing three blocks south of the clicked block, looking down at it. - var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + // Standing three blocks (or `distance`) south of the clicked block, looking down at it. + double distance = use.has("distance") ? use.get("distance").getAsDouble() : 3; + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, distance); + if (use.has("respawn")) { + var r = use.getAsJsonArray("respawn"); + BlockPos point = new BlockPos(r.get(0).getAsInt(), r.get(1).getAsInt(), r.get(2).getAsInt()); + player.setRespawnPosition(new net.minecraft.server.level.ServerPlayer.RespawnConfig( + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), point, 0.0F, 0.0F), false), false); + } VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f); @@ -526,9 +545,33 @@ public final class VanillaDispenserOracle { } List out = new ArrayList<>(player.stats); out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + var respawn = player.getRespawnConfig(); + out.add("respawn " + (respawn == null ? "-" : respawn.respawnData().dimension().identifier() + " " + VanillaBlockUpdateOracle.pos(respawn.respawnData().pos()))); return out; } + /** + * ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at `pos` + * (a respawn anchor, in the Nether or not): the position, the yaw that + * looks at the block, and the charge used (a block change). + */ + static List respawnAt(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception { + var config = new net.minecraft.server.level.ServerPlayer.RespawnConfig( + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos, 0.0F, 0.0F), op.get("forced").getAsBoolean()); + Method find = net.minecraft.server.level.ServerPlayer.class.getDeclaredMethod("findRespawnAndUseSpawnBlock", + ServerLevel.class, net.minecraft.server.level.ServerPlayer.RespawnConfig.class, boolean.class); + find.setAccessible(true); + var found = (Optional) find.invoke(null, w, config, op.get("consume").getAsBoolean()); + if (found.isEmpty()) return List.of("respawn none"); + Object angle = found.get(); + Method position = angle.getClass().getDeclaredMethod("position"); + Method yaw = angle.getClass().getDeclaredMethod("yaw"); + position.setAccessible(true); + yaw.setAccessible(true); + var p = (net.minecraft.world.phys.Vec3) position.invoke(angle); + return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle))); + } + /** The level's block entity positions by x, y, z. */ static List sortedEntities(VanillaBlockUpdateOracle.World w) { List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index f71bbbe4d..9c860ce64 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet -berry bushes and for spawn eggs used on a monster spawner. +berry bushes, for spawn eggs used on a monster spawner and for respawn anchors. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -11,12 +11,18 @@ harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and `useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its `mayPlaceOn` rules, `BoneMealItem.useOn`, eating a consumable that could -not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Horizon runs +not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Respawn +anchors are charged with glowstone, set the respawn point in the Nether and +explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real +`ServerExplosion`, with water at the anchor). Respawn cases call +`ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks +(`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the +position, the yaw that faces the anchor and the charge it uses. Horizon runs `use_item_as_player` on that hit in a headless game -(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, -level events, sounds, game events, the used statistic, the held stack, the -item the player started using, spawners' next spawn data, potentials and -delay, system messages and the level random afterwards. +(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level +events, sounds, game events, the used statistic, the held stack, the item the +player started using, spawners' next spawn data, potentials and delay, the +player's respawn point, system messages and the level random afterwards. """ import json import os @@ -37,6 +43,74 @@ ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'car # What is in the way above the clicked block. ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] EGGS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'pig', 'creeper', 'blaze', 'ghast', 'villager', 'bee', 'cod'] +# What stands around an anchor that explodes. +AROUND = ['stone', 'dirt', 'oak_planks', 'cobblestone', 'glass', 'obsidian', 'netherrack', 'water', 'tnt', 'oak_log', + 'grass_block', 'soul_sand', 'gravel', 'crying_obsidian'] + + +STAND = ['air'] * 6 + ['stone', 'stone', 'oak_slab', 'snow', 'lava', 'magma_block', 'fire', 'cactus', 'water', + 'ladder', 'oak_trapdoor', 'short_grass', 'white_carpet', 'campfire', 'sweet_berry_bush', + 'oak_fence', 'powder_snow', 'farmland', 'soul_sand', 'cobweb', 'end_portal'] + + +def respawn_case(rng, states, case): + """Respawning at an anchor with blocks around it.""" + charges = rng.choice([0, 1, 1, 2, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))]] + for dy in (-2, -1, 0, 1, 2): + for dx in range(-1, 2): + for dz in range(-1, 2): + if (dx, dy, dz) == (0, 0, 0): + continue + if dy == -1 or dy == -2: + name = rng.choice(['stone'] * 6 + STAND) + else: + name = rng.choice(['air'] * 3 + STAND) + if name == 'air': + continue + state = states.any(rng, name) if name in ('oak_trapdoor', 'oak_slab', 'snow', 'campfire', 'water', 'ladder') else states.get(name) + cells.append([dx, dy, dz, state]) + if rng.random() < 0.6: + case['dim'] = 'nether' + case['respawn_at'] = {'forced': rng.random() < 0.2, 'consume': rng.random() < 0.8} + case['cells'] = cells + + +def anchor_case(rng, states, case): + """A respawn anchor clicked in the Nether or the Overworld, with blocks + and water around it.""" + charges = rng.choice([0, 0, 1, 2, 3, 4, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))], + [0, -1, 0, states.get(rng.choice(['netherrack', 'stone', 'soul_sand', 'obsidian', 'soul_soil']))]] + taken = {(0, 0, 0), (0, -1, 0)} + for _ in range(rng.choice([0, 3, 8, 20, 40])): + p = (rng.randrange(-3, 4), rng.randrange(-2, 3), rng.randrange(-3, 4)) + if p in taken: + continue + taken.add(p) + name = rng.choice(AROUND) + state = states.any(rng, 'water') if name == 'water' and rng.random() < 0.5 else states.get(name) + cells.append([*p, state]) + if rng.random() < 0.2: + # Water that would flow into the anchor's place. + d = rng.choice([(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1), (0, 1, 0)]) + cells = [c for c in cells if tuple(c[:3]) != d] + cells.append([*d, states.any(rng, 'water') if rng.random() < 0.4 else states.get('water')]) + nether = rng.random() < 0.5 + if nether: + case['dim'] = 'nether' + item = rng.choice(['glowstone'] * 5 + ['apple', '-', 'stone', 'glowstone_dust']) + count = rng.choice([1, 1, 16, 64]) + use = {'item': '-' if item == '-' else d_plain(item, count), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.1, 'food': 20, + # Away from the blast: the stand-in player is not an entity of the level. + 'distance': 3 if nether else 12} + if rng.random() < 0.3: + use['respawn'] = rng.choice([[0, 0, 0], [5, 0, 5]]) + if rng.random() < 0.2: + case['rules'] = {'block_explosion_drop_decay': False} + case['use_item'] = use + case['cells'] = cells def cases(facts, count, seed): @@ -46,6 +120,18 @@ def cases(facts, count, seed): case = {**h.environment(rng), 'pos': [0, 0, 0]} case.pop('raining', None) case.pop('thundering', None) + if rng.random() < 0.1: + respawn_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue + if rng.random() < 0.15: + anchor_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue cells = [] item = rng.choice(ITEMS) if rng.random() < 0.15: @@ -83,8 +169,14 @@ def cases(facts, count, seed): yield case +def d_plain(item, count): + return d.plain(item, count) + + def kind(case, facts): first = facts.states[case['cells'][0][3]][0].split(':')[1] + if 'respawn_at' in case: + return f'respawn at {first}' item = case['use_item']['item'] item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand' return f'{item} on {first}' @@ -119,13 +211,15 @@ def main(): rust = h.split_cases((work / 'rust.txt').read_text(), ignore) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) groups, errors = {}, {} - planted = eaten = 0 + planted = eaten = respawned = exploded = 0 for case, a, b in zip(all_cases, native, rust): if a and a[0].startswith('error'): errors.setdefault(a[0], []).append(case) continue planted += any(line.startswith('set 0,1,0') for line in a) eaten += any(line.startswith('held') and not line.endswith('using -') for line in a) + respawned += any(line.startswith('respawn ') and line != 'respawn none' and 'respawn_at' in case for line in a) + exploded += any(line.endswith(' minecraft:explode') for line in a) if not d.same(a, b): groups.setdefault(kind(case, facts), []).append((case, a, b)) for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): @@ -133,13 +227,14 @@ def main(): for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): print(f'{name}: {len(entries)} differing') for case, a, b in entries[:args.show]: - print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case['use_item'])) + print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case.get('use_item', case.get('respawn_at')))) print(' native ' + ' | '.join(sorted(a))) print(' rust ' + ' | '.join(sorted(b))) total = sum(len(v) for v in groups.values()) skipped = sum(len(v) for v in errors.values()) print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); ' - f'vanilla planted in {planted} and started eating in {eaten}') + f'vanilla planted in {planted}, started eating in {eaten}, exploded {exploded} times and found a respawn ' + f'spot in {respawned}') h.finish(total + skipped) From 190f89b21452143b33b739fe96ad329b391d9235 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:17:53 +0200 Subject: [PATCH 20/43] Beds and straw beds blow up when used in the Nether and the End A right click on a bed in the Nether or the End tried to sleep in it (and set the respawn point) as in the Overworld. AbstractBedBlock.useWithoutItem reads the dimension's bed rule, which in the Nether and the End is destroy_on_use: BedBlock.destroyOnUse removes the head, then the foot behind it if it is still the bed, and explodes at the head (power 5, fire, BLOCK interaction, the bad_respawn_point damage source: "Intentional Game Design"); StrawBedBlock.destroyBed plays block.straw_bed.break_leave and removes it. tools/test_use_item_on_parity.py clicks beds and straw beds (head or foot, whole or missing their other half, among blocks) in the Nether and the End, through vanilla's real explosion; the oracle gains the End. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 ++ .../src/game/dispense_fixture.rs | 6 ++- .../horizon-client/src/game/respawn_anchor.rs | 53 +++++++++++++++++++ .../parity/VanillaDispenserOracle.java | 8 ++- tools/test_use_item_on_parity.py | 47 +++++++++++++++- 5 files changed, 112 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 71610bfb7..890387ac8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1711,6 +1711,9 @@ impl Game<'_> { } LevelEvent::Player { pos, effect, .. } => match effect { PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]), + PlayerEffect::Sleep if self.beds_destroy_on_use() => { + self.destroy_bed_on_use([pos.x, pos.y, pos.z])? + } PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]), PlayerEffect::GiveItem(item) => { if let Some(rest) = self.give(ItemStack { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 6e10b53b1..355a188da 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -164,8 +164,10 @@ impl Game<'_> { } } self.world.game_time = case["time"].as_i64().unwrap_or(0); - if case["dim"].as_str() == Some("nether") { - self.dim = super::Dim::Nether; + match case["dim"].as_str() { + Some("nether") => self.dim = super::Dim::Nether, + Some("end") => self.dim = super::Dim::End, + _ => {} } // The oracle level's clock stands at day time 6000. self.world.day_time = 6000; diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index b1b9e18fe..f2f21469f 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -240,6 +240,59 @@ impl Game<'_> { ]; self.block_explosion(center, in_water.then_some(pos)) } + /// `BedRule.destroyOnUse` of the dimension's `bed_rule` and + /// `straw_bed_rule`: true in the Nether and the End. + pub(super) fn beds_destroy_on_use(&self) -> bool { + self.dim != Dim::Overworld + } + /// `AbstractBedBlock.useWithoutItem` where the bed rule destroys on use + /// (the bed's head at `head`): `BedBlock.destroyOnUse` removes both + /// halves and explodes; `StrawBedBlock` just falls apart. + pub(super) fn destroy_bed_on_use(&mut self, head: [i32; 3]) -> Result<()> { + let state = self.world.block(head[0], head[1], head[2]); + let name = self.res.facts.get(state).name.clone(); + let center = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5, + f64::from(head[2]) + 0.5, + ]; + if &*name == "minecraft:straw_bed" { + // StrawBedBlock.destroyBed. + self.audio.play( + "minecraft:block.straw_bed.break_leave", + Some(center), + 1.0, + 1.0, + ); + return self.level_set(head, self.world.air); + } + // removeBlock(head), then the foot behind it if it is still this bed. + let facing = self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()) + .unwrap_or_default(); + let back = match facing.as_str() { + "north" => [0, 0, 1], + "south" => [0, 0, -1], + "west" => [1, 0, 0], + _ => [-1, 0, 0], + }; + self.level_set(head, self.world.air)?; + let foot = [head[0] + back[0], head[1], head[2] + back[2]]; + if self + .res + .facts + .get(self.world.block(foot[0], foot[1], foot[2])) + .name + == name + { + self.level_set(foot, self.world.air)?; + } + self.block_explosion(center, None) + } /// `Level.explode(null, badRespawnPointExplosion(center), calculator, /// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors): /// `water_at` is the block that resists like water. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index e1c3ff4e8..24cf82ae5 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -253,6 +253,12 @@ public final class VanillaDispenserOracle { w.type = NETHER; w.dimensionKey = Level.NETHER; w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(NETHER.attributes()).build(); + } else if (f.has("dim") && f.get("dim").getAsString().equals("end")) { + // The End's (beds explode, anchors do too). + if (END == null) END = VanillaBlockUpdateOracle.loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.END); + w.type = END; + w.dimensionKey = Level.END; + w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(END.attributes()).build(); } if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { @@ -389,7 +395,7 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } - static net.minecraft.world.level.dimension.DimensionType NETHER; + static net.minecraft.world.level.dimension.DimensionType NETHER, END; /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ static final class User extends net.minecraft.server.level.ServerPlayer { diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 9c860ce64..5b3c40971 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet -berry bushes, for spawn eggs used on a monster spawner and for respawn anchors. +berry bushes, for spawn eggs used on a monster spawner, for respawn anchors and +for beds in the Nether and the End. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -17,7 +18,10 @@ explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real `ServerExplosion`, with water at the anchor). Respawn cases call `ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks (`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the -position, the yaw that faces the anchor and the charge it uses. Horizon runs +position, the yaw that faces the anchor and the charge it uses. Beds and straw +beds clicked (head or foot, whole or broken) in the Nether and the End blow up +or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's +`bed_rule`: `BedBlock.destroyOnUse`, `StrawBedBlock.destroyBed`). Horizon runs `use_item_as_player` on that hit in a headless game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level events, sounds, game events, the used statistic, the held stack, the item the @@ -76,6 +80,39 @@ def respawn_case(rng, states, case): case['cells'] = cells +BED_COLORS = ['red', 'white', 'black', 'cyan', 'lime'] +FACINGS = {'north': (0, -1), 'south': (0, 1), 'west': (-1, 0), 'east': (1, 0)} + + +def bed_case(rng, states, case): + """A bed (or straw bed) clicked in the Nether or the End, among blocks.""" + name = 'straw_bed' if rng.random() < 0.25 else rng.choice(BED_COLORS) + '_bed' + facing = rng.choice(list(FACINGS)) + dx, dz = FACINGS[facing] + # The clicked block is the origin; the other half lies along the facing. + part = rng.choice(['head', 'foot']) + other = (-dx, 0, -dz) if part == 'head' else (dx, 0, dz) + cells = [[0, 0, 0, states.get(name, facing=facing, part=part, occupied='false')], + [0, -1, 0, states.get(rng.choice(['netherrack', 'end_stone', 'obsidian', 'stone']))], + [other[0], -1, other[2], states.get('stone')]] + if rng.random() < 0.9: + cells.append([*other, states.get(name, facing=facing, part='foot' if part == 'head' else 'head', occupied='false')]) + taken = {tuple(c[:3]) for c in cells} + for _ in range(rng.choice([0, 3, 10, 30])): + p = (rng.randrange(-3, 4), rng.randrange(-2, 3), rng.randrange(-3, 4)) + if p in taken: + continue + taken.add(p) + cells.append([*p, states.get(rng.choice(AROUND))]) + case['dim'] = rng.choice(['nether', 'end']) + item = rng.choice(['-', '-', 'apple', 'stone', 'glowstone']) + case['use_item'] = {'item': '-' if item == '-' else d_plain(item, 1), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.1, 'food': 20, 'distance': 12} + if rng.random() < 0.2: + case['rules'] = {'block_explosion_drop_decay': False} + case['cells'] = cells + + def anchor_case(rng, states, case): """A respawn anchor clicked in the Nether or the Overworld, with blocks and water around it.""" @@ -120,6 +157,12 @@ def cases(facts, count, seed): case = {**h.environment(rng), 'pos': [0, 0, 0]} case.pop('raining', None) case.pop('thundering', None) + if rng.random() < 0.1: + bed_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue if rng.random() < 0.1: respawn_case(rng, states, case) case['items'] = [] From 72074eb080ac285cb5c665ad966b72d120648042 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:50:21 +0100 Subject: [PATCH 21/43] Fix LAN host tab list to include connected guests --- crates/horizon-client/src/game/scoreboard.rs | 114 ++++++++++++++++++- 1 file changed, 110 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index ced283669..e35a9d918 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -10,9 +10,11 @@ use horizon_client::{ }, hud::HudBatch, hud_layout, hud_overlays, + lan::guest::Guest, save::{self, uuid_from_text, uuid_text}, scoreboard::{self as sb, Comp, Scoreboard, literal}, scoreboard_cmd::{self, Env, Holder}, + tab_list::TabPlayer, text::Text, }; use horizon_world::nbt::Tag; @@ -581,10 +583,10 @@ impl Game<'_> { impl Game<'_> { /// `Hud.extractTabList`: the player list while the player-list key is - /// held. A single-player world lists only its player, so it shows only - /// with a `list` objective. + /// held. A local world shows it with a joined LAN guest or a `list` + /// objective. pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) { - use horizon_client::tab_list::{self, TabInputs, TabPlayer}; + use horizon_client::tab_list::{self, TabInputs}; let chatting = self.remote.is_some() && self.remote_chat_open(); let key = self.screen == super::Screen::Playing && !chatting @@ -600,7 +602,14 @@ impl Game<'_> { let mut me = TabPlayer::new(uuid, PLAYER_NAME); me.game_mode = self.mode_id(); me.skin = "entity/player/wide/steve".into(); - (vec![me], true, Vec::new()) + let guests = self.lan.as_ref().map_or(&[][..], |h| &h.hub.guests); + let players = local_tab_players(me, guests); + let upside_down = players + .iter() + .filter(|p| p.name == "Dinnerbone" || p.name == "Grumm") + .map(|p| p.uuid) + .collect(); + (players, true, upside_down) } }; let board = &self.score.board; @@ -635,6 +644,103 @@ impl Game<'_> { } } +/// The host and guests that have entered the world, rebuilt from live state. +fn local_tab_players(me: TabPlayer, guests: &[Guest]) -> Vec { + let mut players = vec![me]; + players.extend(guests.iter().filter(|g| g.placed).map(|g| { + let mut player = TabPlayer::new(g.uuid, &g.name); + player.game_mode = g.game_mode; + player.latency = g.latency.load(std::sync::atomic::Ordering::Relaxed); + player + })); + players +} + +#[cfg(test)] +mod tab_list_tests { + use super::*; + use horizon_client::{ + lan::{Joined, PlayerSender}, + tab_list, + }; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{ + Arc, + atomic::{AtomicI32, Ordering}, + mpsc, + }; + + fn guest(uuid: u128, name: &str) -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: uuid as u32, + uuid, + name: name.into(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender { + tx, + pending: Arc::default(), + }, + latency: Arc::new(AtomicI32::new(42)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + uuid as i32, + [0.0, 64.0, 0.0], + 8, + ) + } + + #[test] + fn lan_tab_list_tracks_join_and_disconnect() { + let me = TabPlayer::new(1, PLAYER_NAME); + let mut guests = vec![guest(2, "Alex")]; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players, [me.clone()]); + assert!(!tab_list::visible(true, true, players.len(), false)); + + guests[0].placed = true; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players.len(), 2); + assert_eq!(players[0], me); + assert_eq!(players[1].uuid, 2); + assert_eq!(players[1].name, "Alex"); + assert!(tab_list::visible(true, true, players.len(), false)); + assert!(!tab_list::visible(false, true, players.len(), false)); + + guests.clear(); + let players = local_tab_players(me, &guests); + assert_eq!(players.len(), 1); + assert!(!tab_list::visible(true, true, players.len(), false)); + assert!(tab_list::visible(true, true, players.len(), true)); + } + + #[test] + fn lan_tab_list_reads_current_guest_state() { + let me = TabPlayer::new(1, PLAYER_NAME); + let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")]; + for guest in &mut guests { + guest.placed = true; + } + guests[0].game_mode = tab_list::SPECTATOR; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players.len(), 3); + assert_eq!(players[1].game_mode, tab_list::SPECTATOR); + assert_eq!(players[1].latency, 42); + assert_eq!(players[1].skin, tab_list::default_skin(2)); + assert_eq!(players[2].name, "Grumm"); + + guests[0].game_mode = 1; + guests[0].latency.store(123, Ordering::Relaxed); + guests.remove(1); + let players = local_tab_players(me, &guests); + assert_eq!(players.len(), 2); + assert_eq!(players[1].game_mode, 1); + assert_eq!(players[1].latency, 123); + } +} + /// The commands' view of the game. struct GameEnv<'a, 'b> { g: &'a mut Game<'b>, From 1b1e1291122ee0146c59938901196b93462c75b9 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:51:23 +0100 Subject: [PATCH 22/43] Fix LAN shutdown when leaving a singleplayer world --- crates/horizon-client/src/game.rs | 2 + tools/test_lan_lifecycle.py | 144 ++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 tools/test_lan_lifecycle.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..cfe524711 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5937,6 +5937,7 @@ impl Game<'_> { if self.remote.is_none() { self.stats.custom("leave_game", 1); } + self.lan_close(false); self.save_game() } fn close_world(&mut self) -> Result<()> { @@ -5950,6 +5951,7 @@ impl Game<'_> { } self.stats.custom("leave_game", 1); self.save_game()?; + self.lan_close(false); horizon_client::crash::clear_detail("World"); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); diff --git a/tools/test_lan_lifecycle.py b/tools/test_lan_lifecycle.py new file mode 100644 index 000000000..5344e7564 --- /dev/null +++ b/tools/test_lan_lifecycle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Check LAN shutdown when leaving a singleplayer world through the pause menu. + +Requires a built horizon-client, prepared resources and a display on Unix: + xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client +Worlds and settings are created in a temporary directory. +""" +import argparse +import json +import os +from pathlib import Path +import socket +import subprocess +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +GROUP = '224.0.2.60' +DISCOVERY_PORT = 4445 + + +def command(endpoint, line): + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(60) + connection.connect(str(endpoint)) + connection.sendall((line + '\n').encode()) + with connection.makefile('r') as reply: + result = json.loads(reply.readline()) + assert 'error' not in result, (line, result) + return result + + +def wait_for(endpoint, line, predicate, timeout=60): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + result = command(endpoint, line) + except (FileNotFoundError, ConnectionRefusedError): + time.sleep(0.1) + continue + if predicate(result): + return result + time.sleep(0.1) + raise AssertionError(f'timed out waiting for {line}') + + +def announcement(scanner, port, timeout): + deadline = time.monotonic() + timeout + marker = f'[AD]{port}[/AD]'.encode() + while time.monotonic() < deadline: + scanner.settimeout(max(0.001, deadline - time.monotonic())) + try: + message, _ = scanner.recvfrom(4096) + except socket.timeout: + return False + if marker in message: + return True + return False + + +def scenario(endpoint, scanner): + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + command(endpoint, 'open LanLifecycle 0 creative') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + assert command(endpoint, 'lan status') == {'open': False} + port = 0 + for _ in range(2): + port = command(endpoint, f'lan open {port}')['port'] + with socket.create_connection(('127.0.0.1', port), timeout=2): + pass + assert announcement(scanner, port, 5), 'LAN world was not advertised' + command(endpoint, 'key esc tap') + screen = wait_for(endpoint, 'screen', lambda value: any( + button['label'] == 'Save and Quit to Title' for button in value['buttons'])) + assert screen['screen'] == 'paused', screen + command(endpoint, 'click-button Save and Quit to Title') + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + assert command(endpoint, 'lan status') == {'open': False}, 'LAN stayed open after leaving' + try: + connection = socket.create_connection(('127.0.0.1', port), timeout=2) + except ConnectionRefusedError: + pass + else: + connection.close() + raise AssertionError('LAN still accepts connections after leaving') + # Discard datagrams queued before shutdown, then listen for more than + # two announcement intervals (the pinger sends every 1.5 seconds). + scanner.setblocking(False) + try: + while True: + scanner.recvfrom(4096) + except BlockingIOError: + pass + assert not announcement(scanner, port, 3.5), 'LAN kept advertising after leaving' + command(endpoint, 'open LanLifecycle') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + assert command(endpoint, 'lan status') == {'open': False}, 'LAN reopened with the world' + command(endpoint, 'lan open 0') + command(endpoint, 'quit') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--client', type=Path, required=True) + parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3') + args = parser.parse_args() + client, resources = args.client.resolve(), args.resources.resolve() + with tempfile.TemporaryDirectory(prefix='horizon-lan-') as directory: + work = Path(directory) + endpoint = work / 'control.sock' + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as scanner: + scanner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + scanner.bind(('', DISCOVERY_PORT)) + scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0')) + with (work / 'client.log').open('w+') as log: + process = subprocess.Popen([ + str(client), '--resources', str(resources), '--render-distance', '2', + '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', + ], cwd=work, env=dict(os.environ, HORIZON_HOME=str(work), HORIZON_NO_AUDIO='1', + HORIZON_MENU_STYLE='classic'), + stdout=log, stderr=subprocess.STDOUT) + try: + scenario(endpoint, scanner) + assert process.wait(timeout=20) == 0, 'client exited unsuccessfully' + except Exception: + log.seek(0) + print('\n'.join(log.read().splitlines()[-20:])) + raise + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private') + + +if __name__ == '__main__': + main() From 0ed50ae6ae9d7c712b3f36f7e8b224682e1a280c Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:53:45 +0100 Subject: [PATCH 23/43] Fix LAN worlds pausing when the host opens menus --- crates/horizon-client/src/game.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..f9de2923c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3111,6 +3111,7 @@ impl Game<'_> { /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { self.remote.is_none() + && self.lan.is_none() && self.title.is_none() && (matches!( self.screen, From 20988e810e4aa17c4fe8f71040b782e3de2d0e3d Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:14:10 -0400 Subject: [PATCH 24/43] fix(prepare): reuse verified imports from installed versions --- crates/horizon-prepare/src/artifacts.rs | 229 +++++++++++++++++++++++- crates/horizon-prepare/src/lib.rs | 2 +- launcher/README.md | 5 +- launcher/src/backend.rs | 45 ++--- launcher/src/main.rs | 9 +- 5 files changed, 257 insertions(+), 33 deletions(-) diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index a3e6c2cc0..6f8e45bf8 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -573,6 +573,69 @@ pub struct Artifacts { pub libraries: Vec, } +/// Reuses checked imports from this root or another installed version beside it. +pub fn reuse_imported(root: &Path, log: Log) -> Result { + let root = fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; + let lock = Lock::read(&root)?; + let checked = |directory: PathBuf| -> Result, String> { + let candidate = Lock { + json: lock.json.clone(), + version: lock.version.clone(), + java_major: lock.java_major, + directory, + }; + let found = verify(&candidate)?; + let client = client_libraries(&candidate, &found.manifest)?; + let mut files = vec![ + candidate.directory.join("manifest.json"), + candidate.directory.join("jars/client.jar"), + candidate.directory.join("jars/server.jar"), + found.jars["server"].clone(), + ]; + files.extend(found.libraries); + files.extend(client); + Ok(files) + }; + if checked(lock.directory.clone()).is_ok() { + log(&format!("Using imported Minecraft {}", lock.version)); + return Ok(true); + } + let Some(versions) = root.parent() else { + return Ok(false); + }; + let mut siblings: Vec<_> = fs::read_dir(versions) + .map_err(|e| format!("{}: {e}", versions.display()))? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path != &root && path.is_dir()) + .collect(); + siblings.sort(); + for sibling in siblings { + let source = sibling.join(".local/minecraft").join(&lock.version); + let Ok(files) = checked(source.clone()) else { + continue; + }; + for file in files { + let relative = file.strip_prefix(&source).map_err(|e| e.to_string())?; + import_copy( + &file, + &lock.directory.join(relative), + &digest(&file, "sha256")?, + "sha256", + "", + )?; + } + checked(lock.directory.clone())?; + log(&format!( + "Reused imported Minecraft {} from {}", + lock.version, + sibling.display() + )); + return Ok(true); + } + Ok(false) +} + pub fn verify(lock: &Lock) -> Result { let manifest_path = lock.directory.join("manifest.json"); if !manifest_path.exists() { @@ -597,7 +660,10 @@ pub fn verify(lock: &Lock) -> Result { .and_then(|d| d.get(side)) .and_then(|d| d.get("sha1")) .and_then(Value::as_str); - if !jar.exists() || Some(digest(&jar, "sha1")?.as_str()) != pinned { + if pinned != Some(lock.pin(&format!("{side}_sha1"))?) + || !jar.exists() + || Some(digest(&jar, "sha1")?.as_str()) != pinned + { return Err(format!( "{side} artifact checksum changed; prepare again with --prepare" )); @@ -648,6 +714,167 @@ pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, S #[cfg(test)] mod tests { use super::*; + use std::io::Write; + + struct Imports { + directory: PathBuf, + source: PathBuf, + target: PathBuf, + } + + impl Imports { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let directory = std::env::temp_dir() + .join(format!("horizon-import-reuse-{}-{n}", std::process::id())); + let source = directory.join("old"); + let target = directory.join("new"); + fs::create_dir_all(&target).unwrap(); + let imported = source.join(".local/minecraft/9.9"); + let write = |path: &str, data: &[u8]| { + let path = imported.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + write("jars/client.jar", b"client"); + write("jars/server-game.jar", b"server game"); + write("libraries/server/server.jar", b"server library"); + write("libraries/client/client.jar", b"client library"); + write("reports/private.txt", b"not an imported artifact"); + let mut bundle = + zip::ZipWriter::new(fs::File::create(imported.join("jars/server.jar")).unwrap()); + let entries = [ + ( + "META-INF/versions.list", + format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(b"server game")), + ), + ( + "META-INF/libraries.list", + format!( + "{}\tserver:library:1\tserver.jar\n", + crate::sha256_hex(b"server library") + ), + ), + ]; + for (name, text) in entries { + bundle + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + bundle.write_all(text.as_bytes()).unwrap(); + } + for (name, bytes) in [ + ("META-INF/versions/game.jar", b"server game".as_slice()), + ( + "META-INF/libraries/server.jar", + b"server library".as_slice(), + ), + ] { + bundle + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + bundle.write_all(bytes).unwrap(); + } + bundle.finish().unwrap(); + let client_sha1 = digest(&imported.join("jars/client.jar"), "sha1").unwrap(); + let server_sha1 = digest(&imported.join("jars/server.jar"), "sha1").unwrap(); + let library_sha1 = + digest(&imported.join("libraries/client/client.jar"), "sha1").unwrap(); + let manifest = format!( + "{{\"id\":\"9.9\",\"downloads\":{{\"client\":{{\"sha1\":\"{client_sha1}\"}},\"server\":{{\"sha1\":\"{server_sha1}\"}}}},\"libraries\":[{{\"name\":\"client:library:1\",\"downloads\":{{\"artifact\":{{\"path\":\"client.jar\",\"sha1\":\"{library_sha1}\"}}}}}}]}}" + ); + write("manifest.json", manifest.as_bytes()); + let manifest_sha1 = digest(&imported.join("manifest.json"), "sha1").unwrap(); + let lock = format!( + "{{\"minecraft\":{{\"version\":\"9.9\",\"java_major\":25,\"manifest_sha1\":\"{manifest_sha1}\",\"client_sha1\":\"{client_sha1}\",\"server_sha1\":\"{server_sha1}\"}}}}" + ); + fs::write(target.join("research-lock.json"), lock).unwrap(); + Self { + directory, + source, + target, + } + } + + fn imported(&self, root: &Path) -> PathBuf { + root.join(".local/minecraft/9.9") + } + } + + impl Drop for Imports { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.directory); + } + } + + #[test] + fn imported_files_are_reused_without_the_official_install() { + let fixture = Imports::new(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + let lock = Lock::read(&fixture.target).unwrap(); + let artifacts = verify(&lock).unwrap(); + assert_eq!( + client_libraries(&lock, &artifacts.manifest).unwrap().len(), + 1 + ); + assert_eq!(artifacts.libraries.len(), 1); + assert!(!lock.directory.join("reports/private.txt").exists()); + // The current root's valid imports suffice even after the older copy is corrupted. + fs::write( + fixture.imported(&fixture.source).join("jars/client.jar"), + b"bad", + ) + .unwrap(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + } + + #[test] + fn reuse_rejects_corrupt_imports() { + for file in [ + "manifest.json", + "jars/client.jar", + "jars/server.jar", + "jars/server-game.jar", + "libraries/client/client.jar", + "libraries/server/server.jar", + ] { + let fixture = Imports::new(); + fs::write(fixture.imported(&fixture.source).join(file), b"bad").unwrap(); + assert!(!reuse_imported(&fixture.target, &|_| {}).unwrap(), "{file}"); + assert!(!fixture.imported(&fixture.target).exists()); + } + } + + #[test] + fn reuse_checks_the_target_pins() { + let fixture = Imports::new(); + let mut lock = Lock::read(&fixture.target).unwrap(); + let client = lock.pin("client_sha1").unwrap().to_string(); + let text = fs::read_to_string(fixture.target.join("research-lock.json")).unwrap(); + fs::write( + fixture.target.join("research-lock.json"), + text.replace(&client, "wrong-client-pin"), + ) + .unwrap(); + assert!(!reuse_imported(&fixture.target, &|_| {}).unwrap()); + lock.directory = fixture.imported(&fixture.source); + assert!(verify(&lock).is_ok()); + } + + #[test] + fn reuse_skips_a_bad_sibling_and_repairs_bad_current_imports() { + let fixture = Imports::new(); + let bad = fixture.directory.join("a-bad"); + fs::rename(&fixture.source, &bad).unwrap(); + let valid = Imports::new(); + fs::rename(&valid.source, &fixture.source).unwrap(); + fs::write(fixture.imported(&bad).join("jars/client.jar"), b"bad").unwrap(); + let target = fixture.imported(&fixture.target); + fs::create_dir_all(target.join("jars")).unwrap(); + fs::write(target.join("jars/client.jar"), b"bad").unwrap(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + assert_eq!(fs::read(target.join("jars/client.jar")).unwrap(), b"client"); + } #[test] fn natives_follow_the_architecture() { diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 246cb4d51..24cf44645 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -402,7 +402,7 @@ pub fn prepare(options: &Options, log: Log) -> Result { let lock = artifacts::Lock::read(root)?; // Java first: nothing below can finish without it, and the player should hear it at once. let jdk = java::find(lock.java_major)?; - if options.import { + if options.import && !artifacts::reuse_imported(root, log)? { artifacts::import( root, &lock, diff --git a/launcher/README.md b/launcher/README.md index f77d345d2..4eda309d1 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -21,7 +21,10 @@ The opening, then Play ([clip](docs/opening.webm)): server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is horizon-prepare: linked into the launcher, used in-process when a version ships the same preparer sources, else that version's own `horizon-prepare`; versions released before it - still prepare with their Python script and need Python 3.10+. + still prepare with their Python script and need Python 3.10+. Before importing, + preparation reuses checksum-verified game jars and libraries from the current + or another installed Horizon version, so the original Minecraft install is + only required when no valid imported copy exists. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Join Discord" and "Website" links sit in the sidebar footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 354837d2c..6bac3f6cd 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -591,17 +591,18 @@ fn preparer_binary(dir: &Path) -> Option { /// Java (and Python, for versions before horizon-prepare). pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result { let version = game_version(tag); + let dir = version_dir(tag); + let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?; let manifest = minecraft .join("versions") .join(&version) .join(format!("{version}.json")); - if !manifest.exists() { + if !reused && !manifest.exists() { return Err(format!( "Minecraft {version} is not in {}. Play {version} once from the official launcher, or choose another folder.", minecraft.display() )); } - let dir = version_dir(tag); let binary = preparer_binary(&dir); let python = if binary.is_some() { // The JDK the version pins, found as horizon-prepare finds it, so a missing one is @@ -625,7 +626,7 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result
 Result
 Result<(), String> {
 }
 
 /// The Minecraft folder to prepare from: the one given, the one chosen in the launcher, or the
-/// official launcher's default.
+/// official launcher's default. It may be absent when imported files can be reused.
 pub fn minecraft_dir(requested: Option) -> Result {
-    requested
+    Ok(requested
         .or(Settings::load().minecraft_dir)
         .or_else(default_minecraft_dir)
-        .ok_or_else(|| {
-            "No Minecraft folder found. Pass the official launcher's game folder.".into()
-        })
+        .unwrap_or_else(|| horizon_prepare::artifacts::minecraft_dir(None)))
 }
 
 /// The server folder: the one given, the one chosen in the launcher, or `server/` in the data folder.
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index be556226f..2a950b1a4 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -501,10 +501,11 @@ impl Launcher {
         let Some(tag) = self.selected().cloned() else {
             return;
         };
-        let Some(minecraft) = self.settings.minecraft_dir.clone() else {
-            self.prepare_error = Some("Choose your Minecraft folder first.".into());
-            return;
-        };
+        let minecraft = self
+            .settings
+            .minecraft_dir
+            .clone()
+            .unwrap_or_else(|| horizon_prepare::artifacts::minecraft_dir(None));
         self.prepare_log.clear();
         self.prepare_error = None;
         self.prepare_log

From 56aae0e9023609cbc1efaa1e59f3e6fd60fe9968 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 21:00:13 +0200
Subject: [PATCH 25/43] Maces smash: fall damage bonus, Density, Breach, Wind
 Burst, knockback

A mace hit after falling more than 1.5 blocks is now a smash attack
(MaceItem): the fall-based damage bonus plus Density, mace_smash damage,
the stopped fall with its damage waived, the ground/air smash sounds, the
dust pillars (level event 2013) and the knockback of the creatures around
the target, then the fall reset and landing particles. Breach thins the
target's armor (CombatRules.getDamageAfterAbsorb), Wind Burst bursts at
the player's feet (ExplodeEffect, trigger), and weapons wear by their
weapon component and award the used statistic.

Vanilla details matched on the way: the hurt knockback is 0.4F and reads
the live knockback-resistance attribute, explosion exposure uses the
exact COLLIDER clip, a burst posts the explode game event and ends the
impulse grace unless it is a wind charge's, visible armor stands feel
bursts that affect block-like entities, attack sounds play at the player.

tools/test_mace_parity.py compares the hit with VanillaDispenserOracle's
real MaceItem / hurtServer / post-attack effects: 3000/3000.

Co-Authored-By: Claude Opus 5.5 
---
 crates/horizon-client/src/enchant.rs          |  35 +-
 crates/horizon-client/src/game.rs             |  78 +++--
 .../src/game/commands/world_cmds.rs           |   1 +
 crates/horizon-client/src/game/creatures.rs   |   1 +
 .../src/game/dispense_fixture.rs              | 141 +++++++-
 .../src/game/enchant_effects.rs               |  63 ++++
 crates/horizon-client/src/game/explosion.rs   | 117 +++++--
 crates/horizon-client/src/game/mace.rs        | 330 ++++++++++++++++++
 crates/horizon-client/src/game/sculk.rs       |  13 +
 crates/horizon-client/src/game/wind.rs        |  64 +++-
 crates/horizon-client/src/items.rs            |   7 +
 crates/horizon-client/src/mobs.rs             |  30 +-
 crates/horizon-client/src/mobs/creaking.rs    |   1 +
 crates/horizon-client/src/mobs/guardian.rs    |   5 +-
 crates/horizon-client/src/mobs/sulfur_cube.rs |   1 +
 crates/horizon-client/src/motion.rs           |  20 ++
 .../parity/VanillaBlockUpdateOracle.java      |   2 +
 .../parity/VanillaDispenserOracle.java        | 157 +++++++++
 tools/test_mace_parity.py                     | 204 +++++++++++
 19 files changed, 1174 insertions(+), 96 deletions(-)
 create mode 100644 crates/horizon-client/src/game/mace.rs
 create mode 100644 tools/test_mace_parity.py

diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs
index 6e806712a..c62a67a07 100644
--- a/crates/horizon-client/src/enchant.rs
+++ b/crates/horizon-client/src/enchant.rs
@@ -628,7 +628,8 @@ impl Enchantments {
                 } else {
                     spec
                 };
-                spec.is_null() && entity.is_some() || self.entity_matches(spec, entity)
+                (spec.is_null() && entity.is_some() || self.entity_matches(spec, entity))
+                    && movement_matches(&c["predicate"], role_state(c, ctx))
             }
             "minecraft:random_chance" => {
                 let chance = match &c["chance"] {
@@ -661,6 +662,38 @@ pub struct EffectContext<'a> {
     pub this: Option<&'a str>,
     pub attacker: Option<&'a str>,
     pub direct_attacker: Option<&'a str>,
+    /// The direct attacker's fall distance and whether it flies (elytra or
+    /// abilities), for `movement` and `flags` predicates.
+    pub direct_motion: Option<(f64, bool)>,
+}
+/// The fall distance and flying flag known for an `entity_properties` role.
+fn role_state(c: &Value, ctx: &EffectContext<'_>) -> Option<(f64, bool)> {
+    match c["entity"].as_str().unwrap_or("this") {
+        "direct_attacker" => ctx.direct_motion,
+        _ => None,
+    }
+}
+/// `EntityPredicate`'s `minecraft:movement` fall distance and
+/// `minecraft:flags` is_flying (the parts enchantment requirements use); an
+/// entity whose state is unknown matches neither.
+fn movement_matches(predicate: &Value, state: Option<(f64, bool)>) -> bool {
+    let fall = &predicate["minecraft:movement"]["fall_distance"];
+    let flying = predicate["minecraft:flags"]["is_flying"].as_bool();
+    if fall.is_null() && flying.is_none() {
+        return true;
+    }
+    let Some((distance, is_flying)) = state else {
+        return false;
+    };
+    // MinMaxBounds.Doubles: a number is an exact bound.
+    let bound = |key: &str| {
+        fall.as_f64()
+            .or_else(|| fall.get(key).and_then(Value::as_f64))
+    };
+    // MinMaxBounds.Doubles.matches
+    bound("min").is_none_or(|min| min <= distance)
+        && bound("max").is_none_or(|max| distance <= max)
+        && flying.is_none_or(|f| f == is_flying)
 }
 fn next_int(random: &mut R, bound: i32) -> i32 {
     random.next_int_bound(bound.max(1)).unwrap_or(0)
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 890387ac8..2ace3cd25 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -58,6 +58,7 @@ mod level_particles;
 mod lightning;
 mod llamas;
 mod loom;
+mod mace;
 mod machines;
 mod maps;
 mod minecarts;
@@ -1640,6 +1641,11 @@ impl Game<'_> {
                 LevelEvent::LevelEvent { id: 2004, pos, .. } => {
                     self.spawner_burst([pos.x, pos.y, pos.z])
                 }
+                LevelEvent::LevelEvent {
+                    id: 2013,
+                    pos,
+                    data,
+                } => self.smash_dust(pos, data),
                 LevelEvent::LevelEvent {
                     id: id @ 3002..=3005,
                     pos,
@@ -2916,6 +2922,11 @@ impl Game<'_> {
                 MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
                 MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
                 MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
+                MotionEvent::SmashLanding {
+                    state,
+                    position,
+                    fall_distance,
+                } => self.smash_landing_particles(state, position, fall_distance),
                 _ => {}
             }
         }
@@ -5182,19 +5193,20 @@ impl Game<'_> {
         let delay = 20.0 / speed;
         let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
         let mut amount = damage * (0.2 + scale * scale * 0.8);
+        let target_kind = self.mobs[index].kind.id.clone();
+        let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
+        // Item.getAttackDamageBonus (a mace's smash), before the critical hit.
+        amount += self.smash_damage_bonus(&target_kind);
         let player = self.player.as_ref();
+        // Player.canCriticalAttack: falling, off the ground, not sprinting.
         let falling =
-            player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting);
+            player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
         let crit = scale > 0.9 && falling;
         if crit {
             amount *= 1.5;
         }
         // Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
-        let target_kind = self.mobs[index].kind.id.clone();
-        amount += self.enchant_damage_bonus(&format!(
-            "minecraft:{}",
-            target_kind.trim_start_matches("minecraft:")
-        )) * scale;
+        amount += self.enchant_damage_bonus(&target_kind) * scale;
         self.attack_ticks = 0;
         if let Some(p) = self.player.as_mut()
             && !self.creative
@@ -5206,21 +5218,23 @@ impl Game<'_> {
         self.swing_arm();
         // LivingEntity.setLastHurtMob (tamed wolves join in).
         self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
-        let mob = &mut self.mobs[index];
-        let center = [
-            mob.position.x,
-            mob.position.y + mob.kind.height / 2.0,
-            mob.position.z,
-        ];
-        let dealt = (amount.min(mob.health.max(0.0)) * 10.0).round() as i32;
-        if mob.hurt(amount, from, &mut self.world.random) {
-            self.stats.custom("damage_dealt", dealt);
+        let old_health = self.mobs[index].health;
+        let source = match from {
+            Some(f) => self.attack_source(f),
+            None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic),
+        };
+        if self.hurt_by_player(index, amount, source) {
+            let mob = &self.mobs[index];
+            // Player.damageStatsAndHearts: the damage the hit actually did.
+            let actual = old_health - mob.health;
             // Player.attack: crit emitter and damage indicator hearts.
             let (feet, width, height) = (
                 [mob.position.x, mob.position.y, mob.position.z],
                 mob.kind.width,
                 mob.kind.height,
             );
+            self.stats
+                .custom("damage_dealt", (actual * 10.0).round() as i32);
             if crit {
                 self.particles.tracking_emitter(
                     horizon_client::particles::ParticleOptions::simple(
@@ -5231,7 +5245,7 @@ impl Game<'_> {
                     height,
                 );
             }
-            if amount > 2.0 {
+            if actual > 2.0 {
                 let indicator = horizon_client::particles::ParticleOptions::simple(
                     horizon_client::particles::ParticleType::DamageIndicator,
                 );
@@ -5240,10 +5254,10 @@ impl Game<'_> {
                     [feet[0], feet[1] + height * 0.5, feet[2]],
                     [0.1, 0.0, 0.1],
                     0.2,
-                    (amount * 0.5) as u32,
+                    (actual * 0.5) as u32,
                 );
             }
-            self.last_hurt_by_player.insert(mob.id);
+            self.last_hurt_by_player.insert(self.mobs[index].id);
             let sound = if crit {
                 "minecraft:entity.player.attack.crit"
             } else if scale > 0.9 {
@@ -5251,33 +5265,21 @@ impl Game<'_> {
             } else {
                 "minecraft:entity.player.attack.weak"
             };
-            self.audio.play(sound, Some(center), 1.0, 1.0);
+            // Player.playServerSideSound: at the player.
+            self.audio.play(sound, from, 1.0, 1.0);
             // The hurt or death sound the mob raised (getHurtSound / getDeathSound,
             // its voice pitch from its own random).
             let queued = std::mem::take(&mut self.mobs[index].outbox);
             for event in queued {
-                if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event {
+                if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
                     self.audio
-                        .play(&format!("minecraft:{s}"), Some(center), volume, pitch);
-                }
-            }
-            self.post_attack(index);
-            if let Some(stack) = self.inventory[self.selected].clone()
-                && let Some(max) = self
-                    .res
-                    .items
-                    .get(&stack.item)
-                    .filter(|i| i.max_damage > 0)
-                    .map(|i| i.max_damage)
-            {
-                let loss = self.durability_loss(&stack, 1);
-                if let Some(stack) = self.inventory[self.selected].as_mut() {
-                    stack.damage += loss;
-                    if stack.damage >= max {
-                        self.inventory[self.selected] = None;
-                    }
+                        .play(&format!("minecraft:{s}"), Some(at), volume, pitch);
                 }
             }
+            self.weapon_hit(index);
+        } else {
+            self.audio
+                .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
         }
         true
     }
diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs
index 43049111a..578153247 100644
--- a/crates/horizon-client/src/game/commands/world_cmds.rs
+++ b/crates/horizon-client/src/game/commands/world_cmds.rs
@@ -89,6 +89,7 @@ impl Game<'_> {
     fn damage_kind(ty: &str) -> DamageKind {
         match ty.trim_start_matches("minecraft:") {
             "player_attack" => DamageKind::PlayerAttack,
+            "mace_smash" => DamageKind::MaceSmash,
             "mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
             "arrow" => DamageKind::Arrow,
             "thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index ab480f1c0..6a0757252 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -2572,6 +2572,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
     use horizon_client::mobs::DamageKind as K;
     match kind {
         K::PlayerAttack => "minecraft:player_attack",
+        K::MaceSmash => "minecraft:mace_smash",
         K::MobAttack => "minecraft:mob_attack",
         K::Arrow => "minecraft:arrow",
         K::Thrown => "minecraft:thrown",
diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs
index 355a188da..f8440f06e 100644
--- a/crates/horizon-client/src/game/dispense_fixture.rs
+++ b/crates/horizon-client/src/game/dispense_fixture.rs
@@ -59,8 +59,18 @@ pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
     }
 }
 
+/// Java's `String.format("%.6f")`: the exact value rounded half up (away
+/// from zero) where Rust rounds a tie to even.
 fn num(v: f64) -> String {
-    format!("{v:.6}")
+    let exact = format!("{:.40}", v.abs());
+    let tie = exact
+        .split_once('.')
+        .is_some_and(|(_, f)| f[6..].starts_with('5') && f[7..].bytes().all(|b| b == b'0'));
+    if tie {
+        format!("{:.6}", v + 0.5e-6_f64.copysign(v))
+    } else {
+        format!("{v:.6}")
+    }
 }
 fn floor_pos(p: [f64; 3]) -> String {
     format!(
@@ -299,6 +309,8 @@ impl Game<'_> {
                 ),
                 None => "respawn none".to_owned(),
             });
+        } else if let Some(op) = case.get("attack") {
+            used = self.fixture_attack(op, &targets)?;
         } else if case.get("hopper").is_some() {
             // HopperBlockEntity.pushItemsTick, once.
             self.hopper_try_move_items((origin.x, origin.y, origin.z));
@@ -559,6 +571,119 @@ impl Game<'_> {
         Ok(out)
     }
 
+    /// The player's hit on the first target with the case's item, from the
+    /// attack strength's scaled `base` damage on: the item's damage bonus and
+    /// source, the hurt with the weapon's armor effects, then `weapon_hit`
+    /// (the mace's smash, post-attack enchantments, the wear), as
+    /// `VanillaDispenserOracle.attack` prints them.
+    fn fixture_attack(&mut self, op: &Value, targets: &[Target]) -> Result> {
+        let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
+        self.mode = if op["creative"].as_bool().unwrap_or(false) {
+            GameMode::Creative
+        } else {
+            GameMode::Survival
+        };
+        self.creative = self.mode == GameMode::Creative;
+        let v3 = |v: &Value| {
+            horizon_core::geometry::Vec3::new(
+                v[0].as_f64().unwrap_or(0.0),
+                v[1].as_f64().unwrap_or(0.0),
+                v[2].as_f64().unwrap_or(0.0),
+            )
+        };
+        let mut player = PlayerMotion::new(self.motion, v3(&op["player"]))?;
+        player.velocity = v3(&op["motion"]);
+        player.fall_distance = op["fall"].as_f64().unwrap_or(0.0);
+        player.fall_flying = op["fall_flying"].as_bool().unwrap_or(false);
+        player.flying = op["flying"].as_bool().unwrap_or(false);
+        player.may_fly = self.creative;
+        if !op["impact"].is_null() {
+            player.impulse.impact_position = Some(v3(&op["impact"]));
+        }
+        let feet = [player.position.x, player.position.y, player.position.z];
+        self.player = Some(player);
+        self.inventory[self.selected] = stack.clone();
+        let used_before = stack
+            .as_ref()
+            .map_or(0, |s| self.stats.get("used", &s.item));
+        let Some(&Target::Mob(id)) = targets.first() else {
+            return Err("an attack case hits a mob".into());
+        };
+        let index = self
+            .mobs
+            .iter()
+            .position(|m| m.id == id)
+            .ok_or("the target is gone")?;
+        let kind = self.mobs[index].kind.id.clone();
+        let base = op["base"].as_f64().unwrap_or(0.0) as f32;
+        let bonus = self.smash_damage_bonus(&kind);
+        let source = self.attack_source(feet);
+        let hurt = self.hurt_by_player(index, base + bonus, source);
+        // The hurt sound the mob raised, where it stands.
+        for event in std::mem::take(&mut self.mobs[index].outbox) {
+            if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
+                self.audio
+                    .play(&format!("minecraft:{s}"), Some(at), volume, pitch);
+            }
+        }
+        if hurt {
+            self.weapon_hit(index);
+        }
+        self.process_level_events()?;
+        let mut out = Vec::new();
+        if let Some(s) = &stack {
+            let used = self.stats.get("used", &s.item) - used_before;
+            if used != 0 {
+                out.push(format!("stat {} minecraft:used {used}", s.item));
+            }
+        }
+        let source = match source.kind {
+            horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
+            _ => "minecraft:player_attack",
+        };
+        out.push(format!(
+            "attack bonus={} source={source} hurt={hurt}",
+            num(f64::from(bonus))
+        ));
+        for (i, t) in targets.iter().enumerate() {
+            let (health, v) = match *t {
+                Target::Mob(id) => match self.mobs.iter().find(|m| m.id == id) {
+                    Some(m) => (num(f64::from(m.health)), m.velocity),
+                    None => continue,
+                },
+                Target::Stand(id) => match self.armor_stands.iter().find(|s| s.id == id) {
+                    Some(s) => ("-".to_owned(), s.velocity),
+                    None => continue,
+                },
+            };
+            out.push(format!(
+                "V {i} {health} {} {} {}",
+                num(v.x),
+                num(v.y),
+                num(v.z)
+            ));
+        }
+        if let Some(p) = self.player.take() {
+            let impact = p.impulse.impact_position.map_or("-".to_owned(), |i| {
+                format!("{},{},{}", num(i.x), num(i.y), num(i.z))
+            });
+            out.push(format!(
+                "P {} {} {} fall={} impact={impact} grace={} extra={}",
+                num(p.velocity.x),
+                num(p.velocity.y),
+                num(p.velocity.z),
+                num(p.fall_distance),
+                p.impulse.reset_grace_time,
+                p.spawn_extra_particles_on_fall
+            ));
+        }
+        out.push(format!(
+            "held {}",
+            canon_stack(self.inventory[self.selected].as_ref())
+        ));
+        Ok(out)
+    }
+
     /// A stack in a block entity's slot: a container's, a jukebox's record, a
     /// lectern's book, or the items of a block entity Horizon keeps as saved.
     fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) {
@@ -678,8 +803,10 @@ impl Game<'_> {
         self.next_entity += 1;
         let id = self.next_entity;
         if kind == "minecraft:armor_stand" {
-            self.armor_stands
-                .push(horizon_client::entities::ArmorStand::new(id, at, yaw));
+            let mut stand = horizon_client::entities::ArmorStand::new(id, at, yaw);
+            stand.marker = e["marker"].as_bool().unwrap_or(false);
+            stand.on_ground = e["ground"].as_bool().unwrap_or(false);
+            self.armor_stands.push(stand);
             return Ok(Target::Stand(id));
         }
         let t = self
@@ -728,6 +855,14 @@ impl Game<'_> {
         if flag("loot") {
             mob.extra.pick_up_loot = true;
         }
+        mob.on_ground = flag("ground");
+        if let Some(health) = e["health"].as_f64() {
+            mob.attrs.max_health = health as f32;
+            mob.health = health as f32;
+        }
+        if let Some(resistance) = e["knockback_resistance"].as_f64() {
+            mob.attrs.knockback_resistance = resistance;
+        }
         if flag("brown") && s == Species::Mooshroom {
             mob.extra.variant = 1;
         }
diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs
index 88268379a..5f98fa52a 100644
--- a/crates/horizon-client/src/game/enchant_effects.rs
+++ b/crates/horizon-client/src/game/enchant_effects.rs
@@ -165,6 +165,69 @@ impl Game<'_> {
             self.potions.burning.retain(|(m, _)| *m != id);
             self.potions.burning.push((id, (ignite * 20.0) as i32));
         }
+        self.post_attack_bursts(&held, &kind);
+    }
+    /// `minecraft:post_attack` explode effects on the attacker (wind burst):
+    /// a burst at the player's feet that only knocks back and triggers
+    /// blocks (`ExplodeEffect` with `block_interaction: trigger`).
+    fn post_attack_bursts(&mut self, held: &ItemStack, victim: &str) {
+        let Some(p) = self.player.as_ref() else {
+            return;
+        };
+        // EntityFlagsPredicate.isFlying: gliding or flying.
+        let motion = (p.fall_distance, p.fall_flying || p.flying);
+        let feet = [p.position.x, p.position.y, p.position.z];
+        let ctx = EffectContext {
+            this: Some(victim),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            items: Some(&self.res.items),
+            direct_motion: Some(motion),
+            ..Default::default()
+        };
+        let mut bursts = Vec::new();
+        for (id, level) in held.enchantments() {
+            let Some(def) = self.res.stations.enchantments.get(id) else {
+                continue;
+            };
+            for effect in def.effects["minecraft:post_attack"]
+                .as_array()
+                .into_iter()
+                .flatten()
+            {
+                let e = &effect["effect"];
+                if effect["enchanted"] != "attacker"
+                    || effect["affected"] != "attacker"
+                    || e["type"] != "minecraft:explode"
+                    || e["block_interaction"] != "trigger"
+                {
+                    continue;
+                }
+                let ok = effect.get("requirements").is_none_or(|r| {
+                    self.res.stations.enchantments.condition(
+                        r,
+                        *level,
+                        &ctx,
+                        &mut self.world.random,
+                    )
+                });
+                if !ok {
+                    continue;
+                }
+                let radius = horizon_client::enchant::level_value(&e["radius"], *level).max(0.0);
+                // ExplosionDamageCalculator.getKnockbackMultiplier: 1 unless given.
+                let knockback = if e["knockback_multiplier"].is_null() {
+                    1.0
+                } else {
+                    horizon_client::enchant::level_value(&e["knockback_multiplier"], *level)
+                };
+                bursts.push((radius, knockback));
+            }
+        }
+        for (radius, knockback) in bursts {
+            let _ = self.wind_burst(feet, radius, knockback, false, false);
+        }
     }
     /// Burning mobs (fire aspect): one damage every 20 ticks, flame particles.
     pub(super) fn tick_burning(&mut self) {
diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs
index c03b99609..b871e8df9 100644
--- a/crates/horizon-client/src/game/explosion.rs
+++ b/crates/horizon-client/src/game/explosion.rs
@@ -3,14 +3,64 @@
 //! draws), entity damage with exposure and knockback, block interaction with
 //! merged drops and TNT chain priming, and optional fire.
 use super::Game;
-use horizon_client::{Result, blocks::Fluid, items::ItemStack};
+use horizon_client::{Result, blocks::Fluid, collisions::SceneCollisions, items::ItemStack};
 use horizon_core::{
-    geometry::Vec3,
+    geometry::{Vec3, VoxelShape},
     position::BlockPos,
     random::{LegacyRandom, RandomSource},
 };
-use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
-use std::cmp::Ordering;
+use horizon_world::{
+    collision_context::{CollisionContext, CollisionEntity, CollisionItem},
+    entity_obstruction::EntityIdentity,
+    java_hash_map::{JavaHashMap, JavaKey},
+    registry::BlockStateId,
+    world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world},
+};
+use std::{cmp::Ordering, io};
+
+/// `Level.clip` with `ClipContext.Block.COLLIDER`, no fluids and the
+/// collision context of the entity whose exposure is measured.
+struct ColliderRays<'a, 'r> {
+    scene: SceneCollisions<'a, 'r>,
+    context: CollisionContext<'static>,
+}
+impl RayWorld for ColliderRays<'_, '_> {
+    type Error = io::Error;
+    type Block = BlockStateId;
+    type Fluid = ();
+    fn block_state(&mut self, p: BlockPos) -> io::Result {
+        Ok(self.scene.world.block(p.x, p.y, p.z))
+    }
+    fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> {
+        Ok(())
+    }
+    fn block_shape(
+        &mut self,
+        state: BlockStateId,
+        p: BlockPos,
+        _: RayBlockMode,
+    ) -> io::Result {
+        let binding = self.scene.binding;
+        binding
+            .collision_shape_with_context(&mut self.scene, state, p, &self.context)
+            .map_err(|e| io::Error::other(format!("{e:?}")))
+    }
+    fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result {
+        Ok(VoxelShape::empty())
+    }
+    fn fluid_is_source(&mut self, _: ()) -> io::Result {
+        Ok(false)
+    }
+    fn fluid_is_empty(&mut self, _: ()) -> io::Result {
+        Ok(true)
+    }
+    fn fluid_is_water(&mut self, _: ()) -> io::Result {
+        Ok(false)
+    }
+    fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result {
+        Ok(VoxelShape::empty())
+    }
+}
 
 /// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
 #[derive(Clone, Copy, PartialEq, Eq)]
@@ -48,35 +98,6 @@ pub(super) fn client_float() -> f32 {
 }
 
 impl Game<'_> {
-    /// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
-    /// collision cubes as obstacles.
-    fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
-        let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
-        let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
-        let steps = (length / 0.1).ceil().max(1.0) as i32;
-        let mut last = [i32::MIN; 3];
-        for i in 0..=steps {
-            let t = f64::from(i) / f64::from(steps);
-            let b = [
-                (from[0] + d[0] * t).floor() as i32,
-                (from[1] + d[1] * t).floor() as i32,
-                (from[2] + d[2] * t).floor() as i32,
-            ];
-            if b == last {
-                continue;
-            }
-            last = b;
-            if self
-                .res
-                .facts
-                .get(self.world.block(b[0], b[1], b[2]))
-                .full_collision
-            {
-                return false;
-            }
-        }
-        true
-    }
     /// `ServerExplosion.getSeenPercent` for an entity box.
     pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
         let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
@@ -87,6 +108,23 @@ impl Game<'_> {
         if xs < 0.0 || ys < 0.0 || zs < 0.0 {
             return 0.0;
         }
+        // ClipContext(..., entity): the entity standing at the box's bottom.
+        let mut rays = ColliderRays {
+            scene: SceneCollisions {
+                world: &self.world,
+                binding: self.collision,
+                subject: None,
+            },
+            context: CollisionContext::for_entity(
+                CollisionEntity {
+                    identity: EntityIdentity(0),
+                    y: min[1],
+                    descending: false,
+                    main_hand: Some(CollisionItem::EMPTY),
+                },
+                false,
+            ),
+        };
         let (mut hits, mut count) = (0, 0);
         let mut xx = 0.0;
         while xx <= 1.0 {
@@ -97,7 +135,18 @@ impl Game<'_> {
                     let x = min[0] + (max[0] - min[0]) * xx;
                     let y = min[1] + (max[1] - min[1]) * yy;
                     let z = min[2] + (max[2] - min[2]) * zz;
-                    if self.clear_line([x + x_offset, y, z + z_offset], center) {
+                    let from = Vec3::new(x + x_offset, y, z + z_offset);
+                    let to = Vec3::new(center[0], center[1], center[2]);
+                    let missed = clip_world(
+                        &mut rays,
+                        from,
+                        to,
+                        RayBlockMode::Collider,
+                        RayFluidMode::None,
+                        4096,
+                    )
+                    .is_ok_and(|r| r.miss);
+                    if missed {
                         hits += 1;
                     }
                     count += 1;
diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs
new file mode 100644
index 000000000..062d04525
--- /dev/null
+++ b/crates/horizon-client/src/game/mace.rs
@@ -0,0 +1,330 @@
+//! Maces (`MaceItem`): a hit after falling more than one and a half blocks is
+//! a smash attack. It adds damage for the height fallen (more with Density),
+//! stops the fall, cancels its damage and knocks the creatures around the
+//! target away. The rest of a weapon hit (`Player.itemAttackInteraction`)
+//! is here too: `hurtEnemy`, the post-attack enchantments and `postHurtEnemy`.
+use super::Game;
+use horizon_client::{
+    enchant::EffectContext,
+    mobs::{Damage, Mob, Species},
+    particles::{ParticleOptions, ParticleType},
+};
+use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
+use horizon_world::registry::BlockStateId;
+
+/// `MaceItem.SMASH_ATTACK_FALL_THRESHOLD`.
+const FALL_THRESHOLD: f64 = 1.5;
+/// `MaceItem.SMASH_ATTACK_HEAVY_THRESHOLD`.
+const HEAVY_THRESHOLD: f64 = 5.0;
+/// `MaceItem.SMASH_ATTACK_KNOCKBACK_RADIUS`.
+const KNOCKBACK_RADIUS: f64 = 3.5;
+/// `MaceItem.SMASH_ATTACK_KNOCKBACK_POWER`.
+const KNOCKBACK_POWER: f32 = 0.7;
+
+/// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob
+/// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and
+/// `Allay.considersEntityAsAlly` (an allay that likes it).
+fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
+    let tamable = matches!(
+        m.species(),
+        Species::Wolf
+            | Species::Cat
+            | Species::Parrot
+            | Species::Nautilus
+            | Species::ZombieNautilus
+    );
+    tamable && m.extra.tame && m.extra.owner.is_some() && m.extra.owner == player
+        || m.species() == Species::Allay && m.extra.tame
+}
+
+impl Game<'_> {
+    fn holds_mace(&self) -> bool {
+        self.inventory[self.selected]
+            .as_ref()
+            .is_some_and(|s| &*s.item == "minecraft:mace")
+    }
+    /// `MaceItem.canSmashAttack` for the player: falling and not gliding.
+    fn can_smash_attack(&self) -> bool {
+        self.player
+            .as_ref()
+            .is_some_and(|p| p.fall_distance > FALL_THRESHOLD && !p.fall_flying)
+    }
+    /// A held mace about to smash (`MaceItem.getItemDamageSource`: the attack
+    /// is `mace_smash` damage).
+    pub(super) fn smash_attack(&self) -> bool {
+        self.holds_mace() && self.can_smash_attack()
+    }
+    /// The damage source of the player's hit from `from` with the held item.
+    pub(super) fn attack_source(&self, from: [f64; 3]) -> Damage {
+        if self.smash_attack() {
+            Damage::mace(from)
+        } else {
+            Damage::player(from)
+        }
+    }
+    /// `MaceItem.getAttackDamageBonus` against `victim`: 4 per block for the
+    /// first three blocks fallen, 2 for the next five, 1 after that, plus
+    /// `smash_damage_per_fallen_block` (Density) for every block.
+    pub(super) fn smash_damage_bonus(&mut self, victim: &str) -> f32 {
+        if !self.smash_attack() {
+            return 0.0;
+        }
+        let fall = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
+        let damage = if fall <= 3.0 {
+            4.0 * fall
+        } else if fall <= 8.0 {
+            12.0 + 2.0 * (fall - 3.0)
+        } else {
+            22.0 + fall - 8.0
+        };
+        let held = self.inventory[self.selected].clone();
+        let ctx = EffectContext {
+            this: Some(victim),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            damage_type: Some("minecraft:mace_smash"),
+            items: Some(&self.res.items),
+            ..Default::default()
+        };
+        // EnchantmentHelper.modifyFallBasedDamage(..., 0)
+        let per_block = self.res.stations.enchantments.modify_value(
+            held.as_ref(),
+            "minecraft:smash_damage_per_fallen_block",
+            &ctx,
+            &mut self.world.random,
+            0.0,
+        );
+        (damage + f64::from(per_block) * fall) as f32
+    }
+    /// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
+    /// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
+    pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
+        let held = self.inventory[self.selected].clone();
+        let kind = self.mobs[index].kind.id.clone();
+        let ctx = EffectContext {
+            this: Some(&kind),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            damage_type: Some(match source.kind {
+                horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
+                _ => "minecraft:player_attack",
+            }),
+            items: Some(&self.res.items),
+            ..Default::default()
+        };
+        let enchantments = &self.res.stations.enchantments;
+        let random = &mut self.world.random;
+        // CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness.
+        let mut breach = |fraction: f32| {
+            enchantments.modify_value(
+                held.as_ref(),
+                "minecraft:armor_effectiveness",
+                &ctx,
+                random,
+                fraction,
+            )
+        };
+        let old_health = self.mobs[index].health;
+        let hurt = self.mobs[index].damage_with(amount, source, Some(&mut breach));
+        if hurt && self.mobs[index].health != old_health {
+            self.mob_damage_event(self.mobs[index].id);
+        }
+        hurt
+    }
+    /// `Player.itemAttackInteraction` after the player's hit landed on the mob
+    /// at `index`: the item's `hurtEnemy` (the "used" statistic of a weapon),
+    /// the post-attack enchantments, then `postHurtEnemy` with the weapon's
+    /// wear.
+    pub(super) fn weapon_hit(&mut self, index: usize) {
+        let Some(stack) = self.inventory[self.selected].clone() else {
+            return;
+        };
+        let weapon = self
+            .res
+            .items
+            .get(&stack.item)
+            .and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
+        let smash = self.smash_attack();
+        if smash {
+            self.mace_hurt_enemy(index);
+        }
+        if weapon.is_some() {
+            self.stats.add("used", &stack.item, 1);
+        }
+        self.post_attack(index);
+        // MaceItem.postHurtEnemy
+        if smash && let Some(p) = self.player.as_mut() {
+            p.fall_distance = 0.0;
+        }
+        // ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
+        if let Some((per_attack, max)) = weapon
+            && max > 0
+            && !self.creative
+        {
+            let loss = self.durability_loss(&stack, per_attack);
+            if let Some(held) = self.inventory[self.selected].as_mut() {
+                held.damage += loss;
+                if held.damage >= max {
+                    self.inventory[self.selected] = None;
+                }
+            }
+        }
+    }
+    /// `MaceItem.hurtEnemy` for a smash: the fall stops and its damage is
+    /// waived from where the hit landed, the ground or air smash sounds, and
+    /// the knockback around the target.
+    fn mace_hurt_enemy(&mut self, index: usize) {
+        let target_on_ground = self.mobs[index].on_ground;
+        let Some(p) = self.player.as_mut() else {
+            return;
+        };
+        p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z);
+        // calculateImpactPosition: an earlier impact below the player stays.
+        let impact = match p.impulse.impact_position {
+            Some(at) if at.y <= p.position.y => at,
+            _ => p.position,
+        };
+        p.impulse.set_ignore_fall_damage(true, Some(impact));
+        let fall = p.fall_distance;
+        let feet = [p.position.x, p.position.y, p.position.z];
+        let sound = if target_on_ground {
+            p.spawn_extra_particles_on_fall = true;
+            if fall > HEAVY_THRESHOLD {
+                "minecraft:item.mace.smash_ground_heavy"
+            } else {
+                "minecraft:item.mace.smash_ground"
+            }
+        } else {
+            "minecraft:item.mace.smash_air"
+        };
+        self.audio.play(sound, Some(feet), 1.0, 1.0);
+        self.smash_knockback(index, fall);
+    }
+    /// `MaceItem.knockback`: the dust pillar (level event 2013) under the
+    /// target, then every living entity within 3.5 blocks of it but the
+    /// player and the target pushed away and up, harder after a fall of more
+    /// than five blocks. Spectators, the player's allies (`isAlliedTo`: its
+    /// pets and the allays that like it), marker armor stands and creative
+    /// flyers are spared; the predicate's own tamed-animal test asks whether
+    /// the target owns the animal, which a mob never does.
+    fn smash_knockback(&mut self, index: usize, fall: f64) {
+        let target = &self.mobs[index];
+        let (id, center) = (target.id, target.position);
+        // Entity.getOnPos without a supporting block.
+        let on_pos = [
+            center.x.floor() as i32,
+            (center.y - f64::from(1.0e-5f32)).floor() as i32,
+            center.z.floor() as i32,
+        ];
+        self.level_event_at(2013, on_pos, 750);
+        let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 };
+        // getKnockbackPower and the push of one entity at `at`.
+        let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| {
+            let d = [at.x - center.x, at.y - center.y, at.z - center.z];
+            let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
+            if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
+                return;
+            }
+            let length = distance_sqr.sqrt();
+            let power = (KNOCKBACK_RADIUS - length)
+                * f64::from(KNOCKBACK_POWER)
+                * heavy
+                * (1.0 - resistance);
+            if power <= 0.0 {
+                return;
+            }
+            // Vec3.normalize: a vector shorter than 1e-5 has no direction.
+            let (x, z) = if length < f64::from(1.0e-5f32) {
+                (0.0, 0.0)
+            } else {
+                (d[0] / length * power, d[2] / length * power)
+            };
+            *velocity = Vec3::new(
+                velocity.x + x,
+                velocity.y + f64::from(KNOCKBACK_POWER),
+                velocity.z + z,
+            );
+        };
+        let player = self.level.player_uuid.or(Some([0, 0, 0, 1]));
+        for m in self
+            .mobs
+            .iter_mut()
+            .filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player))
+        {
+            push(m.position, &mut m.velocity, m.attrs.knockback_resistance);
+        }
+        for s in self.armor_stands.iter_mut().filter(|s| !s.marker) {
+            push(s.position, &mut s.velocity, 0.0);
+        }
+    }
+    /// `ServerPlayer.checkFallDamage` after a smash on a grounded target:
+    /// the landing block's particles, 50 for every block fallen (200 at most).
+    pub(super) fn smash_landing_particles(
+        &mut self,
+        state: BlockStateId,
+        pos: BlockPos,
+        fall_distance: f64,
+    ) {
+        let Some((sprite, tint)) = self.particle_sprite(state) else {
+            return;
+        };
+        let count = (50.0 * fall_distance).clamp(0.0, 200.0) as u32;
+        let spread = f64::from(0.3f32);
+        self.particles.send_particles(
+            &ParticleOptions::block(ParticleType::Block, sprite, tint),
+            [
+                f64::from(pos.x) + 0.5,
+                f64::from(pos.y) + 1.0,
+                f64::from(pos.z) + 0.5,
+            ],
+            [spread; 3],
+            f64::from(0.15f32),
+            count,
+        );
+    }
+    /// Level event 2013 (`ParticleUtils.spawnSmashAttackParticles`): dust
+    /// pillars of the block at `pos`, a cluster over it and a ring 3.5 out.
+    pub(super) fn smash_dust(&mut self, pos: BlockPos, count: i32) {
+        let state = self.world.block(pos.x, pos.y, pos.z);
+        let Some((sprite, tint)) = self.particle_sprite(state) else {
+            return;
+        };
+        let options = ParticleOptions::block(ParticleType::DustPillar, sprite, tint);
+        let center = [
+            f64::from(pos.x) + 0.5,
+            f64::from(pos.y) + 1.0,
+            f64::from(pos.z) + 0.5,
+        ];
+        let near = f64::from(0.2f32);
+        let mut i = 0;
+        while (i as f32) < count as f32 / 3.0 {
+            let r = self.particles.random();
+            let x = center[0] + r.next_gaussian() / 2.0;
+            let z = center[2] + r.next_gaussian() / 2.0;
+            let v = [
+                r.next_gaussian() * near,
+                r.next_gaussian() * near,
+                r.next_gaussian() * near,
+            ];
+            self.particles.add(&options, [x, center[1], z], v);
+            i += 1;
+        }
+        let far = f64::from(0.05f32);
+        let mut i = 0;
+        while (i as f32) < count as f32 / 1.5 {
+            let r = self.particles.random();
+            let angle = f64::from(i);
+            let x = center[0] + KNOCKBACK_RADIUS * angle.cos() + r.next_gaussian() / 2.0;
+            let z = center[2] + KNOCKBACK_RADIUS * angle.sin() + r.next_gaussian() / 2.0;
+            let v = [
+                r.next_gaussian() * far,
+                r.next_gaussian() * far,
+                r.next_gaussian() * far,
+            ];
+            self.particles.add(&options, [x, center[1], z], v);
+            i += 1;
+        }
+    }
+}
diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs
index c42a3aedf..fb23cc498 100644
--- a/crates/horizon-client/src/game/sculk.rs
+++ b/crates/horizon-client/src/game/sculk.rs
@@ -507,6 +507,19 @@ impl Game<'_> {
         let ctx = self.who_context(who, state);
         self.post_game_event(event, center((pos[0], pos[1], pos[2])), ctx);
     }
+    /// `LivingEntity.actuallyHurt`'s damage vibration, heard as the hit lands;
+    /// the end-of-tick scan then knows this damage.
+    pub(super) fn mob_damage_event(&mut self, id: u32) {
+        if let Some(t) = self
+            .mobs
+            .iter()
+            .find(|m| m.id == id)
+            .and_then(|m| m.last_damage.map(|(_, t)| t))
+        {
+            self.sculk.damaged.insert(id, t);
+        }
+        self.post_entity_event("minecraft:entity_damage", Who::Mob(id));
+    }
     /// A game event of an entity at its position.
     pub(super) fn post_entity_event(&mut self, event: &'static str, who: Who) {
         let at = match who {
diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs
index b3cc188d8..3b48e929f 100644
--- a/crates/horizon-client/src/game/wind.rs
+++ b/crates/horizon-client/src/game/wind.rs
@@ -101,13 +101,7 @@ impl Game<'_> {
             ],
             Hit::None => return Ok(()),
         };
-        self.wind_burst(
-            center,
-            radius,
-            knockback,
-            breeze,
-            p.owner == Some(Who::Player),
-        )
+        self.wind_burst(center, radius, knockback, breeze, !breeze)
     }
     /// `AbstractWindCharge.onHitEntity`: one point of damage.
     fn wind_charge_damage(&mut self, p: &Projectile, who: Who) {
@@ -208,7 +202,8 @@ impl Game<'_> {
         center: [f64; 3],
         radius: f32,
         multiplier: f32,
-        player_charge: bool,
+        wind_charge: bool,
+        blocklike: bool,
     ) {
         let diameter = f64::from(radius * 2.0);
         let distance = |p: [f64; 3]| {
@@ -257,11 +252,10 @@ impl Game<'_> {
                         p.velocity.y + dir[1] * power,
                         p.velocity.z + dir[2] * power,
                     );
-                    // ServerPlayer.onExplosionHit: a player's own charge cancels the fall.
-                    if player_charge {
-                        let at = p.position;
-                        p.impulse.set_ignore_fall_damage(true, Some(at));
-                    }
+                    // ServerPlayer.onExplosionHit: a wind charge's burst cancels the
+                    // fall; any other burst ends the grace of the last impulse.
+                    let at = p.position;
+                    p.impulse.set_ignore_fall_damage(wind_charge, Some(at));
                 }
             }
         }
@@ -288,6 +282,39 @@ impl Game<'_> {
             );
         }
         self.mobs = mobs;
+        // ArmorStand.ignoreExplosion: a visible stand feels only a burst that
+        // affects block-like entities (never a wind charge's).
+        if blocklike {
+            let mut stands = std::mem::take(&mut self.armor_stands);
+            for s in stands.iter_mut().filter(|s| !s.invisible) {
+                let feet = [s.position.x, s.position.y, s.position.z];
+                let dist = distance(feet) / diameter;
+                if dist > 1.0 {
+                    continue;
+                }
+                // EntityType.ARMOR_STAND's size, halved when small; a marker has none.
+                let (w, h, eye) = if s.marker {
+                    (0.0, 0.0, 0.0)
+                } else if s.small {
+                    (0.125, f64::from(0.9875f32), f64::from(0.9875f32))
+                } else {
+                    (0.25, f64::from(1.975f32), f64::from(1.7775f32))
+                };
+                let exposure = self.seen_percent(
+                    center,
+                    [feet[0] - w, feet[1], feet[2] - w],
+                    [feet[0] + w, feet[1] + h, feet[2] + w],
+                );
+                let power = (1.0 - dist) * f64::from(exposure) * multiplier;
+                let dir = direction([feet[0], feet[1] + eye, feet[2]]);
+                s.velocity = Vec3::new(
+                    s.velocity.x + dir[0] * power,
+                    s.velocity.y + dir[1] * power,
+                    s.velocity.z + dir[2] * power,
+                );
+            }
+            self.armor_stands = stands;
+        }
         // Arrows and other projectiles (the charges themselves ignore it).
         let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| {
             let feet = [position.x, position.y, position.z];
@@ -331,16 +358,21 @@ impl Game<'_> {
         self.tnts = tnts;
     }
     /// The burst: knockback, the blocks that react, the gust and the sound.
-    fn wind_burst(
+    pub(super) fn wind_burst(
         &mut self,
         center: [f64; 3],
         radius: f32,
         multiplier: f32,
         breeze: bool,
-        player_charge: bool,
+        wind_charge: bool,
     ) -> Result<()> {
+        // ServerExplosion.explode: the blast is heard first.
+        let ctx = horizon_client::sculk::Context::default();
+        self.post_game_event("minecraft:explode", center, ctx);
         let mut targets = self.wind_positions(center, radius);
-        self.wind_knockback(center, radius, multiplier, player_charge);
+        // ServerExplosion.shouldAffectBlocklikeEntities
+        let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing");
+        self.wind_knockback(center, radius, multiplier, wind_charge, blocklike);
         // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing.
         if !breeze || self.ui.rules.bool("mob_griefing") {
             // Util.shuffle(list, level.random)
diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs
index f336d432e..fc1667298 100644
--- a/crates/horizon-client/src/items.rs
+++ b/crates/horizon-client/src/items.rs
@@ -70,6 +70,8 @@ pub struct ItemInfo {
     pub blocks_attacks: Option,
     /// `weapon.disable_blocking_for_seconds` (axes).
     pub disable_blocking_seconds: f32,
+    /// `weapon.item_damage_per_attack`, when the item is a weapon.
+    pub weapon_damage: Option,
     /// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2).
     pub use_speed: f32,
     /// `glider` (elytra).
@@ -439,6 +441,11 @@ impl Items {
                     disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"]
                         .as_f64()
                         .unwrap_or(0.0) as f32,
+                    weapon_damage: c["minecraft:weapon"].is_object().then(|| {
+                        c["minecraft:weapon"]["item_damage_per_attack"]
+                            .as_u64()
+                            .unwrap_or(1) as u32
+                    }),
                     equip_asset: c["minecraft:equippable"]["asset_id"]
                         .as_str()
                         .map(str::to_owned),
diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs
index 328265585..e5135fc7c 100644
--- a/crates/horizon-client/src/mobs.rs
+++ b/crates/horizon-client/src/mobs.rs
@@ -492,6 +492,8 @@ pub enum Who {
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub enum DamageKind {
     PlayerAttack,
+    /// `mace_smash`: a mace hit after a fall (the player attack tags too).
+    MaceSmash,
     MobAttack,
     Arrow,
     Thrown,
@@ -541,6 +543,14 @@ impl Damage {
             from: Some(from),
         }
     }
+    /// `DamageSources.mace`: a player's smash attack.
+    pub fn mace(from: [f64; 3]) -> Self {
+        Self {
+            kind: DamageKind::MaceSmash,
+            attacker: Some(Who::Player),
+            from: Some(from),
+        }
+    }
     pub fn mob(id: u32, from: [f64; 3]) -> Self {
         Self {
             kind: DamageKind::MobAttack,
@@ -1518,6 +1528,16 @@ impl Mob {
         .fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
     }
     pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
+        self.damage_with(amount, source, None)
+    }
+    /// `damage` by a source with a weapon: `armor_effectiveness` runs the
+    /// weapon's armor-effectiveness enchantments (breach) over the armor fraction.
+    pub fn damage_with(
+        &mut self,
+        amount: f32,
+        source: Damage,
+        armor_effectiveness: Option<&mut dyn FnMut(f32) -> f32>,
+    ) -> bool {
         raider::note_hurt(self);
         if !self.alive() || self.removed || self.invulnerable_flag {
             return false;
@@ -1535,7 +1555,11 @@ impl Mob {
             let armor = self.kind.armor + worn;
             let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0;
             let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
-            amount *= 1.0 - effective / 25.0;
+            let mut fraction = effective / 25.0;
+            if let Some(modify) = armor_effectiveness {
+                fraction = modify(fraction).clamp(0.0, 1.0);
+            }
+            amount *= 1.0 - fraction;
         }
         // CombatRules.getDamageAfterMagicAbsorb: enchantment protection.
         let epf = gear::protection(self, source.kind);
@@ -1570,7 +1594,7 @@ impl Mob {
             let (dx, dz) = source.from.map_or((0.0, 0.0), |f| {
                 (f[0] - self.position.x, f[2] - self.position.z)
             });
-            self.knockback(0.4, dx, dz);
+            self.knockback(f64::from(0.4f32), dx, dz);
         }
         ai::after_hurt(self, &source);
         if self.health <= 0.0 {
@@ -1597,7 +1621,7 @@ impl Mob {
     }
     /// LivingEntity.knockback(power, xd, zd) towards the negative direction.
     pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) {
-        let power = power * (1.0 - self.kind.knockback_resistance);
+        let power = power * (1.0 - self.attrs.knockback_resistance);
         if power <= 0.0 {
             return;
         }
diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs
index 1d8da0ae8..fd6248d2b 100644
--- a/crates/horizon-client/src/mobs/creaking.rs
+++ b/crates/horizon-client/src/mobs/creaking.rs
@@ -117,6 +117,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
     let direct = matches!(
         source.kind,
         DamageKind::PlayerAttack
+            | DamageKind::MaceSmash
             | DamageKind::MobAttack
             | DamageKind::Arrow
             | DamageKind::Thrown
diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs
index 5eb72a6e4..d6219794d 100644
--- a/crates/horizon-client/src/mobs/guardian.rs
+++ b/crates/horizon-client/src/mobs/guardian.rs
@@ -291,7 +291,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) {
     if m.hurt_time == 10
         && !moving
         && let Some((d, _)) = m.last_damage
-        && matches!(d.kind, DamageKind::PlayerAttack | DamageKind::MobAttack)
+        && matches!(
+            d.kind,
+            DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
+        )
     {
         let from = [m.position.x, m.position.y, m.position.z];
         match d.attacker {
diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs
index 57e48d6e2..00b846b86 100644
--- a/crates/horizon-client/src/mobs/sulfur_cube.rs
+++ b/crates/horizon-client/src/mobs/sulfur_cube.rs
@@ -289,6 +289,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool {
     let immune = matches!(
         source.kind,
         DamageKind::PlayerAttack
+            | DamageKind::MaceSmash
             | DamageKind::MobAttack
             | DamageKind::Arrow
             | DamageKind::Thrown
diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs
index ee08f43d4..8830fb6f4 100644
--- a/crates/horizon-client/src/motion.rs
+++ b/crates/horizon-client/src/motion.rs
@@ -143,6 +143,13 @@ pub enum MotionEvent {
     InsidePortal {
         pos: BlockPos,
     },
+    /// `ServerPlayer.checkFallDamage` after a mace smash: block particles
+    /// from the landing block, more the further the fall.
+    SmashLanding {
+        state: BlockStateId,
+        position: BlockPos,
+        fall_distance: f64,
+    },
 }
 pub struct PlayerMotion {
     pub position: Vec3,
@@ -200,6 +207,9 @@ pub struct PlayerMotion {
     pub events: Vec,
     pub attributes: LiveAttributes i32>>,
     pub impulse: ImpulseContext,
+    /// `ServerPlayer.spawnExtraParticlesOnFall`: a mace smash on a grounded
+    /// target makes the next landing throw up the block below.
+    pub spawn_extra_particles_on_fall: bool,
     pub health: crate::health::PlayerHealth,
     /// Status effects and armor protection seen by movement and damage.
     pub status: crate::effects::StatusFlags,
@@ -259,6 +269,7 @@ impl PlayerMotion {
             health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?,
             status: crate::effects::StatusFlags::default(),
             impulse: ImpulseContext::default(),
+            spawn_extra_particles_on_fall: false,
             position,
             velocity: Vec3::ZERO,
             ground: GroundState::default(),
@@ -1385,6 +1396,15 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
         state: BlockStateId,
         position: BlockPos,
     ) -> Result<()> {
+        if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
+        {
+            self.player.events.push(MotionEvent::SmashLanding {
+                state,
+                position,
+                fall_distance: self.player.fall_distance,
+            });
+            self.player.spawn_extra_particles_on_fall = false;
+        }
         self.player.events.push(MotionEvent::Landing {
             dy,
             grounded,
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
index 077a6dbff..956570d0f 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
@@ -281,6 +281,8 @@ public final class VanillaBlockUpdateOracle {
             if (entities != null) entities.add(entity);
             return true;
         }
+        /** No players watch: the hurt animation and its sound are not sent. */
+        @Override public void broadcastDamageEvent(Entity entity, net.minecraft.world.damagesource.DamageSource source) { }
         @Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
         @Override public void playSeededSound(Entity except, double x, double y, double z, net.minecraft.core.Holder sound, SoundSource source, float volume, float pitch, long seed) {
             emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
index 24cf82ae5..4115c9063 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
@@ -218,6 +218,19 @@ public final class VanillaDispenserOracle {
         }
         if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true);
         if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true);
+        if (e.has("ground")) ent.setOnGround(true);
+        if (e.has("health") && ent instanceof LivingEntity living) {
+            living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH).setBaseValue(e.get("health").getAsDouble());
+            living.setHealth(e.get("health").getAsFloat());
+        }
+        if (e.has("knockback_resistance") && ent instanceof LivingEntity living) {
+            living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.KNOCKBACK_RESISTANCE).setBaseValue(e.get("knockback_resistance").getAsDouble());
+        }
+        if (e.has("marker") && ent instanceof net.minecraft.world.entity.decoration.ArmorStand stand) {
+            Method marker = net.minecraft.world.entity.decoration.ArmorStand.class.getDeclaredMethod("setMarker", boolean.class);
+            marker.setAccessible(true);
+            marker.invoke(stand, true);
+        }
         if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) {
             Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class);
             variant.setAccessible(true);
@@ -318,6 +331,8 @@ public final class VanillaDispenserOracle {
             used = useItem(w, origin, f.getAsJsonObject("use_item"));
         } else if (f.has("respawn_at")) {
             used = respawnAt(w, origin, f.getAsJsonObject("respawn_at"));
+        } else if (f.has("attack")) {
+            used = attack(w, f.getAsJsonObject("attack"), targets);
         } else if (f.has("hopper")) {
             // HopperBlockEntity.pushItemsTick, once.
             var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
@@ -578,6 +593,148 @@ public final class VanillaDispenserOracle {
         return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle)));
     }
 
+    /**
+     * The player of an "attack" case: a `ServerPlayer` with a place, a fall
+     * and a velocity, a stand-in connection and abilities.
+     */
+    static final class Attacker extends net.minecraft.server.level.ServerPlayer {
+        VanillaBlockUpdateOracle.World world;
+        boolean creative, fallFlying;
+        ItemStack hand;
+        List stats;
+        Attacker() {
+            super(null, null, null, null);
+        }
+        @Override public ServerLevel level() { return world; }
+        @Override public boolean hasInfiniteMaterials() { return creative; }
+        @Override public boolean isCreative() { return creative; }
+        @Override public boolean isSpectator() { return false; }
+        @Override public boolean isFallFlying() { return fallFlying; }
+        @Override public net.minecraft.world.phys.Vec3 getKnownMovement() { return getDeltaMovement(); }
+        @Override public EntityType getType() { return EntityTypes.PLAYER; }
+        @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
+        @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; }
+        @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
+            return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
+        }
+        @Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) {
+            if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack;
+        }
+        @Override public void awardStat(net.minecraft.stats.Stat stat, int count) {
+            stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
+        }
+    }
+
+    /** The synched data `Entity`'s constructor defines (a player's air supply is 300). */
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    static void defineData(Entity e) throws Exception {
+        var builder = new net.minecraft.network.syncher.SynchedEntityData.Builder(e);
+        Object[][] base = {{"DATA_SHARED_FLAGS_ID", (byte) 0}, {"DATA_AIR_SUPPLY_ID", 300}, {"DATA_CUSTOM_NAME_VISIBLE", false},
+            {"DATA_CUSTOM_NAME", Optional.empty()}, {"DATA_SILENT", false}, {"DATA_NO_GRAVITY", false}, {"DATA_POSE", Pose.STANDING},
+            {"DATA_TICKS_FROZEN", 0}};
+        for (Object[] d : base) {
+            Field f = Entity.class.getDeclaredField((String) d[0]);
+            f.setAccessible(true);
+            builder.define((net.minecraft.network.syncher.EntityDataAccessor) f.get(null), d[1]);
+        }
+        Method define = Entity.class.getDeclaredMethod("defineSynchedData", net.minecraft.network.syncher.SynchedEntityData.Builder.class);
+        define.setAccessible(true);
+        define.invoke(e, builder);
+        VanillaBlockUpdateOracle.set(Entity.class, e, "entityData", builder.build());
+    }
+
+    /** A connection to no client: the motion packets a smash sends go nowhere. */
+    static final class Silent extends net.minecraft.server.network.ServerGamePacketListenerImpl {
+        Silent() { super(null, null, null, null); }
+        @Override public void send(net.minecraft.network.protocol.Packet packet) { }
+    }
+
+    /**
+     * A player hit on the first target with the case's item, as
+     * `Player.attack` and `itemAttackInteraction` run it after the attack
+     * strength scaled the base damage to `base`: the item's damage bonus
+     * (`MaceItem.getAttackDamageBonus`) and damage source, the target's real
+     * `hurtServer` (armor with the weapon's Breach), then `hurtEnemy` (the
+     * mace's smash), the post-attack enchantments (Wind Burst) and
+     * `postHurtEnemy` (the fall reset and the weapon's wear). Every target's
+     * health and velocity, the player's velocity, fall, impulse and the
+     * statistics follow.
+     */
+    static List attack(VanillaBlockUpdateOracle.World w, JsonObject op, List targets) throws Exception {
+        if (VanillaBlockUpdateOracle.Server.players == null) {
+            VanillaBlockUpdateOracle.Server.players = (Ops) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Ops.class);
+        }
+        Attacker player = (Attacker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Attacker.class);
+        player.world = w;
+        player.creative = op.get("creative").getAsBoolean();
+        player.fallFlying = op.get("fall_flying").getAsBoolean();
+        player.hand = stack(op.get("item").getAsString());
+        player.stats = new ArrayList<>();
+        var abilities = new net.minecraft.world.entity.player.Abilities();
+        abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative;
+        abilities.flying = op.get("flying").getAsBoolean();
+        VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities);
+        var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class);
+        VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>());
+        VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements);
+        player.connection = (Silent) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Silent.class);
+        defineData(player);
+        player.setId(w.getNextEntityId());
+        VanillaBlockUpdateOracle.set(LivingEntity.class, player, "attributes",
+            new net.minecraft.world.entity.ai.attributes.AttributeMap(net.minecraft.world.entity.player.Player.createAttributes().build()));
+        player.setUUID(new UUID(0L, 1L));
+        VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "gameProfile",
+            new com.mojang.authlib.GameProfile(new UUID(0L, 1L), "Player"));
+        var p = op.getAsJsonArray("player");
+        var at = new net.minecraft.world.phys.Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble());
+        VanillaBlockUpdateOracle.set(Entity.class, player, "position", at);
+        VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at));
+        var standing = EntityTypes.PLAYER.getDimensions();
+        VanillaBlockUpdateOracle.set(Entity.class, player, "dimensions", standing);
+        VanillaBlockUpdateOracle.set(Entity.class, player, "eyeHeight", standing.eyeHeight());
+        player.setBoundingBox(standing.makeBoundingBox(at));
+        var m = op.getAsJsonArray("motion");
+        player.setDeltaMovement(m.get(0).getAsDouble(), m.get(1).getAsDouble(), m.get(2).getAsDouble());
+        player.fallDistance = op.get("fall").getAsDouble();
+        if (op.has("impact")) {
+            var i = op.getAsJsonArray("impact");
+            player.currentImpulseImpactPos = new net.minecraft.world.phys.Vec3(i.get(0).getAsDouble(), i.get(1).getAsDouble(), i.get(2).getAsDouble());
+        }
+        // The player stands in the level, for the bursts that push it.
+        w.entities.add(player);
+        LivingEntity target = (LivingEntity) targets.get(0);
+        ItemStack weapon = player.hand;
+        var source = weapon.getDamageSource(player);
+        float base = op.get("base").getAsFloat();
+        float bonus = weapon.getItem().getAttackDamageBonus(target, base, source);
+        boolean hurt = target.hurtServer(w, source, base + bonus);
+        if (hurt) {
+            boolean weaponHit = weapon.hurtEnemy(target, player);
+            net.minecraft.world.item.enchantment.EnchantmentHelper.doPostAttackEffectsWithItemSource(w, target, source, weapon);
+            if (weaponHit) weapon.postHurtEnemy(target, player);
+        }
+        w.entities.remove(player);
+        List out = new ArrayList<>(player.stats);
+        out.add("attack bonus=" + num(bonus) + " source=" + source.typeHolder().getRegisteredName() + " hurt=" + hurt);
+        for (int i = 0; i < targets.size(); i++) {
+            Entity e = targets.get(i);
+            var v = e.getDeltaMovement();
+            String health = e instanceof LivingEntity living && !(e instanceof net.minecraft.world.entity.decoration.ArmorStand) ? num(living.getHealth()) : "-";
+            out.add("V " + i + " " + health + " " + num(v.x) + " " + num(v.y) + " " + num(v.z));
+        }
+        var v = player.getDeltaMovement();
+        var impact = player.currentImpulseImpactPos;
+        Field grace = LivingEntity.class.getDeclaredField("currentImpulseContextResetGraceTime");
+        grace.setAccessible(true);
+        Field extra = net.minecraft.server.level.ServerPlayer.class.getDeclaredField("spawnExtraParticlesOnFall");
+        extra.setAccessible(true);
+        out.add("P " + num(v.x) + " " + num(v.y) + " " + num(v.z) + " fall=" + num(player.fallDistance)
+            + " impact=" + (impact == null ? "-" : num(impact.x) + "," + num(impact.y) + "," + num(impact.z))
+            + " grace=" + grace.getInt(player) + " extra=" + extra.getBoolean(player));
+        out.add("held " + ParityData.canon(player.hand));
+        return out;
+    }
+
     /** The level's block entity positions by x, y, z. */
     static List sortedEntities(VanillaBlockUpdateOracle.World w) {
         List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
diff --git a/tools/test_mace_parity.py b/tools/test_mace_parity.py
new file mode 100644
index 000000000..123f19693
--- /dev/null
+++ b/tools/test_mace_parity.py
@@ -0,0 +1,204 @@
+"""Compare a player's melee hit with a mace (and other weapons) with vanilla's.
+
+Every case has a stone floor, a target mob standing on it or hanging in the
+air (health raised so no hit kills it, sometimes in armor), other mobs and
+armor stands around it, and a player near the target holding a mace with
+Density, Breach, Wind Burst and Unbreaking in any mix, or a sword, an axe, a
+stick or nothing. The player has fallen some distance (sometimes gliding or
+flying), moves, and may still have the impact point of an earlier impulse.
+
+Vanilla runs, over the headless level of the dispenser harness
+(`VanillaDispenserOracle.attack`), the steps of `Player.attack` after the
+attack strength scaled the base damage: `Item.getAttackDamageBonus`
+(`MaceItem`'s smash bonus with Density), the item's damage source
+(`mace_smash` or `player_attack`), the target's real `hurtServer` (armor
+thinned by Breach in `CombatRules.getDamageAfterAbsorb`), then
+`itemAttackInteraction`: `ItemStack.hurtEnemy` (`MaceItem.hurtEnemy`: the
+stopped fall, the waived fall damage, the smash sounds, the dust-pillar level
+event and the knockback around the target), the post-attack enchantments
+(Wind Burst's `ExplodeEffect` on the player) and `postHurtEnemy` (the fall
+reset and the weapon's wear with Unbreaking). Horizon runs the same steps
+through the helpers `Game::attack` uses (`smash_damage_bonus`,
+`hurt_by_player`, `weapon_hit`) in a headless game
+(`HORIZON_DISPENSE_FIXTURE`). Both print every target's health and
+velocity, the player's velocity, fall distance, impulse impact and grace
+time and its landing-particle flag, sounds, level and game events, the used
+statistic, the held stack and the level random afterwards.
+"""
+import json
+import math
+import os
+import random
+try:
+    from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
+except ImportError:
+    import block_update_harness as h
+    import lab
+    import test_dispenser_parity as d
+    import test_rust_parity as base
+
+TARGETS = ['pig', 'cow', 'sheep', 'zombie', 'husk', 'skeleton', 'zombie', 'pig']
+AROUND = ['pig', 'cow', 'zombie', 'sheep', 'armor_stand']
+ARMOR = ['iron', 'diamond', 'golden', 'chainmail', 'leather']
+FALLS = [0.0, 0.5, 1.0, 1.5, 1.5000001, 2.0, 2.75, 3.0, 3.25, 5.0, 5.0001, 6.5, 8.0, 8.5, 12.0, 25.3, 60.0]
+
+
+def stack(item, enchantments=None, damage=0):
+    components = []
+    if enchantments:
+        levels = ','.join(f'"minecraft:{e}":{lvl}' for e, lvl in enchantments.items())
+        components.append('"minecraft:enchantments":{%s}' % levels)
+    if damage:
+        components.append(f'"minecraft:damage":{damage}')
+    extra = ',components:{%s}' % ','.join(components) if components else ''
+    return '{id:"minecraft:%s",count:1%s}' % (item, extra)
+
+
+def weapon(rng):
+    roll = rng.random()
+    if roll < 0.75:
+        enchantments = {}
+        for name, top in [('density', 5), ('breach', 4), ('wind_burst', 3), ('unbreaking', 3)]:
+            if rng.random() < 0.35:
+                enchantments[name] = rng.randint(1, top)
+        return stack('mace', enchantments, rng.choice([0, 0, 0, 7, 300]))
+    if roll < 0.85:
+        return stack(rng.choice(['diamond_sword', 'iron_axe', 'stone_pickaxe']),
+                     {'breach': 2} if rng.random() < 0.2 else None, rng.choice([0, 0, 10]))
+    return rng.choice([stack('stick'), '-'])
+
+
+def cases(facts, count, seed):
+    rng = random.Random(seed)
+    states = d.States(facts)
+    floors = [states.get(b) for b in ['stone', 'grass_block', 'dirt', 'sand', 'oak_planks']]
+    for n in range(count):
+        case = {**h.environment(rng), 'pos': [0, 0, 0]}
+        case.pop('raining', None)
+        case.pop('thundering', None)
+        floor = rng.choice(floors)
+        case['cells'] = [[x, -1, z, floor] for x in range(-6, 7) for z in range(-6, 7)]
+        if rng.random() < 0.2:
+            # A wall the burst and the dust have to get past.
+            wall = states.get(rng.choice(['stone', 'glass', 'oak_planks']))
+            x = rng.choice([-3, -2, 2, 3])
+            case['cells'] += [[x, y, z, wall] for y in range(0, 3) for z in range(-2, 3)]
+        item = weapon(rng)
+        wind = 'wind_burst' in item
+        grounded = rng.random() < 0.75
+        tx, tz = rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)
+        ty = 0.0 if grounded else rng.choice([0.5, 1.25, 2.0])
+        target = {'type': 'minecraft:' + rng.choice(TARGETS), 'pos': [tx, ty, tz], 'yaw': rng.uniform(-180, 180),
+                  'health': 1000.0}
+        if grounded:
+            target['ground'] = True
+        if target['type'] in ('minecraft:zombie', 'minecraft:husk', 'minecraft:skeleton') and rng.random() < 0.6:
+            material = rng.choice(ARMOR)
+            target['equip'] = {'chest': d.plain(f'{material}_chestplate')}
+            if rng.random() < 0.5:
+                target['equip']['head'] = d.plain(f'{material}_helmet')
+        if rng.random() < 0.15:
+            target['knockback_resistance'] = rng.choice([0.25, 0.5, 1.0])
+        entities = [target]
+        for _ in range(rng.choice([0, 1, 2, 3, 5])):
+            kind = rng.choice(AROUND)
+            near = rng.random() < 0.8
+            spread = 3.2 if near else 5.0
+            e = {'type': 'minecraft:' + kind, 'pos': [tx + rng.uniform(-spread, spread), rng.choice([0.0, 0.0, 0.5, 1.0]),
+                                                      tz + rng.uniform(-spread, spread)], 'yaw': rng.uniform(-180, 180)}
+            if kind == 'armor_stand':
+                # A marker is spared by the smash; Wind Burst's explosion would
+                # need its zero-size box.
+                if not wind and rng.random() < 0.4:
+                    e['marker'] = True
+            else:
+                e['health'] = 1000.0
+                if rng.random() < 0.2:
+                    e['knockback_resistance'] = rng.choice([0.4, 1.0])
+            if e['pos'][1] == 0.0 and rng.random() < 0.8:
+                e['ground'] = True
+            entities.append(e)
+        case['entities'] = entities
+        angle = rng.uniform(0, 6.283)
+        reach = rng.uniform(0.6, 2.8)
+        px, pz = tx + math.cos(angle) * reach, tz + math.sin(angle) * reach
+        py = ty + rng.choice([0.0, 0.3, 1.0, 1.7, 2.5])
+        fall = rng.choice(FALLS) if rng.random() < 0.7 else round(rng.uniform(0, 30), 3)
+        attack = {'item': item, 'creative': rng.random() < 0.15, 'player': [px, py, pz],
+                  'motion': [rng.uniform(-0.3, 0.3), -rng.uniform(0, 2.5), rng.uniform(-0.3, 0.3)],
+                  'fall': fall, 'fall_flying': rng.random() < 0.08, 'flying': rng.random() < 0.04,
+                  'base': round(rng.uniform(1.2, 7.0), 3)}
+        if rng.random() < 0.3:
+            attack['impact'] = [px + rng.uniform(-1, 1), py + rng.choice([-3.0, -0.5, 0.0, 2.0]), pz + rng.uniform(-1, 1)]
+        case['attack'] = attack
+        case['items'] = []
+        case['mode'] = 'dispense'
+        yield case
+
+
+def kind(case):
+    item = case['attack']['item']
+    name = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand'
+    smash = case['attack']['fall'] > 1.5 and not case['attack']['fall_flying']
+    if name == 'mace':
+        name += ' smash' if smash else ' hit'
+        if 'wind_burst' in item:
+            name += ' with wind burst'
+    return name
+
+
+def main():
+    parser = h.argument_parser(__doc__)
+    args = parser.parse_args()
+    if args.count == 40000:
+        args.count = 3000
+    lock, jars, libraries = base.verify_artifacts()
+    facts = h.load_facts()
+    resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
+    work = lab.LOCAL / 'mace-parity'
+    work.mkdir(parents=True, exist_ok=True)
+    all_cases = list(cases(facts, args.count, args.seed))
+    (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
+    classes = work / 'classes'
+    classes.mkdir(exist_ok=True)
+    dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
+    java_root = lab.ROOT / 'mods/horizon/src/test/java'
+    d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
+           '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
+    d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
+           str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
+    d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
+          env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
+    d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
+          env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
+    ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
+    native = h.split_cases((work / 'native.txt').read_text(), ignore)
+    rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+    assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
+    groups, errors = {}, {}
+    smashed = burst = 0
+    for case, a, b in zip(all_cases, native, rust):
+        if a and a[0].startswith('error'):
+            errors.setdefault(a[0], []).append(case)
+            continue
+        smashed += any('source=minecraft:mace_smash hurt=true' in line for line in a)
+        burst += any(line.endswith('minecraft:entity.wind_charge.wind_burst') for line in a)
+        if not d.same(a, b):
+            groups.setdefault(kind(case), []).append((case, a, b))
+    for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
+        print(f'oracle error x{len(entries)}: {name}')
+    for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
+        print(f'{name}: {len(entries)} differing')
+        for case, a, b in entries[:args.show]:
+            print('  case entities=' + json.dumps(case['entities']) + ' attack=' + json.dumps(case['attack']) + f' seed={case["seed"]}')
+            print('   native ' + ' | '.join(sorted(a)))
+            print('   rust   ' + ' | '.join(sorted(b)))
+    total = sum(len(v) for v in groups.values())
+    skipped = sum(len(v) for v in errors.values())
+    print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); '
+          f'vanilla smashed in {smashed} and burst in {burst}')
+    h.finish(total + skipped)
+
+
+if __name__ == '__main__':
+    main()

From 322a87cf93d5a20de2ee407b8ef4047e5f3970e0 Mon Sep 17 00:00:00 2001
From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com>
Date: Wed, 14 Oct 2026 20:34:25 +0100
Subject: [PATCH 26/43] Fix Clippy warnings in LAN tab list regression tests

---
 crates/horizon-client/src/game/scoreboard.rs | 170 +++++++++----------
 1 file changed, 85 insertions(+), 85 deletions(-)

diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs
index e35a9d918..7bcb6ceed 100644
--- a/crates/horizon-client/src/game/scoreboard.rs
+++ b/crates/horizon-client/src/game/scoreboard.rs
@@ -656,91 +656,6 @@ fn local_tab_players(me: TabPlayer, guests: &[Guest]) -> Vec {
     players
 }
 
-#[cfg(test)]
-mod tab_list_tests {
-    use super::*;
-    use horizon_client::{
-        lan::{Joined, PlayerSender},
-        tab_list,
-    };
-    use horizon_protocol::packets::configuration::ClientInformation;
-    use std::sync::{
-        Arc,
-        atomic::{AtomicI32, Ordering},
-        mpsc,
-    };
-
-    fn guest(uuid: u128, name: &str) -> Guest {
-        let (tx, _rx) = mpsc::channel();
-        Guest::new(
-            Joined {
-                conn: uuid as u32,
-                uuid,
-                name: name.into(),
-                info: ClientInformation::new(8),
-                brand: "test".into(),
-                sender: PlayerSender {
-                    tx,
-                    pending: Arc::default(),
-                },
-                latency: Arc::new(AtomicI32::new(42)),
-                address: "127.0.0.1:25565".parse().unwrap(),
-            },
-            uuid as i32,
-            [0.0, 64.0, 0.0],
-            8,
-        )
-    }
-
-    #[test]
-    fn lan_tab_list_tracks_join_and_disconnect() {
-        let me = TabPlayer::new(1, PLAYER_NAME);
-        let mut guests = vec![guest(2, "Alex")];
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players, [me.clone()]);
-        assert!(!tab_list::visible(true, true, players.len(), false));
-
-        guests[0].placed = true;
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players.len(), 2);
-        assert_eq!(players[0], me);
-        assert_eq!(players[1].uuid, 2);
-        assert_eq!(players[1].name, "Alex");
-        assert!(tab_list::visible(true, true, players.len(), false));
-        assert!(!tab_list::visible(false, true, players.len(), false));
-
-        guests.clear();
-        let players = local_tab_players(me, &guests);
-        assert_eq!(players.len(), 1);
-        assert!(!tab_list::visible(true, true, players.len(), false));
-        assert!(tab_list::visible(true, true, players.len(), true));
-    }
-
-    #[test]
-    fn lan_tab_list_reads_current_guest_state() {
-        let me = TabPlayer::new(1, PLAYER_NAME);
-        let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")];
-        for guest in &mut guests {
-            guest.placed = true;
-        }
-        guests[0].game_mode = tab_list::SPECTATOR;
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players.len(), 3);
-        assert_eq!(players[1].game_mode, tab_list::SPECTATOR);
-        assert_eq!(players[1].latency, 42);
-        assert_eq!(players[1].skin, tab_list::default_skin(2));
-        assert_eq!(players[2].name, "Grumm");
-
-        guests[0].game_mode = 1;
-        guests[0].latency.store(123, Ordering::Relaxed);
-        guests.remove(1);
-        let players = local_tab_players(me, &guests);
-        assert_eq!(players.len(), 2);
-        assert_eq!(players[1].game_mode, 1);
-        assert_eq!(players[1].latency, 123);
-    }
-}
-
 /// The commands' view of the game.
 struct GameEnv<'a, 'b> {
     g: &'a mut Game<'b>,
@@ -798,3 +713,88 @@ impl Env for GameEnv<'_, '_> {
         self.g.feedback(message);
     }
 }
+
+#[cfg(test)]
+mod tab_list_tests {
+    use super::*;
+    use horizon_client::{
+        lan::{Joined, PlayerSender},
+        tab_list,
+    };
+    use horizon_protocol::packets::configuration::ClientInformation;
+    use std::sync::{
+        Arc,
+        atomic::{AtomicI32, Ordering},
+        mpsc,
+    };
+
+    fn guest(uuid: u128, name: &str) -> Guest {
+        let (tx, _rx) = mpsc::channel();
+        Guest::new(
+            Joined {
+                conn: uuid as u32,
+                uuid,
+                name: name.into(),
+                info: ClientInformation::new(8),
+                brand: "test".into(),
+                sender: PlayerSender {
+                    tx,
+                    pending: Arc::default(),
+                },
+                latency: Arc::new(AtomicI32::new(42)),
+                address: "127.0.0.1:25565".parse().unwrap(),
+            },
+            uuid as i32,
+            [0.0, 64.0, 0.0],
+            8,
+        )
+    }
+
+    #[test]
+    fn lan_tab_list_tracks_join_and_disconnect() {
+        let me = TabPlayer::new(1, PLAYER_NAME);
+        let mut guests = vec![guest(2, "Alex")];
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.as_slice(), std::slice::from_ref(&me));
+        assert!(!tab_list::visible(true, true, players.len(), false));
+
+        guests[0].placed = true;
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.len(), 2);
+        assert_eq!(players[0], me);
+        assert_eq!(players[1].uuid, 2);
+        assert_eq!(players[1].name, "Alex");
+        assert!(tab_list::visible(true, true, players.len(), false));
+        assert!(!tab_list::visible(false, true, players.len(), false));
+
+        guests.clear();
+        let players = local_tab_players(me, &guests);
+        assert_eq!(players.len(), 1);
+        assert!(!tab_list::visible(true, true, players.len(), false));
+        assert!(tab_list::visible(true, true, players.len(), true));
+    }
+
+    #[test]
+    fn lan_tab_list_reads_current_guest_state() {
+        let me = TabPlayer::new(1, PLAYER_NAME);
+        let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")];
+        for guest in &mut guests {
+            guest.placed = true;
+        }
+        guests[0].game_mode = tab_list::SPECTATOR;
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.len(), 3);
+        assert_eq!(players[1].game_mode, tab_list::SPECTATOR);
+        assert_eq!(players[1].latency, 42);
+        assert_eq!(players[1].skin, tab_list::default_skin(2));
+        assert_eq!(players[2].name, "Grumm");
+
+        guests[0].game_mode = 1;
+        guests[0].latency.store(123, Ordering::Relaxed);
+        guests.remove(1);
+        let players = local_tab_players(me, &guests);
+        assert_eq!(players.len(), 2);
+        assert_eq!(players[1].game_mode, 1);
+        assert_eq!(players[1].latency, 123);
+    }
+}

From 79ab688bda0059173b43b00dffb51d9727be365e Mon Sep 17 00:00:00 2001
From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com>
Date: Wed, 14 Oct 2026 20:34:26 +0100
Subject: [PATCH 27/43] Fix banner rendering test lint on Rust 1.99

---
 crates/horizon-client/src/item_render/gui.rs | 28 ++++++++++++--------
 1 file changed, 17 insertions(+), 11 deletions(-)

diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs
index 9456b26e4..e3d7cc876 100644
--- a/crates/horizon-client/src/item_render/gui.rs
+++ b/crates/horizon-client/src/item_render/gui.rs
@@ -274,17 +274,23 @@ mod tests {
 
     // Sample the emitted triangles in draw order, using opaque test faces.
     fn color_at(batch: &HudBatch, p: Vec2) -> Option {
-        batch.vertices.chunks_exact(3).rev().find_map(|tri| {
-            let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos));
-            let area = (b - a).perp_dot(c - a);
-            if area.abs() < 1e-6 {
-                return None;
-            }
-            let u = (b - p).perp_dot(c - p) / area;
-            let v = (c - p).perp_dot(a - p) / area;
-            let w = 1.0 - u - v;
-            (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color)
-        })
+        batch
+            .vertices
+            .as_chunks::<3>()
+            .0
+            .iter()
+            .rev()
+            .find_map(|tri| {
+                let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos));
+                let area = (b - a).perp_dot(c - a);
+                if area.abs() < 1e-6 {
+                    return None;
+                }
+                let u = (b - p).perp_dot(c - p) / area;
+                let v = (c - p).perp_dot(a - p) / area;
+                let w = 1.0 - u - v;
+                (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color)
+            })
     }
 
     #[test]

From 8caee518976214dfeb5cdda6495afd84d6dd6367 Mon Sep 17 00:00:00 2001
From: Cosmic <84875247+Online5277@users.noreply.github.com>
Date: Wed, 14 Oct 2026 15:37:32 -0400
Subject: [PATCH 28/43] Regenerate preparation metadata when reusing imports

---
 crates/horizon-prepare/src/artifacts.rs | 152 +++++++++++++++++++++---
 1 file changed, 134 insertions(+), 18 deletions(-)

diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs
index 6f8e45bf8..c9b1947ed 100644
--- a/crates/horizon-prepare/src/artifacts.rs
+++ b/crates/horizon-prepare/src/artifacts.rs
@@ -513,7 +513,27 @@ pub fn import(
             &hint(LAUNCHER_HINT, version),
         )?);
     }
-    for (side, jar) in [("client", &client), ("server", &server)] {
+    write_import_metadata(
+        root,
+        lock,
+        &client,
+        &server,
+        &client_libraries,
+        &server_libraries,
+        log,
+    )
+}
+
+fn write_import_metadata(
+    root: &Path,
+    lock: &Lock,
+    client: &Path,
+    server: &Path,
+    client_libraries: &[PathBuf],
+    server_libraries: &[PathBuf],
+    log: Log,
+) -> Result<(), String> {
+    for (side, jar) in [("client", client), ("server", server)] {
         let data = crate::inventory::inventory(jar)?;
         let count = |key| data.get(key).cloned().unwrap_or(Value::Null);
         write_json(
@@ -538,25 +558,19 @@ pub fn import(
     write_json(
         &lock.directory.join("prepared.json"),
         &Value::Object(vec![
-            ("version".into(), Value::str(id)),
+            ("version".into(), Value::str(&lock.version)),
             (
                 "jars".into(),
                 Value::Object(vec![
-                    (
-                        "client".into(),
-                        Value::Str(relative_display(&client, root)?),
-                    ),
-                    (
-                        "server".into(),
-                        Value::Str(relative_display(&server, root)?),
-                    ),
+                    ("client".into(), Value::Str(relative_display(client, root)?)),
+                    ("server".into(), Value::Str(relative_display(server, root)?)),
                 ]),
             ),
             (
                 "libraries".into(),
                 Value::Object(vec![
-                    ("client".into(), paths(&client_libraries)?),
-                    ("server".into(), paths(&server_libraries)?),
+                    ("client".into(), paths(client_libraries)?),
+                    ("server".into(), paths(server_libraries)?),
                 ]),
             ),
         ]),
@@ -597,12 +611,33 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result {
         Ok(files)
     };
     if checked(lock.directory.clone()).is_ok() {
+        if [
+            "prepared.json",
+            "reports/client-inventory.json",
+            "reports/server-inventory.json",
+        ]
+        .iter()
+        .any(|path| !lock.directory.join(path).is_file())
+        {
+            let found = verify(&lock)?;
+            let client_libraries = client_libraries(&lock, &found.manifest)?;
+            write_import_metadata(
+                &root,
+                &lock,
+                &found.jars["client"],
+                &found.jars["server"],
+                &client_libraries,
+                &found.libraries,
+                log,
+            )?;
+        }
         log(&format!("Using imported Minecraft {}", lock.version));
         return Ok(true);
     }
     let Some(versions) = root.parent() else {
         return Ok(false);
     };
+    // Sibling discovery is intended for the launcher's versions/ folder.
     let mut siblings: Vec<_> = fs::read_dir(versions)
         .map_err(|e| format!("{}: {e}", versions.display()))?
         .filter_map(Result::ok)
@@ -625,7 +660,17 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result {
                 "",
             )?;
         }
-        checked(lock.directory.clone())?;
+        let found = verify(&lock)?;
+        let client_libraries = client_libraries(&lock, &found.manifest)?;
+        write_import_metadata(
+            &root,
+            &lock,
+            &found.jars["client"],
+            &found.jars["server"],
+            &client_libraries,
+            &found.libraries,
+            log,
+        )?;
         log(&format!(
             "Reused imported Minecraft {} from {}",
             lock.version,
@@ -716,6 +761,15 @@ mod tests {
     use super::*;
     use std::io::Write;
 
+    fn jar(marker: &[u8]) -> Vec {
+        let mut archive = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+        archive
+            .start_file("marker", zip::write::SimpleFileOptions::default())
+            .unwrap();
+        archive.write_all(marker).unwrap();
+        archive.finish().unwrap().into_inner()
+    }
+
     struct Imports {
         directory: PathBuf,
         source: PathBuf,
@@ -737,8 +791,10 @@ mod tests {
                 fs::create_dir_all(path.parent().unwrap()).unwrap();
                 fs::write(path, data).unwrap();
             };
-            write("jars/client.jar", b"client");
-            write("jars/server-game.jar", b"server game");
+            let client = jar(b"client");
+            let game = jar(b"server game");
+            write("jars/client.jar", &client);
+            write("jars/server-game.jar", &game);
             write("libraries/server/server.jar", b"server library");
             write("libraries/client/client.jar", b"client library");
             write("reports/private.txt", b"not an imported artifact");
@@ -747,7 +803,7 @@ mod tests {
             let entries = [
                 (
                     "META-INF/versions.list",
-                    format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(b"server game")),
+                    format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(&game)),
                 ),
                 (
                     "META-INF/libraries.list",
@@ -764,7 +820,7 @@ mod tests {
                 bundle.write_all(text.as_bytes()).unwrap();
             }
             for (name, bytes) in [
-                ("META-INF/versions/game.jar", b"server game".as_slice()),
+                ("META-INF/versions/game.jar", game.as_slice()),
                 (
                     "META-INF/libraries/server.jar",
                     b"server library".as_slice(),
@@ -810,6 +866,11 @@ mod tests {
     #[test]
     fn imported_files_are_reused_without_the_official_install() {
         let fixture = Imports::new();
+        fs::write(
+            fixture.imported(&fixture.source).join("prepared.json"),
+            b"stale source metadata",
+        )
+        .unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
         let lock = Lock::read(&fixture.target).unwrap();
         let artifacts = verify(&lock).unwrap();
@@ -818,14 +879,66 @@ mod tests {
             1
         );
         assert_eq!(artifacts.libraries.len(), 1);
+        let prepared = read_json(&lock.directory.join("prepared.json")).unwrap();
+        assert_eq!(prepared.get("version").and_then(Value::as_str), Some("9.9"));
+        for side in ["client", "server"] {
+            assert_eq!(
+                prepared
+                    .get("jars")
+                    .unwrap()
+                    .get(side)
+                    .and_then(Value::as_str),
+                Some(
+                    relative_display(&artifacts.jars[side], &fixture.target)
+                        .unwrap()
+                        .as_str()
+                )
+            );
+            let inventory = read_json(
+                &lock
+                    .directory
+                    .join(format!("reports/{side}-inventory.json")),
+            )
+            .unwrap();
+            assert_eq!(
+                inventory.get("jar_sha256").and_then(Value::as_str),
+                Some(digest(&artifacts.jars[side], "sha256").unwrap().as_str())
+            );
+        }
         assert!(!lock.directory.join("reports/private.txt").exists());
+        for side in ["client", "server"] {
+            let libraries = prepared
+                .get("libraries")
+                .unwrap()
+                .get(side)
+                .unwrap()
+                .as_array()
+                .unwrap();
+            assert_eq!(libraries.len(), 1);
+            assert_eq!(
+                libraries[0].as_str(),
+                Some(
+                    relative_display(
+                        &lock.directory.join(format!("libraries/{side}/{side}.jar")),
+                        &fixture.target
+                    )
+                    .unwrap()
+                    .as_str()
+                )
+            );
+        }
         // The current root's valid imports suffice even after the older copy is corrupted.
         fs::write(
             fixture.imported(&fixture.source).join("jars/client.jar"),
             b"bad",
         )
         .unwrap();
+        // Repair metadata omitted by earlier reuse implementations, without a sibling.
+        fs::remove_file(lock.directory.join("prepared.json")).unwrap();
+        fs::remove_file(lock.directory.join("reports/client-inventory.json")).unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
+        assert!(read_json(&lock.directory.join("prepared.json")).is_ok());
+        assert!(read_json(&lock.directory.join("reports/client-inventory.json")).is_ok());
     }
 
     #[test]
@@ -873,7 +986,10 @@ mod tests {
         fs::create_dir_all(target.join("jars")).unwrap();
         fs::write(target.join("jars/client.jar"), b"bad").unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
-        assert_eq!(fs::read(target.join("jars/client.jar")).unwrap(), b"client");
+        assert_eq!(
+            fs::read(target.join("jars/client.jar")).unwrap(),
+            fs::read(fixture.imported(&fixture.source).join("jars/client.jar")).unwrap()
+        );
     }
 
     #[test]

From 874d111d6059a22e692ff41992c54bb703353ee0 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 18:38:06 +0200
Subject: [PATCH 29/43] checks: cached verify, and a parity job on the Mac mini
 for the harnesses a PR can affect

verify keeps its dependencies and workspace build in a cache saved by main's runs (Swatinem/rust-cache).
The new parity job runs on the Mac mini's self-hosted runner (label horizon-game), which holds the
maintainer's own Minecraft files: tools/ci/vanilla-data.sh links .local/ to the runner's copy and prepares
the resources with the pull request's own horizon-prepare, once per preparer version; then
tools/parity.py --changed  runs only the harnesses whose traced dependencies changed since the merge
base and that have no pass for their current inputs. A fork's pull request runs it only when a maintainer
adds run-parity, once per label, on the commit it had then.

parity.py: --changed REF, and linux_only in tools/parity_hosts.json for harnesses that differ on other
platforms for a reason that is not a Horizon bug (skipped there with the reason, unless named).

docs/release-flow.md starts with the pull request checks and merging.

Co-Authored-By: Claude Opus 5.5 
---
 .github/actionlint.yaml     |  3 ++
 .github/workflows/ci.yml    | 48 +++++++++++++++++++++++++++++
 docs/release-flow.md        | 61 +++++++++++++++++++++++++++++++++++++
 tests/test_parity_runner.py | 19 ++++++++++++
 tools/ci/runner-env.sh      | 16 ++++++++++
 tools/ci/vanilla-data.sh    | 51 +++++++++++++++++++++++++++++++
 tools/parity.py             | 60 +++++++++++++++++++++++++++++++++---
 7 files changed, 253 insertions(+), 5 deletions(-)
 create mode 100644 .github/actionlint.yaml
 create mode 100644 docs/release-flow.md
 create mode 100755 tools/ci/runner-env.sh
 create mode 100755 tools/ci/vanilla-data.sh

diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml
new file mode 100644
index 000000000..af951fe12
--- /dev/null
+++ b/.github/actionlint.yaml
@@ -0,0 +1,3 @@
+self-hosted-runner:
+  # The Mac mini's runner (ludovics-mac-mini), which holds the maintainer's own Minecraft files.
+  labels: [horizon-game, ludovics-mac-mini]
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7b1a63710..dd9cde557 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,14 +1,25 @@
 name: checks
+# verify: every pull request and every push to main, on GitHub's runners (the repository is public).
+# parity: the vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the
+# maintainer's own Minecraft files (Horizon never downloads the game). A fork's pull request runs it only when
+# a maintainer adds the run-parity label, once per label. See docs/release-flow.md.
 on:
   push:
     branches: [main]
   pull_request:
+    types: [opened, synchronize, reopened, labeled]
   workflow_dispatch:
 permissions:
   contents: read
+concurrency:
+  # A new push to a pull request replaces its running checks; main's runs all finish (releases follow them).
+  group: checks-${{ github.event.pull_request.number || github.sha }}-${{ github.event.action == 'labeled' && 'label' || 'run' }}
+  cancel-in-progress: ${{ github.event_name == 'pull_request' }}
 jobs:
   verify:
+    if: github.event.action != 'labeled'
     runs-on: ubuntu-latest
+    timeout-minutes: 30
     steps:
       - uses: actions/checkout@v4
         with:
@@ -26,12 +37,49 @@ jobs:
         run: |
           sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
           rustup toolchain install stable --profile minimal --component rustfmt --component clippy
+      # Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache).
+      - uses: Swatinem/rust-cache@v2
+        with:
+          shared-key: verify
+          save-if: ${{ github.ref == 'refs/heads/main' }}
       - name: Check formatting and lint
         run: |
           cargo +stable fmt --all -- --check
           cargo +stable clippy --workspace --all-targets -- -D warnings
       - name: Test Rust core and voxel kernel correctness
         run: cargo +stable test --workspace
+  parity:
+    if: >-
+      github.event_name == 'pull_request' && (
+        (github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') ||
+        (github.event.action == 'labeled' && github.event.label.name == 'run-parity'))
+    runs-on: [self-hosted, horizon-game]
+    timeout-minutes: 45
+    steps:
+      - uses: actions/checkout@v4
+        with:
+          # The commit the event names: a fork's later pushes need another run-parity label.
+          ref: ${{ github.event.pull_request.head.sha }}
+          fetch-depth: 0
+          persist-credentials: false
+          # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
+          clean: false
+      - uses: dtolnay/rust-toolchain@stable
+      - name: Tools from the runner
+        run: bash tools/ci/runner-env.sh
+      - name: Vanilla data, and resources prepared by this preparer
+        run: bash tools/ci/vanilla-data.sh
+      - name: The harnesses this change can affect
+        env:
+          PARITY_HOSTS: ''
+        run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 1500
+      - name: Logs of the failed harnesses
+        if: failure()
+        uses: actions/upload-artifact@v4
+        with:
+          name: parity-logs
+          path: .local/parity-runner/logs/
+          if-no-files-found: ignore
   # Horizon never downloads the game. These jobs need a self-hosted Linux runner
   # (label horizon-game) holding the maintainer's own copy: the official launcher's
   # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
diff --git a/docs/release-flow.md b/docs/release-flow.md
new file mode 100644
index 000000000..abccac599
--- /dev/null
+++ b/docs/release-flow.md
@@ -0,0 +1,61 @@
+# Release flow
+
+How a change gets from a pull request to players: the checks a pull request passes, how it merges, and the
+automatic releases that follow. Releases are automatic and frequent so the latest Horizon is always playable;
+there is no separate development channel.
+
+## Pull request checks
+
+The `checks` workflow (`.github/workflows/ci.yml`) runs two jobs on every pull request:
+
+| Job | Runs on | What | Time |
+| --- | --- | --- | --- |
+| `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm |
+| `parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness |
+
+Pushes to main run `verify` only; the nightly audit covers main's harnesses.
+
+### The parity job
+
+Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own
+copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its checkout between runs
+(`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand.
+
+1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH.
+2. `tools/ci/vanilla-data.sh` links `.local/` to the runner's copy of the vanilla data, cloned once from
+   `~/code/horizon-parity/shared-local` into `~/.actions-runners/horizon/_work/horizon/shared-local`, and
+   prepares `.local/horizon-client` with the pull request's own `horizon-prepare` once per preparer version
+   (its sources, the exporters in `mods/horizon/src/test/java` and `research-lock.json`).
+3. `tools/parity.py --changed ` picks the harnesses whose traced dependencies (their script, Python
+   modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any
+   harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to
+   `Cargo.lock` or `research-lock.json` affects every harness. Each harness has 25 minutes, the job 45.
+
+Failed harnesses' logs are uploaded as the `parity-logs` artifact.
+
+**Platform-specific harnesses.** A harness listed under `linux_only` in `tools/parity_hosts.json` gives
+different results on macOS for a reason that is not a Horizon bug (the reason is printed). `parity.py` skips it on
+other platforms unless it is named on the command line.
+
+**Pull requests from forks** never run code on the Mac mini by themselves. A maintainer who has read the change
+adds the `run-parity` label: that runs the job once, on the commit the pull request had then. To run it again
+after new pushes, remove the label and add it again.
+
+**One runner.** The Mac mini has one runner for this repository: parity jobs, the macOS release builds and the
+nightly audit queue behind each other.
+
+## Merging
+
+Pull requests merge with a merge commit. The orchestrator sessions review a pull request, then turn on
+auto-merge (`gh pr merge  --auto --merge`): GitHub merges it once the required checks pass. Branch
+protection on main requires `verify`. Branches don't have to be up to date with main: two sessions merge in
+parallel, and main's own `checks` run catches the rare semantic conflict.
+
+`parity` becomes required once it has run green on pull requests for a while (a week without a false failure):
+
+```sh
+gh api -X POST repos/ludovic111/horizon/branches/main/protection/required_status_checks/contexts -f 'contexts[]=parity'
+```
+
+A skipped `parity` (a fork without the label, a run started by a label) counts as passed, so requiring it never
+blocks a fork's pull request; the maintainer decides whether to run it.
diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py
index ad69e8c67..78716787a 100644
--- a/tests/test_parity_runner.py
+++ b/tests/test_parity_runner.py
@@ -44,6 +44,25 @@ class ParityRunnerTests(unittest.TestCase):
             source.write_text("two!")
             self.assertTrue(parity.stale("x", state, hasher, "env"))
 
+    def test_a_change_affects_the_harnesses_that_depend_on_it(self):
+        with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)), \
+                mock.patch.object(parity, "SHARED", Path(temp, "shared")):
+            found = {name: Path(temp, "tools", f"test_{name}_parity.py") for name in ("food", "light", "new")}
+            records = {"food": {"dependencies": ["crates/a.rs", "tools/lab.py"]},
+                       "light": {"dependencies": ["crates/lib.rs#keep:light"]}}
+            self.assertEqual(parity.affected_harnesses(found, records, {"crates/a.rs"}), {"food", "new"})
+            self.assertEqual(parity.affected_harnesses(found, records, {"crates/lib.rs"}), {"light", "new"})
+            self.assertEqual(parity.affected_harnesses(found, records, {"tools/test_light_parity.py"}), {"light", "new"})
+            self.assertEqual(parity.affected_harnesses(found, records, {"Cargo.lock"}), {"food", "light", "new"})
+            self.assertEqual(parity.affected_harnesses(found, records, {"README.md"}), {"new"})
+
+    def test_platform_specific_harnesses_are_skipped_elsewhere(self):
+        config = {"linux_only": {"options": "libm"}}
+        with mock.patch.object(parity.sys, "platform", "linux"):
+            self.assertEqual(parity.platform_skips(config), {})
+        with mock.patch.object(parity.sys, "platform", "darwin"):
+            self.assertEqual(parity.platform_skips(config), {"options": "libm"})
+
     def test_a_pass_from_another_worktree_counts_only_for_the_same_content(self):
         with tempfile.TemporaryDirectory() as temp:
             elsewhere, here, shared = Path(temp, "a"), Path(temp, "b"), Path(temp, "shared")
diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh
new file mode 100755
index 000000000..b4c5094bd
--- /dev/null
+++ b/tools/ci/runner-env.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# The tools the vanilla harnesses need, on the self-hosted Mac mini runner (label horizon-game): its service
+# starts with a bare PATH. Python 3.13 and the JDK pinned by research-lock.json come from the machine, never
+# from a download. Writes them to $GITHUB_PATH and $GITHUB_ENV for the next steps.
+set -euo pipefail
+java_major=$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' research-lock.json | head -1)
+bin="$RUNNER_TEMP/horizon-bin"
+mkdir -p "$bin"
+if [ "$(uname)" = Darwin ]; then
+  ln -sfn /opt/homebrew/bin/python3.13 "$bin/python3"
+  ln -sfn /opt/homebrew/bin/python3.13 "$bin/python"
+  java_home=$(/usr/libexec/java_home -v "$java_major")
+  { echo "$bin"; echo "$java_home/bin"; echo /opt/homebrew/bin; } >> "$GITHUB_PATH"
+  echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV"
+fi
+echo "HORIZON_NO_AUDIO=1" >> "$GITHUB_ENV"
diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh
new file mode 100755
index 000000000..c5e76b388
--- /dev/null
+++ b/tools/ci/vanilla-data.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# The vanilla data for this checkout on the self-hosted runner. Horizon never downloads the game: the runner
+# holds the maintainer's own copy, imported and decompiled once (HORIZON_SHARED_SOURCE, default
+# ~/code/horizon-parity/shared-local). It is cloned once into the runner's work folder ($RUNNER_WORKSPACE/
+# shared-local; APFS clones, so no second copy of the bytes), and .local/ links to it as in a parity worktree.
+# .local/horizon-client, the resources horizon-prepare makes, is prepared by this checkout's own preparer
+# once per preparer version (its sources, the exporters and research-lock.json), so a change to the preparer
+# is checked with what it prepares; the four newest preparations are kept.
+set -euo pipefail
+shared="${RUNNER_WORKSPACE:?}/shared-local"
+source="${HORIZON_SHARED_SOURCE:-$HOME/code/horizon-parity/shared-local}"
+version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1)
+if [ ! -f "$shared/minecraft/$version/prepared.json" ]; then
+  [ -f "$source/minecraft/$version/prepared.json" ] || { echo "::error::no imported Minecraft $version in $source"; exit 1; }
+  mkdir -p "$shared"
+  if [ "$(uname)" = Darwin ]; then
+    for entry in "$source"/*; do
+      [ "$(basename "$entry")" = horizon-client ] || cp -cR "$entry" "$shared/"
+    done
+  else
+    for entry in "$source"/*; do
+      [ "$(basename "$entry")" = horizon-client ] || cp -R --reflink=auto "$entry" "$shared/"
+    done
+  fi
+fi
+mkdir -p .local "$shared/prepared"
+for entry in "$shared"/*; do
+  name=$(basename "$entry")
+  case "$name" in prepared|horizon-client|*.log) continue ;; esac
+  if [ -L ".local/$name" ] || [ ! -e ".local/$name" ]; then ln -sfn "$entry" ".local/$name"; fi
+done
+
+key=$(git ls-files -s crates/horizon-prepare mods/horizon/src/test/java research-lock.json | shasum -a 256 | cut -c1-16)
+prepared="$shared/prepared/$key"
+ln -sfn "$prepared" .local/horizon-client
+if [ ! -f "$prepared/.done" ]; then
+  echo "Preparing resources with this checkout's horizon-prepare ($key)"
+  rm -rf "$prepared" && mkdir -p "$prepared"
+  started=$SECONDS
+  cargo build --release --locked -p horizon-prepare
+  if ! target/release/horizon-prepare --root "$PWD" > "$RUNNER_TEMP/prepare.log" 2>&1; then
+    tail -40 "$RUNNER_TEMP/prepare.log"
+    rm -rf "$prepared"
+    exit 1
+  fi
+  touch "$prepared/.done"
+  echo "Prepared in $((SECONDS - started)) s"
+fi
+touch "$prepared"
+# The four newest preparations stay.
+ls -1dt "$shared/prepared"/*/ 2>/dev/null | tail -n +5 | while read -r old; do rm -rf "$old"; done
diff --git a/tools/parity.py b/tools/parity.py
index c7063f987..85d079c14 100644
--- a/tools/parity.py
+++ b/tools/parity.py
@@ -6,6 +6,7 @@
     python3 tools/parity.py --fresh ...     # don't reuse vanilla oracle results
     python3 tools/parity.py food light      # these harnesses (names without test_/_parity.py)
     python3 tools/parity.py --failed        # the ones that failed last time
+    python3 tools/parity.py --changed origin/main   # those a branch's changes can affect (pull requests)
     python3 tools/parity.py --list          # what would run, without running it
     python3 tools/parity.py --status        # last result of every harness
 
@@ -1059,18 +1060,29 @@ def trace_main(output, script, arguments):
     runpy.run_path(script, run_name="__main__")
 
 
-def changed_harnesses(found, records, ref):
-    """Harnesses new or changed since the merge base of HEAD and ref: their script, or a dependency of theirs that is
-    an oracle (Java under mods/horizon/src/test) or a probe (a crate's example or binary), changed or was added."""
+# Files every harness's result depends on (part of environment_key): a change to one affects them all.
+SHARED_INPUTS = {"research-lock.json", "Cargo.lock"}
+
+
+def changed_files(ref):
+    """Files changed between the merge base of HEAD and ref and HEAD (committed or not), or None without a merge base."""
     def git(*arguments):
         result = subprocess.run(["git", *arguments], cwd=ROOT, capture_output=True, text=True)
         return result.stdout.split("\n") if result.returncode == 0 else None
     base = git("merge-base", "HEAD", ref)
     if not base or not base[0]:
+        return None
+    return set(filter(None, git("diff", "--name-only", base[0]) or [])) | \
+        set(filter(None, git("ls-files", "--others", "--exclude-standard") or []))
+
+
+def changed_harnesses(found, records, ref):
+    """Harnesses new or changed since the merge base of HEAD and ref: their script, or a dependency of theirs that is
+    an oracle (Java under mods/horizon/src/test) or a probe (a crate's example or binary), changed or was added."""
+    changed = changed_files(ref)
+    if changed is None:
         print(f"note: no merge base with {ref}; the flake check repeats nothing", flush=True)
         return set()
-    changed = set(filter(None, git("diff", "--name-only", base[0]) or [])) | \
-        set(filter(None, git("ls-files", "--others", "--exclude-standard") or []))
     found_changed = set()
     for name, script in found.items():
         specific = [path for path in records.get(name, {}).get("dependencies", [])
@@ -1080,6 +1092,30 @@ def changed_harnesses(found, records, ref):
     return found_changed
 
 
+def affected_harnesses(found, records, changed):
+    """Harnesses the changed files can affect: their script or a recorded dependency (here, or in the shared
+    dependency lists) changed, a file every harness depends on changed, or nothing is recorded about them yet."""
+    if changed & SHARED_INPUTS:
+        return set(found)
+    affected = set()
+    for name, script in found.items():
+        dependencies = records.get(name, {}).get("dependencies")
+        template = SHARED / "dependencies" / f"{name}.json"
+        if dependencies is None and template.exists():
+            dependencies = json.loads(template.read_text()).get("dependencies")
+        if dependencies is None or str(Path(script).relative_to(ROOT)) in changed or \
+                any(path.split(KEEP)[0] in changed for path in dependencies):
+            affected.add(name)
+    return affected
+
+
+def platform_skips(config):
+    """Harnesses tools/parity_hosts.json marks as giving different results on this platform: {name: reason}."""
+    if sys.platform == "linux":
+        return {}
+    return dict(config.get("linux_only", {}))
+
+
 def finished_run(failed):
     """Record that this run completed, for tools/gate.py: a crashed runner never writes it."""
     STATE_DIR.mkdir(parents=True, exist_ok=True)
@@ -1110,6 +1146,8 @@ def main():
     parser.add_argument("--flake-check", metavar="REF", help="harnesses new or changed since the merge base with REF "
                         "must pass --flake-rounds times in a row (tools/gate.py)")
     parser.add_argument("--flake-rounds", type=int, default=3, help="runs required by --flake-check (default 3)")
+    parser.add_argument("--changed", metavar="REF", help="only harnesses the changes since the merge base with REF can "
+                        "affect (and that have not passed with their current inputs): the pull-request check")
     args = parser.parse_args()
 
     found = harnesses()
@@ -1137,8 +1175,20 @@ def main():
         chosen = list(found)
     elif args.failed:
         chosen = [name for name in found if records.get(name, {}).get("status") == "fail"]
+    elif args.changed:
+        changed = changed_files(args.changed)
+        if changed is None:
+            parser.error(f"no merge base with {args.changed}")
+        affected = affected_harnesses(found, records, changed)
+        chosen = [name for name in found if name in affected and stale(name, state, hasher, environment)]
+        print(f"{len(changed)} files changed since the merge base with {args.changed}: {len(affected)} harnesses "
+              f"depend on them, {len(chosen)} without a pass for their current inputs.", flush=True)
     else:
         chosen = [name for name in found if stale(name, state, hasher, environment)]
+    skips = platform_skips(host_config())
+    for name in [name for name in chosen if base_name(name) in skips and not args.names]:
+        print(f"skipped on {sys.platform}: {name}: {skips[base_name(name)]}", flush=True)
+        chosen.remove(name)
     rounds = {name: args.repeat for name in chosen} if args.repeat > 1 else {}
     if args.flake_check:
         changed = changed_harnesses(found, records, args.flake_check)

From 989f843b1c744946f8bac7a9ddd6c2e08724c1a7 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 18:46:05 +0200
Subject: [PATCH 30/43] vanilla-data.sh: keep everything horizon-prepare writes
 per preparer version, beside the shared data

The first parity run kept only .local/horizon-client per preparer version; the exporters' outputs beside it
stayed in the checkout, and the dedicated server, which finds registries.json at
/../../datagen, didn't find it next to the prepared folder (world_spawn failed).

Co-Authored-By: Claude Opus 5.5 
---
 tools/ci/vanilla-data.sh | 35 +++++++++++++++++++++++++++--------
 1 file changed, 27 insertions(+), 8 deletions(-)

diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh
index c5e76b388..e89969a57 100755
--- a/tools/ci/vanilla-data.sh
+++ b/tools/ci/vanilla-data.sh
@@ -3,9 +3,9 @@
 # holds the maintainer's own copy, imported and decompiled once (HORIZON_SHARED_SOURCE, default
 # ~/code/horizon-parity/shared-local). It is cloned once into the runner's work folder ($RUNNER_WORKSPACE/
 # shared-local; APFS clones, so no second copy of the bytes), and .local/ links to it as in a parity worktree.
-# .local/horizon-client, the resources horizon-prepare makes, is prepared by this checkout's own preparer
-# once per preparer version (its sources, the exporters and research-lock.json), so a change to the preparer
-# is checked with what it prepares; the four newest preparations are kept.
+# .local/horizon-client and the exporter outputs beside it, what horizon-prepare makes, are prepared by this
+# checkout's own preparer once per preparer version (its sources, the exporters and research-lock.json), so a
+# change to the preparer is checked with what it prepares; the four newest preparations are kept.
 set -euo pipefail
 shared="${RUNNER_WORKSPACE:?}/shared-local"
 source="${HORIZON_SHARED_SOURCE:-$HOME/code/horizon-parity/shared-local}"
@@ -26,16 +26,22 @@ fi
 mkdir -p .local "$shared/prepared"
 for entry in "$shared"/*; do
   name=$(basename "$entry")
-  case "$name" in prepared|horizon-client|*.log) continue ;; esac
+  case "$name" in prepared|*.log) continue ;; esac
   if [ -L ".local/$name" ] || [ ! -e ".local/$name" ]; then ln -sfn "$entry" ".local/$name"; fi
 done
 
 key=$(git ls-files -s crates/horizon-prepare mods/horizon/src/test/java research-lock.json | shasum -a 256 | cut -c1-16)
 prepared="$shared/prepared/$key"
-ln -sfn "$prepared" .local/horizon-client
-if [ ! -f "$prepared/.done" ]; then
+# horizon-prepare writes .local/horizon-client and its exporters' outputs beside it: all of them live in
+# $prepared, listed in $prepared/.entries, and .local/ links to them.
+if [ ! -f "$prepared/.entries" ]; then
   echo "Preparing resources with this checkout's horizon-prepare ($key)"
   rm -rf "$prepared" && mkdir -p "$prepared"
+  # Links to another preparation's outputs go first, so what this one writes shows up as new entries.
+  for entry in .local/*; do
+    if [ -L "$entry" ] && [[ "$(readlink "$entry")" == "$shared/prepared/"* ]]; then rm "$entry"; fi
+  done
+  before=$(ls -1A .local | LC_ALL=C sort)
   started=$SECONDS
   cargo build --release --locked -p horizon-prepare
   if ! target/release/horizon-prepare --root "$PWD" > "$RUNNER_TEMP/prepare.log" 2>&1; then
@@ -43,9 +49,22 @@ if [ ! -f "$prepared/.done" ]; then
     rm -rf "$prepared"
     exit 1
   fi
-  touch "$prepared/.done"
-  echo "Prepared in $((SECONDS - started)) s"
+  LC_ALL=C comm -13 <(echo "$before") <(ls -1A .local | LC_ALL=C sort) > "$RUNNER_TEMP/prepared-entries"
+  while read -r name; do mv ".local/$name" "$prepared/$name"; done < "$RUNNER_TEMP/prepared-entries"
+  mv "$RUNNER_TEMP/prepared-entries" "$prepared/.entries"
+  echo "Prepared in $((SECONDS - started)) s: $(tr '\n' ' ' < "$prepared/.entries")"
 fi
+# The game finds some data relative to its resources (/../../datagen): beside the prepared folders,
+# the same neighbours as in the shared folder.
+for entry in "$shared"/*; do
+  name=$(basename "$entry")
+  case "$name" in prepared|*.log) continue ;; esac
+  [ -e "$prepared/$name" ] || ln -sfn "$entry" "$prepared/$name"
+done
+while read -r name; do
+  if [ -L ".local/$name" ] || [ ! -e ".local/$name" ]; then ln -sfn "$prepared/$name" ".local/$name"; else
+    echo "::error::.local/$name is not a link to the prepared resources"; exit 1; fi
+done < "$prepared/.entries"
 touch "$prepared"
 # The four newest preparations stay.
 ls -1dt "$shared/prepared"/*/ 2>/dev/null | tail -n +5 | while read -r old; do rm -rf "$old"; done

From 8aacb487984615009fdb2aba4fe1e8890a2956a3 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 18:48:29 +0200
Subject: [PATCH 31/43] release: automatic game releases after main's green
 checks

release.yml now releases the game by itself: after every green checks run of a push to main, every hour
(a release the cooldown held goes out without another merge) and by hand. tools/release_train.py decides
from the pull requests merged since the last published game release: a release when one changed what
players run and the last release is 3 hours old, at once for a pull request labelled release-now;
skip-release pull requests don't count. RELEASES_PAUSED=1 stops it. Tags vYYYY.MM.DD, then .1, .2 the
same UTC day.

Linux (ubuntu-22.04) and Windows build on GitHub with Cargo caches, macOS on the Mac mini's runner
(MAC_RUNNER=macos-latest sends it to GitHub). Each builds horizon-client, horizon-ctl and horizon-prepare
(all three named: --bin selects only the named binaries), checks all three exist, checks their libraries,
starts each one, packages with xtask and archives; the Mac also runs the game offscreen for 300 frames on
a new world with resources prepared from its own Minecraft. The notes: New (label feature), Fixed (the
rest), Known issues (docs/known-issues.md). A hand-started run off main, or with dry_run, builds
everything and writes the notes but publishes nothing.

docs/release-flow.md describes the flow, the labels, pausing and rolling back; the launcher gets a test
that a release turned back into a draft is never offered.

Co-Authored-By: Claude Opus 5.5 
---
 .github/workflows/release.yml | 243 ++++++++++++++++++++++-----
 docs/known-issues.md          |   6 +
 docs/release-flow.md          | 115 +++++++++++++
 launcher/src/backend.rs       |  23 +++
 tests/test_release_train.py   |  99 +++++++++++
 tools/release_train.py        | 302 ++++++++++++++++++++++++++++++++++
 6 files changed, 748 insertions(+), 40 deletions(-)
 create mode 100644 docs/known-issues.md
 create mode 100644 tests/test_release_train.py
 create mode 100644 tools/release_train.py

diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 88a91ee97..cd2ad5ce0 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,57 +1,220 @@
-name: release builds
-# Started by hand: gh workflow run release.yml --ref 
-# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl and horizon-prepare) and uploads the playable folders
-# as artifacts.
-# macOS builds are made on the development machines. Linux is built here, on an older Ubuntu,
-# so the binary uses the standard loader and runs on any recent distribution (and on NixOS
-# through nix-ld): a build made on NixOS asks for a /nix/store loader no other system has.
+name: release
+# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release
+# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release
+# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at
+# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them.
+# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
+# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
+# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests.
+#   gh workflow run release --ref                        # dry run: builds and notes, publishes nothing
+#   gh workflow run release -f dry_run=false -f force=true       # on main: release now, whatever the rules say
 on:
+  workflow_run:
+    workflows: [checks]
+    types: [completed]
+    branches: [main]
+  schedule:
+    - cron: '17 * * * *'
   workflow_dispatch:
+    inputs:
+      dry_run:
+        description: Build everything and write the notes, but publish nothing
+        type: boolean
+        default: true
+      force:
+        description: Release even without player-facing changes, within the cooldown or while paused
+        type: boolean
+        default: false
 permissions:
   contents: read
+concurrency:
+  group: game-release
+  cancel-in-progress: false
 jobs:
-  windows:
-    runs-on: windows-latest
+  decide:
+    if: >-
+      github.event_name != 'workflow_run' ||
+      (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    outputs:
+      release: ${{ steps.decide.outputs.release }}
+      tag: ${{ steps.decide.outputs.tag }}
+      head: ${{ steps.decide.outputs.head }}
+      dry_run: ${{ steps.mode.outputs.dry_run }}
     steps:
       - uses: actions/checkout@v4
-      - name: Install Rust toolchain
-        run: rustup toolchain install stable --profile minimal
-      - name: Build the client
-        # The C runtime linked in, so the game runs without the Visual C++ redistributable.
+        with:
+          fetch-depth: 0
+      - id: mode
+        # A dry run never publishes; a hand-started run off main is always one.
+        run: echo "dry_run=${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run || github.ref != 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
+      - id: decide
         env:
-          RUSTFLAGS: -C target-feature=+crt-static
-        run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
-      - name: Only system DLLs
-        # Vulkan and the rest are loaded at run time; a linked non-system DLL is a
-        # "DLL not found" dialog on some players' machines.
+          GH_TOKEN: ${{ github.token }}
+          RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }}
+          # The commit whose checks just passed; a dry run builds the branch it was started on; otherwise
+          # main's newest commit with green checks.
+          HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }}
+          FORCE: ${{ inputs.force && 'yes' || '' }}
         run: |
-          python tools/check_imports.py target/release/horizon-client.exe
-          python tools/check_imports.py target/release/horizon-ctl.exe
-          python tools/check_imports.py target/release/horizon-prepare.exe
-      - name: Package
-        run: cargo +stable run --locked -p xtask -- package target/release/horizon-client.exe dist/horizon-windows-x64
-      - uses: actions/upload-artifact@v4
-        with:
-          name: horizon-windows-x64
-          path: dist/horizon-windows-x64
-  linux:
-    runs-on: ubuntu-22.04
+          python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json
+          echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY"
+          # A dry run builds whatever the decision, to test the builds.
+          if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi
+
+  build:
+    needs: decide
+    if: needs.decide.outputs.release == 'true'
+    name: build ${{ matrix.name }}
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - name: linux
+            os: ubuntu-22.04
+            dir: horizon-linux-x86_64
+            asset: horizon-linux-x86_64.tar.gz
+          - name: windows
+            os: windows-latest
+            dir: horizon-windows-x64
+            asset: horizon-windows-x64.zip
+            exe: .exe
+            # The C runtime linked in, so the game runs without the Visual C++ redistributable.
+            rustflags: -C target-feature=+crt-static
+          - name: macos
+            mac: true
+            dir: horizon-macos-arm64
+            asset: horizon-macos-arm64.zip
+    runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }}
+    timeout-minutes: 40
+    env:
+      RUSTFLAGS: ${{ matrix.rustflags }}
+    defaults:
+      run:
+        shell: bash
     steps:
       - uses: actions/checkout@v4
-      - name: Install Rust toolchain
-        run: rustup toolchain install stable --profile minimal
+        with:
+          ref: ${{ needs.decide.outputs.head }}
+          persist-credentials: false
+          # On the Mac mini's runner, keep target/ (incremental) and .local/ (the prepared resources).
+          clean: ${{ runner.environment == 'github-hosted' }}
+      - uses: dtolnay/rust-toolchain@stable
+      - uses: Swatinem/rust-cache@v2
+        if: runner.environment == 'github-hosted'
+        with:
+          shared-key: release-${{ matrix.name }}
       - name: ALSA and udev headers
+        if: runner.os == 'Linux'
         run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
-      - name: Build the client
-        run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
-      - name: Standard loader and libraries only
+      - name: Build the client, horizon-ctl and horizon-prepare
+        run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
+      - name: Every program the release folder takes was built
         run: |
-          python3 tools/check_imports.py target/release/horizon-client
-          python3 tools/check_imports.py target/release/horizon-ctl
-          python3 tools/check_imports.py target/release/horizon-prepare
+          for binary in horizon-client horizon-ctl horizon-prepare; do
+            test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; }
+          done
+      - name: Only system libraries
+        # Windows: no non-system DLL (a "DLL not found" dialog on some players' machines). Linux: the standard
+        # loader and libraries every desktop distribution has. macOS: only the system's own libraries.
+        run: |
+          for binary in horizon-client horizon-ctl horizon-prepare; do
+            file="target/release/$binary${{ matrix.exe }}"
+            if [[ "$RUNNER_OS" == macOS ]]; then
+              others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true)
+              [[ -z "$others" ]] || { echo "::error::$binary links $others"; exit 1; }
+            else
+              ${{ runner.os == 'Windows' && 'python' || 'python3' }} tools/check_imports.py "$file"
+            fi
+          done
+      - name: Every program starts
+        run: |
+          set -euo pipefail
+          bin=target/release
+          "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources'
+          "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null
+          "$bin/horizon-prepare${{ matrix.exe }}" --version
+          "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir'
+      - name: Tools from the runner
+        if: runner.environment == 'self-hosted'
+        run: bash tools/ci/runner-env.sh
+      - name: Resources prepared from the runner's own Minecraft
+        if: runner.environment == 'self-hosted'
+        run: bash tools/ci/vanilla-data.sh
+      - name: The game runs (offscreen, a new world, 300 frames)
+        if: runner.environment == 'self-hosted'
+        run: |
+          set -euo pipefail
+          home="$RUNNER_TEMP/horizon-smoke"
+          rm -rf "$home" && mkdir -p "$home"
+          version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1)
+          HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 target/release/horizon-client \
+            --resources ".local/horizon-client/$version" --offscreen --render-distance 4 --seed 1 \
+            --frames 300 --timeout-seconds 180 --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1 \
+            || { tail -40 "$home/client.log"; exit 1; }
+          python3 - "$home/smoke.json" <<'EOF'
+          import json, sys
+          report = json.load(open(sys.argv[1]))
+          print({key: report.get(key) for key in ("adapter", "presented_frames", "resident_chunks", "error")})
+          if report.get("error") is not None or report.get("presented_frames") != 300 or not report.get("resident_chunks"):
+              sys.exit("the smoke run did not draw a world: " + json.dumps(report)[:2000])
+          EOF
       - name: Package
-        run: cargo +stable run --locked -p xtask -- package target/release/horizon-client dist/horizon-linux-x86_64
+        run: |
+          set -euo pipefail
+          cargo run --locked -p xtask -- package "target/release/horizon-client${{ matrix.exe }}" "dist/${{ matrix.dir }}"
+          cd dist
+          rm -f "${{ matrix.asset }}"
+          case "${{ matrix.asset }}" in
+            *.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;;
+            *) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null
+               else ditto -c -k --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}"; fi ;;
+          esac
+          ls -l "${{ matrix.asset }}"
       - uses: actions/upload-artifact@v4
         with:
-          name: horizon-linux-x86_64
-          path: dist/horizon-linux-x86_64
+          name: ${{ matrix.asset }}
+          path: dist/${{ matrix.asset }}
+          if-no-files-found: error
+          retention-days: 7
+
+  publish:
+    needs: [decide, build]
+    runs-on: ubuntu-latest
+    timeout-minutes: 10
+    permissions:
+      contents: write
+    steps:
+      - uses: actions/checkout@v4
+        with:
+          fetch-depth: 0
+      - name: Notes
+        env:
+          GH_TOKEN: ${{ github.token }}
+        run: |
+          python3 tools/release_train.py notes --kind game --tag "${{ needs.decide.outputs.tag }}" \
+            --head "${{ needs.decide.outputs.head }}" --out notes > /dev/null
+          { echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY"
+      - uses: actions/download-artifact@v4
+        with:
+          path: dist
+          merge-multiple: true
+      - name: Publish ${{ needs.decide.outputs.tag }}
+        if: needs.decide.outputs.dry_run != 'true'
+        env:
+          GH_TOKEN: ${{ github.token }}
+          TAG: ${{ needs.decide.outputs.tag }}
+        run: |
+          gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
+            --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \
+            dist/horizon-macos-arm64.zip
+      - name: Dry run, the release that would be published
+        if: needs.decide.outputs.dry_run == 'true'
+        run: |
+          echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)"
+          ls -l dist
+      - uses: actions/upload-artifact@v4
+        with:
+          name: release-notes
+          path: notes/
diff --git a/docs/known-issues.md b/docs/known-issues.md
new file mode 100644
index 000000000..2c63f4c03
--- /dev/null
+++ b/docs/known-issues.md
@@ -0,0 +1,6 @@
+# Known issues
+
+Every game release lists the bullets below under "Known issues" (tools/release_train.py). Keep them short and
+written for players; remove a bullet in the pull request that fixes it.
+
+- Sprint-jumping has been reported as broken, but we couldn't reproduce it. If it happens to you, describe it in #horizon-bugs on Discord.
diff --git a/docs/release-flow.md b/docs/release-flow.md
index e46ec7dd3..ac2598fc6 100644
--- a/docs/release-flow.md
+++ b/docs/release-flow.md
@@ -69,3 +69,118 @@ gh api -X POST repos/ludovic111/horizon/branches/main/protection/required_status
 
 A skipped `parity` (a fork without the label, a run started by a label) counts as passed, so requiring it never
 blocks a fork's pull request; the maintainer decides whether to run it.
+
+## Game releases
+
+`.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` run of a push
+to main, every hour at :17 (so a release the cooldown held goes out without another merge), and by hand.
+
+```mermaid
+flowchart LR
+    pr(["pull request"]) --> checks{"verify
parity"} + checks -- green --> automerge["auto-merge
(merge commit)"] + automerge --> main(["main"]) + main --> mainchecks{"checks on main"} + mainchecks -- green --> decide{"decide
tools/release_train.py"} + cron(["every hour :17"]) --> decide + decide -- "player-facing PRs, 3 h since the last release,
or release-now" --> build + decide -- otherwise --> wait(["wait"]) + subgraph build["build, in parallel"] + linux["Linux x86_64
GitHub ubuntu-22.04"] + windows["Windows x64
GitHub windows-latest"] + mac["macOS arm64
Mac mini runner
+ offscreen game run"] + end + build --> publish["publish vYYYY.MM.DD[.N]
notes from the merged PRs"] + publish --> launcher(["launchers install it"]) + publish --> kira(["Kira posts it;
pings only with ### New"]) +``` + +### When it releases + +`tools/release_train.py decide --kind game` looks at the pull requests merged into main (first-parent merge +commits) since the last **published** game release: + +- A pull request counts when it changed what players run: `crates/` (not `examples/`, `tests/`, `benches/`), + `xtask/`, `packaging/`, `Cargo.toml`, `Cargo.lock`, `research-lock.json`, or an exporter `horizon-prepare` + compiles (the `mods/horizon/src/test/java/dev/horizonlab/parity/*.java` files its sources name). Markdown never + counts. +- It releases when at least one pull request counts and the last game release is at least 3 hours old. +- A pull request labelled `release-now` (a crash or a blocker) releases at once, cooldown or not. +- A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. +- One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing. +- A scheduled or hand-started run releases main's newest commit whose `checks` passed; after `checks`, the commit + they passed on. + +### Labels + +| Label | Effect | +| --- | --- | +| `feature` | Listed under **New** (Kira pings the releases role); makes the next launcher release a minor one | +| `release-now` | Releases as soon as main's checks pass, without the cooldown | +| `skip-release` | Doesn't trigger a release and isn't listed in the notes | +| `run-parity` | Runs the parity job once on a fork's pull request | +| `parity-regression` | Opened by the nightly audit for a harness that fails on main | + +Pull requests without `feature` are listed under **Fixed**. Titles are written for players, since they become +the notes. + +### Builds + +| Archive | Runs on | Checks | +| --- | --- | --- | +| `horizon-linux-x86_64.tar.gz` | GitHub `ubuntu-22.04` (an older glibc, so it runs on any recent distribution) | the standard loader and libraries only (`tools/check_imports.py`) | +| `horizon-windows-x64.zip` | GitHub `windows-latest`, C runtime linked in | system DLLs only (`tools/check_imports.py`) | +| `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 300-frame offscreen run of a new world with resources prepared from the runner's own Minecraft (`--offscreen --frames 300 --smoke-report`) | + +Each builds `horizon-client`, `horizon-ctl` and `horizon-prepare` in release mode, checks all three exist, starts +each one (`--help`, `--version`), packages the folder with `cargo run -p xtask -- package` and archives it. The +GitHub jobs keep their Cargo caches (`Swatinem/rust-cache`); the Mac mini keeps its `target/`. Only the Mac +runs the game: GitHub's runners have neither a GPU worth the name nor the game files. + +### Notes + +`tools/release_train.py notes` writes them from the same pull requests: + +- the title, `Horizon 2026.10.15.1: `, features first, newest first; +- `### New` (label `feature`) and `### Fixed` (the rest), one line per pull request: its title, its number, the + issues it closes; +- `### Known issues`: the bullets of [docs/known-issues.md](known-issues.md); +- thanks to outside contributors, how to install, the disclaimer. + +Kira posts every published release in #releases and pings the releases role only when the notes have a +`### New` section. + +### Starting one by hand + +```sh +gh workflow run release --ref # dry run: builds everything, writes the notes, publishes nothing +gh workflow run release --ref main -f dry_run=false # the usual decision, now +gh workflow run release --ref main -f dry_run=false -f force=true # release now, whatever the rules (even while paused) +``` + +A hand-started run on any branch but main is always a dry run. The notes are in the run's summary and its +`release-notes` artifact. + +### Pausing + +```sh +gh variable set RELEASES_PAUSED --body 1 # no automatic game or launcher releases +gh variable delete RELEASES_PAUSED # back on; the next hourly run catches up +``` + +While paused, runs still decide and say why in their summary; `force=true` still releases. + +### Rolling back + +A bad release is withdrawn by turning it back into a draft: + +```sh +gh release edit v2026.10.15.1 --draft +``` + +Launchers list only published releases: the previous version becomes the newest one again, launchers that +didn't install the bad one won't, and players who did can pick the previous version in the launcher's version +list (`launcher/src/backend.rs` tests `withdrawn_release_is_never_offered`). The tag stays, so the next release +that day takes the next number, and its notes start from the last *published* release, so they list the +withdrawn release's changes again with the fix. Usually the better way out is forward: revert the pull request, +label the revert `release-now`, and a fixed release is out as soon as main's checks pass. diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 4d1a9654c..da84e17c3 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1537,6 +1537,29 @@ mod tests { assert_eq!(launcher, ["launcher-v9.0.0"]); } + /// Rolling a release back (`gh release edit --draft`, docs/release-flow.md) makes the + /// previous one the newest again: it is what `install latest` and the update check offer. + #[test] + fn withdrawn_release_is_never_offered() { + let asset = ASSET.unwrap_or("horizon-linux-x86_64.tar.gz"); + let list = serde_json::json!([ + {"tag_name": "v2026.10.15.1", "draft": true, "assets": [{"name": asset, "browser_download_url": "bad", "size": 1}]}, + {"tag_name": "v2026.10.15", "assets": [{"name": asset, "browser_download_url": "good", "size": 1}]}, + {"tag_name": "v2026.10.14", "assets": [{"name": asset, "browser_download_url": "old", "size": 1}]}, + ]); + let releases = parse_releases(&list, Some(asset), is_game_tag); + assert!(releases.iter().all(|r| r.tag != "v2026.10.15.1")); + assert_eq!(latest(&releases).map(|r| r.tag.as_str()), Some("v2026.10.15")); + let offered = |installed: &[&str]| { + let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); + horizon_update(&releases, &installed).map(|r| r.tag) + }; + assert_eq!(offered(&["v2026.10.14"]), Some("v2026.10.15".into())); + assert_eq!(offered(&[]), Some("v2026.10.15".into())); + // Who installed the withdrawn one is not told to "update" to an older version. + assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); + } + #[test] fn versions_compare_by_number() { assert_eq!(compare_versions("v2026.10.13", "v2026.10.12"), Greater); diff --git a/tests/test_release_train.py b/tests/test_release_train.py new file mode 100644 index 000000000..d69fc0793 --- /dev/null +++ b/tests/test_release_train.py @@ -0,0 +1,99 @@ +import datetime as dt +from pathlib import Path +import tempfile +import unittest + +from tools import release_train as train + +NOW = dt.datetime(2026, 10, 15, 12, 0, tzinfo=dt.timezone.utc) + + +def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111"): + return {"number": number, "title": title, "labels": list(labels), "paths": list(paths), "issues": list(issues), + "author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}"} + + +class ReleaseTrainTests(unittest.TestCase): + def test_player_facing_paths(self): + exporters = {"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobDataExporter.java"} + self.assertTrue(train.player_facing("crates/horizon-client/src/game.rs", "game")) + self.assertTrue(train.player_facing("Cargo.lock", "game")) + self.assertTrue(train.player_facing("xtask/src/main.rs", "game")) + self.assertTrue(train.player_facing(next(iter(exporters)), "game", exporters)) + self.assertFalse(train.player_facing("mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodOracle.java", "game", exporters)) + self.assertFalse(train.player_facing("crates/horizon-world/examples/probe.rs", "game")) + self.assertFalse(train.player_facing("crates/horizon-client/README.md", "game")) + self.assertFalse(train.player_facing("tools/test_food_parity.py", "game")) + self.assertFalse(train.player_facing("launcher/src/main.rs", "game")) + self.assertTrue(train.player_facing("launcher/src/main.rs", "launcher")) + self.assertTrue(train.player_facing("crates/horizon-prepare/src/lib.rs", "launcher")) + self.assertFalse(train.player_facing("launcher/links.json", "launcher")) + self.assertFalse(train.player_facing("crates/horizon-client/src/game.rs", "launcher")) + + def test_the_exporters_are_those_horizon_prepare_names(self): + found = train.exporters() + self.assertIn(train.EXPORTERS + "VanillaMobDataExporter.java", found) + self.assertTrue(all(path.endswith(".java") for path in found)) + + def test_game_tags_count_up_within_a_day(self): + today = dt.date(2026, 10, 15) + self.assertEqual(train.next_game_tag(["v2026.10.14", "launcher-v0.1.4"], today), "v2026.10.15") + self.assertEqual(train.next_game_tag(["v2026.10.15"], today), "v2026.10.15.1") + self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.1", "v2026.10.15.2"], today), "v2026.10.15.3") + + def test_launcher_tags_bump_the_patch_or_the_minor(self): + tags = ["launcher-v0.1.3", "launcher-v0.1.10", "v2026.10.15", "launcher-v0.1.4"] + self.assertEqual(train.next_launcher_tag(tags, minor=False), "launcher-v0.1.11") + self.assertEqual(train.next_launcher_tag(tags, minor=True), "launcher-v0.2.0") + + def test_decision(self): + hour = dt.timedelta(hours=1) + decide = lambda prs, age, **kw: train.decision("game", prs, NOW - age, NOW, **kw)[0] + self.assertTrue(decide([pr(1)], 4 * hour)) + self.assertFalse(decide([pr(1)], 2 * hour), "within the cooldown") + self.assertTrue(decide([pr(1, labels=["release-now"])], 0.1 * hour)) + self.assertFalse(decide([pr(1, paths=[])], 9 * hour), "nothing players run") + self.assertFalse(decide([pr(1, labels=["skip-release"])], 9 * hour)) + self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])], 9 * hour)) + self.assertFalse(decide([pr(1)], 9 * hour, paused=True)) + self.assertTrue(decide([], 0.1 * hour, paused=True, force=True)) + self.assertTrue(train.decision("game", [pr(1)], None, NOW)[0], "the first release") + + def test_notes(self): + prs = [pr(5, "Nether portals: vanilla timing and linking (fixes #94)", issues=[94]), + pr(6, "Controllers: gilrs input layer and gameplay", labels=["feature"], author="cosmic"), + pr(7, "Release folder in Rust", labels=["skip-release"]), + pr(8, "Website footer", paths=[])] + title, body = train.notes("game", "v2026.10.15.1", prs, ["- Sound cuts out after an hour."]) + self.assertEqual(title, "Horizon 2026.10.15.1: Controllers, nether portals") + self.assertIn("### New\n- Controllers: gilrs input layer and gameplay (#6)", body) + self.assertIn("### Fixed\n- Nether portals: vanilla timing and linking (#5, fixes #94)", body) + self.assertIn("### Known issues\n- Sound cuts out after an hour.", body) + self.assertNotIn("#7", body) + self.assertNotIn("#8", body) + self.assertIn("Thanks to @cosmic.", body) + self.assertLess(body.index("### New"), body.index("### Fixed")) + + def test_a_long_release_is_named_after_its_first_titles(self): + prs = [pr(n, f"Change number {n} with a fairly long title") for n in range(1, 10)] + title, _ = train.notes("game", "v2026.10.15", prs, []) + self.assertTrue(title.startswith("Horizon 2026.10.15: Change number 9"), title) + self.assertTrue(title.endswith("more fixes"), title) + self.assertLess(len(title), 100) + + def test_launcher_notes(self): + title, body = train.notes("launcher", "launcher-v0.2.0", [pr(3, "Launcher: say the self-update succeeded")], []) + self.assertEqual(title, "Horizon launcher 0.2.0") + self.assertIn("### Fixed\n- Launcher: say the self-update succeeded (#3)", body) + self.assertNotIn("Known issues", body) + + def test_known_issues_are_the_bullets_of_the_file(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp, "known-issues.md") + path.write_text("# Known issues\n\nSome text.\n\n- One.\n- Two, with **bold**.\n continued\n") + self.assertEqual(train.known_issues(path), ["- One.", "- Two, with **bold**."]) + self.assertEqual(train.known_issues(Path(temp, "missing.md")), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/release_train.py b/tools/release_train.py new file mode 100644 index 000000000..511ccac5e --- /dev/null +++ b/tools/release_train.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +"""Decides when Horizon releases, names the release and writes its notes (.github/workflows/release.yml). + + python3 tools/release_train.py decide --kind game [--head SHA] [--force] + python3 tools/release_train.py decide --kind launcher + python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes + +A kind releases when a pull request merged into main since its last published release changed one of its +player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and that release is at least COOLDOWN old, or when one of those +pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count +towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases. + +Game releases are tagged vYYYY.MM.DD, then .1, .2 the same UTC day; launcher releases launcher-vX.Y.Z, the +patch after the last launcher tag, or the next minor when a merged pull request is labelled feature. Notes: +"### New" lists the pull requests labelled feature, "### Fixed" the others, "### Known issues" the bullets of +docs/known-issues.md. See docs/release-flow.md. + +Prints the decision as JSON and writes it to $GITHUB_OUTPUT when set. Needs git history and the gh CLI. +""" + +import argparse +import datetime as dt +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") +COOLDOWN = dt.timedelta(hours=3) +EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/" + +# What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count. +GAME_PATHS = ["crates/", "xtask/", "packaging/", "Cargo.toml", "Cargo.lock", "research-lock.json"] +LAUNCHER_PATHS = ["launcher/", "crates/horizon-prepare/", "crates/horizon-theme/"] +LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"] + +FOOTER = { + "game": "Install or update it from the Horizon launcher: it installs new versions by itself. " + "New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.", + "launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, " + "and run `horizon-launcher`. Website: https://playhorizon.dev", +} +DISCLAIMER = "Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft." + + +def run(*command, check=True): + result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True) + if check and result.returncode: + raise SystemExit(f"{' '.join(command)}: {result.stderr.strip()}") + return result.stdout + + +def gh_json(*arguments): + return json.loads(run("gh", *arguments) or "null") + + +def exporters(): + """The exporter and oracle sources horizon-prepare compiles: those its sources name.""" + names = set() + for source in (ROOT / "crates" / "horizon-prepare" / "src").glob("*.rs"): + names.update(re.findall(r'"([A-Z]\w+\.java)"', source.read_text())) + return {EXPORTERS + name for name in names} + + +def player_facing(path, kind, exporter_paths=frozenset()): + """Whether a change to path ships to players in a release of this kind.""" + if path.endswith(".md") or re.match(r"(crates|launcher)/([\w-]+/)?(examples|tests|benches)/", path): + return False + if kind == "launcher": + return any(path.startswith(p) for p in LAUNCHER_PATHS) and not any(path.startswith(p) for p in LAUNCHER_IGNORED) + return any(path == p or path.startswith(p) for p in GAME_PATHS) or path in exporter_paths + + +def is_game_tag(tag): + return re.fullmatch(r"v\d{4}\.\d{2}\.\d{2}(\.\d+)?", tag) is not None + + +def is_launcher_tag(tag): + return re.fullmatch(r"launcher-v\d+\.\d+\.\d+", tag) is not None + + +def tag_key(tag): + return tuple(int(part) for part in re.findall(r"\d+", tag)) + + +def next_game_tag(tags, today): + """vYYYY.MM.DD, or .1, .2... when that day already has a tag (drafts and rolled-back releases included).""" + day = f"v{today:%Y.%m.%d}" + taken = [tag for tag in tags if tag == day or tag.startswith(day + ".")] + if not taken: + return day + return f"{day}.{max(int(tag.split('.')[3]) if tag.count('.') == 3 else 0 for tag in taken) + 1}" + + +def next_launcher_tag(tags, minor): + versions = sorted((tag_key(tag) for tag in tags if is_launcher_tag(tag)), reverse=True) + major, minor_, patch = versions[0] if versions else (0, 1, 0) + return f"launcher-v{major}.{minor_ + 1}.0" if minor else f"launcher-v{major}.{minor_}.{patch + 1}" + + +def merged_pull_requests(base, head): + """(number, merge commit) of the pull requests merged into main between base and head, oldest first.""" + found = [] + for line in run("git", "log", "--first-parent", "--reverse", "--format=%H%x09%s", f"{base}..{head}").splitlines(): + commit, _, subject = line.partition("\t") + match = re.match(r"Merge pull request #(\d+) ", subject) or re.search(r"\(#(\d+)\)$", subject) + if match: + found.append((int(match.group(1)), commit)) + return found + + +def changed_paths(commit): + """The files a pull request changed: its merge commit against main before it (first parent).""" + return run("git", "diff", "--name-only", f"{commit}^1", commit).split() + + +def pull_request(number): + data = gh_json("pr", "view", str(number), "--repo", REPO, "--json", + "number,title,url,labels,closingIssuesReferences,author") + return { + "number": data["number"], + "title": data["title"].strip(), + "url": data["url"], + "labels": sorted(label["name"] for label in data["labels"]), + "issues": sorted(issue["number"] for issue in data.get("closingIssuesReferences") or []), + "author": (data.get("author") or {}).get("login", ""), + } + + +def published_releases(): + """Published (not draft, not pre-release) releases, newest first, with their tags and dates.""" + releases = gh_json("api", f"repos/{REPO}/releases?per_page=100", "--paginate", "--slurp") + flat = [release for page in releases for release in page] + return [release for release in flat if not release["draft"] and not release["prerelease"]] + + +def last_release(releases, kind): + keep = is_game_tag if kind == "game" else is_launcher_tag + ours = [release for release in releases if keep(release["tag_name"])] + return max(ours, key=lambda release: tag_key(release["tag_name"]), default=None) + + +def decision(kind, prs, last_published, now, paused=False, force=False): + """Whether to release now, and why. prs: the merged pull requests since the last release, each with the + files it changed under "paths" (player-facing ones only).""" + counted = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] + urgent = [pr for pr in counted if "release-now" in pr["labels"]] + age = now - last_published if last_published else None + if force: + return True, "started by hand with force" + if paused: + return False, "RELEASES_PAUSED is set" + if not counted: + return False, "no merged pull request changed what players run" + if urgent: + return True, "release-now: " + ", ".join(f"#{pr['number']}" for pr in urgent) + if age is not None and age < COOLDOWN: + wait = COOLDOWN - age + return False, f"{len(counted)} pull requests wait for the cooldown ({wait.seconds // 60} more minutes)" + return True, f"{len(counted)} pull requests changed what players run" + + +def clause(title): + """The start of a pull request title, for a release's name: "Nether portals: vanilla timing" -> "Nether portals".""" + return re.split(r"[:;(]| — | - ", title, maxsplit=1)[0].strip().rstrip(".") + + +def summary(new, fixed, limit=72): + """A short name for the release, from its pull request titles, features first.""" + titles = [clause(pr["title"]) for pr in new[::-1] + fixed[::-1]] + shown, text = [], "" + for title in titles: + title = title if not shown or not title[1:2].islower() else title[0].lower() + title[1:] + candidate = ", ".join(shown + [title]) + if shown and len(candidate) > limit - 20: + break + shown.append(title) + text = candidate + rest = len(titles) - len(shown) + if rest: + text += f" and {rest} more {'changes' if new else 'fixes'}" + return text + + +def bullet(pr): + """A pull request as a line of notes: its title (written for people), its number and the issues it closes.""" + title = re.sub(r"\s*\((?:fixes|closes) #\d+\)|,? stacked on #\d+", "", pr["title"]).strip().rstrip(".") + issues = "".join(f", fixes #{issue}" for issue in pr["issues"]) + return f"- {title} (#{pr['number']}{issues})" + + +def known_issues(path=ROOT / "docs" / "known-issues.md"): + if not path.exists(): + return [] + return [line.rstrip() for line in path.read_text().splitlines() if line.startswith("- ")] + + +def notes(kind, version, prs, issues): + """(title, body) of a release.""" + shown = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] + new = [pr for pr in shown if "feature" in pr["labels"]] + fixed = [pr for pr in shown if "feature" not in pr["labels"]] + if kind == "game": + title = f"Horizon {version.removeprefix('v')}" + (f": {summary(new, fixed)}" if shown else "") + else: + title = f"Horizon launcher {version.removeprefix('launcher-v')}" + parts = [] if shown else ["Rebuilt from the latest main."] + if new: + parts.append("### New\n" + "\n".join(map(bullet, new))) + if fixed: + parts.append("### Fixed\n" + "\n".join(map(bullet, fixed))) + if issues and kind == "game": + parts.append("### Known issues\n" + "\n".join(issues)) + contributors = sorted({pr["author"] for pr in shown if pr["author"] and pr["author"] != REPO.split("/")[0]}) + if contributors: + parts.append("Thanks to " + ", ".join(f"@{name}" for name in contributors) + ".") + parts.append(FOOTER[kind]) + parts.append(DISCLAIMER) + return title, "\n\n".join(parts) + "\n" + + +def gather(kind, head, releases=None): + """The last published release of this kind and the pull requests merged since, with their player-facing paths.""" + releases = published_releases() if releases is None else releases + last = last_release(releases, kind) + base = last["tag_name"] if last else run("git", "rev-list", "--max-parents=0", head).split()[0] + exporter_paths = exporters() + prs = [] + for number, commit in merged_pull_requests(base, head): + pr = pull_request(number) + pr["paths"] = [path for path in changed_paths(commit) if player_facing(path, kind, exporter_paths)] + prs.append(pr) + return last, prs + + +def green_main_head(): + """The newest commit on main whose checks passed: what an automatic release builds.""" + runs = gh_json("run", "list", "--repo", REPO, "--workflow", "checks", "--branch", "main", "--event", "push", + "--limit", "10", "--json", "headSha,status,conclusion") + for entry in runs: + if entry["status"] == "completed": + return entry["headSha"] if entry["conclusion"] == "success" else None + return None + + +def write_outputs(values): + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a") as out: + for name, value in values.items(): + out.write(f"{name}={value}\n") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("command", choices=["decide", "notes"]) + parser.add_argument("--kind", choices=["game", "launcher"], required=True) + parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)") + parser.add_argument("--tag", help="notes: the release's tag") + parser.add_argument("--force", action="store_true", help="release even without player-facing changes or within the cooldown") + parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") + parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") + args = parser.parse_args() + now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc) + + head = args.head or green_main_head() + if not head: + result = {"release": False, "reason": "main's latest checks did not pass"} + print(json.dumps(result, indent=1)) + write_outputs({"release": "false", "reason": result["reason"]}) + return 0 + head = run("git", "rev-parse", head).strip() + last, prs = gather(args.kind, head) + if args.command == "notes": + version = args.tag or "unreleased" + title, body = notes(args.kind, version, prs, known_issues()) + if args.out: + args.out.mkdir(parents=True, exist_ok=True) + (args.out / "title.txt").write_text(title + "\n") + (args.out / "body.md").write_text(body) + print(title + "\n\n" + body) + return 0 + + published = dt.datetime.fromisoformat(last["published_at"].replace("Z", "+00:00")) if last else None + release, reason = decision(args.kind, prs, published, now, os.environ.get("RELEASES_PAUSED") == "1", args.force) + tags = run("git", "tag", "--list").split() + minor = any("feature" in pr["labels"] for pr in prs if pr["paths"]) + tag = next_game_tag(tags, now.date()) if args.kind == "game" else next_launcher_tag(tags, minor) + result = { + "release": release, "reason": reason, "tag": tag, "head": head, + "last": last["tag_name"] if last else None, "last_published": last["published_at"] if last else None, + "pull_requests": [{key: pr[key] for key in ("number", "title", "labels", "paths")} for pr in prs], + } + print(json.dumps(result, indent=1)) + write_outputs({"release": str(release).lower(), "reason": reason, "tag": tag, "head": head}) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From f6191fe8ee050eab8c6cc3a4c40c477e4375fb14 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:09:46 +0200 Subject: [PATCH 32/43] parity_hosts.json: linux_only, empty: the four harnesses that once differed on macOS pass there options, chunk_generation, world_border_render and mob_ai all pass on the Mac mini (7.3 min). Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 4 +++- tools/parity_hosts.json | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index abccac599..4b23f1b7c 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -35,7 +35,9 @@ Failed harnesses' logs are uploaded as the `parity-logs` artifact. **Platform-specific harnesses.** A harness listed under `linux_only` in `tools/parity_hosts.json` gives different results on macOS for a reason that is not a Horizon bug (the reason is printed). `parity.py` skips it on -other platforms unless it is named on the command line. +other platforms unless it is named on the command line. The list is empty today: `options`, `chunk_generation`, +`world_border_render` and `mob_ai`, which once differed on macOS through the platform's libm, pass on the Mac mini +since `horizon_core::jmath` computes what HotSpot computes (checked 2026-10-14). **Pull requests from forks** never run code on the Mac mini by themselves. A maintainer who has read the change adds the `run-parity` label: that runs the job once, on the commit the pull request had then. To run it again diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 4d5bd1bcd..6707b0ad8 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -26,5 +26,6 @@ }, "local_only": { "save_roundtrip": "runs the game on a virtual screen (vscreen) with a null ALSA device" - } + }, + "linux_only": {} } From 7adfe44f6cc235de58263639823f6965d080f58b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:52:00 +0200 Subject: [PATCH 33/43] launcher: rustfmt the rollback test Co-Authored-By: Claude Opus 5.5 --- launcher/src/backend.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index da84e17c3..44c29dda9 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1549,7 +1549,10 @@ mod tests { ]); let releases = parse_releases(&list, Some(asset), is_game_tag); assert!(releases.iter().all(|r| r.tag != "v2026.10.15.1")); - assert_eq!(latest(&releases).map(|r| r.tag.as_str()), Some("v2026.10.15")); + assert_eq!( + latest(&releases).map(|r| r.tag.as_str()), + Some("v2026.10.15") + ); let offered = |installed: &[&str]| { let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); horizon_update(&releases, &installed).map(|r| r.tag) From 7b82ee8c16dd42fc0f76538102383576727c7c62 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:34:46 +0200 Subject: [PATCH 34/43] Two Horizon runners on the Mac mini: one preparation at a time; docs A second runner (ludovics-mac-mini-2, same labels) shares the first one's vanilla data through a link, so vanilla-data.sh prepares under a lock; a 30-minute audit no longer holds a release's macOS build back. Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 8 ++++++-- tools/ci/vanilla-data.sh | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index 4b23f1b7c..4ab775b17 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -43,8 +43,12 @@ since `horizon_core::jmath` computes what HotSpot computes (checked 2026-10-14). adds the `run-parity` label: that runs the job once, on the commit the pull request had then. To run it again after new pushes, remove the label and add it again. -**One runner.** The Mac mini has one runner for this repository: parity jobs, the macOS release builds and the -nightly audit queue behind each other. +**Two runners.** The Mac mini has two runners for this repository, `ludovics-mac-mini` +(`~/.actions-runners/horizon`, `CARGO_BUILD_JOBS=10`) and `ludovics-mac-mini-2` (`~/.actions-runners/horizon-2`, +`CARGO_BUILD_JOBS=6`), with the same labels, so the 30-minute nightly audit or a long parity job never holds a +release's macOS build back. Each keeps its own checkout, `target/` and Rust install; the second's +`_work/horizon/shared-local` links to the first's, so they share the vanilla data, the preparations (one at a +time, under a lock) and the parity passes and slots. ## Merging diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh index e89969a57..6eba9bddb 100755 --- a/tools/ci/vanilla-data.sh +++ b/tools/ci/vanilla-data.sh @@ -32,6 +32,14 @@ done key=$(git ls-files -s crates/horizon-prepare mods/horizon/src/test/java research-lock.json | shasum -a 256 | cut -c1-16) prepared="$shared/prepared/$key" +# Two runners share the vanilla data (~/.actions-runners/horizon-2/_work/horizon/shared-local links to the first +# one's): one preparation at a time. A lock older than 30 minutes belongs to a job that died. +lock="$shared/prepared/.lock" +until mkdir "$lock" 2>/dev/null; do + if [ -n "$(find "$lock" -maxdepth 0 -mmin +30 2>/dev/null)" ]; then rmdir "$lock" 2>/dev/null || true; fi + sleep 5 +done +trap 'rmdir "$lock" 2>/dev/null || true' EXIT # horizon-prepare writes .local/horizon-client and its exporters' outputs beside it: all of them live in # $prepared, listed in $prepared/.entries, and .local/ links to them. if [ ! -f "$prepared/.entries" ]; then From e994c8ab95007e4b872999d692c2f361155cf3ed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:09:46 +0200 Subject: [PATCH 35/43] release: the macOS smoke run opens a world (from a scratch folder) and checks it drew one Without --world the client stays on the title screen: 300 frames and no chunks. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 17 ++++++++++------- docs/release-flow.md | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cd2ad5ce0..f7b6c68ac 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -146,19 +146,22 @@ jobs: if: runner.environment == 'self-hosted' run: | set -euo pipefail + # From a scratch folder: the game keeps its saves and options in the folder it starts in. home="$RUNNER_TEMP/horizon-smoke" rm -rf "$home" && mkdir -p "$home" version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1) - HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 target/release/horizon-client \ - --resources ".local/horizon-client/$version" --offscreen --render-distance 4 --seed 1 \ - --frames 300 --timeout-seconds 180 --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1 \ - || { tail -40 "$home/client.log"; exit 1; } + client="$PWD/target/release/horizon-client" + resources="$PWD/.local/horizon-client/$version" + (cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \ + --world smoke --seed 1 --render-distance 4 --frames 300 --timeout-seconds 180 \ + --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; } python3 - "$home/smoke.json" <<'EOF' import json, sys report = json.load(open(sys.argv[1])) - print({key: report.get(key) for key in ("adapter", "presented_frames", "resident_chunks", "error")}) - if report.get("error") is not None or report.get("presented_frames") != 300 or not report.get("resident_chunks"): - sys.exit("the smoke run did not draw a world: " + json.dumps(report)[:2000]) + print(json.dumps(report)) + if report.get("error") is not None or report.get("frames") != 300 or not report.get("chunks") \ + or not report.get("meshed_sections") or not report.get("player"): + sys.exit("the smoke run did not draw a world") EOF - name: Package run: | diff --git a/docs/release-flow.md b/docs/release-flow.md index ac2598fc6..e5a04ac64 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -130,7 +130,7 @@ the notes. | --- | --- | --- | | `horizon-linux-x86_64.tar.gz` | GitHub `ubuntu-22.04` (an older glibc, so it runs on any recent distribution) | the standard loader and libraries only (`tools/check_imports.py`) | | `horizon-windows-x64.zip` | GitHub `windows-latest`, C runtime linked in | system DLLs only (`tools/check_imports.py`) | -| `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 300-frame offscreen run of a new world with resources prepared from the runner's own Minecraft (`--offscreen --frames 300 --smoke-report`) | +| `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 300-frame offscreen run of a new world with resources prepared from the runner's own Minecraft (`--offscreen --world smoke --frames 300 --smoke-report`: frames drawn, chunks generated and meshed, a player, no error) | Each builds `horizon-client`, `horizon-ctl` and `horizon-prepare` in release mode, checks all three exist, starts each one (`--help`, `--version`), packages the folder with `cargo run -p xtask -- package` and archives it. The From cfad57d0b17b95d6ba4edd44c4c631f0f35b9d49 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:17:23 +0200 Subject: [PATCH 36/43] Mac runner: the game's sounds in each preparation; save_roundtrip Linux-only The first audit on the Mac mini failed 7 audio harnesses (no sounds in the prepared resources: the Mac mini has no official launcher for horizon-prepare sounds to copy from) and save_roundtrip (it needs vscreen). The sounds depend only on the Minecraft version: kept once in shared-local/sounds// and linked into each preparation. Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 12 ++++++++---- tools/ci/vanilla-data.sh | 10 ++++++++-- tools/parity_hosts.json | 4 +++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index 4ab775b17..05e867b65 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -25,7 +25,10 @@ copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its 2. `tools/ci/vanilla-data.sh` links `.local/` to the runner's copy of the vanilla data, cloned once from `~/code/horizon-parity/shared-local` into `~/.actions-runners/horizon/_work/horizon/shared-local`, and prepares `.local/horizon-client` with the pull request's own `horizon-prepare` once per preparer version - (its sources, the exporters in `mods/horizon/src/test/java` and `research-lock.json`). + (its sources, the exporters in `mods/horizon/src/test/java` and `research-lock.json`). The game's sounds, which + depend only on the Minecraft version, are kept once in `shared-local/sounds//` (copied from a folder + `horizon-prepare sounds` made from the maintainer's own game; the Mac mini has no official launcher of its own) + and linked into each preparation, for the audio harnesses. 3. `tools/parity.py --changed ` picks the harnesses whose traced dependencies (their script, Python modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to @@ -35,9 +38,10 @@ Failed harnesses' logs are uploaded as the `parity-logs` artifact. **Platform-specific harnesses.** A harness listed under `linux_only` in `tools/parity_hosts.json` gives different results on macOS for a reason that is not a Horizon bug (the reason is printed). `parity.py` skips it on -other platforms unless it is named on the command line. The list is empty today: `options`, `chunk_generation`, -`world_border_render` and `mob_ai`, which once differed on macOS through the platform's libm, pass on the Mac mini -since `horizon_core::jmath` computes what HotSpot computes (checked 2026-10-14). +other platforms unless it is named on the command line. Today it holds only `save_roundtrip` (it needs `vscreen`): +`options`, `chunk_generation`, `world_border_render` and `mob_ai`, which once differed on macOS through the +platform's libm, pass on the Mac mini since `horizon_core::jmath` computes what HotSpot computes (checked +2026-10-14). **Pull requests from forks** never run code on the Mac mini by themselves. A maintainer who has read the change adds the `run-parity` label: that runs the job once, on the commit the pull request had then. To run it again diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh index 6eba9bddb..e00f9bb78 100755 --- a/tools/ci/vanilla-data.sh +++ b/tools/ci/vanilla-data.sh @@ -26,7 +26,7 @@ fi mkdir -p .local "$shared/prepared" for entry in "$shared"/*; do name=$(basename "$entry") - case "$name" in prepared|*.log) continue ;; esac + case "$name" in prepared|sounds|*.log) continue ;; esac if [ -L ".local/$name" ] || [ ! -e ".local/$name" ]; then ln -sfn "$entry" ".local/$name"; fi done @@ -66,13 +66,19 @@ fi # the same neighbours as in the shared folder. for entry in "$shared"/*; do name=$(basename "$entry") - case "$name" in prepared|*.log) continue ;; esac + case "$name" in prepared|sounds|*.log) continue ;; esac [ -e "$prepared/$name" ] || ln -sfn "$entry" "$prepared/$name" done while read -r name; do if [ -L ".local/$name" ] || [ ! -e ".local/$name" ]; then ln -sfn "$prepared/$name" ".local/$name"; else echo "::error::.local/$name is not a link to the prepared resources"; exit 1; fi done < "$prepared/.entries" +# The game's sounds (horizon-prepare sounds copies them from the official launcher's asset store) depend only on the +# Minecraft version: kept once in $shared/sounds// (sounds.json and sounds/) and linked into each preparation. +assets="$prepared/horizon-client/$version/assets/minecraft" +if [ -f "$shared/sounds/$version/sounds.json" ] && [ -d "$assets" ]; then + for entry in sounds.json sounds; do [ -e "$assets/$entry" ] || ln -sfn "$shared/sounds/$version/$entry" "$assets/$entry"; done +fi touch "$prepared" # The four newest preparations stay. ls -1dt "$shared/prepared"/*/ 2>/dev/null | tail -n +5 | while read -r old; do rm -rf "$old"; done diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 6707b0ad8..09725f56a 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -27,5 +27,7 @@ "local_only": { "save_roundtrip": "runs the game on a virtual screen (vscreen) with a null ALSA device" }, - "linux_only": {} + "linux_only": { + "save_roundtrip": "runs the game on a virtual screen (vscreen), which only the Linux desktop has" + } } From fb256809a709f37496bd306b1972458abb640371 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:42:53 +0200 Subject: [PATCH 37/43] release: the macOS smoke run draws 1500 frames; 300 end before the world has loaded Checked on the Mac mini: 1500 offscreen frames in 12 s, 81 chunks generated, 4153 sections meshed, a player. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 6 +++--- docs/release-flow.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f7b6c68ac..4b8444176 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -142,7 +142,7 @@ jobs: - name: Resources prepared from the runner's own Minecraft if: runner.environment == 'self-hosted' run: bash tools/ci/vanilla-data.sh - - name: The game runs (offscreen, a new world, 300 frames) + - name: The game runs (offscreen, a new world, 1500 frames) if: runner.environment == 'self-hosted' run: | set -euo pipefail @@ -153,13 +153,13 @@ jobs: client="$PWD/target/release/horizon-client" resources="$PWD/.local/horizon-client/$version" (cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \ - --world smoke --seed 1 --render-distance 4 --frames 300 --timeout-seconds 180 \ + --world smoke --seed 1 --render-distance 4 --frames 1500 --timeout-seconds 180 \ --smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; } python3 - "$home/smoke.json" <<'EOF' import json, sys report = json.load(open(sys.argv[1])) print(json.dumps(report)) - if report.get("error") is not None or report.get("frames") != 300 or not report.get("chunks") \ + if report.get("error") is not None or report.get("frames", 0) < 1500 or not report.get("chunks") \ or not report.get("meshed_sections") or not report.get("player"): sys.exit("the smoke run did not draw a world") EOF diff --git a/docs/release-flow.md b/docs/release-flow.md index e5a04ac64..bd7454a6f 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -130,7 +130,7 @@ the notes. | --- | --- | --- | | `horizon-linux-x86_64.tar.gz` | GitHub `ubuntu-22.04` (an older glibc, so it runs on any recent distribution) | the standard loader and libraries only (`tools/check_imports.py`) | | `horizon-windows-x64.zip` | GitHub `windows-latest`, C runtime linked in | system DLLs only (`tools/check_imports.py`) | -| `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 300-frame offscreen run of a new world with resources prepared from the runner's own Minecraft (`--offscreen --world smoke --frames 300 --smoke-report`: frames drawn, chunks generated and meshed, a player, no error) | +| `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 1500-frame offscreen run of a new world (about 12 s; 300 frames end before the world has loaded) with resources prepared from the runner's own Minecraft (`--offscreen --world smoke --frames 1500 --smoke-report`: frames drawn, chunks generated and meshed, a player, no error) | Each builds `horizon-client`, `horizon-ctl` and `horizon-prepare` in release mode, checks all three exist, starts each one (`--help`, `--version`), packages the folder with `cargo run -p xtask -- package` and archives it. The From 9e016b623502bab7a2e90a42e11219e50952633b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:45:46 +0200 Subject: [PATCH 38/43] vanilla-data.sh: clone the sounds into each preparation instead of linking them Vanilla's resource packs refuse symbolic links inside a pack: with linked sounds the vanilla sound oracles found no sound files while Rust did (sound_event, sound_engine on #133's parity run). Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 2 +- tools/ci/vanilla-data.sh | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index 05e867b65..e46ec7dd3 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -28,7 +28,7 @@ copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its (its sources, the exporters in `mods/horizon/src/test/java` and `research-lock.json`). The game's sounds, which depend only on the Minecraft version, are kept once in `shared-local/sounds//` (copied from a folder `horizon-prepare sounds` made from the maintainer's own game; the Mac mini has no official launcher of its own) - and linked into each preparation, for the audio harnesses. + and cloned into each preparation (not linked: vanilla's packs refuse symbolic links), for the audio harnesses. 3. `tools/parity.py --changed ` picks the harnesses whose traced dependencies (their script, Python modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh index e00f9bb78..5234a48f5 100755 --- a/tools/ci/vanilla-data.sh +++ b/tools/ci/vanilla-data.sh @@ -74,10 +74,17 @@ while read -r name; do echo "::error::.local/$name is not a link to the prepared resources"; exit 1; fi done < "$prepared/.entries" # The game's sounds (horizon-prepare sounds copies them from the official launcher's asset store) depend only on the -# Minecraft version: kept once in $shared/sounds// (sounds.json and sounds/) and linked into each preparation. +# Minecraft version: kept once in $shared/sounds// (sounds.json and sounds/) and copied into each preparation +# as clones (APFS, or reflinks on Linux: no second copy of the bytes). Not links: vanilla's resource packs refuse +# symbolic links inside a pack, so its sound oracles would find no sound files. assets="$prepared/horizon-client/$version/assets/minecraft" if [ -f "$shared/sounds/$version/sounds.json" ] && [ -d "$assets" ]; then - for entry in sounds.json sounds; do [ -e "$assets/$entry" ] || ln -sfn "$shared/sounds/$version/$entry" "$assets/$entry"; done + for entry in sounds.json sounds; do + [ -L "$assets/$entry" ] && rm "$assets/$entry" + [ -e "$assets/$entry" ] && continue + if [ "$(uname)" = Darwin ]; then cp -cR "$shared/sounds/$version/$entry" "$assets/" + else cp -R --reflink=auto "$shared/sounds/$version/$entry" "$assets/"; fi + done fi touch "$prepared" # The four newest preparations stay. From 6d759dc7bbaa623ed67b85d0a61487329d864d06 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:58:33 +0200 Subject: [PATCH 39/43] release_train: name a feature split over several pull requests once in the title; no leading Fix Today's main would have been titled "Controllers, controllers, controllers and 17 more changes". Co-Authored-By: Claude Opus 5.5 --- tests/test_release_train.py | 8 ++++++++ tools/release_train.py | 10 ++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/test_release_train.py b/tests/test_release_train.py index d69fc0793..17414abbd 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -81,6 +81,14 @@ class ReleaseTrainTests(unittest.TestCase): self.assertTrue(title.endswith("more fixes"), title) self.assertLess(len(title), 100) + def test_a_feature_split_over_several_pull_requests_is_named_once(self): + prs = [pr(1, "Controllers: rumble", labels=["feature"]), pr(2, "Controllers: menus", labels=["feature"]), + pr(3, "Maces: smash attacks"), pr(4, "Fix stuck keys when opening Options")] + title, _ = train.notes("game", "v2026.10.15", prs, []) + self.assertEqual(title, "Horizon 2026.10.15: Controllers, stuck keys when opening Options, maces") + self.assertEqual(train.summary([], [pr(n, f"Change number {n} with a fairly long title") for n in range(4)]), + "Change number 3 with a fairly long title and 3 more fixes") + def test_launcher_notes(self): title, body = train.notes("launcher", "launcher-v0.2.0", [pr(3, "Launcher: say the self-update succeeded")], []) self.assertEqual(title, "Horizon launcher 0.2.0") diff --git a/tools/release_train.py b/tools/release_train.py index 511ccac5e..cf3219fde 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -165,12 +165,17 @@ def decision(kind, prs, last_published, now, paused=False, force=False): def clause(title): """The start of a pull request title, for a release's name: "Nether portals: vanilla timing" -> "Nether portals".""" + title = re.sub(r"^(?:fix|fixes|fixed)\s+(?:the\s+)?", "", title.strip(), flags=re.I) return re.split(r"[:;(]| — | - ", title, maxsplit=1)[0].strip().rstrip(".") def summary(new, fixed, limit=72): """A short name for the release, from its pull request titles, features first.""" - titles = [clause(pr["title"]) for pr in new[::-1] + fixed[::-1]] + titles = [] + for pr in new[::-1] + fixed[::-1]: # several pull requests of one feature ("Controllers: ...") name it once + title = clause(pr["title"]) + if title.lower() not in (t.lower() for t in titles): + titles.append(title) shown, text = [], "" for title in titles: title = title if not shown or not title[1:2].islower() else title[0].lower() + title[1:] @@ -181,7 +186,8 @@ def summary(new, fixed, limit=72): text = candidate rest = len(titles) - len(shown) if rest: - text += f" and {rest} more {'changes' if new else 'fixes'}" + noun = ("change" if new else "fix") + ("" if rest == 1 else "es" if not new else "s") + text += f" and {rest} more {noun}" return text From fa61f262c3be87ffabe261771f9093e5ed2bb79b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:52:37 +0200 Subject: [PATCH 40/43] launcher: automatic releases, the version built in from the tag launcher.yml releases the launcher by itself: after a push to main that changes launcher/, crates/horizon-prepare or crates/horizon-theme, hourly, and by hand, with the game's rules (tools/release_train.py decide --kind launcher: player-facing pull requests and a 3-hour cooldown, release-now, skip-release, RELEASES_PAUSED). launcher-vX.Y.Z is the next patch, or the next minor after a pull request labelled feature. Linux on ubuntu-22.04, Windows on GitHub, macOS on the Mac mini's runner; published with --latest=false. No version-bump commits: VERSION reads HORIZON_LAUNCHER_VERSION with option_env!, falling back to Cargo.toml's, and --version, the User-Agent and the self-update comparison use it; each build checks --version says the release's version. With several game releases a day, the newest launcher release soon falls out of the newest 100 (launcher) or 30 (website) releases: both now look the newest launcher-v tags up one by one when the list has none. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 158 +++++++++++++++++++++++++++------ docs/release-flow.md | 27 ++++++ launcher/README.md | 11 +-- launcher/src/backend.rs | 111 +++++++++++++++++++++-- launcher/src/cli.rs | 2 +- website/build.mjs | 2 +- website/src/main.js | 43 +++++---- 7 files changed, 296 insertions(+), 58 deletions(-) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 50a9ca9ca..c0b140d61 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,64 +1,147 @@ name: launcher -# Builds the launcher on Linux, macOS and Windows. A pushed `launcher-vX.Y.Z` tag also puts the -# three archives on a draft GitHub release of that tag, to publish by hand. Horizon's own -# releases are tagged `vYYYY.MM.DD`; the launcher reads only `launcher-v*` releases for itself. +# Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a +# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme), +# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game. +# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull +# request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits. +# Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases. +# gh workflow run launcher --ref # dry run: builds everything, publishes nothing +# gh workflow run launcher --ref main -f dry_run=false -f force=true on: - workflow_dispatch: push: - branches: [launcher, 'launcher-*'] - tags: ['launcher-v*'] + branches: [main, launcher, 'launcher-*'] + paths: + - 'launcher/**' + - 'crates/horizon-prepare/**' + - 'crates/horizon-theme/**' + - '.github/workflows/launcher.yml' + schedule: + - cron: '47 * * * *' + workflow_dispatch: + inputs: + dry_run: + description: Build everything and write the notes, but publish nothing + type: boolean + default: true + force: + description: Release even without launcher changes, within the cooldown or while paused + type: boolean + default: false permissions: contents: read +concurrency: + group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }} + cancel-in-progress: false + jobs: + decide: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + release: ${{ steps.decide.outputs.release }} + tag: ${{ steps.decide.outputs.tag }} + head: ${{ steps.decide.outputs.head }} + version: ${{ steps.decide.outputs.version }} + dry_run: ${{ steps.mode.outputs.dry_run }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - id: mode + # Off main every run is a dry run (a launcher branch's push only builds). + run: echo "dry_run=${{ github.ref != 'refs/heads/main' || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }}" >> "$GITHUB_OUTPUT" + - id: decide + env: + GH_TOKEN: ${{ github.token }} + RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }} + # A push or a run off main builds its own commit; otherwise main's newest commit with green checks. + HEAD_SHA: ${{ (github.event_name == 'push' || steps.mode.outputs.dry_run == 'true') && github.sha || '' }} + FORCE: ${{ inputs.force && 'yes' || '' }} + run: | + python3 tools/release_train.py decide --kind launcher ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json + echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + tag=$(jq -r '.tag' decision.json) + echo "version=${tag#launcher-v}" >> "$GITHUB_OUTPUT" + # A dry run (and a launcher branch's push) builds whatever the decision. + if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then + echo "release=true" >> "$GITHUB_OUTPUT" + echo "head=$GITHUB_SHA" >> "$GITHUB_OUTPUT" + fi + build: + needs: decide + if: needs.decide.outputs.release == 'true' + name: build ${{ matrix.name }} strategy: fail-fast: false matrix: include: - - os: ubuntu-latest + - name: linux + os: ubuntu-22.04 asset: horizon-launcher-linux-x86_64.tar.gz binary: horizon-launcher - - os: macos-latest + - name: macos + mac: true asset: horizon-launcher-macos-arm64.zip binary: horizon-launcher - - os: windows-latest + - name: windows + os: windows-latest asset: horizon-launcher-windows-x64.zip binary: horizon-launcher.exe # The C runtime linked in: without it the launcher asks for VCRUNTIME140.dll, # which only the Visual C++ redistributable installs. rustflags: -C target-feature=+crt-static - runs-on: ${{ matrix.os }} + runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }} + timeout-minutes: 40 env: RUSTFLAGS: ${{ matrix.rustflags }} # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} + # The release's version, built in (launcher/src/backend.rs VERSION); a launcher branch's build keeps + # Cargo.toml's. + HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} defaults: run: working-directory: launcher shell: bash steps: - uses: actions/checkout@v4 + with: + ref: ${{ needs.decide.outputs.head }} + persist-credentials: false + # The Mac mini's runner keeps its target/ between runs. + clean: ${{ runner.environment == 'github-hosted' }} - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 + if: runner.environment == 'github-hosted' with: workspaces: launcher + shared-key: launcher-${{ matrix.name }} - name: Linux libraries GPUI links to if: runner.os == 'Linux' run: | sudo apt-get update sudo apt-get install -y libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev - - name: The tag matches Cargo.toml - if: startsWith(github.ref, 'refs/tags/launcher-v') - run: grep -qx "version = \"${GITHUB_REF_NAME#launcher-v}\"" Cargo.toml - run: cargo test --release --locked --lib - run: cargo build --release --locked + - name: The version is the release's + run: | + out=$(target/release/${{ matrix.binary }} --version) + echo "$out" + expected="${HORIZON_LAUNCHER_VERSION:-$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)}" + [[ "$out" == "horizon-launcher $expected" ]] || { echo "::error::expected horizon-launcher $expected"; exit 1; } - name: Only system libraries - if: runner.os == 'Windows' - run: python ../tools/check_imports.py target/release/${{ matrix.binary }} + run: | + file=target/release/${{ matrix.binary }} + case "$RUNNER_OS" in + Windows) python ../tools/check_imports.py "$file" ;; + macOS) others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true) + [[ -z "$others" ]] || { echo "::error::links $others"; exit 1; } ;; + esac - name: Smoke test env: HORIZON_LAUNCHER_NO_SELF_UPDATE: '1' @@ -67,10 +150,10 @@ jobs: set -euo pipefail export HORIZON_LAUNCHER_HOME="${RUNNER_TEMP//\\//}/horizon-launcher-smoke" export HORIZON_HOME="$HORIZON_LAUNCHER_HOME/game" + rm -rf "$HORIZON_LAUNCHER_HOME" launcher="$PWD/target/release/${{ matrix.binary }}" # GitHub's API rate-limits shared runner addresses now and then: try a few times. retry() { for i in 1 2 3 4; do "$@" && return 0; sleep $((i * 15)); done; return 1; } - "$launcher" --version retry "$launcher" versions retry "$launcher" install latest "$launcher" versions --installed @@ -86,16 +169,16 @@ jobs: soft() { if [[ "$RUNNER_OS" == "Linux" ]]; then "$@" || echo "::warning::$* failed"; else "$@"; fi; } if [[ "$RUNNER_OS" == "Windows" ]]; then python ../tools/check_imports.py "$client" - python ../tools/check_imports.py "$launcher" elif [[ "$RUNNER_OS" == "Linux" ]]; then soft python3 ../tools/check_imports.py "$client" fi # The client starts: --help prints before any window or GPU is needed. help() { "$client" --help > "$RUNNER_TEMP/help.txt" 2>&1 && head -3 "$RUNNER_TEMP/help.txt" && grep -q -- '--resources' "$RUNNER_TEMP/help.txt"; } soft help + rm -rf "$HORIZON_LAUNCHER_HOME" - name: Package run: | - mkdir -p dist + rm -rf dist ${{ matrix.asset }} && mkdir -p dist cp target/release/${{ matrix.binary }} dist/ cd dist if [[ "${{ matrix.asset }}" == *.tar.gz ]]; then @@ -109,23 +192,44 @@ jobs: with: name: ${{ matrix.asset }} path: launcher/${{ matrix.asset }} + retention-days: 7 release: - if: startsWith(github.ref, 'refs/tags/launcher-v') - needs: build + needs: [decide, build] runs-on: ubuntu-latest + timeout-minutes: 10 permissions: contents: write steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Notes + env: + GH_TOKEN: ${{ github.token }} + run: | + python3 tools/release_train.py notes --kind launcher --tag "${{ needs.decide.outputs.tag }}" \ + --head "${{ needs.decide.outputs.head }}" --out notes > /dev/null + { echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY" - uses: actions/download-artifact@v4 with: path: dist merge-multiple: true - # A draft, and never marked latest: Horizon's own releases stay the repository's latest. - - uses: softprops/action-gh-release@v2 + # Never marked latest: Horizon's own releases stay the repository's latest. + - name: Publish ${{ needs.decide.outputs.tag }} + if: needs.decide.outputs.dry_run != 'true' + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.decide.outputs.tag }} + run: | + gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ + --notes-file notes/body.md --latest=false dist/horizon-launcher-* + - name: Dry run, the release that would be published + if: needs.decide.outputs.dry_run == 'true' + run: | + echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)" + ls -l dist + - uses: actions/upload-artifact@v4 with: - tag_name: ${{ github.ref_name }} - name: Horizon launcher ${{ github.ref_name }} - draft: true - make_latest: false - files: dist/* + name: launcher-release-notes + path: notes/ diff --git a/docs/release-flow.md b/docs/release-flow.md index bd7454a6f..78f084252 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -184,3 +184,30 @@ list (`launcher/src/backend.rs` tests `withdrawn_release_is_never_offered`). The that day takes the next number, and its notes start from the last *published* release, so they list the withdrawn release's changes again with the fix. Usually the better way out is forward: revert the pull request, label the revert `release-now`, and a fixed release is out as soon as main's checks pass. + +## Launcher releases + +`.github/workflows/launcher.yml` releases the launcher the same way. It starts on a push to main that changes +`launcher/`, `crates/horizon-prepare/` or `crates/horizon-theme/` (what the launcher builds in), every hour at :47, +and by hand; pushes to `launcher` and `launcher-*` branches only build. + +- `tools/release_train.py decide --kind launcher` counts the pull requests merged since the last published + launcher release that changed those paths (not `launcher/links.json`, which the launcher reads from main, nor + tests or Markdown), with the same 3-hour cooldown, `release-now`, `skip-release` and `RELEASES_PAUSED`. +- The tag is `launcher-vX.Y.Z`: the patch after the last launcher tag, or the next minor (`X.Y+1.0`) when one of + those pull requests is labelled `feature`. +- No version-bump commits: the build gets the version in `HORIZON_LAUNCHER_VERSION`, which + `launcher/src/backend.rs` reads with `option_env!` (falling back to `Cargo.toml`'s), so `--version`, the window, + the User-Agent and the self-update comparison all use it. Each build checks `--version` says it. +- Linux on GitHub `ubuntu-22.04`, Windows on `windows-latest`, macOS on the Mac mini's runner; each runs the + launcher's tests, checks its libraries, and installs the latest game release with the new launcher. +- Published with `--latest=false`: the repository's latest release stays a game release. Notes list the pull + requests under New and Fixed; Kira posts launcher releases without pinging. + +Starting by hand, pausing and rolling back work as for the game (`gh workflow run launcher …`, +`RELEASES_PAUSED`, `gh release edit launcher-vX.Y.Z --draft`). Launchers older than the withdrawn release then +see the previous one as the newest; launchers that already updated keep running. + +With several game releases a day, the newest launcher release soon falls out of the newest 100 releases the +launcher and the website read: both then look the newest `launcher-v` tags up one by one +(`git/matching-refs/tags/launcher-v`, then `releases/tags/`). diff --git a/launcher/README.md b/launcher/README.md index d6e0e4251..530d7f9b3 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -52,11 +52,12 @@ It also updates itself from GitHub releases tagged `launcher-vX.Y.Z` (Horizon's own binary, and offers "Restart to update" in the sidebar. Development builds and `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` never replace themselves. -To release the launcher: set `version` in `Cargo.toml`, then push a tag `launcher-vX.Y.Z`. The -`launcher` workflow builds Linux, macOS and Windows and attaches -`horizon-launcher-linux-x86_64.tar.gz`, `horizon-launcher-macos-arm64.zip` and -`horizon-launcher-windows-x64.zip` to a draft release of that tag, never marked latest. Publish -it by hand. +Launcher releases are automatic (docs/release-flow.md in the repository): when main changes the +launcher, `horizon-prepare` or `horizon-theme`, the `launcher` workflow builds Linux, macOS and +Windows and publishes `launcher-vX.Y.Z` (the next patch, or the next minor after a pull request +labelled `feature`) with `horizon-launcher-linux-x86_64.tar.gz`, `horizon-launcher-macos-arm64.zip` +and `horizon-launcher-windows-x64.zip`, never marked latest. The version is built in from the tag +(`HORIZON_LAUNCHER_VERSION`); `Cargo.toml`'s version is only what local builds report. ## Command line diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 44c29dda9..d1ddc2b8c 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -10,10 +10,18 @@ use std::sync::{Arc, Mutex}; pub const REPO: &str = "ludovic111/horizon"; pub const README_URL: &str = "https://github.com/ludovic111/horizon/blob/main/launcher/README.md"; -pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// This launcher's version: the release workflow sets `HORIZON_LAUNCHER_VERSION` from the +/// `launcher-vX.Y.Z` tag it builds (no version-bump commits); other builds say Cargo.toml's. +pub const VERSION: &str = version_or(option_env!("HORIZON_LAUNCHER_VERSION")); /// Launcher releases are tagged `launcher-vX.Y.Z`; Horizon's own are `vYYYY.MM.DD`. pub const LAUNCHER_TAG_PREFIX: &str = "launcher-v"; -const AGENT: &str = concat!("horizon-launcher/", env!("CARGO_PKG_VERSION")); + +const fn version_or(injected: Option<&'static str>) -> &'static str { + match injected { + Some(v) if !v.is_empty() => v, + _ => env!("CARGO_PKG_VERSION"), + } +} #[derive(Clone, Debug, serde::Serialize)] pub struct Release { @@ -63,7 +71,9 @@ const CLIENT: &str = if cfg!(windows) { }; fn agent() -> ureq::Agent { - ureq::AgentBuilder::new().user_agent(AGENT).build() + ureq::AgentBuilder::new() + .user_agent(&format!("horizon-launcher/{VERSION}")) + .build() } fn get(url: &str) -> Result { @@ -176,11 +186,53 @@ pub fn releases() -> Result, String> { /// Published launcher releases (`launcher-v…`), newest first, with this platform's archive. pub fn launcher_releases() -> Result, String> { - Ok(parse_releases( - &release_list()?, - LAUNCHER_ASSET, - is_launcher_tag, - )) + Ok(launcher_releases_in(&release_list()?)) +} + +/// The launcher releases in `list` (the newest 100 releases). Game releases come out several times +/// a day, so the newest launcher release can be older than all of those: then the newest +/// `launcher-v` tags are looked up one by one (a draft's tag is skipped: it has no public release). +fn launcher_releases_in(list: &serde_json::Value) -> Vec { + let found = parse_releases(list, LAUNCHER_ASSET, is_launcher_tag); + if found.iter().any(|r| r.asset.is_some()) { + return found; + } + let json = |url: String| -> Result { + get(&url)?.into_json().map_err(|e| e.to_string()) + }; + let api = format!("https://api.github.com/repos/{REPO}"); + let Ok(refs) = json(format!( + "{api}/git/matching-refs/tags/{LAUNCHER_TAG_PREFIX}" + )) else { + return found; + }; + for tag in newest_launcher_tags(&refs).into_iter().take(3) { + if let Ok(release) = json(format!("{api}/releases/tags/{tag}")) { + let one = parse_releases( + &serde_json::json!([release]), + LAUNCHER_ASSET, + is_launcher_tag, + ); + if one.iter().any(|r| r.asset.is_some()) { + return one; + } + } + } + found +} + +/// The `launcher-vX.Y.Z` tags in GitHub's matching-refs answer, newest first. +fn newest_launcher_tags(refs: &serde_json::Value) -> Vec { + let mut tags: Vec = refs + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r["ref"].as_str()?.strip_prefix("refs/tags/")) + .filter(|t| is_launcher_tag(t)) + .map(String::from) + .collect(); + tags.sort_by(|a, b| compare_versions(b, a)); + tags } /// The newest Horizon release that has a build for this platform. @@ -1125,7 +1177,7 @@ pub fn check_updates() -> Result { let list = release_list()?; Ok(Updates { horizon: horizon_update(&parse_releases(&list, ASSET, is_game_tag), &installed()), - launcher: launcher_update(&parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag)), + launcher: launcher_update(&launcher_releases_in(&list)), }) } @@ -1563,6 +1615,47 @@ mod tests { assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); } + #[test] + fn the_version_is_the_one_the_release_workflow_injects() { + assert_eq!(version_or(Some("0.4.2")), "0.4.2"); + assert_eq!(version_or(Some("")), env!("CARGO_PKG_VERSION")); + assert_eq!(version_or(None), env!("CARGO_PKG_VERSION")); + assert_eq!( + VERSION, + option_env!("HORIZON_LAUNCHER_VERSION") + .filter(|v| !v.is_empty()) + .unwrap_or(env!("CARGO_PKG_VERSION")) + ); + // Self-update compares releases with that version: this launcher's own release is no update. + let r = |tag: String| Release { + tag, + name: String::new(), + body: String::new(), + date: String::new(), + asset: Some(("u".into(), 1)), + }; + assert!(launcher_update(&[r(format!("{LAUNCHER_TAG_PREFIX}{VERSION}"))]).is_none()); + assert_eq!( + parse_version_output(&format!("horizon-launcher {VERSION}\n")), + Some(VERSION) + ); + } + + #[test] + fn launcher_tags_from_matching_refs_newest_first() { + let refs = serde_json::json!([ + {"ref": "refs/tags/launcher-v0.1.9"}, + {"ref": "refs/tags/launcher-v0.1.10"}, + {"ref": "refs/tags/launcher-vnext"}, + {"ref": "refs/tags/v2026.10.15"}, + {"ref": "refs/tags/launcher-v0.2.0"}, + ]); + assert_eq!( + newest_launcher_tags(&refs), + ["launcher-v0.2.0", "launcher-v0.1.10", "launcher-v0.1.9"] + ); + } + #[test] fn versions_compare_by_number() { assert_eq!(compare_versions("v2026.10.13", "v2026.10.12"), Greater); diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 46827ca85..43cb39482 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -10,7 +10,7 @@ use std::process::Command; #[derive(Parser)] #[command( name = "horizon-launcher", - version, + version = backend::VERSION, about = "Installs, prepares and starts Horizon. Without a subcommand, opens the window." )] struct Cli { diff --git a/website/build.mjs b/website/build.mjs index 3d7d94d3d..5e6299ee4 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -40,7 +40,7 @@ try { let releases = []; try { - const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=30`, { + const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=100`, { // An optional token (a Railway variable, or `gh auth token` locally) lifts the rate limit. headers: { Accept: "application/vnd.github+json", ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}) }, signal: AbortSignal.timeout(15000), diff --git a/website/src/main.js b/website/src/main.js index 118cd149a..e661d3eb8 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -31,21 +31,34 @@ async function get(url, as = "json") { return as === "json" ? res.json() : res.text(); } -const releases = cached("horizon:releases", () => - get(`https://api.github.com/repos/${REPO}/releases?per_page=30`).then((list) => - list - .filter((r) => !r.draft) - .map((r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), - })), - ), -).catch(() => baked.releases); +const slim = (r) => ({ + tag_name: r.tag_name, + name: r.name, + published_at: r.published_at, + html_url: r.html_url, + prerelease: r.prerelease, + body: r.body || "", + assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), +}); +const isLauncher = (r) => r.tag_name.startsWith("launcher-v") && !r.prerelease; +const versionKey = (tag) => tag.replace("launcher-v", "").split(".").map(Number); +const newer = (a, b) => versionKey(b).reduce((d, n, i) => d || n - (versionKey(a)[i] || 0), 0); + +// The newest 30 releases. Game releases come out several times a day, so the newest launcher release can be +// older than all of them: then it is looked up by its tag (the newest launcher-v tag with a published release). +async function loadReleases() { + const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=30`)).filter((r) => !r.draft).map(slim); + if (list.some(isLauncher)) return list; + const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/launcher-v`).catch(() => []); + const tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter((t) => /^launcher-v\d+\.\d+\.\d+$/.test(t)).sort(newer); + for (const tag of tags.slice(0, 3)) { + const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); + if (release && !release.draft) return [...list, slim(release)]; + } + return list; +} + +const releases = cached("horizon:releases", loadReleases).catch(() => baked.releases); async function setUpContributors() { let list = baked.contributors || []; From 76f3e7c2a82eb06e78384ad69b9d007d5ebbd3de Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:20:02 +0200 Subject: [PATCH 41/43] launcher.yml: GPUI's runtime shaders on a Mac runner without the Metal toolchain (the Mac mini) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index c0b140d61..3f25e7f0b 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -126,8 +126,17 @@ jobs: run: | sudo apt-get update sudo apt-get install -y libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev - - run: cargo test --release --locked --lib - - run: cargo build --release --locked + - name: Metal shaders compiled now, or at run time without the Metal toolchain + # GPUI compiles its Metal shaders when it builds; the Mac mini has Xcode without the Metal toolchain + # (xcodebuild -downloadComponent MetalToolchain), so there they are compiled when the launcher starts. + if: runner.os == 'macOS' + run: | + if ! xcrun metal --version > /dev/null 2>&1; then + echo "::notice::No Metal toolchain on this runner: GPUI compiles its shaders at run time" + echo "LAUNCHER_FEATURES=gpui/runtime_shaders" >> "$GITHUB_ENV" + fi + - run: cargo test --release --locked --lib ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} + - run: cargo build --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} - name: The version is the release's run: | out=$(target/release/${{ matrix.binary }} --version) From 98ca844f07db77a586721b886acea1363313cf4c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:18:31 +0200 Subject: [PATCH 42/43] launcher: the Microsoft sign-in's User-Agent says the built-in version too Co-Authored-By: Claude Opus 5.5 --- launcher/src/account.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/src/account.rs b/launcher/src/account.rs index e64141646..de46b729f 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -56,7 +56,7 @@ impl Endpoints { fn agent() -> ureq::Agent { ureq::AgentBuilder::new() .timeout(Duration::from_secs(20)) - .user_agent(concat!("horizon-launcher/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("horizon-launcher/{}", crate::backend::VERSION)) .build() } From beac11eaa50784693c2f3571192c985fe7e15ea8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:54:17 +0200 Subject: [PATCH 43/43] Nightly parity audit on the Mac mini, with an issue per regressed harness nightly.yml runs every harness from scratch on main at 03:00 Paris time on the Mac mini's runner, after preparing the resources again if the preparer changed. tools/ci/parity_issues.py compares the results with the previous audit: a harness that passed and now fails gets one issue labelled parity-regression (an open one is commented on), and an issue closes when its harness passes again. The bugs session picks them up. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/nightly.yml | 79 ++++++++++++++++++++++++ docs/release-flow.md | 16 +++++ tests/test_parity_issues.py | 27 +++++++++ tools/ci/parity_issues.py | 111 ++++++++++++++++++++++++++++++++++ 4 files changed, 233 insertions(+) create mode 100644 .github/workflows/nightly.yml create mode 100644 tests/test_parity_issues.py create mode 100644 tools/ci/parity_issues.py diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..59560e262 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,79 @@ +name: nightly audit +# Every vanilla harness, from scratch, on main, at 03:00 Paris time on the Mac mini's runner (it holds the +# maintainer's own Minecraft files). The resources are prepared again first when the preparer or its exporters +# changed (tools/ci/vanilla-data.sh). A harness that passed in the previous audit and fails now gets an issue +# labelled parity-regression (one per harness); its issue closes when it passes again +# (tools/ci/parity_issues.py). The bugs session picks those up. See docs/release-flow.md. +# gh workflow run "nightly audit" # now +# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues +on: + schedule: + # GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris. + - cron: '7 1 * * *' + - cron: '7 2 * * *' + workflow_dispatch: + inputs: + dry_run: + description: Run the audit, but only print what it would do with issues + type: boolean + default: false +permissions: + contents: read + issues: write +concurrency: + group: nightly-audit + cancel-in-progress: false +jobs: + audit: + runs-on: [self-hosted, horizon-game] + timeout-minutes: 150 + steps: + - name: 03:00 in Paris + id: when + run: | + hour=$(TZ=Europe/Paris date +%H) + if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then + echo "It is ${hour}:00 in Paris: the other schedule runs the audit." + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + - uses: actions/checkout@v4 + if: steps.when.outputs.run == 'true' + with: + fetch-depth: 0 + persist-credentials: false + # Keeps .local/ (parity state, probe builds, the previous audit) and target/. + clean: false + - uses: dtolnay/rust-toolchain@stable + if: steps.when.outputs.run == 'true' + - name: Tools from the runner + if: steps.when.outputs.run == 'true' + run: bash tools/ci/runner-env.sh + - name: Vanilla data, prepared again if the preparer changed + if: steps.when.outputs.run == 'true' + run: bash tools/ci/vanilla-data.sh + - name: Every harness + id: audit + if: steps.when.outputs.run == 'true' + env: + PARITY_HOSTS: '' + run: | + echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT" + set +e + python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log" + echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT" + { echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + - name: Issues for the harnesses that regressed + if: steps.when.outputs.run == 'true' && always() && steps.audit.outputs.since + env: + GH_TOKEN: ${{ github.token }} + run: python3 tools/ci/parity_issues.py --since "${{ steps.audit.outputs.since }}" ${{ inputs.dry_run && '--dry-run' || '' }} | tee -a "$GITHUB_STEP_SUMMARY" + - name: Logs of the failed harnesses + if: steps.when.outputs.run == 'true' && steps.audit.outputs.exit != '0' + uses: actions/upload-artifact@v4 + with: + name: nightly-parity-logs + path: .local/parity-runner/logs/ + if-no-files-found: ignore + retention-days: 14 diff --git a/docs/release-flow.md b/docs/release-flow.md index 78f084252..a9bfc166d 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -211,3 +211,19 @@ see the previous one as the newest; launchers that already updated keep running. With several game releases a day, the newest launcher release soon falls out of the newest 100 releases the launcher and the website read: both then look the newest `launcher-v` tags up one by one (`git/matching-refs/tags/launcher-v`, then `releases/tags/`). + +## Nightly audit + +`.github/workflows/nightly.yml` runs every harness from scratch (`tools/parity.py --all`) on main at 03:00 Paris +time, on the Mac mini's runner, after preparing the resources again if the preparer or its exporters changed. +`tools/ci/parity_issues.py` then compares the results with the previous audit +(`.local/parity-runner/audit.json` in the runner's checkout): + +- a harness that passed last night and fails now gets an issue labelled `parity-regression`, titled + `Parity regression: `, with the commit, the run and the end of its log (one issue per harness: an open + one gets a comment instead); +- a harness with an open issue that passes again gets its issue closed. + +The bugs session picks the issues up. The audit's logs are the run's `nightly-parity-logs` artifact; harnesses +listed `linux_only` are skipped there (see above). By hand: `gh workflow run "nightly audit"` (add +`-f dry_run=true` to leave issues alone). diff --git a/tests/test_parity_issues.py b/tests/test_parity_issues.py new file mode 100644 index 000000000..1c202c272 --- /dev/null +++ b/tests/test_parity_issues.py @@ -0,0 +1,27 @@ +import unittest + +from tools.ci import parity_issues as issues + + +class ParityIssuesTests(unittest.TestCase): + def test_results_merge_shards_and_skip_earlier_runs(self): + state = {"harnesses": { + "food": {"status": "pass", "finished": "2026-10-15T03:10:00"}, + "datafix#1": {"status": "pass", "finished": "2026-10-15T03:20:00"}, + "datafix#2": {"status": "fail", "finished": "2026-10-15T03:21:00"}, + "light": {"status": "fail", "finished": "2026-10-14T03:30:00"}, + "copied": {"status": "pass", "finished": "2026-10-15T03:30:00", "shared": True}, + }} + self.assertEqual(issues.results(state, "2026-10-15T03:00:00"), {"food": "pass", "datafix": "fail"}) + + def test_plan_opens_comments_and_closes(self): + now = {"a": "fail", "b": "fail", "c": "pass", "d": "fail", "e": "pass"} + previous = {"a": "pass", "b": "fail", "c": "fail", "e": "pass"} + self.assertEqual(issues.plan(now, previous, {"b": 7, "c": 8}), + [("open", "a"), ("comment", "b"), ("close", "c")]) + # A harness that never passed in an audit (d) gets no issue; one that keeps passing (e) nothing. + self.assertEqual(issues.plan(now, {}, {}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ci/parity_issues.py b/tools/ci/parity_issues.py new file mode 100644 index 000000000..f8fb47345 --- /dev/null +++ b/tools/ci/parity_issues.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Turns the nightly audit's results into GitHub issues (.github/workflows/nightly.yml). + + python3 tools/ci/parity_issues.py --since 2026-10-15T03:00:00 [--dry-run] + +Reads tools/parity.py's state (.local/parity-runner/state.json) for the harnesses that finished since --since, +shards merged into their harness, and compares them with the previous audit (.local/parity-runner/audit.json): + +- a harness that fails now and passed in the previous audit gets one open issue labelled parity-regression, + titled "Parity regression: " (an open one is commented on instead of opening another); +- a harness with an open issue that still fails gets a comment on it; +- a harness with an open issue that passes again gets its issue closed. + +The first audit only records the results. Needs the gh CLI; --dry-run prints what it would do. +""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +STATE = ROOT / ".local" / "parity-runner" / "state.json" +AUDIT = ROOT / ".local" / "parity-runner" / "audit.json" +LOGS = ROOT / ".local" / "parity-runner" / "logs" +LABEL = "parity-regression" +TITLE = "Parity regression: " + + +def results(state, since): + """{harness: "pass" | "fail"} of the harnesses that finished since `since`; a harness fails if a shard does.""" + found = {} + for name, record in state.get("harnesses", {}).items(): + if record.get("finished", "") < since or record.get("shared"): + continue + harness = name.split("#")[0] + found[harness] = "fail" if record["status"] != "pass" or found.get(harness) == "fail" else "pass" + return found + + +def plan(now, previous, open_issues): + """The actions to take: (kind, harness) with kind open, comment or close. open_issues: {harness: number}.""" + actions = [] + for harness, status in sorted(now.items()): + if status == "fail" and harness in open_issues: + actions.append(("comment", harness)) + elif status == "fail" and previous.get(harness) == "pass": + actions.append(("open", harness)) + elif status == "pass" and harness in open_issues: + actions.append(("close", harness)) + return actions + + +def log_tail(harness, lines=60): + logs = sorted(LOGS.glob(f"{harness}*.log")) + text = "\n".join(path.read_text(errors="replace") for path in logs) + return "\n".join(text.splitlines()[-lines:]) + + +def gh(*arguments, dry_run=False): + if dry_run: + print("would run: gh " + " ".join(arguments[:4]) + " ...") + return "" + return subprocess.run(["gh", *arguments], cwd=ROOT, check=True, capture_output=True, text=True).stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--since", required=True, help="the audit's start (the state's local time format)") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + now = results(json.loads(STATE.read_text()), args.since) + previous = json.loads(AUDIT.read_text()) if AUDIT.exists() else None + listed = json.loads(gh("issue", "list", "--label", LABEL, "--state", "open", "--limit", "200", + "--json", "number,title") or "[]") + open_issues = {issue["title"][len(TITLE):]: issue["number"] for issue in listed if issue["title"].startswith(TITLE)} + commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip() + run = f"{os.environ.get('GITHUB_SERVER_URL', 'https://github.com')}/{os.environ.get('GITHUB_REPOSITORY', '')}" \ + f"/actions/runs/{os.environ.get('GITHUB_RUN_ID', '')}" + failing = sorted(harness for harness, status in now.items() if status == "fail") + print(f"{len(now)} harnesses ran: {len(now) - len(failing)} passed, {len(failing)} failed" + + (f" ({', '.join(failing)})" if failing else "")) + if previous is None: + print("First audit: results recorded, no issues opened.") + actions = plan(now, {}, open_issues) + else: + actions = plan(now, previous, open_issues) + for kind, harness in actions: + details = (f"Nightly audit of `{commit[:12]}` ({run}).\n\n" + f"Reproduce: `python3 tools/parity.py {harness}`\n\n
End of the log\n\n" + f"```\n{log_tail(harness)}\n```\n
\n") + print(f"{kind}: {harness}") + if kind == "open": + gh("issue", "create", "--label", LABEL, "--title", TITLE + harness, "--body", + f"`{harness}` passed in the previous nightly audit and fails now.\n\n" + details, dry_run=args.dry_run) + elif kind == "comment": + gh("issue", "comment", str(open_issues[harness]), "--body", "Still failing.\n\n" + details, dry_run=args.dry_run) + else: + gh("issue", "close", str(open_issues[harness]), "--comment", + f"Passes again in the nightly audit of `{commit[:12]}` ({run}).", dry_run=args.dry_run) + if not args.dry_run: + merged = dict(previous or {}) + merged.update(now) + AUDIT.write_text(json.dumps(merged, indent=1, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())