diff --git a/Cargo.lock b/Cargo.lock index 3138764a0..d6bbf30d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1253,6 +1253,7 @@ dependencies = [ "horizon-core", "horizon-dualsense", "horizon-friends", + "horizon-mods", "horizon-protocol", "horizon-telemetry", "horizon-theme", @@ -1285,6 +1286,7 @@ dependencies = [ name = "horizon-dualsense" version = "0.1.0" dependencies = [ + "cpal", "hidapi", "log", ] diff --git a/README.md b/README.md index 02efe2016..f4f3094ae 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,8 @@ It runs rustfmt, clippy with warnings denied, the tests of the crates you touche [MIT](LICENSE), for the project's original work only. Dependencies keep their own licences. Minecraft is a trademark of Mojang Synergies AB; Minecraft code and assets belong to Mojang and Microsoft and are covered by the [Minecraft EULA](https://www.minecraft.net/en-us/eula). Decompiled game source and prepared resources stay on your machine and are never published. +Third-party credits and licenses: [Third-party notices](THIRD_PARTY_NOTICES.md). + ## Author Made by [Ludovic Marie](https://lu4ovic.com) ([@ludovic111](https://github.com/ludovic111)). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..585224f8f --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,31 @@ +# Third-party notices + +## CullLeaves + +The optional leaf and mangrove-root face-culling behavior is adapted from +[CullLeaves](https://github.com/TeamMidnightDust/CullLeaves) by MidnightDust. +Its MIT license is reproduced below. + +```text +MIT License + +Copyright (c) 2020 MidnightDust + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 09d24c7f2..b9aeb7aea 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -13,6 +13,8 @@ horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } horizon-protocol = { path = "../horizon-protocol" } horizon-friends = { path = "../horizon-friends" } +# Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). +horizon-mods = { path = "../horizon-mods" } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index 0d4a71ce6..6ad2cbd99 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -139,6 +139,7 @@ fn main() -> Result<()> { blend_radius: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, }; let mut best = f64::MAX; let mut quads = 0usize; diff --git a/crates/horizon-client/examples/mipmap_probe.rs b/crates/horizon-client/examples/mipmap_probe.rs index 0cdb9655f..99155fb32 100644 --- a/crates/horizon-client/examples/mipmap_probe.rs +++ b/crates/horizon-client/examples/mipmap_probe.rs @@ -31,14 +31,7 @@ fn main() -> horizon_client::Result<()> { }; let s = sprites.mips[layer as usize]; writeln!(out, "== {name}")?; - for mip in horizon_client::mipmap::generate( - base, - size.trailing_zeros(), - s.strategy, - s.alpha_cutoff_bias, - s.has_transparent, - s.item, - ) { + for mip in horizon_client::mipmap::generate(base, size.trailing_zeros(), s) { write!(out, "{}x{}", mip.width, mip.height)?; for row in mip.pixels.chunks(mip.width as usize) { out.push(' '); diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index 7d4f5547d..a42448794 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -134,6 +134,7 @@ fn scene( blend_radius, smooth_lighting, cutout_leaves, + cull_leaves: false, }; let section_y = int(&row["section_y"])?; let started = Instant::now(); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 762d633fe..6156a041d 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -518,7 +518,9 @@ impl ChatScreen { } if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { let parse = self.parse.as_ref().expect("parsed above"); - let (range, list) = c.dispatcher.suggestions(parse, cursor_b, c.registries); + let (range, list) = c + .dispatcher + .client_suggestions(parse, cursor_b, c.registries); self.pending = Some((range.0, list)); self.update_usage_info(m, c); } diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 79041beb5..3ff96d29b 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -930,19 +930,41 @@ impl Dispatcher { let context = Context::new(0, start); self.parse_nodes(0, input, start, &context, reg, reg.permission) } - /// CommandDispatcher.getCompletionSuggestions at `cursor`. + /// CommandDispatcher.getCompletionSuggestions at `cursor`: brigadier + /// lists every child, whatever its requirement. pub fn suggestions( &self, parse: &ParseResults, cursor: usize, reg: &Registries, + ) -> (Range, Vec) { + self.suggestions_within(parse, cursor, reg, u8::MAX) + } + /// The suggestions the player's chat shows: the client's tree only holds + /// the nodes the player may use (Commands.sendCommands prunes by canUse). + pub fn client_suggestions( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + ) -> (Range, Vec) { + self.suggestions_within(parse, cursor, reg, reg.permission) + } + fn suggestions_within( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + permission: u8, ) -> (Range, Vec) { let (parent, start, context) = parse.context.suggestion_context(cursor); let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; let mut all = Vec::new(); - // Brigadier lists every child, whatever its requirement. for &child in &self.nodes[parent].children { + if self.nodes[child].permission > permission { + continue; + } let mut builder = SuggestionsBuilder::new(truncated, start); match &self.nodes[child].kind { NodeKind::Literal(l) => { diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index ea29da523..1bd23be82 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -185,6 +185,42 @@ fn vanilla_error_messages() { assert_eq!(e.message.plain(), "argument.block.property.invalid"); } #[test] +fn commands_need_allow_commands() { + // IntegratedServer.getProfilePermissions: the owner of a world without + // Allow Commands is at LevelBasedPermissionSet.ALL. + let reg = Registries { + permission: 0, + ..reg() + }; + let d = vanilla::game_dispatcher(); + let e = d.parse("gamemode creative", ®).executable().unwrap_err(); + assert_eq!(e.message.plain(), "command.unknown.command"); + assert!(d.parse("me waves", ®).executable().is_ok()); + let parse = d.parse("", ®); + // Brigadier itself lists every literal; the chat's (client tree) only + // the ones the player may use. + assert!( + d.suggestions(&parse, 0, ®) + .1 + .iter() + .any(|s| s.text == "gamemode") + ); + let root: Vec = d + .client_suggestions(&parse, 0, ®) + .1 + .into_iter() + .map(|s| s.text) + .collect(); + // Commands.java with CommandSelection.INTEGRATED: seed and version need no level. + assert_eq!( + root, + [ + "help", "list", "me", "msg", "random", "seed", "teammsg", "tell", "tm", "trigger", + "version", "w" + ] + ); +} +#[test] fn suggestions_like_vanilla() { let root = suggestions(""); assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned())); diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index a0b68260d..b361a50ff 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -164,7 +164,8 @@ fn operating_system() -> String { ) } -fn cpu() -> String { +/// Logical processors and the CPU's name (`12x AMD Ryzen 5 5600X ...`). +pub fn cpu() -> String { let threads = std::thread::available_parallelism().map_or(0, |n| n.get()); let name = if cfg!(target_os = "linux") { read("/proc/cpuinfo").and_then(|t| { diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs index 68a469415..d006a8ab6 100644 --- a/crates/horizon-client/src/debug_chart.rs +++ b/crates/horizon-client/src/debug_chart.rs @@ -72,6 +72,8 @@ pub struct DebugCharts { pub ping: SampleLogger, /// `bandwidthLogger`: bytes received per tick. pub bandwidth: SampleLogger, + /// `MinecraftServer.smoothedTickTimeMillis`. + pub smoothed_tick_ms: f32, previous_tick: Option, bytes_seen: Option, } @@ -110,6 +112,7 @@ impl DebugCharts { self.bandwidth.reset(); self.previous_tick = None; self.bytes_seen = None; + self.smoothed_tick_ms = 0.0; } /// One integrated server tick that started at `started` and ran its /// tick method for `method` (`MinecraftServer.logFullTickTime` and @@ -123,6 +126,7 @@ impl DebugCharts { .max(method); self.previous_tick = Some(started); self.tick_times.log_full([full, method, 0, full - method]); + self.smoothed_tick_ms = self.smoothed_tick_ms * 0.8 + method as f32 / 1e6 * 0.199_999_99; } /// `BandwidthDebugMonitor.tick`: the bytes received since the last /// tick, from the connection's running total. diff --git a/crates/horizon-client/src/debug_overlay.rs b/crates/horizon-client/src/debug_overlay.rs new file mode 100644 index 000000000..3448ea411 --- /dev/null +++ b/crates/horizon-client/src/debug_overlay.rs @@ -0,0 +1,340 @@ +//! `DebugScreenOverlay`: the F3 text. The entries of the default profile +//! (`DebugScreenEntries.PROFILES`) report priority lines, regular lines and +//! groups; the overlay splits them into a left and a right column and draws +//! them last, over any screen, at the debug GUI scale. +use crate::{ + font::Font, + hud_layout::{GuiDraw, PoseOp, fill}, + text::Text, +}; + +/// `extractLines`'s background: ARGB 0x90505050. +const BACKGROUND: u32 = 0x9050_5050; +/// `extractLines`'s text colour: ARGB 0xFFE0E0E0. +const TEXT: u32 = 0xFFE0_E0E0; +/// `Font.lineHeight`. +const LINE_HEIGHT: i32 = 9; + +/// What the enabled entries reported (`DebugScreenDisplayer`). +#[derive(Default, Debug)] +pub struct Displayer { + left: Vec, + right: Vec, + lines: Vec, + groups: Vec<(&'static str, Vec)>, +} + +impl Displayer { + /// `addPriorityLine`: to the shorter column, the left one first. + pub fn priority(&mut self, line: impl Into) { + if self.left.len() > self.right.len() { + self.right.push(line.into()); + } else { + self.left.push(line.into()); + } + } + /// `addLine`: split between the columns after the priority lines. + pub fn line(&mut self, line: impl Into) { + self.lines.push(line.into()); + } + /// `addToGroup`: lines kept together, groups in the order first added. + pub fn group(&mut self, group: &'static str, lines: impl IntoIterator) { + let index = match self.groups.iter().position(|(g, _)| *g == group) { + Some(i) => i, + None => { + self.groups.push((group, Vec::new())); + self.groups.len() - 1 + } + }; + self.groups[index].1.extend(lines); + } + /// `extractRenderState`: the left and right columns, then `footer` (the + /// chart keys, shown while the overlay is open) under the left one. + pub fn columns(self, footer: &[String]) -> (Vec, Vec) { + let (mut left, mut right) = (self.left, self.right); + if !left.is_empty() { + left.push(String::new()); + } + if !right.is_empty() { + right.push(String::new()); + } + if !self.lines.is_empty() { + let mid = self.lines.len().div_ceil(2); + left.extend_from_slice(&self.lines[..mid]); + right.extend_from_slice(&self.lines[mid..]); + left.push(String::new()); + if mid < self.lines.len() { + right.push(String::new()); + } + } + let mid = self.groups.len().div_ceil(2); + for (i, (_, lines)) in self.groups.into_iter().enumerate() { + if lines.is_empty() { + continue; + } + let column = if i < mid { &mut left } else { &mut right }; + column.extend(lines); + column.push(String::new()); + } + if !footer.is_empty() { + left.push(String::new()); + left.extend_from_slice(footer); + } + (left, right) + } +} + +/// `Mth.wrapDegrees`. +fn wrap_degrees(angle: f32) -> f32 { + let wrapped = angle % 360.0; + if wrapped >= 180.0 { + wrapped - 360.0 + } else if wrapped < -180.0 { + wrapped + 360.0 + } else { + wrapped + } +} + +/// `DebugEntryPosition` and `DebugEntrySectionPosition` for a camera at +/// `pos` looking `yaw`/`pitch` in `dimension` with `forced` force-loaded chunks. +pub fn position( + pos: [f64; 3], + yaw: f32, + pitch: f32, + dimension: &str, + forced: usize, +) -> Vec { + let block = pos.map(|v| v.floor() as i32); + let (cx, sy, cz) = (block[0] >> 4, block[1] >> 4, block[2] >> 4); + // Direction.fromYRot: floor(yRot / 90 + 0.5) & 3 as a 2D data value. + let (direction, towards) = match ((f64::from(yaw) / 90.0 + 0.5).floor() as i32) & 3 { + 0 => ("south", "Towards positive Z"), + 1 => ("west", "Towards negative X"), + 2 => ("north", "Towards negative Z"), + _ => ("east", "Towards positive X"), + }; + vec![ + format!("XYZ: {:.3} / {:.5} / {:.3}", pos[0], pos[1], pos[2]), + format!("Block: {} {} {}", block[0], block[1], block[2]), + format!( + "Chunk: {cx} {sy} {cz} [{} {} in r.{}.{}.mca]", + cx & 31, + cz & 31, + cx >> 5, + cz >> 5 + ), + format!( + "Facing: {direction} ({towards}) ({:.1} / {:.1})", + wrap_degrees(yaw), + wrap_degrees(pitch) + ), + format!("{dimension} FC: {forced}"), + format!( + "Section-relative: {:02} {:02} {:02}", + block[0] & 15, + block[1] & 15, + block[2] & 15 + ), + ] +} + +/// `VideoMode.refreshRateLabel`: whole rates without decimals. +pub fn refresh_rate_label(hz: f64) -> String { + if hz == hz.round() { + format!("{}", hz as i64) + } else { + format!("{hz:.2}") + } +} + +/// `DeviceInfo.vendorName` for a PCI vendor id. +pub fn vendor_name(id: u32) -> String { + match id { + 0x10de => "NVIDIA Corporation".into(), + 0x1002 | 0x1022 => "AMD".into(), + 0x8086 => "Intel".into(), + 0x106b => "Apple".into(), + 0x5143 => "Qualcomm".into(), + 0x13b5 => "ARM".into(), + 0x10005 => "Mesa".into(), + 0 => "unknown".into(), + other => format!("{other:#06x}"), + } +} + +/// The overlay's scale against the GUI scale and the scaled screen size it +/// lays out in. `debugGuiScale`: -1 keeps the GUI scale, 0 (the default) is +/// half the largest automatic scale, n is `calculateScale(n)`; only a scale +/// below the GUI scale applies. +pub fn scale( + framebuffer: [i32; 2], + gui_scale: i32, + option: i32, + unicode: bool, + gui_size: [i32; 2], +) -> (f32, [i32; 2]) { + let scale = match option { + -1 => gui_scale, + 0 => crate::window::calculate_scale(framebuffer, 0, unicode) / 2, + n => crate::window::calculate_scale(framebuffer, n, unicode), + }; + if scale < gui_scale && scale > 0 { + ( + scale as f32 / gui_scale as f32, + [framebuffer[0] / scale, framebuffer[1] / scale], + ) + } else { + (1.0, gui_size) + } +} + +/// `extractLines` for both columns under the overlay's pose: each line's +/// background first, then the text, right-aligned in the right column. +pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec { + let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])]; + for (lines, align_left) in [(columns[0], true), (columns[1], false)] { + let placed: Vec<(&String, i32, i32)> = lines + .iter() + .enumerate() + .filter(|(_, l)| !l.is_empty()) + .map(|(i, l)| { + let w = font.width(l) as i32; + let left = if align_left { 2 } else { width - 2 - w }; + (l, left, 2 + LINE_HEIGHT * i as i32) + }) + .collect(); + for (line, left, top) in &placed { + let w = font.width(line) as i32; + out.push(fill( + left - 1, + top - 1, + left + w + 1, + top + LINE_HEIGHT - 1, + BACKGROUND, + )); + } + for (line, left, top) in placed { + out.push(GuiDraw::Text { + text: Text::literal(line.clone()), + x: left, + y: top, + color: TEXT, + shadow: false, + }); + } + } + out.push(GuiDraw::Pop); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(v: &[&str]) -> Vec { + v.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn columns_follow_the_vanilla_split() { + // The default profile's entries, sorted by identifier as + // DebugScreenEntryList.rebuildCurrentList does: fps, game_version, + // memory, player_position, player_section_position, + // simple_performance_impactors, system_specs, tps. + let mut d = Displayer::default(); + d.priority("112 fps T: 120 (fifo) @165Hz"); + d.priority("Minecraft 26.3 (26.3/vanilla)"); + d.group("memory", lines(&["Mem: 25% 1046/4096MiB"])); + d.group("position", lines(&["XYZ: 1 / 2 / 3", "Block: 1 2 3"])); + d.group("position", lines(&["Section-relative: 01 02 03"])); + d.line("fancy-clouds B: 2"); + d.line("Filtering: RGSS"); + d.line("Terrain Rendering: multidrawindirect"); + d.group( + "system", + lines(&["CPU: 12x Ryzen", "Display: 854x709 (NVIDIA)"]), + ); + d.line("Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx"); + let footer = lines(&["Debug charts: ...", "To edit: press [F3+F6]"]); + let (left, right) = d.columns(&footer); + // As the issue's vanilla screenshot (#376) shows them. + assert_eq!( + left, + lines(&[ + "112 fps T: 120 (fifo) @165Hz", + "", + "fancy-clouds B: 2", + "Filtering: RGSS", + "", + "Mem: 25% 1046/4096MiB", + "", + "XYZ: 1 / 2 / 3", + "Block: 1 2 3", + "Section-relative: 01 02 03", + "", + "", + "Debug charts: ...", + "To edit: press [F3+F6]", + ]) + ); + assert_eq!( + right, + lines(&[ + "Minecraft 26.3 (26.3/vanilla)", + "", + "Terrain Rendering: multidrawindirect", + "Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx", + "", + "CPU: 12x Ryzen", + "Display: 854x709 (NVIDIA)", + "", + ]) + ); + } + + #[test] + fn position_lines_match_vanilla() { + // The issue's vanilla screenshot (#376). + assert_eq!( + position([108.5, 104.0, -51.5], -1.0, 7.1, "minecraft:overworld", 0), + lines(&[ + "XYZ: 108.500 / 104.00000 / -51.500", + "Block: 108 104 -52", + "Chunk: 6 6 -4 [6 28 in r.0.-1.mca]", + "Facing: south (Towards positive Z) (-1.0 / 7.1)", + "minecraft:overworld FC: 0", + "Section-relative: 12 08 12", + ]) + ); + assert_eq!( + position([0.0, 64.0, 0.0], 450.0, 0.0, "minecraft:the_nether", 2)[3], + "Facing: west (Towards negative X) (90.0 / 0.0)" + ); + assert_eq!(refresh_rate_label(165.0), "165"); + assert_eq!(refresh_rate_label(59.94), "59.94"); + } + + #[test] + fn debug_scale_is_half_the_automatic_scale() { + // The issue's window: 854x709 at GUI scale 2 draws F3 at scale 1. + assert_eq!( + scale([854, 709], 2, 0, false, [427, 355]), + (0.5, [854, 709]) + ); + // 1920x1080 at GUI scale 4: auto is 4, so F3 is at 2. + assert_eq!( + scale([1920, 1080], 4, 0, false, [480, 270]), + (0.5, [960, 540]) + ); + // A GUI scale already at or under the debug scale is kept. + assert_eq!( + scale([1920, 1080], 2, 0, false, [960, 540]), + (1.0, [960, 540]) + ); + assert_eq!( + scale([1920, 1080], 3, -1, false, [640, 360]), + (1.0, [640, 360]) + ); + } +} diff --git a/crates/horizon-client/src/entity_culling.rs b/crates/horizon-client/src/entity_culling.rs new file mode 100644 index 000000000..611eff1af --- /dev/null +++ b/crates/horizon-client/src/entity_culling.rs @@ -0,0 +1,266 @@ +//! Conservative, budgeted occlusion against full opaque block cross-sections. +//! +//! A covered projection rectangle proves that an entire bounding box is hidden. +//! Testing a few rays would miss openings between those rays. +use std::cell::Cell; + +const EPSILON: f64 = 1.0e-5; + +pub struct Culler { + pub camera: [f64; 3], + remaining: Cell, +} + +impl Culler { + pub fn new(camera: [f64; 3], budget: usize) -> Self { + Self { + camera, + remaining: Cell::new(budget), + } + } + + /// Remove only this entity's completed camera-relative mesh when hidden. + pub fn cull_vertices( + &self, + vertices: &mut Vec, + start: usize, + opaque: impl FnMut([i32; 3]) -> bool, + ) -> bool { + if start >= vertices.len() || self.remaining.get() == 0 { + return false; + } + let mut min = [f64::INFINITY; 3]; + let mut max = [f64::NEG_INFINITY; 3]; + for vertex in &vertices[start..] { + for a in 0..3 { + let value = f64::from(vertex.pos[a]) + self.camera[a]; + if !value.is_finite() { + return false; + } + min[a] = min[a].min(value); + max[a] = max[a].max(value); + } + } + // Cover floating-point and rasterization edges as well as the vertices. + if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) { + vertices.truncate(start); + return true; + } + false + } + + /// Returns true only when a complete opaque block plane covers the bounds. + /// Unknown blocks, invalid bounds and an exhausted lookup budget stay visible. + pub fn occluded( + &self, + min: [f64; 3], + max: [f64; 3], + mut opaque: impl FnMut([i32; 3]) -> bool, + ) -> bool { + if (0..3).any(|a| { + !self.camera[a].is_finite() + || !min[a].is_finite() + || !max[a].is_finite() + || min[a] > max[a] + }) { + return false; + } + let mut best = (0, 0.0, 0.0); + for a in 0..3 { + let (gap, sign) = if self.camera[a] < min[a] { + (min[a] - self.camera[a], 1.0) + } else { + (self.camera[a] - max[a], -1.0) + }; + if gap > best.1 { + best = (a, gap, sign); + } + } + let (axis, gap, sign) = best; + if !gap.is_finite() || gap <= EPSILON { + return false; + } + let across = [(axis + 1) % 3, (axis + 2) % 3]; + let Some(mut cell) = floor_cell(self.camera[axis]) else { + return false; + }; + let step = sign as i32; + if (f64::from(cell) + 0.5 - self.camera[axis]) * sign <= EPSILON { + let Some(next) = cell.checked_add(step) else { + return false; + }; + cell = next; + } + loop { + let depth = (f64::from(cell) + 0.5 - self.camera[axis]) * sign; + if depth >= gap - EPSILON || self.remaining.get() == 0 { + return false; + } + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for corner in 0..8 { + let point: [f64; 3] = std::array::from_fn(|a| { + if corner & (1 << a) == 0 { + min[a] + } else { + max[a] + } + }); + let t = depth / ((point[axis] - self.camera[axis]) * sign); + for (i, &a) in across.iter().enumerate() { + let p = self.camera[a] + t * (point[a] - self.camera[a]); + if !p.is_finite() { + return false; + } + lo[i] = lo[i].min(p); + hi[i] = hi[i].max(p); + } + } + let bounds = [ + floor_cell(lo[0] - EPSILON), + floor_cell(hi[0] + EPSILON), + floor_cell(lo[1] - EPSILON), + floor_cell(hi[1] + EPSILON), + ]; + let [Some(x0), Some(x1), Some(y0), Some(y1)] = bounds else { + return false; + }; + let mut pos = [0; 3]; + pos[axis] = cell; + pos[across[0]] = x0 + ((i64::from(x1) - i64::from(x0)) / 2) as i32; + pos[across[1]] = y0 + ((i64::from(y1) - i64::from(y0)) / 2) as i32; + self.remaining.set(self.remaining.get() - 1); + if opaque(pos) { + let area = (i64::from(x1) - i64::from(x0) + 1) + .checked_mul(i64::from(y1) - i64::from(y0) + 1) + .and_then(|n| usize::try_from(n).ok()); + let Some(area) = area.filter(|&n| n <= self.remaining.get()) else { + return false; + }; + // Reserve the worst-case lookups before walking the rectangle. + self.remaining.set(self.remaining.get() - area); + let covered = (x0..=x1).all(|x| { + (y0..=y1).all(|y| { + pos[across[0]] = x; + pos[across[1]] = y; + opaque(pos) + }) + }); + if covered { + return true; + } + } + let Some(next) = cell.checked_add(step) else { + return false; + }; + cell = next; + } + } +} + +fn floor_cell(value: f64) -> Option { + let n = value.floor(); + (n.is_finite() && n >= f64::from(i32::MIN) && n <= f64::from(i32::MAX)).then_some(n as i32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn completed_mesh_culling_preserves_prior_geometry_and_protruding_parts() { + let vertex = |pos| crate::mesher::Vertex { + pos, + uv: [0.0; 2], + layer: 0, + color: u32::MAX, + light: 0, + normal: [0; 4], + }; + let prior = vertex([0.0; 3]); + let body = [vertex([8.0, -1.0, -1.0]), vertex([10.0, 1.0, 1.0])]; + let wall = |p: [i32; 3]| p[0] == 4 && (-1..=0).contains(&p[1]); + let mut hidden = vec![prior]; + hidden.extend(body); + assert!(Culler::new([0.0; 3], 1_000).cull_vertices(&mut hidden, 1, wall)); + assert_eq!(hidden.len(), 1); + assert_eq!(hidden[0].pos, prior.pos); + + // A held item or animated part beyond the wall keeps the whole model. + let mut exposed = vec![prior]; + exposed.extend(body); + exposed.push(vertex([8.0, 5.0, 0.0])); + let before = exposed.clone(); + assert!(!Culler::new([0.0; 3], 1_000).cull_vertices(&mut exposed, 1, wall)); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&exposed), + bytemuck::cast_slice::<_, u8>(&before) + ); + assert!(!Culler::new([0.0; 3], 0).cull_vertices(&mut exposed, 1, |_| panic!())); + } + + #[test] + fn opaque_walls_hide_bounds_in_all_directions() { + for axis in 0..3 { + for sign in [-1.0, 1.0] { + let mut min = [-2.0; 3]; + let mut max = [2.0; 3]; + min[axis] = if sign > 0.0 { 8.0 } else { -10.0 }; + max[axis] = if sign > 0.0 { 10.0 } else { -8.0 }; + let wall = if sign > 0.0 { 4 } else { -5 }; + assert!(Culler::new([0.0; 3], 1_000).occluded(min, max, |p| p[axis] == wall)); + } + } + } + + #[test] + fn windows_slits_and_partial_walls_stay_visible() { + let min = [8.0, -4.0, -4.0]; + let max = [10.0, 4.0, 4.0]; + for opening in 0..3 { + assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |p| { + p[0] == 4 + && match opening { + 0 => !(p[1] == 1 && p[2] == 1), + 1 => p[1] != 1, + _ => p[1] < 0, + } + })); + } + assert!(!Culler::new([0.0; 3], 1_000).occluded(min, max, |_| false)); + } + + #[test] + fn budgets_are_shared_and_exhaustion_fails_open() { + let culler = Culler::new([0.0; 3], 3); + let calls = Cell::new(0); + for _ in 0..2 { + assert!(!culler.occluded([8.0; 3], [10.0; 3], |_| { + calls.set(calls.get() + 1); + false + })); + } + assert_eq!(calls.get(), 3); + assert!(!Culler::new([0.0; 3], 0).occluded([8.0; 3], [10.0; 3], |_| panic!())); + assert!(!Culler::new([0.0; 3], 1).occluded([8.0; 3], [10.0; 3], |_| true)); + } + + #[test] + fn camera_inside_invalid_and_target_crossing_wall_stay_visible() { + let culler = Culler::new([0.0; 3], 1_000); + assert!(!culler.occluded([-1.0; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([f64::NAN; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([2.0; 3], [1.0; 3], |_| panic!())); + assert!(!culler.occluded([4.0, -1.0, -1.0], [8.0, 1.0, 1.0], |p| p[0] == 4)); + assert!(!Culler::new([f64::INFINITY; 3], 1_000).occluded( + [8.0; 3], + [10.0; 3], + |_| panic!() + )); + assert!(!Culler::new([f64::MAX; 3], 1_000).occluded( + [-f64::MAX; 3], + [-1.0; 3], + |_| panic!() + )); + } +} diff --git a/crates/horizon-client/src/extras_hud.rs b/crates/horizon-client/src/extras_hud.rs index df23b533f..f6fc1ba12 100644 --- a/crates/horizon-client/src/extras_hud.rs +++ b/crates/horizon-client/src/extras_hud.rs @@ -129,6 +129,32 @@ pub fn draw_fps( ); } +/// A box of text lines (a mod's HUD panel): `(text, 0xRRGGBB)` each. +pub fn draw_lines( + batch: &mut HudBatch, + atlas: &HudAtlas, + corners: &mut Corners, + corner: Corner, + lines: &[(&str, u32)], +) { + if lines.is_empty() { + return; + } + let w = lines + .iter() + .map(|(text, _)| HudBatch::text_width(atlas, text)) + .fold(0.0, f32::max) + + 4.0; + let h = 10.0 * lines.len() as f32 + 2.0; + let (x, y) = corners.place(corner, w, h); + batch.fill(atlas, x, y, w, h, BACKGROUND); + for (i, (text, color)) in lines.iter().enumerate() { + let [_, r, g, b] = color.to_be_bytes(); + let y = y + 2.0 + 10.0 * i as f32; + batch.text(atlas, text, x + 2.0, y, rgba(r, g, b, 255), true); + } +} + /// What the keystroke overlay shows. pub struct Keystrokes { /// Forward, left, back, right: held, and the bound key's name. diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index e6224683f..7b1771000 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -441,7 +441,9 @@ impl Title { Screen::Direct { .. } => 53, Screen::Friend { .. } => 57, Screen::Disconnected { .. } => 54, + Screen::ConfirmDelete { .. } => 59, }), + CONFIRM_DELETE => Some(58), CANCEL_RETRY => Some(55), DONE => Some(match screen { Screen::Direct { .. } => 52, @@ -840,8 +842,14 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { Some(Ping::Ok { motd, players, ms, .. }) => ( - motd.lines().next().unwrap_or("").trim().to_owned(), - format!("{players} · {ms} ms"), + motd.resolve_legacy() + .plain() + .lines() + .next() + .unwrap_or("") + .trim() + .to_owned(), + format!("{} · {ms} ms", Ping::player_count(*players).plain()), color::ACCENT, ), Some(Ping::Failed(_)) => ( @@ -1035,6 +1043,40 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, ¬e); } } + Screen::ConfirmDelete { name, .. } => { + let mut y = header( + ui, + x, + "Remove this server?", + "It leaves your list. You can add it again later.", + ); + ui.divider(x, y, w); + y += 16.0; + y += notice( + ui, + x, + y, + w, + Some(name), + "Its address and icon will be forgotten.", + ) + 16.0; + let dw = ui.button_width("Delete server", false); + ui.button( + CONFIRM_DELETE, + [x, y, dw, CONTROL], + "Delete server", + Kind::Danger, + true, + ); + let cw = ui.button_width("Cancel", false); + ui.button( + BACK, + [x + dw + 8.0, y, cw, CONTROL], + "Cancel", + Kind::Ghost, + true, + ); + } Screen::Disconnected { reason, retry } => { let mut y = header( ui, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 504cc4682..c05d41760 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod dispenser; mod dragon; mod enchant_effects; mod end; +mod entity_culling; mod events; mod explosion; mod extras; @@ -56,6 +57,7 @@ mod item_particles; mod jukebox; mod lan; mod lan_actions; +mod lan_crafting; mod lan_screen; mod lan_trading; mod leads; @@ -69,6 +71,7 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mods; mod mount_menu; mod mounts; mod music; @@ -100,6 +103,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod shader_packs; mod shield; mod sign_edit; mod sniffers; @@ -225,6 +229,8 @@ struct Options { dedicated: Option>, /// `--benchmark SCENARIO`: run the benchmark, write its report and quit. benchmark: Option, + /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. + dev_mods: Vec, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -274,6 +280,7 @@ impl Options { .filter(|n| !n.is_empty()), dedicated: None, benchmark: None, + dev_mods: Vec::new(), }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -281,7 +288,7 @@ impl Options { 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 --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\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: generated once, kept in horizon-player.txt)\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." + "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 --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\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: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\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); } @@ -323,6 +330,7 @@ impl Options { "--smoke-report" => o.report = Some(value.into()), "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), + "--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?), "--benchmark" => { if horizon_client::benchmark::scenes(&value).is_none() { return Err(format!( @@ -725,6 +733,8 @@ struct Game<'a> { modifiers: winit::keyboard::ModifiersState, /// The window's fullscreen request and reported state. fullscreen: horizon_client::window::FullscreenState, + /// The selected Horizon shader pack (`game/shader_packs.rs`). + shader_packs: shader_packs::ShaderPacks, /// MouseHandler's accumulated look and wheel state. mouse: MouseLook, /// An agent moved the mouse (`mouse-move`) since the pointer was last @@ -952,10 +962,13 @@ struct Game<'a> { frame_graph: horizon_client::perf_overlay::FrameGraph, /// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`. extras: extras::ExtrasState, + /// Horizon mods (`game/mods.rs`), none running unless turned on. + mods: mods::ModsState, /// 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. view_frustum: Option, + entity_culler: Option, /// A scripted flight from the control socket (`fly`). flight: Option, /// The running agent action from the control socket (game/agent.rs). @@ -1000,13 +1013,14 @@ struct Game<'a> { /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u16)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// `ContainerOpenersCounter`: how many players (the host and the guests) + /// have each chest open. + lid_openers: HashMap<(i32, i32, i32), i32>, lan_acting: Option, /// Command feedback to forward to a guest. chat_capture: Option>, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, - /// Allow Cheats: whether guests may be given commands. - cheats: bool, ui: chat::UiState, combat: combat::CombatTracker, mount: mounts::MountState, @@ -2957,6 +2971,7 @@ impl Game<'_> { self.apply_totem(); self.update_totem_ready(); self.tick_command_extras(); + self.tick_mods(); let camera_eye = self.camera_eye_height(); let stick = self.pad_move(); if self.riding.is_some() && self.player.is_some() { @@ -3605,6 +3620,9 @@ impl Game<'_> { } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); + // Gui.extractRenderState: the debug overlay comes after the screen + // and the toasts, so it is over everything, menus included. + self.draw_debug_overlay(&mut batch, size); self.frame_graph .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); self.draw_pad_cursor(&mut batch); @@ -3667,7 +3685,8 @@ impl Game<'_> { let indicator = self.settings.attack_indicator; let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed()); let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed()); - if self.camera_type.first_person() && !spectator { + // The 3D crosshair (F3) takes the 2D one's place. + if self.camera_type.first_person() && !spectator && !self.debug_crosshair() { let attack = (indicator == 1).then_some(strength); let full = attack.is_some_and(|a| { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) @@ -3785,117 +3804,6 @@ impl Game<'_> { } } let atlas = &self.res.atlas; - if self.debug { - let p = self - .player - .as_ref() - .map(|p| p.position) - .unwrap_or(Vec3::ZERO); - let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - let biome = self - .world - .chunks - .get(&(block[0] >> 4, block[2] >> 4)) - .map(|c| { - self.res - .biomes - .get(c.biome(block[0], block[1], block[2])) - .name - .clone() - }) - .unwrap_or_default(); - let light = self.world.light(block[0], block[1], block[2]); - let facing = match ((self.yaw.rem_euclid(360.0) + 45.0) / 90.0) as i32 % 4 { - 0 => "south (Towards positive Z)", - 1 => "west (Towards negative X)", - 2 => "north (Towards negative Z)", - _ => "east (Towards positive X)", - }; - let mut lines = vec![ - format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), - format!( - "C: {} chunks, {} sections drawn / {}", - self.world.chunks.len(), - self.renderer.as_ref().map_or(0, |r| r.drawn_sections), - self.renderer.as_ref().map_or(0, |r| r.section_count()) - ), - format!("Pending jobs: {}", self.streaming.pending()), - String::new(), - format!("XYZ: {:.3} / {:.5} / {:.3}", p.x, p.y, p.z), - format!("Block: {} {} {}", block[0], block[1], block[2]), - format!( - "Chunk: {} {} {} in {} {} {}", - block[0] & 15, - block[1] & 15, - block[2] & 15, - block[0] >> 4, - block[1] >> 4, - block[2] >> 4 - ), - format!( - "Facing: {facing} ({:.1} / {:.1})", - self.yaw.rem_euclid(360.0) - - if self.yaw.rem_euclid(360.0) > 180.0 { - 360.0 - } else { - 0.0 - }, - self.pitch - ), - format!( - "Light: {} (sky {}, block {})", - (light >> 4).max(light & 15), - light >> 4, - light & 15 - ), - format!("Biome: {biome}"), - format!( - "Day {} time {}", - self.world.day_time / 24000, - self.world.day_time % 24000 - ), - String::new(), - ]; - lines.extend(self.debug_chart_lines()); - for (i, line) in lines.iter().enumerate() { - if line.is_empty() { - continue; - } - let tw = HudBatch::text_width(atlas, line); - batch.fill( - atlas, - 1.0, - 2.0 + i as f32 * 9.0 - 1.0, - tw + 2.0, - 9.0, - rgba(80, 80, 80, 144), - ); - batch.text( - atlas, - line, - 2.0, - 2.0 + i as f32 * 9.0, - rgba(224, 224, 224, 255), - false, - ); - } - let charts = self.debug_charts.draw( - &atlas.font, - w as i32, - h as i32, - self.settings.max_fps, - 1000.0 / self.clock.rate(), - self.remote.is_some(), - ); - hud_layout::paint(&mut batch, atlas, &charts); - if self.debug_charts.lightmap - && let Some(r) = &self.renderer - { - let view = - horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32); - hud_layout::paint(&mut batch, atlas, &view); - } - } if !self.ui.hide_gui && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -5290,6 +5198,7 @@ impl Game<'_> { alpha: f64, mut out: Vec, ) -> Vec { + self.prepare_entity_culling(camera); let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront { self.yaw + 180.0 } else { @@ -5477,9 +5386,21 @@ impl Game<'_> { v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0)) }) }); - self.res - .block_entity_render - .render(&scene, visible, &mut out); + if self.entity_culler.is_some() { + for block in visible { + let start = out.len(); + self.res + .block_entity_render + .render(&scene, std::iter::once(block), &mut out); + if !off_screen(block.1) { + self.cull_entity_vertices(&mut out, start); + } + } + } else { + self.res + .block_entity_render + .render(&scene, visible, &mut out); + } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self @@ -6151,7 +6072,6 @@ impl Game<'_> { horizon_client::save::migrate_legacy(&save_root)?; self.session_lock = None; self.session_lock = Some(horizon_client::save::SessionLock::acquire(&save_root)?); - self.persist = Default::default(); self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); @@ -6190,6 +6110,11 @@ impl Game<'_> { level.allow_commands = Some(o.commands(creative)); horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; } + // Worlds made without the Create New World screen (--world, the + // control socket) take its default: commands on for Creative only. + if created { + level.allow_commands.get_or_insert(creative); + } horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); @@ -6285,8 +6210,7 @@ impl Game<'_> { self.block_ticks = Ticks::new(self.level.seed as i32); self.install_live_features(); self.tick_chunks.clear(); - self.falling.clear(); - self.tnts.clear(); + self.clear_entities(); self.travelling = None; self.player = None; self.spawn = None; @@ -6305,14 +6229,8 @@ impl Game<'_> { self.spawn_origin = None; self.spawn_spiral = Default::default(); self.player_spawn = None; - self.mobs.clear(); self.creatures.reset_trader(); self.portals = Default::default(); - self.creatures.projectiles.clear(); - self.dropped.clear(); - self.particles.clear(); - self.pickups.clear(); - self.orbs.clear(); self.experience = Experience { level: self.level.xp_level, progress: self.level.xp_progress, @@ -6408,6 +6326,7 @@ impl Game<'_> { streaming.biome_blend = self.settings.biome_blend; streaming.smooth_lighting = self.settings.smooth_lighting; streaming.cutout_leaves = self.settings.cutout_leaves; + streaming.cull_leaves = self.settings.horizon.cull_leaves; streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; @@ -6635,11 +6554,7 @@ impl Game<'_> { self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; - self.mobs.clear(); - self.creatures.projectiles.clear(); - self.dropped.clear(); - self.particles.clear(); - self.pickups.clear(); + self.clear_entities(); self.screen = Screen::Playing; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); @@ -6651,6 +6566,33 @@ impl Game<'_> { self.capture(false); Ok(()) } + /// Let go of every entity of the level (saved first): the next world + /// opened must not inherit them, nor save them as its own. + fn clear_entities(&mut self) { + self.mobs.clear(); + self.dropped.clear(); + self.orbs.clear(); + self.creatures.projectiles.clear(); + self.falling.clear(); + self.tnts.clear(); + self.boats.clear(); + self.carts.clear(); + self.armor_stands.clear(); + self.item_frames.clear(); + self.paintings.clear(); + self.others.clear(); + self.dragon = None; + self.crystals.clear(); + self.dragon_fireballs.clear(); + self.breath_clouds.clear(); + self.tridents.clear(); + self.rockets.clear(); + self.bolts.clear(); + self.particles.clear(); + self.pickups.clear(); + self.riding = None; + self.persist = Default::default(); + } /// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges). fn apply_equipment(&mut self) { let Some(player) = self.player.as_mut() else { @@ -7668,11 +7610,21 @@ impl Game<'_> { // Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves: // LevelExtractor.allChanged when they change. let (s, st) = (&self.settings, &self.streaming); - let remesh = (s.biome_blend, s.smooth_lighting, s.cutout_leaves) - != (st.biome_blend, st.smooth_lighting, st.cutout_leaves); + let remesh = ( + s.biome_blend, + s.smooth_lighting, + s.cutout_leaves, + s.horizon.cull_leaves, + ) != ( + st.biome_blend, + st.smooth_lighting, + st.cutout_leaves, + st.cull_leaves, + ); self.streaming.biome_blend = self.settings.biome_blend; self.streaming.smooth_lighting = self.settings.smooth_lighting; self.streaming.cutout_leaves = self.settings.cutout_leaves; + self.streaming.cull_leaves = self.settings.horizon.cull_leaves; if remesh { self.all_sections_changed(); } @@ -8343,6 +8295,7 @@ impl Game<'_> { Ok(()) } fn render(&mut self) -> Result { + self.poll_shader_pack(); let Some(size) = self .renderer .as_ref() @@ -8410,6 +8363,13 @@ impl Game<'_> { } let view = horizon_client::camera::view_matrix(view_yaw, view_pitch); let at = camera.to_array(); + // GameRenderer.renderLevel: the debug crosshair, first person with the HUD shown. + if self.debug_crosshair() && self.camera_type.first_person() && !self.ui.hide_gui { + let mut g = horizon_client::gizmos::Gizmos::default(); + let scale = HudBatch::new(size).scale; + g.debug_crosshair(at, view_pitch, view_yaw, scale); + on_top.extend(g.on_top); + } let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view); let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view); // LevelRenderer.renderHitOutline: the outline shape's edges. @@ -8536,6 +8496,7 @@ impl Game<'_> { .then(|| self.border_draw(camera.to_array(), alpha as f32)) .flatten(); let frame = Frame { + shader: self.shader_inputs(camera, alpha as f32), nether_lighting: self.dim == Dim::Nether, camera, yaw, @@ -9488,6 +9449,7 @@ impl ApplicationHandler for Game<'_> { } } self.extras_frame(elapsed); + self.mods_frame(elapsed); self.extras_retry()?; self.apply_mouse_look(); self.pad_look(elapsed.as_secs_f32()); @@ -9883,6 +9845,7 @@ pub fn run() -> Result<()> { focused: true, modifiers: winit::keyboard::ModifiersState::empty(), fullscreen: horizon_client::window::FullscreenState::new(false), + shader_packs: Default::default(), mouse: MouseLook::default(), agent_pointer: false, smooth_camera: false, @@ -10045,9 +10008,11 @@ pub fn run() -> Result<()> { events: Default::default(), agent: agent::Agent::default(), view_frustum: None, + entity_culler: None, pending_uploads: Vec::new(), frame_graph: Default::default(), extras: Default::default(), + mods: Default::default(), sky_darken_memo: Default::default(), persist: Default::default(), remote: None, @@ -10068,10 +10033,10 @@ pub fn run() -> Result<()> { lan_events: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), + lid_openers: HashMap::new(), lan_acting: None, chat_capture: None, cmds: Default::default(), - cheats: true, ui: Default::default(), combat: Default::default(), mount: Default::default(), @@ -10104,6 +10069,11 @@ pub fn run() -> Result<()> { game.options.no_pause = true; } game.apply_settings(); + // Benchmarks measure the game alone. + if game.options.benchmark.is_none() { + game.mods.dev = game.options.dev_mods.clone(); + game.start_mods(); + } if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) .map_err(|e| format!("control socket {}: {e}", path.display()))?; diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index fcfd5ff3d..62b4f8624 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -4,7 +4,7 @@ //! take time run as a task advanced every frame and reply when they finish or //! time out, so `horizon-ctl break 10 64 3` returns what the block dropped. use super::{Game, Screen}; -use horizon_client::{Result, items::ItemStack, widgets}; +use horizon_client::{Result, block_entity_anim::Ticker, items::ItemStack, widgets}; use horizon_core::geometry::Vec3; use horizon_world::registry::BlockStateId; use serde_json::{Value, json}; @@ -309,12 +309,19 @@ impl Game<'_> { } fn block_json(&self, pos: [i32; 3]) -> Value { let state = self.world.block(pos[0], pos[1], pos[2]); - json!({ + let mut v = json!({ "pos": pos, "block": &*self.res.facts.get(state).name, "state": self.state_string(state), "loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)), - }) + }); + // How far a chest's or a shulker box's lid is open, 0..1, as drawn. + match self.be_anims.ticker(state.0) { + Some(Ticker::Lid) => v["lid"] = json!(self.chest_lid(pos, 1.0)), + Some(Ticker::Shulker { .. }) => v["lid"] = json!(self.block_anim(pos, 1.0).shulker.0), + _ => {} + } + v } pub(super) fn stack_value(&self, s: &ItemStack) -> Value { let mut v = json!({ "item": &*s.item, "count": s.count }); @@ -1465,7 +1472,7 @@ impl Game<'_> { self.send_chat(&command); return ok(json!({ "ok": true })); } - self.handle_chat_input(&command); + self.as_console(|g| g.handle_chat_input(&command)); ok(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) })) } "respawn" if self.remote.is_none() => { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index df85b9e62..c856738a9 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -7,7 +7,7 @@ use horizon_client::{ entities::ArmorStand, items::ItemStack, mesher::Vertex, - mobs::{Part, anim::Poses}, + mobs::{Mob, Part, anim::Poses}, }; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -92,21 +92,26 @@ impl Game<'_> { /// `HumanoidArmorLayer` for the player: (model, texture rect, colour) of /// each worn piece, head to feet. pub(super) fn player_armor_layers(&self) -> Vec<(&Part, [f32; 4], u32)> { + self.armor_layers(self.armor.each_ref().map(|s| s.as_ref().map(|s| &*s.item))) + } + /// `HumanoidArmorLayer` for another player's model: the armour it wears + /// (`extra.head` .. `extra.feet`). + pub(super) fn worn_armor_layers(&self, m: &Mob) -> Vec<(&Part, [f32; 4], u32)> { + let e = &m.extra; + self.armor_layers([&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref())) + } + /// The layers of the armour items `worn`, head to feet. + fn armor_layers(&self, worn: [Option<&str>; 4]) -> Vec<(&Part, [f32; 4], u32)> { let assets = &self.armor_stand_assets; let mut out = Vec::new(); - for (i, layer) in ["helmet", "chestplate", "leggings", "boots"] + for (item, layer) in worn .into_iter() - .enumerate() + .zip(["helmet", "chestplate", "leggings", "boots"]) { - let Some(stack) = &self.armor[i] else { + let Some(item) = item else { continue; }; - let Some(asset) = self - .res - .items - .get(&stack.item) - .and_then(|i| i.equip_asset.clone()) - else { + let Some(asset) = self.res.items.get(item).and_then(|i| i.equip_asset.clone()) else { continue; }; let kind = if layer == "leggings" { @@ -404,6 +409,7 @@ impl Game<'_> { return; }; for a in &self.armor_stands { + let entity_start = out.len(); if a.invisible { continue; } @@ -519,6 +525,7 @@ impl Game<'_> { out, ); } + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 3fe6959bc..15ca99ba9 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -174,6 +174,7 @@ impl Game<'_> { streaming.biome_blend = self.settings.biome_blend; streaming.smooth_lighting = self.settings.smooth_lighting; streaming.cutout_leaves = self.settings.cutout_leaves; + streaming.cull_leaves = self.settings.horizon.cull_leaves; streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.paused = true; self.streaming = streaming; diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index c448767c1..446b56b55 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -69,17 +69,19 @@ impl Game<'_> { /// on both halves of a double chest (`CompoundContainer`). pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) { // Spectators never count as openers. - if self.spectator() { - return; + if !self.spectator() { + self.container_openers_changed(key, open); } + } + /// `container_opener_event` for a player who is not a spectator (a guest). + pub(super) fn container_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { let pos = [key.0, key.1, key.2]; let state = self.world.block(pos[0], pos[1], pos[2]).0; match self.be_anims.ticker(state) { Some(Ticker::Lid) => { - let count = i32::from(open); - self.block_entity_event(pos, 1, count); + self.lid_openers_changed(key, open); if let Some(other) = self.chest_other_half(key) { - self.block_entity_event([other.0, other.1, other.2], 1, count); + self.lid_openers_changed(other, open); } } Some(Ticker::Shulker { .. }) => { @@ -90,10 +92,26 @@ impl Game<'_> { shulker.stop_open() }; self.block_entity_event(pos, 1, count); + self.lan_block_event(pos, 1, count); } _ => {} } } + /// `ContainerOpenersCounter.incrementOpeners` / `decrementOpeners` of the + /// chest at `key` (the host and the guests are counted), then + /// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here + /// and for the guests. + fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { + let count = self.lid_openers.entry(key).or_default(); + *count = (*count + if open { 1 } else { -1 }).max(0); + let count = *count; + if count == 0 { + self.lid_openers.remove(&key); + } + let pos = [key.0, key.1, key.2]; + self.block_entity_event(pos, 1, count); + self.lan_block_event(pos, 1, count); + } /// `BellBlockEntity.updateEntities`: the living entities whose bounding /// box meets the bell's block box inflated by 48. fn bell_gather(&self, pos: [i32; 3]) -> Vec { @@ -233,7 +251,8 @@ impl Game<'_> { f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5, ]; - if tick.resonate { + // On a server its own copy does this and sends the sound. + if tick.resonate && self.remote.is_none() { // The server's copy plays the resonance for everyone. self.audio .play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0); @@ -249,8 +268,8 @@ impl Game<'_> { }; self.particles.add(&options, p, [0.0; 3]); } - // makeRaidersGlow. - for m in self.mobs.iter_mut() { + // makeRaidersGlow (the server's effect). + for m in self.mobs.iter_mut().filter(|_| self.remote.is_none()) { if glow.contains(&u64::from(m.id)) { m.add_effect("minecraft:glowing", 60, 0); } @@ -292,7 +311,8 @@ impl Game<'_> { let initial = self.gateway_loaded(pos); let anims = &mut self.be_anims; let server = anims.gateway_servers.entry(pos).or_insert(initial); - let triggered = server.portal_tick(); + // A server sends its copy's block event instead. + let triggered = self.remote.is_none() && server.portal_tick(); let client = anims.gateways.entry(pos).or_insert(initial); if triggered { client.trigger_event(1, 0); diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 9a06c6777..40211161d 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -701,6 +701,7 @@ impl Game<'_> { pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for b in &self.boats { + let entity_start = out.len(); let models = if b.chest { &self.boat_models.chest_models } else { @@ -768,6 +769,7 @@ impl Game<'_> { 0, out, ); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 169148dcb..bd07107b0 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -90,10 +90,28 @@ pub struct UiState { } impl Game<'_> { + /// `PlayerList.isOp` for the single-player owner: the world's Allow Commands. + pub(super) fn allow_commands(&self) -> bool { + self.level.allow_commands == Some(true) + } + /// `IntegratedServer.setWorldAllowCommands`, then `updatePermissions`. + pub(super) fn set_allow_commands(&mut self, allow: bool) { + self.level.allow_commands = Some(allow); + self.ui.registries.permission = owner_permission(allow); + } + /// Commands the game issues itself (the server console, harnesses, the + /// control socket) run at the owner's level whatever Allow Commands says. + pub(super) fn as_console(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + let level = std::mem::replace(&mut self.ui.registries.permission, 4); + let out = f(self); + self.ui.registries.permission = level; + out + } /// Registry contents for argument parsing (built when a world opens). pub(super) fn build_registries(&mut self) { + let permission = owner_permission(self.allow_commands()); let reg = &mut self.ui.registries; - reg.permission = 4; + reg.permission = permission; { let dir = |sub: &str| -> Vec { let root = self.options.resources.join("data/minecraft").join(sub); @@ -408,6 +426,7 @@ impl Game<'_> { return; } let focused = self.screen == Screen::Chat; + let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( &self.res.atlas, text, @@ -415,6 +434,9 @@ impl Game<'_> { self.ticks, focused, ); + if let Some(line) = heard { + self.mods_chat(&line); + } } /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { @@ -511,9 +533,13 @@ impl Game<'_> { &[Text::literal(PLAYER_NAME), Text::literal(message)], ); let focused = self.screen == Screen::Chat; + let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat .add(&self.res.atlas, line, None, self.ticks, focused); + if let Some(line) = heard { + self.mods_chat(&line); + } self.lan_host_chat(message); } } @@ -861,3 +887,9 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: std::fs::write(&path, Compression::Gzip.encode(&out)?)?; Ok(()) } + +/// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when +/// commands are allowed, else `ALL` (0). +fn owner_permission(allow_commands: bool) -> u8 { + if allow_commands { 4 } else { 0 } +} diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs index 0409b410c..ed3f8b336 100644 --- a/crates/horizon-client/src/game/command_harness.rs +++ b/crates/horizon-client/src/game/command_harness.rs @@ -89,7 +89,9 @@ impl Game<'_> { let command = op["cmd"].as_str().unwrap_or(""); self.chat_capture = Some(Vec::new()); self.cmds.results = Some(Vec::new()); - self.run_command(command.strip_prefix('/').unwrap_or(command)); + self.as_console(|g| { + g.run_command(command.strip_prefix('/').unwrap_or(command)) + }); let messages = self.chat_capture.take().unwrap_or_default(); let results = self.cmds.results.take().unwrap_or_default(); if op["record"].as_bool() != Some(false) { diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index e212a4b98..a7385914b 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -78,6 +78,9 @@ fn format_double(v: f64) -> String { impl Game<'_> { /// Commands.performCommand for a line without its slash. pub(super) fn run_command(&mut self, command: &str) { + if self.mod_command(command) { + return; + } let d = vanilla::game_dispatcher(); let parse = d.parse(command, &self.ui.registries); let result = match parse.executable() { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 51e5379f1..921ca03db 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -713,6 +713,10 @@ impl Game<'_> { })), "uptime_seconds": self.started.elapsed().as_secs_f64(), "server": self.remote_status(), + // The names the name tags show now, seen from the eyes. + "name_tags": self + .eye_position() + .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); status["physical_keys"] = json!(physical_keys); status diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8c7baa5b8..5adf6832b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2705,6 +2705,7 @@ impl Game<'_> { let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { + let entity_start = out.len(); let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's // mean edge, scaled by the entity distance option. @@ -2746,16 +2747,28 @@ impl Game<'_> { out, ); } - horizon_client::mobs::render::render( + // Other players on a server: PlayerRenderer's HumanoidArmorLayer. + let armor = if &*mob.kind.id == "minecraft:player" { + self.worn_armor_layers(mob) + } else { + Vec::new() + }; + horizon_client::mobs::render::render_with( mob, alpha as f32, camera, &lookup, packed, &self.res.mob_data, + &armor, out, ); self.mob_block_geometry(mob, camera, alpha, packed, out); + // Glowing outlines and a guardian's beam remain visible independently + // of whether the body is hidden behind terrain. + if !mob.glowing && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() { + self.cull_entity_vertices(out, entity_start); + } // GuardianRenderer: the laser to the locked target. if let Some((time, scale)) = horizon_client::mobs::guardian::beam(mob, alpha as f32) && let Some(target) = self.beam_target(mob.ai.target, alpha) diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 05380d980..07488b51a 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -6,8 +6,11 @@ use horizon_client::{ Result, command::args::GameMode, debug_keys::{CrashNotice, DebugAction, DebugHost, KeyAction, OpenScreen}, + debug_overlay, gizmos::Gizmos, - keybinds, + hud::HudBatch, + hud_layout, keybinds, + save::VERSION_NAME, text::Text, }; use horizon_core::geometry::Axis; @@ -253,6 +256,199 @@ impl Game<'_> { format!("To edit: press {}", key("key.debug.debugOptions")), ] } + /// `DebugScreenOverlay.extractRenderState` with the default profile's + /// entries, over everything the frame drew (menus too), at the debug GUI + /// scale. F1 hides it unless a screen is open. + pub(super) fn draw_debug_overlay(&self, batch: &mut HudBatch, size: [u32; 2]) { + let screen_open = self.title.is_some() || self.screen != Screen::Playing; + if !self.debug || (self.ui.hide_gui && !screen_open) { + return; + } + let framebuffer = size.map(|v| v as i32); + let (scale, [width, height]) = debug_overlay::scale( + framebuffer, + batch.scale as i32, + self.settings.file.int("debugGuiScale"), + self.settings.force_unicode, + [batch.width as i32, batch.height as i32], + ); + let mut d = debug_overlay::Displayer::default(); + // fps: DebugEntryFps. + let limit = self.framerate_limit(); + let present = self + .renderer + .as_ref() + .map_or("", |r| match r.config.present_mode { + wgpu::PresentMode::Immediate => " (immediate)", + wgpu::PresentMode::Mailbox => " (mailbox)", + wgpu::PresentMode::Fifo => " (fifo)", + wgpu::PresentMode::FifoRelaxed => " (fifo relaxed)", + _ => "", + }); + let refresh = self + .window + .as_ref() + .and_then(|w| w.current_monitor()) + .and_then(|m| m.refresh_rate_millihertz()) + .map_or("0".into(), |mhz| { + debug_overlay::refresh_rate_label(f64::from(mhz) / 1000.0) + }); + d.priority(format!( + "{} fps T: {}{present} @{refresh}Hz", + self.fps.round() as i32, + if limit == 260 { + "inf".into() + } else { + limit.to_string() + }, + )); + // game_version: DebugEntryVersion (the launched version and brand). + d.priority(format!("Minecraft {VERSION_NAME} ({VERSION_NAME}/horizon)")); + // player_position, player_section_position. + if let Some(p) = self.player.as_ref() { + let mut lines = debug_overlay::position( + [p.position.x, p.position.y, p.position.z], + self.yaw, + self.pitch, + self.dim.id(), + self.streaming.forced.len(), + ); + let section = lines.pop().unwrap_or_default(); + if !self.reduced_debug_info() { + d.group("position", lines); + } + d.group("position", [section]); + } + // simple_performance_impactors. + let s = &self.settings; + d.line(format!( + "{}{}B: {}", + if s.improved_transparency { + "improved-transparency " + } else { + "" + }, + match s.clouds.as_str() { + "false" => "", + "fast" => "fast-clouds ", + _ => "fancy-clouds ", + }, + s.biome_blend + )); + d.line("Filtering: None"); + d.line(format!( + "Terrain Rendering: {}", + if self.renderer.as_ref().is_some_and(|r| r.multi_draw) { + "multidrawindirect" + } else { + "naive" + } + )); + // system_specs (no Java line: Horizon has no JVM). + if let Some(r) = self.renderer.as_ref() { + static CPU: std::sync::OnceLock = std::sync::OnceLock::new(); + d.group( + "system", + [format!( + "CPU: {}", + CPU.get_or_init(horizon_client::crash::cpu) + )], + ); + let info = &r.info; + d.group( + "system", + [format!( + "Display: {}x{} ({})", + framebuffer[0], + framebuffer[1], + // Metal adapters report no PCI vendor. + if info.vendor == 0 && info.backend == wgpu::Backend::Metal { + "Apple".into() + } else { + debug_overlay::vendor_name(info.vendor) + } + )], + ); + if let Some(w) = self.window.as_ref() { + let density = w.scale_factor(); + let logical = w.inner_size().to_logical::(density); + d.group( + "system", + [format!( + "Window: {}x{} ({density:.2}x pixel density)", + logical.width.round() as i32, + logical.height.round() as i32 + )], + ); + } + let kind = match info.device_type { + wgpu::DeviceType::IntegratedGpu => " (iGPU)", + wgpu::DeviceType::DiscreteGpu => " (dGPU)", + wgpu::DeviceType::VirtualGpu => " (vGPU)", + wgpu::DeviceType::Cpu => " (software)", + wgpu::DeviceType::Other => "", + }; + let driver = format!("{} {}", info.driver, info.driver_info); + d.group( + "system", + [ + format!("{}{kind}", info.name), + format!( + "{:?} {}", + info.backend, + driver.trim().lines().next().unwrap_or("") + ) + .trim_end() + .to_owned(), + ], + ); + } + // tps: DebugEntryTps for the integrated server (it counts no packets). + if self.player.is_some() && self.remote.is_none() { + let (target, status) = if self.clock.sprinting() { + ("-".to_owned(), " (sprinting)") + } else if self.clock.stepping() { + ( + format!("{:.1}", 1000.0 / self.clock.rate()), + " (frozen - stepping)", + ) + } else if self.clock.frozen() { + (format!("{:.1}", 1000.0 / self.clock.rate()), " (frozen)") + } else { + (format!("{:.1}", 1000.0 / self.clock.rate()), "") + }; + d.line(format!( + "Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx", + self.debug_charts.smoothed_tick_ms + )); + } + let (left, right) = d.columns(&self.debug_chart_lines()); + let atlas = &self.res.atlas; + let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); + let charts = self.debug_charts.draw( + &atlas.font, + width, + height, + self.settings.max_fps, + 1000.0 / self.clock.rate(), + self.remote.is_some(), + ); + draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale( + scale, scale, + )])); + draws.extend(charts); + if self.debug_charts.lightmap + && let Some(r) = &self.renderer + { + draws.extend(horizon_client::debug_chart::lightmap( + &r.lightmap_pixels, + width, + height, + )); + } + draws.push(hud_layout::GuiDraw::Pop); + hud_layout::paint(batch, atlas, &draws); + } /// `KeyMapping.getTranslatedKeyMessage`. fn key_text(&self, mapping: &str) -> Text { keybinds::display_name(self.settings.keys.get(mapping)) @@ -283,6 +479,11 @@ impl Game<'_> { fn reduced_debug_info(&self) -> bool { self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info") } + /// The default profile's `3d_crosshair` entry: on while the overlay is + /// open, unless debug info is reduced. + pub(super) fn debug_crosshair(&self) -> bool { + self.debug && !self.reduced_debug_info() + } /// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`). pub(super) fn gamemaster(&self) -> bool { self.ui.registries.permission >= 2 @@ -375,6 +576,7 @@ impl Game<'_> { DebugAction::ReloadResourcePacks => { self.debug_translated("debug.reload_resourcepacks.message"); self.reload_packs(); + self.load_shader_pack(); true } DebugAction::CopyLocation if player => { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index e73de6988..cd7744d87 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -915,7 +915,7 @@ impl Game<'_> { _ => { // The game's dispatcher, captured for the console. self.chat_capture = Some(Vec::new()); - self.run_command(line); + self.as_console(|g| g.run_command(line)); for text in self.chat_capture.take().unwrap_or_default() { self.console_reply(text); } diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs new file mode 100644 index 000000000..71ab13378 --- /dev/null +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -0,0 +1,51 @@ +//! Entity occlusion affects mesh submission, never entity ticking or interaction. +use super::{Game, Vertex}; +use horizon_client::chunk::MIN_Y; +use horizon_client::{ + blocks::{RenderShape, StateFacts}, + entity_culling::Culler, +}; + +fn opaque(facts: &StateFacts) -> bool { + facts.render_shape == RenderShape::Model + && facts.can_occlude + && facts.solid_render + && facts.full_collision +} + +impl Game<'_> { + pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) { + let at = camera.to_array().map(|v| v.floor() as i32); + self.entity_culler = (self.settings.horizon.entity_culling + // Packs can replace an opaque block's model or texture. + && self.settings.resource_packs.iter().all(|id| id == "vanilla") + && self.player.is_some() + && !self.spectator() + && !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2])))) + .then(|| Culler::new(camera.to_array(), 8_192)); + } + + /// Use complete generated geometry so equipment, animation and custom + /// models cannot stick out of an assumed collision-sized culling box. + pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec, start: usize) { + if let Some(culler) = &self.entity_culler { + culler.cull_vertices(vertices, start, |pos| { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !opaque(self.res.facts.get(state)) { + return false; + } + let Some(y) = pos[1].checked_sub(MIN_Y) else { + return false; + }; + let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4); + // Newly edited or not-yet-uploaded terrain is not an occluder. + self.renderer + .as_ref() + .is_some_and(|r| r.has_section(section)) + && !self.world.dirty_sections.contains(§ion) + && !self.streaming.is_meshing(section) + && !self.pending_uploads.iter().any(|(key, _)| *key == section) + }); + } + } +} diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 9fd42d5ff..1495800ec 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -233,7 +233,8 @@ 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 && !e.minimap { + let mod_panels = self.mods.mods.panels().next().is_some(); + if !e.fps && !e.keystrokes && !e.minimap && !mod_panels { return; } let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows); @@ -287,6 +288,9 @@ impl Game<'_> { }; extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); } + if mod_panels { + self.draw_mod_panels(batch, &mut corners); + } } /// The height the status effect icons take at the top right /// (`Hud.extractEffects`: beneficial at y 1, harmful at y 26). diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index c09f5ad17..26e195d4e 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -305,6 +305,7 @@ impl Game<'_> { let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); for f in &self.item_frames { + let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); let s = f.step(); // Pose: to the block centre, then X/Y rotation by facing. @@ -371,6 +372,7 @@ impl Game<'_> { ); } } + self.cull_entity_vertices(out, entity_start); if let Some(id) = map { // ItemFrameRenderer: the map fills the face, in 90-degree steps. let depth = if f.invisible { 0.5 } else { 0.4375 }; @@ -400,6 +402,7 @@ impl Game<'_> { } // `extractRenderState`: FIXED, seeded by the frame entity. for (stack, id, m, light) in items { + let entity_start = out.len(); let owner = super::item_draw::owner_at([0.0; 3], 0.0, "minecraft:item_frame"); let state = self.resolve_item( &stack, @@ -413,9 +416,12 @@ impl Game<'_> { horizon_client::block_entity_render::vertex_light(light), out, ); + self.cull_entity_vertices(out, entity_start); } for (id, m, light) in maps { + let entity_start = out.len(); self.map_vertices(id, m, light, out); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 664455be7..87599042e 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -330,6 +330,7 @@ impl Game<'_> { _ => None, }); for (item, at, partial) in live.chain(taken) { + let entity_start = out.len(); let q = item.position; let pos = glam::DVec3::from_array(at) - camera; if pos.length_squared() > 64.0 * 64.0 { @@ -369,6 +370,7 @@ impl Game<'_> { ) { self.submit_item_world(&state, copy, vertex_light(packed), out); } + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 1bce62bb8..9bdbac2e0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -2,7 +2,7 @@ //! server threads and the play-state hub, feeds it the world's entities each //! tick and turns what the guests do into gameplay. A world that is not open //! costs one `Option` check per tick. -use super::{Game, chat::PLAYER_NAME}; +use super::Game; use horizon_client::{ Result, items::ItemStack, @@ -43,6 +43,8 @@ pub(super) struct LanHost { pub settings: LanSettings, pub host_entity: i32, pub host_uuid: u128, + /// The host's profile name (the account's, or the offline name). + pub host_name: String, /// The guests' models in the host's world. pub models: HashMap, host_mode: i32, @@ -325,6 +327,7 @@ impl Game<'_> { Some("status") => Ok(Some(match &self.lan { Some(h) => json!({ "open": true, + "host": h.host_name, "port": h.settings.port, "guests": h.hub.guests.iter().map(|g| json!({ "name": g.name, @@ -334,6 +337,11 @@ impl Game<'_> { "game_mode": g.game_mode, "chunks": g.sent_chunks.len(), "tracked": g.tracker.len(), + // The armour the host draws on this guest, head to feet. + "model_armor": h.models.get(&g.conn).map(|m| { + [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] + .map(|s| s.as_deref()) + }), })).collect::>(), }), None => json!({ "open": false }), @@ -356,9 +364,11 @@ impl Game<'_> { if self.lan.is_some() || self.remote.is_some() || self.title.is_some() { return Err("already open".into()); } - let motd = format!("{PLAYER_NAME} - {}", self.level.name); + // IntegratedServer.publishServer: the MOTD names the host's profile. + let name = self.options.player_name(); + let motd = format!("{name} - {}", self.level.name); let host_uuid = self.level.player_uuid.map_or_else( - || offline_uuid(PLAYER_NAME), + || offline_uuid(&name), |u| { u128::from(u[0] as u32) << 96 | u128::from(u[1] as u32) << 64 @@ -438,6 +448,7 @@ impl Game<'_> { settings: LanSettings { port, ..settings }, host_entity, host_uuid, + host_name: self.options.player_name(), models: HashMap::new(), host_mode: self.mode_id(), play: HashMap::new(), @@ -509,7 +520,7 @@ impl Game<'_> { equipment[5] = self.armor[0].clone(); Some(HostState { uuid: host.host_uuid, - name: PLAYER_NAME.to_owned(), + name: host.host_name.clone(), entity_id: host.host_entity, position: [p.position.x, p.position.y, p.position.z], yaw: self.yaw, @@ -634,7 +645,14 @@ impl Game<'_> { ); } } - HostEvent::Left(guest) => { + HostEvent::Left(mut guest) => { + // The container they had open loses an opener. + if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos) + && !guest.spectator() + { + self.container_openers_changed(pos, false); + } + self.lan_crafting_left(&mut host, &mut guest); playerdata::save(&guest, &self.world_root); host.models.remove(&guest.conn); if self.options.dedicated.is_some() && guest.placed { @@ -839,6 +857,10 @@ impl Game<'_> { .and_then(|s| s.as_ref()) .map(|s| s.item.clone()); m.extra.off_hand = g.offhand.as_ref().map(|s| s.item.clone()); + [m.extra.head, m.extra.chest, m.extra.legs, m.extra.feet] = g + .armor + .each_ref() + .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; } } @@ -856,6 +878,7 @@ impl Game<'_> { let atlas = &self.res.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { + let entity_start = out.len(); let light = self.world.light( m.position.x.floor() as i32, (m.position.y + 1.62).floor() as i32, @@ -869,16 +892,20 @@ impl Game<'_> { &lookup, packed, &self.res.mob_data, - &self.player_armor_layers(), + &self.worn_armor_layers(m), out, ); + self.held_item_geometry(m, camera, alpha, packed, true, out); + if !m.glowing { + self.cull_entity_vertices(out, entity_start); + } } } /// A chat line the host typed, for the guests. pub(super) fn lan_host_chat(&mut self, message: &str) { if let Some(host) = &self.lan { - host.hub.chat(PLAYER_NAME, message); + host.hub.chat(&host.host_name, message); } } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7faba7f6c..7c8303c82 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -12,13 +12,14 @@ use horizon_client::{ entities::Experience, items::ItemStack, lan::{guest::SPECTATOR, menu::Rules}, - motion::PlayerMotion, + motion::{MotionWorld, PlayerMotion}, }; use horizon_core::geometry::Vec3; use horizon_protocol::{ packets::play::{self, Clientbound as C, Serverbound as S}, text::literal, }; +use horizon_world::entity_move::EntityMoveWorld; use winit::keyboard::KeyCode; /// Per-guest state of the gameplay code that lives outside `Guest`. @@ -37,6 +38,8 @@ pub(super) struct GuestPlay { swung: bool, /// The trading screen the guest has open. pub(super) merchant: Option, + /// The inventory menu and the crafting table the guest crafts in. + pub(super) crafting: super::lan_crafting::GuestCrafting, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -126,6 +129,10 @@ impl Game<'_> { self.keys.remove(&KeyCode::ShiftLeft); } let screen = std::mem::replace(&mut self.screen, Screen::Playing); + // The host's crafting grid stays theirs; a crafting table the guest + // opens shows as the 3x3 size. + let craft_size = std::mem::replace(&mut self.craft_size, 2); + let craft_grid = std::mem::replace(&mut self.craft_grid, vec![None; 9]); let container = self.container.take(); let mining = std::mem::replace(&mut self.mining, play.mining.take()); let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay); @@ -145,6 +152,8 @@ impl Game<'_> { // What the action opened: handed to the guest instead of the host. let opened = self.container.take(); + let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; + self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); self.riding = riding; self.left = left; @@ -200,12 +209,19 @@ impl Game<'_> { host.hub.set_game_mode(conn, new_mode); } host.play.insert(conn, play); - if let Some(pos) = opened { - self.lan_open_container(host, conn, pos); + if let Some(pos) = opened + && !self.lan_open_container(host, conn, pos) + && !host.hub.guests[i].spectator() + { + // Nothing the guest can use opened: its lid closes again. + self.container_openers_changed(pos, false); } if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if opened_table { + self.lan_open_crafting(host, conn); + } Some(result) } @@ -221,19 +237,20 @@ impl Game<'_> { self.creative = self.mode == GameMode::Creative; } - /// Hand a container the guest opened over (ServerPlayer.openMenu). - fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) { + /// Hand a container the guest opened over (ServerPlayer.openMenu); + /// false when it is not one a guest can open. + fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool { let Some(entity) = self.world.block_entities.get(&pos) else { - return; + return false; }; let (menu, title) = match entity { BlockEntity::Chest(items) => match items.len() { 27 => ("minecraft:generic_9x3", "container.chest"), 9 => ("minecraft:generic_3x3", "container.dispenser"), 5 => ("minecraft:hopper", "container.hopper"), - _ => return, + _ => return false, }, - _ => return, + _ => return false, }; let name = &self .res @@ -247,6 +264,8 @@ impl Game<'_> { _ => title, }; let items = entity.slots().to_vec(); + // ServerPlayer.openMenu closes the menu that was open. + self.guest_container_closed(host, conn); host.hub.open_container( conn, menu, @@ -254,6 +273,18 @@ impl Game<'_> { pos, items, ); + true + } + + /// The guest's open container is closing (`AbstractContainerMenu.removed`): + /// it no longer counts among the openers of the lid. + pub(super) fn guest_container_closed(&mut self, host: &mut LanHost, conn: u32) { + if let Some(g) = host.hub.guest(conn) + && let Some(pos) = g.menu.as_ref().and_then(|m| m.pos) + && !g.spectator() + { + self.container_openers_changed(pos, false); + } } /// A packet from a guest that the hub does not handle itself. @@ -392,6 +423,8 @@ impl Game<'_> { host.hub.guests[gi].set_menu_slot(p.slot as usize, item); } S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -399,12 +432,25 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } + S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => { + let g = &mut host.hub.guests[gi]; + if let Some(c) = g.carried.take() { + self.drop_guest_items(host, gi, vec![c]); + } + } S::ContainerClick(p) => { let rules = ItemRules(&self.res.items); - let drops = host.hub.container_click(conn, p, &mut self.world, &rules); + let drops = host.hub.container_click(conn, &p, &mut self.world, &rules); self.drop_guest_items(host, gi, drops); } S::ContainerClose(p) => { + if host.hub.guests[gi] + .menu + .as_ref() + .is_some_and(|m| m.window == p.container) + { + self.guest_container_closed(host, conn); + } host.hub.container_closed(conn, p.container); let g = &mut host.hub.guests[gi]; if let Some(c) = g.carried.take() { @@ -553,7 +599,7 @@ impl Game<'_> { let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect(); if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) { let me = (self.options.dedicated.is_none() && self.player.is_some()) - .then_some((host.host_uuid, super::chat::PLAYER_NAME)); + .then_some((host.host_uuid, host.host_name.as_str())); let content = host.hub.list_reply(me, words.len() == 2); host.hub.send_to( conn, @@ -564,7 +610,10 @@ impl Game<'_> { ); return; } - if !host.settings.guest_commands || !self.cheats { + // A LAN world follows its Allow Commands; a dedicated server leaves + // it to the ops list (the guest's permission level). + let allowed = self.options.dedicated.is_some() || self.allow_commands(); + if !host.settings.guest_commands || !allowed { host.hub.send_to( conn, &C::SystemChat(play::SystemChat { @@ -698,6 +747,7 @@ impl Game<'_> { } }); } + self.guest_server_tick(host, conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); let g = &mut host.hub.guests[gi]; @@ -715,6 +765,51 @@ impl Game<'_> { } } + /// The guest's body on the server each tick: ServerPlayer.tick's damage + /// clock and Entity.baseTick's fluid phase, then + /// ServerPlayer.doCheckFallDamage for each move the guest made (the fall + /// distance grows while they go down and hurts them where they land, as + /// the host's own landing does; water resets it, lava halves it), then + /// regeneration and the food tick (ServerPlayer.doTick). + fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + let moves = std::mem::take(&mut g.moves); + if g.spectator() { + return; + } + self.as_guest(host, conn, |game| { + let (rules, health) = (game.world.health_rules, &game.motion.health); + let Some(player) = game.player.as_mut() else { + return; + }; + let mut w = MotionWorld { + player, + scene: &mut game.world, + assets: &game.res.assets, + collision_binding: game.collision, + resources: game.motion, + }; + w.player.health.advance_clock(); + let _ = w.fluid_base_tick(); + for (moved, on_ground) in moves { + let movement = Vec3::new(moved[0], moved[1], moved[2]); + let landed = (|| -> horizon_client::Result<()> { + w.set_on_ground_with_movement(on_ground, false, movement)?; + let pos = w.legacy_on_position()?; + let state = w.block_state(pos)?; + w.check_fall_damage(moved[1], on_ground, state, pos) + })(); + if landed.is_err() { + break; + } + } + let _ = w.player.peaceful_regeneration(rules); + let _ = w.player.food_tick(health, rules); + }); + } + /// The crack animation other players see. fn guest_dig_feedback(&mut self, host: &mut LanHost, conn: u32) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs new file mode 100644 index 000000000..02db51586 --- /dev/null +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -0,0 +1,287 @@ +//! Crafting for LAN guests: the inventory's 2x2 grid (window 0) and the +//! crafting table (`minecraft:crafting`) run the host's menu engine +//! (`horizon_client::menu`, `Kind::Inventory` / `Kind::Crafting`) over the +//! guest's inventory, with vanilla's packets: OpenScreen, container clicks +//! and their corrections, and the grid back into the inventory when the menu +//! closes (`AbstractContainerMenu.clearContainer`). +use super::{Game, lan::LanHost}; +use horizon_client::{ + items::ItemStack, + lan::guest::Guest, + menu::{Env, Input, Kind, Menu}, +}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// The guest's menus the game runs: kept between clicks, so a drag (quick +/// craft) spans them as in vanilla. +#[derive(Default)] +pub(super) struct GuestCrafting { + /// The inventory menu; its grid lives in the hub's guest. + inventory: Option>, + /// The open crafting table: its window, state id and menu. + table: Option<(i32, i32, Box)>, +} + +/// ServerboundContainerClickPacket's input. +pub(super) fn input(id: i32) -> Input { + match id { + 0 => Input::Pickup, + 1 => Input::QuickMove, + 2 => Input::Swap, + 3 => Input::Clone, + 4 => Input::Throw, + 5 => Input::QuickCraft, + _ => Input::PickupAll, + } +} + +/// The armor's player-container slots, head to feet (`Inventory` 39..36). +const ARMOR: [usize; 4] = [39, 38, 37, 36]; +const OFFHAND: usize = 40; + +/// The guest's inventory, armor, off hand, selection and carried stack into `menu`. +fn load_player(menu: &mut Menu, g: &Guest) { + for i in 0..36 { + menu.set_player_item(i, g.inventory[i].clone()); + } + for (k, slot) in ARMOR.into_iter().enumerate() { + menu.set_player_item(slot, g.armor[k].clone()); + } + menu.set_player_item(OFFHAND, g.offhand.clone()); + menu.selected = g.selected; + menu.creative = g.creative(); + menu.carried = g.carried.clone(); +} + +/// `load_player` back. +fn store_player(menu: &mut Menu, g: &mut Guest) { + for i in 0..36 { + g.inventory[i] = menu.player_item(i).cloned(); + } + for (k, slot) in ARMOR.into_iter().enumerate() { + g.armor[k] = menu.player_item(slot).cloned(); + } + g.offhand = menu.player_item(OFFHAND).cloned(); + g.carried = menu.carried.take(); +} + +/// Inventory.placeItemBackInInventory for each stack: what doesn't fit is +/// left for Player.drop (creative players keep it too). +fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { + menu.creative = false; + for mut stack in stacks { + menu.give(env, &mut stack); + if stack.count > 0 { + menu.dropped.push(stack); + } + } +} + +impl Game<'_> { + fn menu_env(&self) -> Env<'_> { + Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + banners: &self.res.stations.banners, + trade: None, + } + } + + /// Runs `op` on the guest's menu with their inventory copied in and back. + fn guest_menu_op( + &mut self, + host: &mut LanHost, + gi: usize, + menu: &mut Menu, + op: impl FnOnce(&mut Menu, &Env) -> R, + ) -> R { + let env = self.menu_env(); + load_player(menu, &host.hub.guests[gi]); + let result = op(menu, &env); + let dropped = std::mem::take(&mut menu.dropped); + menu.drops.clear(); + menu.crafted.clear(); + store_player(menu, &mut host.hub.guests[gi]); + self.drop_guest_items(host, gi, dropped); + result + } + + /// A click on the guest's inventory menu (window 0): `InventoryMenu`, + /// crafting grid included. False for other windows. + pub(super) fn lan_inventory_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + if p.container != 0 { + return false; + } + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return true; + }; + if host.hub.guests[gi].spectator() { + return true; + } + let crafting = host.play.entry(conn).or_default(); + let mut menu = crafting + .crafting + .inventory + .take() + .unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory))); + let grid = host.hub.guests[gi].craft_grid.clone(); + let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { + for (k, s) in grid.into_iter().enumerate() { + menu.set_slot(env, 1 + k, s); + } + let before: Vec<_> = (0..menu.slot_count()) + .map(|s| menu.slot(s).cloned()) + .collect(); + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + (0..menu.slot_count()) + .filter(|&s| menu.slot(s) != before[s].as_ref()) + .collect::>() + }); + let g = &mut host.hub.guests[gi]; + for k in 0..4 { + g.craft_grid[k] = menu.slot(1 + k).cloned(); + } + g.craft_result = menu.slot(0).cloned(); + host.play.entry(conn).or_default().crafting.inventory = Some(menu); + host.hub.inventory_clicked(conn, p, &self.world, &changed); + true + } + + /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). + pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { + self.lan_crafting_closed(host, conn, None); + // The container it replaces loses its opener. + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable("container.crafting", &[]); + let Some(window) = host.hub.open_window(conn, "minecraft:crafting", title) else { + return; + }; + let menu = Box::new(Menu::new(Kind::Crafting)); + host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu)); + self.lan_send_table_content(host, conn); + } + + /// A click on the guest's crafting table window; false for other windows. + pub(super) fn lan_crafting_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + let Some(play) = host.play.get_mut(&conn) else { + return false; + }; + let Some((window, state, mut menu)) = play + .crafting + .table + .take_if(|(window, _, _)| *window == p.container) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + { + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }); + } + host.play.entry(conn).or_default().crafting.table = Some((window, state, menu)); + self.lan_send_table_content(host, conn); + true + } + + /// The whole crafting table menu for the client (`sendAllDataToRemote`). + fn lan_send_table_content(&mut self, host: &mut LanHost, conn: u32) { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let Some((window, state, menu)) = host + .play + .get_mut(&conn) + .and_then(|p| p.crafting.table.as_mut()) + else { + return; + }; + *state = (*state + 1) & 0x7FFF; + let (window, state) = (*window, *state); + let mut items: Vec> = (0..10).map(|s| menu.slot(s).cloned()).collect(); + let g = &host.hub.guests[gi]; + items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone())); + let carried = g.carried.clone(); + let items = items.iter().map(|s| host.hub.stack(s)).collect(); + let carried = host.hub.stack(&carried); + host.hub.send_to( + conn, + &C::ContainerSetContent(play::ContainerSetContent { + container: window, + state, + items, + carried, + }), + ); + } + + /// `AbstractContainerMenu.removed` of a crafting menu: the closed window + /// (`window`; None closes the table whichever it is, and 0 the inventory + /// menu) gives its grid back to the inventory, what doesn't fit is + /// dropped. False when no such window is open. + pub(super) fn lan_crafting_closed( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + ) -> bool { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return false; + }; + let crafting = &mut host.play.entry(conn).or_default().crafting; + let grid: Vec = if window == Some(0) { + crafting.inventory = None; + let g = &mut host.hub.guests[gi]; + g.craft_result = None; + g.craft_grid.iter_mut().filter_map(Option::take).collect() + } else { + match crafting + .table + .take_if(|(w, _, _)| window.is_none_or(|window| *w == window)) + { + Some((_, _, menu)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(), + None => return false, + } + }; + if grid.is_empty() { + return true; + } + let mut menu = Menu::new(Kind::Inventory); + self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid)); + true + } + + /// A guest left: what their crafting grids held goes back into their + /// inventory before it is saved (dropped where they stood if full). + pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { + let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table); + let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); + g.craft_result = None; + if let Some((_, _, menu)) = table { + grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + } + if grid.is_empty() { + return; + } + let mut menu = Menu::new(Kind::Inventory); + load_player(&mut menu, g); + place_back(&mut menu, &self.menu_env(), grid); + let dropped = std::mem::take(&mut menu.dropped); + store_player(&mut menu, g); + for stack in dropped { + self.spawn_item(stack, g.position, [0.0, 0.1, 0.0], 40); + } + } +} diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index f0eb57b3e..b9ba56c5e 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -170,7 +170,7 @@ impl Game<'_> { let mut options = WorldOptions { default_mode: self.level.mode(), personal_mode: self.mode_id(), - cheats: self.cheats, + cheats: self.allow_commands(), difficulty: self.ui.difficulty, lan, port, @@ -360,7 +360,7 @@ impl Game<'_> { fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) { if wanted.difficulty != before.difficulty { let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3]; - self.run_command(&format!("difficulty {name}")); + self.as_console(|g| g.run_command(&format!("difficulty {name}"))); } if wanted.default_mode != before.default_mode { self.set_default_game_mode(wanted.default_mode); @@ -368,7 +368,9 @@ impl Game<'_> { if wanted.personal_mode != before.personal_mode { self.set_mode_id(wanted.personal_mode); } - self.cheats = wanted.cheats; + if wanted.cheats != before.cheats { + self.set_allow_commands(wanted.cheats); + } let settings_changed = wanted.guest_commands != before.guest_commands || wanted.force != before.force; if wanted.lan != before.lan || (wanted.lan && wanted.port != before.port) { diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 8b033f8b2..d6bfc4141 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -55,6 +55,8 @@ impl Game<'_> { state.session.update_special_prices(); } let title = self.merchant_display_name(&state); + // The container the trading screen replaces loses its opener. + self.guest_container_closed(host, conn); let Some(window) = host.hub.open_merchant_window(conn, title) else { self.merchant_closed(&mut state); return; diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index fd10b4562..f4dc21e06 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1231,6 +1231,7 @@ impl Game<'_> { pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; for c in &self.carts { + let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { continue; }; @@ -1327,6 +1328,7 @@ impl Game<'_> { let m = base * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); let poses = Poses::new(model); horizon_client::mobs::render::draw(model, m, &poses, uv, 0xFFFF_FFFF, packed, 0, out); + self.cull_entity_vertices(out, entity_start); } } /// The chest inside a chest minecart, drawn by the chest block-entity renderer. diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs new file mode 100644 index 000000000..20981ac45 --- /dev/null +++ b/crates/horizon-client/src/game/mods.rs @@ -0,0 +1,235 @@ +//! Horizon mods in the game (`docs/mods.md`): loading the ones turned on, +//! their tick, frame, chat and command hooks, their HUD panels and what +//! they print. With no mod on, `horizon_mods::Mods` holds no engine and +//! every hook here returns after one check. +use super::{Game, Screen}; +use horizon_client::{ + extras::Corner, + extras_hud::{self, Corners}, + hud::HudBatch, + mod_list::{self, Installed}, + text::{self, Text}, +}; +use horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; + +#[derive(Default)] +pub(super) struct ModsState { + pub(super) mods: Mods, + /// `--dev-mod PATH`: always on, reloaded when rebuilt. + pub(super) dev: Vec, + /// When dev mods were last checked for a rebuild. + checked: Option, +} +/// How often dev mods are checked for a rebuild. +const RELOAD_CHECK: Duration = Duration::from_secs(1); + +/// A vanilla command name: mods may not take it. +fn vanilla_command(name: &str) -> bool { + let d = horizon_client::command::vanilla::game_dispatcher(); + d.nodes[0] + .children + .iter() + .any(|&c| d.nodes[c].name() == name) +} + +impl Game<'_> { + /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. + pub(super) fn start_mods(&mut self) { + let dir = Self::options_path().with_file_name(mod_list::DIR); + let dev = &self.mods.dev; + let mut paths = horizon_mods::find(&dir); + paths.retain(|p| !dev.contains(p)); + paths.extend(dev.iter().cloned()); + // A dev mod is on whatever the list says. + let dev_ids: Vec = dev + .iter() + .filter_map(|p| horizon_mods::Package::read(p).ok()) + .map(|p| p.manifest.id) + .collect(); + let enabled = &self.settings.mods.enabled; + let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id); + let mods = Mods::load(&paths, on, vanilla_command); + self.mods.mods = mods; + self.list_mods(); + self.show_mod_output(); + } + /// The Mods page's rows, from what loaded. + fn list_mods(&mut self) { + let dev = &self.mods.dev; + self.settings.mods.installed = self + .mods + .mods + .entries() + .iter() + .map(|e| { + let file = e.path.file_name().unwrap_or_default().to_string_lossy(); + let problem = match &e.status { + Status::Failed(reason) => Some(format!("Stopped: {reason}")), + _ => None, + }; + let Some(m) = &e.manifest else { + return Installed { + id: String::new(), + title: file.into_owned(), + description: String::new(), + problem, + dev: false, + }; + }; + // What it may do first: the row cuts long descriptions. + let may: Vec<&str> = m.capabilities.iter().map(|c| c.describe()).collect(); + let may = if may.is_empty() { + "Asks for nothing.".to_owned() + } else { + format!("May {}.", may.join(", ")) + }; + Installed { + id: m.id.clone(), + title: format!("{} {}", m.name, m.version), + description: format!("{may} {}", m.description).trim().to_owned(), + problem, + dev: dev.contains(&e.path), + } + }) + .collect(); + } + /// After the options changed: restart the mods if the list of the ones + /// turned on did. + pub(super) fn sync_mods(&mut self) { + let running: Vec<&str> = self + .mods + .mods + .entries() + .iter() + .filter(|e| e.status != Status::Off) + .filter_map(|e| Some(e.manifest.as_ref()?.id.as_str())) + .collect(); + let wanted: Vec<&str> = self + .settings + .mods + .installed + .iter() + .enumerate() + .filter(|&(i, _)| self.settings.mods.is_on(i)) + .map(|(_, m)| m.id.as_str()) + .collect(); + if running != wanted { + self.start_mods(); + } + } + /// What mods read this tick. + fn mod_snapshot(&self) -> Snapshot { + let player = self.player.as_ref().map(|p| Player { + x: p.position.x, + y: p.position.y, + z: p.position.z, + yaw: self.yaw, + pitch: self.pitch, + health: p.health.health(), + food: p.health.food.food.max(0) as u32, + dimension: self.dim.id().to_owned(), + }); + let clock = player.is_some().then(|| Clock { + game_time: self.world.game_time.max(0) as u64, + day_time: self.world.day_time.max(0) as u64, + }); + Snapshot { player, clock } + } + /// A game tick. + pub(super) fn tick_mods(&mut self) { + if !self.mods.mods.is_running() { + return; + } + let snapshot = self.mod_snapshot(); + self.mods.mods.set_snapshot(snapshot); + self.mods.mods.tick(self.ticks); + self.show_mod_output(); + } + /// Once per frame: the frame hook, and dev mods' rebuilds. + pub(super) fn mods_frame(&mut self, elapsed: Duration) { + if !self.mods.dev.is_empty() + && self + .mods + .checked + .is_none_or(|t| t.elapsed() >= RELOAD_CHECK) + { + self.mods.checked = Some(Instant::now()); + if self.mods.mods.reload_changed(vanilla_command) { + self.list_mods(); + self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY)); + } + } + if !self.mods.mods.is_running() { + return; + } + self.mods.mods.frame(elapsed.as_secs_f32()); + self.show_mod_output(); + } + /// `/command` typed in chat: true when a mod owns it. + pub(super) fn mod_command(&mut self, command: &str) -> bool { + if !self.mods.mods.is_running() { + return false; + } + // The command may follow a teleport in the same tick. + let snapshot = self.mod_snapshot(); + self.mods.mods.set_snapshot(snapshot); + if !self.mods.mods.command(command) { + return false; + } + self.show_mod_output(); + true + } + /// A chat line the player received. + pub(super) fn mods_chat(&mut self, line: &str) { + self.mods.mods.chat(line); + self.show_mod_output(); + } + /// Chat lines, command feedback and stopped mods, into the chat. + fn show_mod_output(&mut self) { + for output in self.mods.mods.drain() { + let line = match output { + Output::Chat { name, text } => { + let mut line = Text::literal(format!("[{name}] ")).with_color(text::GRAY); + line.push(Text::literal(text)); + line + } + Output::Feedback { text, error: false } => Text::literal(text), + Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED), + Output::Stopped { name, reason } => { + self.list_mods(); + Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED) + } + }; + // Not through system_message: a mod must not hear its own lines. + let focused = self.screen == Screen::Chat; + self.ui + .chat + .add(&self.res.atlas, line, None, self.ticks, focused); + } + } + /// The mods' HUD panels, stacked with the extras in their corners. + pub(super) fn draw_mod_panels(&self, batch: &mut HudBatch, corners: &mut Corners) { + for panel in self.mods.mods.panels() { + let corner = match panel.corner { + horizon_mods::Corner::TopLeft => Corner::TopLeft, + horizon_mods::Corner::TopRight => Corner::TopRight, + horizon_mods::Corner::BottomLeft => Corner::BottomLeft, + horizon_mods::Corner::BottomRight => Corner::BottomRight, + }; + // F3 takes the top left, as it does from the extras. + if self.debug && corner == Corner::TopLeft { + continue; + } + let lines: Vec<(&str, u32)> = panel + .lines + .iter() + .map(|l| (l.text.as_str(), l.color)) + .collect(); + extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines); + } + } +} diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 1b39f051f..2e727259b 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -3,9 +3,10 @@ //! on a translucent black background, shown when the name is visible or the //! mob is under the crosshair within 64 blocks, as its team's name tag //! visibility allows, in the team's colours, with its score in the -//! objective displayed below names. +//! objective displayed below names. Other players' names (on a LAN host +//! or a server) show whenever `LivingEntityRenderer.shouldShowName` allows. use super::{Game, view_vector}; -use horizon_client::{mesher::Vertex, save::uuid_text, scoreboard as sb, text::Text}; +use horizon_client::{mesher::Vertex, mobs::Mob, save::uuid_text, scoreboard as sb, text::Text}; impl Game<'_> { /// A named name tag names the mob under the crosshair. @@ -28,13 +29,12 @@ impl Game<'_> { self.swing_arm(); true } - /// `Entity.belowNameDisplay`: the mob's score in the objective shown below - /// names, then a space and the objective's name. - fn below_name_text(&self, id: u32) -> Option { + /// `Entity.belowNameDisplay`: the score holder's score in the objective + /// shown below names, then a space and the objective's name. + fn below_name_text(&self, holder: &str) -> Option { let board = &self.score.board; let objective = board.display_objective(sb::SLOT_BELOW_NAME)?; - let uuid = self.persist.uuids.get(&id)?; - let score = board.score(&uuid_text(*uuid), &objective.name)?; + let score = board.score(holder, &objective.name)?; // numberFormatOrDefault(StyledFormat.NO_STYLE). let format = score .number_format @@ -47,23 +47,60 @@ impl Game<'_> { t.push(objective.display_text()); Some(t) } - pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + /// The other players' models and names: the guests on a LAN host, the + /// players a server sends on a client. + fn other_players(&self) -> Vec<(&Mob, String)> { + let mut out = Vec::new(); + if let Some(host) = &self.lan { + for (conn, m) in &host.models { + if let Some(g) = host.hub.guest(*conn) { + out.push((m, g.name.clone())); + } + } + } + for (id, name) in self.remote_player_names() { + if let Some(m) = self.mobs.iter().find(|m| m.id == id) { + out.push((m, name)); + } + } + out + } + /// The names the name tags show this frame (the control socket's status). + pub(super) fn shown_name_tags(&self, camera: glam::DVec3) -> Vec { + self.name_tags(camera, 1.0) + .into_iter() + .filter_map(|(_, lines, _)| lines.last().map(|(t, _)| t.plain())) + .collect() + } + /// Each name tag: where it hangs, its lines (text, lift) and its light. + #[allow(clippy::type_complexity)] + fn name_tags( + &self, + camera: glam::DVec3, + alpha: f64, + ) -> Vec<(glam::DVec3, Vec<(Text, f64)>, u32)> { let target = self.mob_hit().map(|(i, _)| self.mobs[i].id); - let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); - let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); - let up = right.cross(forward).normalize_or_zero(); - let white = self.res.atlas.font.white(); let viewer = self.player_team(); - for m in &self.mobs { - let Some(name) = m.custom_name.as_deref() else { - continue; - }; + let mut tags = Vec::new(); + let players = self.other_players(); + let named = self + .mobs + .iter() + .filter_map(|m| Some((m, m.custom_name.clone()?, false))); + let players = players.into_iter().map(|(m, name)| (m, name, true)); + for (m, name, player) in named.chain(players) { if !m.alive() { continue; } + // EntityAttachment.NAME_TAG: 0.5 above the (crouching) height. + let height = if player && m.extra.crouching { + 1.5 + } else { + f64::from(m.height()) + }; let p = glam::DVec3::new( m.previous.x + (m.position.x - m.previous.x) * alpha, - m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5, + m.previous.y + (m.position.y - m.previous.y) * alpha + height + 0.5, m.previous.z + (m.position.z - m.previous.z) * alpha, ); // The name tag distance (64) is measured to the entity. @@ -72,7 +109,17 @@ impl Game<'_> { if distance_sqr >= 64.0 * 64.0 { continue; } - let team = self.mob_team(m.id); + // A player's scores and team go by name, a mob's by UUID. + let holder = if player { + Some(name.clone()) + } else { + self.persist.uuids.get(&m.id).map(|u| uuid_text(*u)) + }; + let team = if player { + self.score.board.players_team(&name) + } else { + self.mob_team(m.id) + }; // LivingEntityRenderer.shouldShowName (team rules included), then // MobRenderer: a visible name, or the mob under the crosshair. let invisible = sb::invisible_to( @@ -82,27 +129,31 @@ impl Game<'_> { m.has_effect("minecraft:invisibility"), ); let view = sb::NameView { - discrete: false, + discrete: player && m.extra.crouching, distance_sqr, invisible_to_viewer: invisible, hud_hidden: self.ui.hide_gui, is_camera: false, is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)), }; - if !sb::name_shown(team, viewer, view) || !(m.name_visible || Some(m.id) == target) { + // MobRenderer.shouldShowName: a visible name, or the mob under the + // crosshair; players (LivingEntityRenderer) need neither. + if !sb::name_shown(team, viewer, view) + || !(player || m.name_visible || Some(m.id) == target) + { continue; } - // getDisplayName: the custom name in the team's prefix, suffix and colour. + // getDisplayName: the name in the team's prefix, suffix and colour. let shown = match team { - Some(t) => t.formatted_name(Text::literal(name)), - None => Text::literal(name), + Some(t) => t.formatted_name(Text::literal(&name)), + None => Text::literal(&name), }; let mut lines = Vec::new(); // EntityRenderer.extractNameTags: the score shows within the // below-name distance (10), under the name. let mut lift = 0.0; if distance_sqr < 10.0 * 10.0 - && let Some(score) = self.below_name_text(m.id) + && let Some(score) = holder.and_then(|h| self.below_name_text(&h)) { lines.push((score, 0.0)); lift = f64::from(9.0f32 * 1.15 * 0.025); @@ -110,11 +161,21 @@ impl Game<'_> { lines.push((shown, lift)); let l = self.world.light( m.position.x.floor() as i32, - (m.position.y + f64::from(m.height())).floor() as i32, + (m.position.y + height).floor() as i32, m.position.z.floor() as i32, ); let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); - let away = forward.as_vec3() * 0.002; + tags.push((p, lines, light)); + } + tags + } + pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); + let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); + let up = right.cross(forward).normalize_or_zero(); + let white = self.res.atlas.font.white(); + let away = forward.as_vec3() * 0.002; + for (p, lines, light) in self.name_tags(camera, alpha) { for (text, lift) in lines { let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3(); let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025); diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 374da7c29..b04337ba4 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -193,6 +193,7 @@ impl Game<'_> { Event::Changed => { self.settings.save(&Self::options_path()); self.apply_settings(); + self.sync_mods(); } Event::Close => { self.settings.save(&Self::options_path()); @@ -262,6 +263,14 @@ impl Game<'_> { font.reset_cache(); self.ui.chat.rescale(&self.res.atlas); } + // A new renderer (resource reload, first window) takes the loaded pack. + let stale = self + .renderer + .as_ref() + .is_some_and(|r| r.shader_pack_id() != self.shader_packs.id()); + if stale && let Err(e) = self.apply_shader_pack() { + log::warn!("Horizon: shader pack: {e}"); + } } /// `Window.updateFullscreenState`: a fullscreen change made by the window /// system is adopted by the option (`Minecraft.fullscreenStateChanged`). diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index ce0633615..cae85bc6c 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -6,7 +6,7 @@ use super::{Game, Screen}; use horizon_client::{ Result, - gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble}, + gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble, TriggerFeel}, keybinds::{KeyBinds, key_code, mouse_button}, mouse::Rotation, }; @@ -59,6 +59,11 @@ pub(super) struct Pads { /// Its own output over HID (rumble here; gilrs only reads it), started once this window /// has the pad in hand; dropped, it releases the pad. output: Option, + /// Its HD haptics, on USB: looked for once each time the output opens. + haptics: Option, + haptics_tried: bool, + /// What it was last told to show. + shown: Option, } fn gilrs_button(button: Button) -> gilrs::Button { @@ -188,6 +193,9 @@ impl Game<'_> { pub(super) fn poll_pads(&mut self, event_loop: &ActiveEventLoop) { let settings = &self.settings.controller; if !settings.enabled { + // Dropping the output frees the triggers. + self.pad.output = None; + self.pad.shown = None; if self.pad.state != PadState::default() { self.pad.state = PadState::default(); for (button, down) in self.pad.edges.release_all() { @@ -214,6 +222,8 @@ impl Game<'_> { if self.pad.dualsense && self.pad.in_use && self.focused && self.pad.output.is_none() { self.pad.output = Some(horizon_dualsense::Link::start()); } + self.pad_haptics(); + self.pad_show(); // Damage from any source, here or on a server; nothing counts on // the title screen. let health = self @@ -407,8 +417,136 @@ impl Game<'_> { (self.pad.dualsense && self.focused && output.open().is_some()).then_some(output) } + /// What the DualSense shows: while playing, its triggers feel what their actions do; in + /// menus, paused, unfocused or with another pad active, they are free. + fn pad_show(&mut self) { + if self.pad.output.is_none() { + return; + } + let playing = self.pad.dualsense + && self.focused + && self.title.is_none() + && self.screen == Screen::Playing + && !self.pause; + let (using, attacking) = if playing { + self.trigger_feels() + } else { + (TriggerFeel::Free, TriggerFeel::Free) + }; + // The lightbar follows the player; menus keep the last colour. + let in_world = self.title.is_none(); + let lightbar = match self.player.as_mut().filter(|_| in_world) { + Some(p) => { + let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; + let health = p.health.health() / max.max(1.0); + self.settings + .controller + .lightbar + .colour(health, self.dim.id()) + } + None => self.pad.shown.and_then(|s| s.lightbar), + }; + let lights = self.settings.controller.lightbar != gamepad::Lightbar::Off; + let state = horizon_dualsense::device::State { + triggers: self.settings.controller.trigger_effects(using, attacking), + lightbar: lightbar.filter(|_| lights), + player_leds: lights.then_some(horizon_dualsense::PLAYER_1), + }; + if self.pad.shown != Some(state) + && let Some(output) = &self.pad.output + { + output.set(state); + self.pad.shown = Some(state); + } + } + + /// What `key.use` and `key.attack` are doing, for the triggers bound to them. + fn trigger_feels(&self) -> (TriggerFeel, TriggerFeel) { + let using = match self.using { + Some((slot, ticks)) => match self.stack_in(slot) { + Some(s) if &*s.item == "minecraft:bow" => { + TriggerFeel::Draw(gamepad::bow_power(ticks)) + } + // TridentItem.THROW_THRESHOLD_TIME. + Some(s) if &*s.item == "minecraft:trident" => { + TriggerFeel::Draw(ticks as f32 / 10.0) + } + Some(s) if &*s.item == "minecraft:crossbow" => { + TriggerFeel::Draw(ticks as f32 / Self::charge_ticks(s).max(1) as f32) + } + Some(s) if self.blocks_attacks(s).is_some() => TriggerFeel::Brace, + _ => TriggerFeel::Free, + }, + None => self.idle_use_feel(), + }; + // Creative breaks at once; blocks that can't be broken have a negative hardness. + let attacking = match &self.mining { + Some(m) if !self.creative => { + let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); + TriggerFeel::Texture(self.res.facts.get(state).hardness) + } + _ => TriggerFeel::Free, + }; + (using, attacking) + } + + /// The use trigger while nothing is in use: a loaded crossbow clicks, an item that boosts (a + /// rocket while gliding, the stick of the mount being ridden) catches, a shield weighs, and + /// locks while an axe has disabled it. + fn idle_use_feel(&self) -> TriggerFeel { + let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying); + let mount = self + .riding + .and_then(|id| self.mobs.iter().find(|m| m.id == id)); + let mount = mount.map_or("", |m| m.kind.id.as_str()); + let feel = |stack: Option<&horizon_client::items::ItemStack>| match stack + .map(|s| (s, &*s.item)) + { + Some((s, "minecraft:crossbow")) if s.data().is_some_and(|d| !d.charged.is_empty()) => { + TriggerFeel::Click + } + Some((_, "minecraft:firework_rocket")) if gliding => TriggerFeel::Boost, + Some((_, "minecraft:carrot_on_a_stick")) if mount == "minecraft:pig" => { + TriggerFeel::Boost + } + Some((_, "minecraft:warped_fungus_on_a_stick")) if mount == "minecraft:strider" => { + TriggerFeel::Boost + } + Some((s, _)) if self.blocks_attacks(s).is_some() => match self.shield_cooldown { + 0 => TriggerFeel::Brace, + _ => TriggerFeel::Locked, + }, + _ => TriggerFeel::Free, + }; + // Use tries the main hand first. + match feel(self.stack_in(self.selected)) { + TriggerFeel::Free => feel(self.offhand.as_ref()), + main => main, + } + } + + /// Open the pad's haptics once its output is open over USB (its audio device is there + /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until + /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). + fn pad_haptics(&mut self) { + let usb = self.pad.output.as_ref().and_then(|o| o.open()) + == Some(horizon_dualsense::Transport::Usb); + if !usb { + self.pad.haptics = None; + self.pad.haptics_tried = false; + } else if !self.pad.haptics_tried { + self.pad.haptics_tried = true; + if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") + && std::env::var_os("HORIZON_NO_AUDIO").is_none() + { + self.pad.haptics = horizon_dualsense::haptics::Haptics::open(); + } + } + } + /// Release the DualSense's output (the game is quitting). pub(super) fn pad_close_output(&mut self) { + self.pad.haptics = None; self.pad.output = None; } @@ -426,9 +564,28 @@ impl Game<'_> { }; self.pad.last_rumble = Some((rumble.name(), pulse)); let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if let Some(haptics) = self + .pad + .haptics + .as_ref() + .filter(|_| self.pad_output().is_some()) + { + let steps = rumble.shape().into_iter().map(|step| { + ( + step.strong, + step.weak, + Duration::from_millis(u64::from(step.millis)), + ) + }); + haptics.play(&steps.collect::>()); + return; + } if let Some(output) = self.pad_output() { - let length = Duration::from_millis(u64::from(pulse.millis)); - output.rumble(vec![([level(pulse.strong), level(pulse.weak)], length)]); + let steps = rumble.shape().into_iter().map(|step| { + let length = Duration::from_millis(u64::from(step.millis)); + ([level(step.strong), level(step.weak)], length) + }); + output.rumble(steps.collect()); return; } let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { @@ -513,6 +670,7 @@ impl Game<'_> { "glyphs": self.pad.style.name(), "dualsense_output": self.pad.output.as_ref().and_then(|o| o.open()) .map(|t| format!("{t:?}")), + "trigger_effects": self.pad.shown.map(|s| s.triggers), "last_rumble": self.pad.last_rumble.map(|(why, p)| json!({ "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, })), diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 09d6d4a36..06bb7f6d0 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -254,6 +254,7 @@ impl Game<'_> { return; }; for p in &self.paintings { + let entity_start = out.len(); let Some(v) = self.painting_variants.get(&p.variant) else { continue; }; @@ -366,6 +367,7 @@ impl Game<'_> { strip, 0.6, ); + self.cull_entity_vertices(out, entity_start); } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ddef62cbb..87d907792 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -831,6 +831,21 @@ impl Game<'_> { } } C::BlockChangedAck(_) => {} + // ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids, + // shulker boxes, bells) when the block is still the one it names. + C::BlockEvent(p) => { + let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); + let block = &self.res.facts.get(state).name; + let named = self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:block")? + .name(p.block) + .map(str::to_owned) + }); + if named.as_deref() == Some(&**block) { + self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + } + } C::LevelEvent(p) if p.kind == 2015 => { self.dragon_egg_particles(p.pos, p.data); } @@ -979,6 +994,29 @@ impl Game<'_> { } } } + // ClientPacketListener.handleSetEquipment: what a mob or another + // player holds and wears (EquipmentSlot ordinals). + C::SetEquipment(p) => { + let items: Vec<(u8, Option>)> = p + .slots + .iter() + .map(|(slot, stack)| (*slot, stack.as_ref().map(|s| self.item_name(s.item)))) + .collect(); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + for (slot, item) in items { + let e = &mut m.extra; + match slot { + 0 => e.main_hand = item, + 1 => e.off_hand = item, + 2 => e.feet = item, + 3 => e.legs = item, + 4 => e.chest = item, + 5 => e.head = item, + _ => {} + } + } + } + } C::TakeItemEntity(p) => { if self .remote @@ -1695,6 +1733,8 @@ impl Game<'_> { // ClientLevel.tick: the border's size change. self.border.tick(); self.tick_remote_entities(); + // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. + self.tick_block_entity_anims(); self.tick_hand(); self.tick_particles(); let Some(player) = self.player.as_mut() else { @@ -1786,6 +1826,8 @@ impl Game<'_> { // The server owns health and hunger: undo local food/fall changes. self.apply_remote_health(); self.tick_avatar(before, false); + // The player's own model (third person, the inventory's preview). + self.tick_player_model(); if !dead { self.remote_mining(); if self.right && self.use_delay == 0 && playing { @@ -2736,6 +2778,18 @@ impl Game<'_> { } } /// Status for `horizon-ctl status`. + /// The other players' entities in the level and their names (from the + /// player list). + pub(super) fn remote_player_names(&self) -> Vec<(u32, String)> { + let Some(r) = self.remote.as_ref() else { + return Vec::new(); + }; + r.level_players + .iter() + .filter(|(_, uuid)| **uuid != r.profile) + .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone()))) + .collect() + } pub(super) fn remote_status(&self) -> Option { let r = self.remote.as_ref()?; Some(serde_json::json!({ @@ -2753,12 +2807,30 @@ impl Game<'_> { }), "players": r.players.values().collect::>(), // Where the other players' entities are (harnesses check movement). + // What the other players hold and wear, as this client draws them. + "player_equipment": self + .mobs + .iter() + .filter(|m| r.level_players.contains_key(&(m.id as i32))) + .map(|m| { + let e = &m.extra; + let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()); + serde_json::json!({ + "id": m.id, + "armor": armor, + "main_hand": e.main_hand.as_deref(), + "off_hand": e.off_hand.as_deref(), + }) + }) + .collect::>(), "player_positions": r .entities .values() .filter(|t| t.kind == "minecraft:player") .map(|t| t.position) .collect::>(), + // The player's own model exists (third person and the inventory draw it). + "player_model": self.player_model.is_some(), "health": r.health.0, "food": r.health.1, "decode_errors": r.decode_errors, diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 10e8ffd13..bc08df07c 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -97,6 +97,39 @@ impl Game<'_> { boss_world_fog: self.dragon_bar_shown(), }) } + /// What a shader pack's `Frame` uniform reads of the game this frame. + pub(super) fn shader_inputs( + &self, + camera: glam::DVec3, + partial_tick: f32, + ) -> horizon_client::gfx::ShaderInputs { + let (rain, thunder) = if self.dim == Dim::Overworld { + self.world.weather.levels(self.clock.fraction() as f32) + } else { + (0.0, 0.0) + }; + let at = [camera.x, camera.y, camera.z]; + let day = self.world.day_time; + horizon_client::gfx::ShaderInputs { + rain, + thunder, + submerged: match fog_type(&self.world, &self.res.facts, at, self.forward()) { + FogType::Atmospheric => 0, + FogType::Water => 1, + FogType::Lava => 2, + FogType::PowderSnow => 3, + }, + dimension: match self.dim { + Dim::Overworld => 0, + Dim::Nether => -1, + Dim::End => 1, + }, + has_sky_light: self.dim == Dim::Overworld, + moon_phase: day.div_euclid(24_000).rem_euclid(8) as u8, + day_fraction: (day.rem_euclid(24_000) as f32 + partial_tick) / 24_000.0, + partial_tick, + } + } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { camera.y < 63.0 diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs new file mode 100644 index 000000000..ddccdcee6 --- /dev/null +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -0,0 +1,92 @@ +//! The selected Horizon shader pack (`shaderPack` in `horizon-graphics.txt`, +//! docs/shader-packs.md): loaded from `shaderpacks/`, given to the renderer, +//! and loaded again when the selection changes, on F3 + T, or when its files +//! change (checked twice a second). A pack that fails leaves the last good +//! one (or the vanilla picture) on and says why in chat. +use super::Game; +use horizon_client::shader_pack::{self, ShaderPack, Stamp}; +use horizon_client::text::Text; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; + +#[derive(Default)] +pub(super) struct ShaderPacks { + /// The pack the renderer runs. + pack: Option, + /// The selection and its files at the last load, success or not. + selected: String, + stamp: Stamp, + checked: Option, +} + +impl ShaderPacks { + /// The loaded pack's folder name. + pub(super) fn id(&self) -> Option<&str> { + self.pack.as_ref().map(|p| p.id.as_str()) + } +} + +/// `shaderpacks/` beside `options.txt`. +pub(super) fn dir() -> PathBuf { + std::env::current_dir() + .unwrap_or_default() + .join(shader_pack::DIR) +} + +impl Game<'_> { + /// Load the selected pack and give it to the renderer. + pub(super) fn load_shader_pack(&mut self) { + let id = self.settings.horizon.shader_pack.clone(); + let dir = dir(); + let state = &mut self.shader_packs; + state.selected = id.clone(); + state.checked = Some(Instant::now()); + let pack = if id.is_empty() { + state.stamp = Stamp::default(); + None + } else { + state.stamp = Stamp::of(&dir.join(&id)); + match ShaderPack::load(&dir.join(&id), &shader_pack::load_values(&dir, &id)) { + Ok(pack) => Some(pack), + Err(e) => return self.shader_pack_error(&id, &e), + } + }; + if let Some(r) = self.renderer.as_mut() + && let Err(e) = r.set_shader_pack(pack.as_ref()) + { + return self.shader_pack_error(&id, &e.to_string()); + } + self.shader_packs.pack = pack; + } + /// Give the loaded pack to the renderer (also after it is rebuilt). + pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { + match self.renderer.as_mut() { + Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()), + None => Ok(()), + } + } + /// Every frame: a new selection or edited pack files load it again. + pub(super) fn poll_shader_pack(&mut self) { + let state = &mut self.shader_packs; + if self.settings.horizon.shader_pack != state.selected { + return self.load_shader_pack(); + } + if state.selected.is_empty() + || state + .checked + .is_some_and(|t| t.elapsed() < Duration::from_millis(500)) + { + return; + } + state.checked = Some(Instant::now()); + if Stamp::of(&dir().join(&state.selected)) != state.stamp { + self.load_shader_pack(); + } + } + fn shader_pack_error(&mut self, id: &str, error: &str) { + log::warn!("Horizon: shader pack {id}: {error}"); + self.system_message(Text::literal(format!("Shader pack {id}: {error}"))); + } +} diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 733dae55f..849c62958 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -30,7 +30,10 @@ impl Game<'_> { &mut self.inventory[slot] } } - fn blocks_attacks(&self, stack: &ItemStack) -> Option<&horizon_client::items::BlocksAttacks> { + pub(super) fn blocks_attacks( + &self, + stack: &ItemStack, + ) -> Option<&horizon_client::items::BlocksAttacks> { self.res.items.get(&stack.item)?.blocks_attacks.as_ref() } /// `ShieldItem.use` (ItemUtils.startUsingInstantly) for the hand at `slot`; diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client/src/gamepad.rs index d67121fbf..a250f5e8c 100644 --- a/crates/horizon-client/src/gamepad.rs +++ b/crates/horizon-client/src/gamepad.rs @@ -385,6 +385,9 @@ pub fn steam_keyboard(choice: TextKeyboard) -> bool { pub struct PadSettings { pub enabled: bool, pub vibration: bool, + /// A DualSense's triggers push back (Horizon's; docs/controllers.md). + pub adaptive_triggers: bool, + pub lightbar: Lightbar, /// 0..1; 0.5 is the default speed, 1 twice that. pub look_sensitivity: f32, pub invert_x: bool, @@ -407,6 +410,8 @@ impl Default for PadSettings { Self { enabled: true, vibration: true, + adaptive_triggers: true, + lightbar: Lightbar::Health, look_sensitivity: 0.5, invert_x: false, invert_y: false, @@ -460,6 +465,8 @@ impl PadSettings { match key.trim() { "enabled" => s.enabled = flag(s.enabled), "vibration" => s.vibration = flag(s.vibration), + "adaptiveTriggers" => s.adaptive_triggers = flag(s.adaptive_triggers), + "lightbar" => s.lightbar = Lightbar::parse(value), "lookSensitivity" => s.look_sensitivity = unit(s.look_sensitivity), "invertX" => s.invert_x = flag(s.invert_x), "invertY" => s.invert_y = flag(s.invert_y), @@ -490,9 +497,11 @@ impl PadSettings { } pub fn serialize(&self) -> String { let mut text = format!( - "enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\nmenuNavigation:{}\nkeyboard:{}\n", + "enabled:{}\nvibration:{}\nadaptiveTriggers:{}\nlightbar:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\nmenuNavigation:{}\nkeyboard:{}\n", bool_text(self.enabled), bool_text(self.vibration), + bool_text(self.adaptive_triggers), + self.lightbar.name(), self.look_sensitivity, bool_text(self.invert_x), bool_text(self.invert_y), @@ -945,6 +954,179 @@ impl Rumble { }), } } + + /// The pulse shaped, for a pad that plays steps (a DualSense): a hit starts at full + /// strength and dies away, an explosion rolls on, a totem swells; a broken block is a tick. + pub fn shape(self) -> Vec { + let Some(p) = self.pulse() else { + return Vec::new(); + }; + let step = |level: f32, millis: u32| Pulse { + strong: p.strong * level, + weak: p.weak * level, + millis, + }; + match self { + Rumble::BlockBroken => vec![Pulse { millis: 35, ..p }], + Rumble::Hurt(_) => { + let tail = p.millis.saturating_sub(50) / 2; + vec![step(1.0, 50), step(0.55, tail), step(0.25, tail)] + } + Rumble::Explosion { .. } => vec![ + step(1.0, 80), + step(0.6, 150), + step(0.35, 150), + step(0.15, 150), + ], + Rumble::Totem => vec![ + step(0.4, 100), + step(0.7, 100), + step(1.0, 200), + step(0.5, 100), + ], + } + } +} + +/// What a trigger feels like on a DualSense, from what its action is doing (docs/controllers.md +/// "Adaptive triggers" for the choices). Only the pad's official modes: Nielk1's notes warn the +/// others may leave the firmware. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum TriggerFeel { + Free, + /// Drawing a bow, charging a trident, loading a crossbow: resistance that grows with the + /// charge, 0..1. + Draw(f32), + /// A loaded crossbow: a gun trigger's catch that gives way where it fires. + Click, + /// Pulling it boosts (a rocket while gliding, the stick while riding a pig or a strider): + /// a lighter catch that gives way where it fires. + Boost, + /// A shield in the use hand, raised or ready: its weight. + Brace, + /// That shield disabled by an axe: the trigger locks until it recovers. + Locked, + /// Mining a block of this hardness: a buzz, stronger and slower on harder blocks. + Texture(f32), +} +impl TriggerFeel { + /// The effect, for a trigger that presses its action at `threshold` (0..1) of its travel. + pub fn effect(self, threshold: f32) -> horizon_dualsense::TriggerEffect { + use horizon_dualsense::trigger; + // The zone (of ten along the travel) where the action presses: a catch gives way there, + // so the click and the shot coincide. + let press = ((threshold.clamp(0.0, 1.0) * 10.0) as u8).clamp(3, 8); + match self { + TriggerFeel::Free => horizon_dualsense::TRIGGER_OFF, + // From the third zone, so the press itself stays light; at most 6 of 8, as the + // draw is held. + TriggerFeel::Draw(charge) => { + trigger::feedback(2, 1 + (5.0 * charge.clamp(0.0, 1.0)).round() as u8) + } + TriggerFeel::Click => trigger::weapon((press - 2).max(2), press, 8), + TriggerFeel::Boost => trigger::weapon((press - 2).max(2), press, 5), + TriggerFeel::Brace => trigger::feedback(2, 3), + TriggerFeel::Locked => trigger::feedback(1, 8), + TriggerFeel::Texture(hardness) if hardness > 0.0 => { + // Dirt 2, stone 3, deepslate 4, obsidian 5 of 8. + let amplitude = (1.0 + 1.6 * hardness.sqrt()).round().clamp(1.0, 5.0); + // Sand and dirt a fine 40 Hz grit; stone 30; wood, deepslate and ores 20; + // obsidian a 10 Hz chisel. + let hertz = match hardness { + h if h < 1.0 => 40, + h if h < 2.0 => 30, + h if h < 5.0 => 20, + _ => 10, + }; + trigger::vibration(1, amplitude as u8, hertz) + } + TriggerFeel::Texture(_) => horizon_dualsense::TRIGGER_OFF, + } + } +} +impl PadSettings { + /// The left and right triggers' effects: each feels the action bound to it, `key.use` or + /// `key.attack`. + pub fn trigger_effects( + &self, + using: TriggerFeel, + attacking: TriggerFeel, + ) -> [horizon_dualsense::TriggerEffect; 2] { + [Button::LeftTrigger, Button::RightTrigger].map(|trigger| { + let actions = self.actions_of(trigger); + let feel = if !self.adaptive_triggers { + TriggerFeel::Free + } else if actions.contains(&"key.use") { + using + } else if actions.contains(&"key.attack") { + attacking + } else { + TriggerFeel::Free + }; + feel.effect(self.trigger_threshold) + }) + } +} +/// What a DualSense's lightbar shows (`lightbar:`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lightbar { + /// Green at full health through amber to red. + Health, + /// A colour per dimension. + Dimension, + /// The pad's own. + Off, +} +impl Lightbar { + pub const ALL: [Lightbar; 3] = [Lightbar::Health, Lightbar::Dimension, Lightbar::Off]; + pub fn name(self) -> &'static str { + match self { + Lightbar::Health => "health", + Lightbar::Dimension => "dimension", + Lightbar::Off => "off", + } + } + pub fn parse(name: &str) -> Self { + match name.trim() { + "dimension" => Lightbar::Dimension, + "off" => Lightbar::Off, + _ => Lightbar::Health, + } + } + /// The colour for a player with this share of their health in this dimension; at half + /// brightness, as the pad's full light is glaring. + pub fn colour(self, health: f32, dimension: &str) -> Option<[u8; 3]> { + let rgb = match self { + Lightbar::Off => return None, + Lightbar::Health => { + // Green to amber over the top half, amber to red below it. + let (green, amber, red) = ( + [34.0, 197.0, 94.0], + [245.0, 158.0, 11.0], + [239.0, 68.0, 68.0], + ); + let h = health.clamp(0.0, 1.0); + let (from, to, k) = if h >= 0.5 { + (amber, green, (h - 0.5) * 2.0) + } else { + (red, amber, h * 2.0) + }; + [0, 1, 2].map(|i| from[i] + (to[i] - from[i]) * k) + } + Lightbar::Dimension => match dimension { + "minecraft:the_nether" => [234.0, 88.0, 12.0], + "minecraft:the_end" => [139.0, 92.0, 246.0], + _ => [14.0, 165.0, 233.0], + }, + }; + Some(rgb.map(|v| (v * 0.5).round() as u8)) + } +} + +/// `BowItem.getPowerForTime`: a bow's draw after this many ticks, 0..1. +pub fn bow_power(ticks: u32) -> f32 { + let f = ticks as f32 / 20.0; + ((f * f + f * 2.0) / 3.0).min(1.0) } #[cfg(test)] @@ -1222,6 +1404,76 @@ mod tests { assert_eq!(w.observe(Some(1.0)), Some(1.0)); } + #[test] + fn triggers_feel_their_action() { + use horizon_dualsense::{TRIGGER_OFF, trigger}; + let mut s = PadSettings::default(); + // Use is LT, attack RT by default. + let [left, right] = s.trigger_effects(TriggerFeel::Draw(1.0), TriggerFeel::Texture(1.5)); + assert_eq!(left, trigger::feedback(2, 6)); + assert_eq!(right, trigger::vibration(1, 3, 30)); + assert_eq!( + s.trigger_effects(TriggerFeel::Draw(0.0), TriggerFeel::Free), + [trigger::feedback(2, 1), TRIGGER_OFF] + ); + // The catch gives way in the zone where the default threshold (0.4) presses: weapon + // 0x25, zones 2 and 4, strength 8 (stored 7) or 5 (stored 4). + let catch = |strength| [0x25, 0x14, 0x00, strength, 0, 0, 0, 0, 0, 0, 0]; + assert_eq!(TriggerFeel::Click.effect(0.4), catch(7)); + assert_eq!(TriggerFeel::Boost.effect(0.4), catch(4)); + // A deeper threshold moves it: zones 5 and 7. + assert_eq!(TriggerFeel::Click.effect(0.7)[1..3], [0xa0, 0x00]); + assert_eq!(TriggerFeel::Click.effect(0.1), trigger::weapon(2, 3, 8)); + assert_eq!(TriggerFeel::Brace.effect(0.4), trigger::feedback(2, 3)); + assert_eq!(TriggerFeel::Locked.effect(0.4), trigger::feedback(1, 8)); + // Harder blocks buzz harder and slower; instant-break blocks don't. + assert_eq!( + TriggerFeel::Texture(0.5).effect(0.4), + trigger::vibration(1, 2, 40) + ); + assert_eq!( + TriggerFeel::Texture(3.0).effect(0.4), + trigger::vibration(1, 4, 20) + ); + assert_eq!( + TriggerFeel::Texture(50.0).effect(0.4), + trigger::vibration(1, 5, 10) + ); + assert_eq!(TriggerFeel::Texture(0.0).effect(0.4), TRIGGER_OFF); + assert_eq!(TriggerFeel::Texture(-1.0).effect(0.4), TRIGGER_OFF); + s.adaptive_triggers = false; + assert_eq!( + s.trigger_effects(TriggerFeel::Click, TriggerFeel::Boost), + [TRIGGER_OFF; 2] + ); + assert!(!PadSettings::parse(&s.serialize()).adaptive_triggers); + } + + #[test] + fn lightbar_colours() { + let full = Lightbar::Health.colour(1.0, "minecraft:overworld").unwrap(); + let empty = Lightbar::Health.colour(0.0, "minecraft:overworld").unwrap(); + assert!(full[1] > full[0], "green at full health: {full:?}"); + assert!(empty[0] > empty[1], "red when dying: {empty:?}"); + assert_eq!(Lightbar::Health.colour(0.5, ""), Some([123, 79, 6])); + assert_ne!( + Lightbar::Dimension.colour(1.0, "minecraft:the_nether"), + Lightbar::Dimension.colour(1.0, "minecraft:overworld") + ); + assert_eq!(Lightbar::Off.colour(1.0, ""), None); + for l in Lightbar::ALL { + assert_eq!(Lightbar::parse(l.name()), l); + } + } + + #[test] + fn bow_draw() { + assert_eq!(bow_power(0), 0.0); + assert!((bow_power(10) - 5.0 / 12.0).abs() < 1e-6); + assert_eq!(bow_power(20), 1.0); + assert_eq!(bow_power(40), 1.0); + } + #[test] fn rumble_pulses() { let small = Rumble::Hurt(1.0).pulse().unwrap(); @@ -1251,6 +1503,26 @@ mod tests { None ); assert_eq!(Rumble::BlockBroken.pulse().unwrap().strong, 0.0); + // Shapes open at the pulse's strength and fade; nothing for what isn't felt. + for rumble in [ + Rumble::Hurt(4.0), + Rumble::Explosion { + distance: 2.0, + radius: 4.0, + }, + ] { + let (pulse, shape) = (rumble.pulse().unwrap(), rumble.shape()); + assert_eq!(shape[0].strong, pulse.strong); + assert!(shape.windows(2).all(|w| w[1].strong < w[0].strong)); + } + let hurt: u32 = Rumble::Hurt(4.0).shape().iter().map(|s| s.millis).sum(); + assert!(hurt.abs_diff(Rumble::Hurt(4.0).pulse().unwrap().millis) <= 1); + assert_eq!( + Rumble::Totem.shape().iter().map(|s| s.millis).sum::(), + 500 + ); + assert_eq!(Rumble::BlockBroken.shape()[0].millis, 35); + assert!(Rumble::Hurt(0.0).shape().is_empty()); } #[test] diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 8d096c3c5..5c9a2b217 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -59,6 +59,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod occlusion; +mod pack_stages; pub mod panorama; mod timing; mod world_post; @@ -173,6 +174,25 @@ pub struct Frame<'a> { /// `Screen.extractBlurredBackground`: blur the frame by this radius /// (`menuBackgroundBlurriness`) before the screen is drawn over it. pub menu_blur: Option, + /// What a shader pack's `Frame` uniform reads beyond the rest of the frame. + pub shader: ShaderInputs, +} +/// A shader pack's view of the game this frame (docs/shader-packs.md, `Frame`). +#[derive(Clone, Copy, Debug, Default)] +pub struct ShaderInputs { + /// `Level.getRainLevel` and `getThunderLevel` at the partial tick. + pub rain: f32, + pub thunder: f32, + /// The camera's fog type: 0 air, 1 water, 2 lava, 3 powder snow. + pub submerged: u8, + /// 0 overworld, -1 the Nether, 1 the End. + pub dimension: i8, + pub has_sky_light: bool, + /// `DimensionType.moonPhase`, 0..=7. + pub moon_phase: u8, + /// The time of day as a fraction (0 sunrise, 0.25 noon) and the partial tick. + pub day_fraction: f32, + pub partial_tick: f32, } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -272,7 +292,7 @@ pub struct Renderer { indirect: wgpu::Buffer, indirect_capacity: u64, /// Indirect draws may set `first_instance` (the section origin). - multi_draw: bool, + pub multi_draw: bool, /// Per-frame scratch, kept to avoid allocating every frame. visible: Vec, origins: Vec<[f32; 4]>, @@ -287,6 +307,8 @@ pub struct Renderer { occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). world_post: world_post::Post, + /// The selected shader pack's stages (Horizon setting; none by default). + pack: Option, pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, @@ -336,10 +358,10 @@ fn mip_chain( for image in crate::mipmap::generate( base, levels - 1, - s.strategy, - s.alpha_cutoff_bias, - has_transparent, - s.item, + crate::mipmap::Settings { + has_transparent, + ..s + }, ) { out.extend(image.pixels.iter().flatten()); } @@ -1434,6 +1456,7 @@ impl Renderer { block_entities: HashMap::new(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), world_post, + pack: None, hud, post: None, menu_blur: None, @@ -1567,6 +1590,9 @@ impl Renderer { pub fn section_count(&self) -> usize { self.sections.len() } + pub fn has_section(&self, key: SectionKey) -> bool { + self.sections.contains_key(&key) + } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); if mesh.block_entities.is_empty() { @@ -1653,6 +1679,23 @@ impl Renderer { self.occlusion.remove(key); self.release_section(key); } + /// Run `pack`'s stages over the world from now on (`None`: no pack, the + /// vanilla frame). On error the previous pack stays. + pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> { + self.pack = match pack { + Some(pack) => Some(pack_stages::PackStages::new( + &self.device, + self.config.format.remove_srgb_suffix(), + pack, + )?), + None => None, + }; + Ok(()) + } + /// The folder name of the pack `set_shader_pack` gave. + pub fn shader_pack_id(&self) -> Option<&str> { + self.pack.as_ref().map(|p| p.id.as_str()) + } /// Horizon's resolution scale (world pixels per window pixel) and FXAA. pub fn set_world_post(&mut self, scale: f32, antialias: bool) { self.world_post.scale = scale.clamp(0.25, 2.0); @@ -1957,6 +2000,15 @@ impl Renderer { }; self.queue .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals)); + let pack_uniform = shader_pack_uniform( + frame, + view, + world_projection(frame.fov_degrees, aspect, frame.depth_far) * frame.bob, + sun, + fog_color, + globals.fog, + globals.fog_ends, + ); // GameRenderer.render3dHud: the hand's projection at hudFov, with the // bob in its pose rather than the projection (same product). let hand_projection = Mat4::from_cols_array(&crate::camera::hand_projection( @@ -2177,9 +2229,10 @@ impl Renderer { timer.begin(&mut encoder); } // The world's targets: the screen, or the scaled target of `post`. - let scaled = self - .world_post - .prepare(&self.device, [self.config.width, self.config.height]); + let pack = self.pack.is_some() && !frame.title; + let scaled = + self.world_post + .prepare(&self.device, [self.config.width, self.config.height], pack); let (world_view, world_depth) = match &scaled { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), @@ -2212,7 +2265,12 @@ impl Renderer { view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), - store: wgpu::StoreOp::Discard, + // A shader pack reads the world's depth. + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, }), stencil_ops: None, }), @@ -2322,7 +2380,22 @@ impl Renderer { ); } } - if scaled.is_some() { + if let (true, Some((color, depth)), Some(size), Some(stages)) = + (pack, &scaled, self.world_post.size(), self.pack.as_mut()) + { + let output = stages.run( + &self.device, + &self.queue, + &mut encoder, + color, + depth, + size, + &self.world_post, + pack_uniform, + ); + self.world_post + .finish_with(&mut encoder, &view_target, output); + } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } if hand_quads > 0 { @@ -2587,6 +2660,59 @@ impl Frustum { /// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests /// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like /// fire_side's 0.01 pixel in front of its block, from z-fighting. +/// The prelude's `Frame` (`shader_pack_prelude.wgsl`); `resolution` and the +/// time are filled per stage. +fn shader_pack_uniform( + frame: &Frame, + view: Mat4, + projection: Mat4, + sun: Vec3, + fog_color: [f32; 4], + fog: [f32; 4], + fog_ends: [f32; 4], +) -> pack_stages::FrameUniform { + let s = frame.shader; + let sky = frame.sky.sky_color; + pack_stages::FrameUniform { + view: view.to_cols_array_2d(), + projection: projection.to_cols_array_2d(), + inverse_view: view.inverse().to_cols_array_2d(), + inverse_projection: projection.inverse().to_cols_array_2d(), + camera_position: [ + frame.camera.x as f32, + frame.camera.y as f32, + frame.camera.z as f32, + 0.0, + ], + time: [0.0, 0.0, s.day_fraction, s.partial_tick], + sun: [sun.x, sun.y, sun.z, frame.sky.sun_angle.to_radians()], + moon: [-sun.x, -sun.y, -sun.z, f32::from(s.moon_phase)], + sky_color: [sky[0], sky[1], sky[2], 1.0], + fog_color, + fog: [fog[0], fog[1], fog_ends[0], fog_ends[1]], + weather: [s.rain, s.thunder, 0.0, 0.0], + camera_state: [ + f32::from(s.submerged), + frame.night_vision, + frame.darkness.1, + 0.0, + ], + view_params: [ + 0.05, + frame.depth_far, + frame.distance, + frame.fov_degrees.to_radians(), + ], + dimension: [ + f32::from(s.dimension), + f32::from(u8::from(s.has_sky_light)), + 0.0, + 0.0, + ], + ..Default::default() + } +} + fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 { Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05) } @@ -2749,7 +2875,8 @@ const ANIMATION_MIP_ENTRIES: usize = 4096; /// renderer on resource reload drops this entire snapshot, including its cache: /// frame indices can never alias another resource's pixels, size or settings. struct AnimatedSprites { - animations: Vec<(SpriteAnimation, usize)>, + /// Each animated sprite and what its layer holds (`None`: not uploaded yet). + animations: Vec<(SpriteAnimation, Option)>, size: u32, settings: Vec, // Cache bookkeeping must not consume randomness or affect other maps' seeding. @@ -2765,11 +2892,7 @@ impl AnimatedSprites { settings: &[crate::mipmap::Settings], ) -> Self { Self { - animations: animations - .iter() - .cloned() - .map(|a| (a, usize::MAX)) - .collect(), + animations: animations.iter().cloned().map(|a| (a, None)).collect(), size, settings: settings.to_vec(), cache: Default::default(), @@ -2786,35 +2909,53 @@ fn animate_sprites( ) { let size = state.size; let levels = size.trailing_zeros() + 1; - for (index, (animation, previous)) in state.animations.iter_mut().enumerate() { - let frame = animation.frame(tick); - if frame == *previous { + let AnimatedSprites { + animations, + settings, + cache, + cache_bytes, + budget, + .. + } = state; + for (index, (animation, previous)) in animations.iter_mut().enumerate() { + let blend = animation.blend(tick); + if *previous == Some(blend) { continue; } - *previous = frame; - let room = state.cache.len() < ANIMATION_MIP_ENTRIES; - let uncached; - let mips: &[u8] = match state.cache.entry((index, frame)) { - std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), - std::collections::hash_map::Entry::Vacant(entry) => { - let (pixels, _) = mip_chain( - animation.pixels(frame), - size, - &state.settings, - animation.layer, - 1, - ); - // Bound both pixel storage and map metadata. Keep admitted - // frames rather than churning them on large/unique workloads; - // frames that do not fit still use the same generation path. - if room && pixels.capacity() <= state.budget - state.cache_bytes { - state.cache_bytes += pixels.capacity(); - entry.insert(pixels) - } else { - uncached = pixels; - &uncached - } - } + *previous = Some(blend); + let (animation, settings) = (&*animation, &**settings); + let chain = |frame: usize| { + move || mip_chain(animation.pixels(frame), size, settings, animation.layer, 1).0 + }; + let (current, mixed); + let mips: &[u8] = if blend.millis > 0 { + let mut mix = frame_mips( + cache, + cache_bytes, + *budget, + (index, blend.frame), + chain(blend.frame), + ) + .into_owned(); + let next = frame_mips( + cache, + cache_bytes, + *budget, + (index, blend.next), + chain(blend.next), + ); + mix_frames(&mut mix, &next, blend.millis); + mixed = mix; + &mixed + } else { + current = frame_mips( + cache, + cache_bytes, + *budget, + (index, blend.frame), + chain(blend.frame), + ); + ¤t }; let mut offset = 0; for level in 0..levels.min(max_levels) { @@ -2825,10 +2966,99 @@ fn animate_sprites( } } } +/// `animate_sprite_interpolate.fsh`: `mix(current, next, millis / 1000)` per +/// channel of every mipmap level, stored as 8-bit unorm. +/// One frame's mip chain: from the cache, or generated and kept while the budget has room. +/// Frames that do not fit still go through the same generation path. +fn frame_mips<'a>( + cache: &'a mut crate::fast_hash::FxHashMap<(usize, usize), Vec>, + cache_bytes: &mut usize, + budget: usize, + key: (usize, usize), + generate: impl FnOnce() -> Vec, +) -> std::borrow::Cow<'a, [u8]> { + let room = cache.len() < ANIMATION_MIP_ENTRIES; + match cache.entry(key) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut().as_slice().into(), + std::collections::hash_map::Entry::Vacant(entry) => { + let pixels = generate(); + // Bound both pixel storage and map metadata. Keep admitted frames + // rather than churning them on large/unique workloads. + if room && pixels.capacity() <= budget - *cache_bytes { + *cache_bytes += pixels.capacity(); + entry.insert(pixels).as_slice().into() + } else { + pixels.into() + } + } + } +} +fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) { + let t = millis as f32 / 1000.0; + for (c, n) in current.iter_mut().zip(next) { + let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0); + *c = ((a * (1.0 - t) + b * t) * 255.0).round() as u8; + } +} #[cfg(test)] mod sprite_upload_tests { use super::*; #[test] + fn real_rail_mips_do_not_change_with_larger_array_layers() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root + .join("assets/minecraft/textures/block/rail.png") + .exists() + { + return; + } + let mut sprites = crate::sprites::Sprites::default(); + let layers: Vec<_> = [ + "rail", + "powered_rail", + "powered_rail_on", + "detector_rail", + "activator_rail", + ] + .map(|name| { + sprites + .insert(&root, &format!("minecraft:block/{name}")) + .unwrap() + }) + .into(); + sprites.finish(); + assert_eq!(sprites.size, 16); + let native: Vec<_> = layers + .iter() + .map(|&layer| { + let start = layer as usize * 16 * 16 * 4; + mip_chain( + &sprites.pixels[start..start + 16 * 16 * 4], + 16, + &sprites.mips, + layer, + 1, + ) + .0 + }) + .collect(); + sprites.insert(&root, "minecraft:block/oak_sign").unwrap(); + sprites.finish(); + assert_eq!(sprites.size, 32); + for (&layer, expected) in layers.iter().zip(native) { + let start = layer as usize * 32 * 32 * 4; + let (actual, _) = mip_chain( + &sprites.pixels[start..start + 32 * 32 * 4], + 32, + &sprites.mips, + layer, + 1, + ); + assert_eq!(&actual[32 * 32 * 4..], expected, "rail layer {layer}"); + } + } + #[test] fn mipmap_option_keeps_real_16px_reductions() { for levels in 0..=4 { assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1); @@ -2843,7 +3073,7 @@ mod sprite_upload_tests { let settings = []; let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1); let mut animations = AnimatedSprites::new(&[animation], size, &settings); - animations.animations[0].1 = 0; + animations.animations[0].1 = Some(animations.animations[0].0.blend(0)); let mut writes = Vec::new(); let mut record = |layer, level, edge, data: &[u8]| { assert_eq!(layer, 7); @@ -2949,4 +3179,35 @@ mod sprite_upload_tests { }); assert_eq!(actual, expected); } + + #[test] + fn interpolated_animation_uploads_the_mix_every_tick() { + let animation = crate::sprites::test_clip(16, 3, r#"{"frametime":4,"interpolate":true}"#); + let settings = []; + let (_, levels) = mip_chain(animation.pixels(0), 16, &settings, 3, 1); + let mut cached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings); + let mut uncached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings); + uncached.budget = 0; + for state in [&mut cached, &mut uncached] { + state.animations[0].1 = Some(animation.blend(0)); + } + let mut blues = Vec::new(); + let mut uncached_blues = Vec::new(); + let mut record = |_, level, _, data: &[u8]| { + if level == 0 { + blues.push(data[2]); + } + }; + for tick in [0, 1, 1, 2, 4] { + animate_sprites(&mut cached, tick, levels, &mut record); + animate_sprites(&mut uncached, tick, levels, |_, level, _, data: &[u8]| { + if level == 0 { + uncached_blues.push(data[2]); + } + }); + } + // Frame 0 is blue 0, frame 1 blue 99: a quarter, a half, then frame 1. + assert_eq!(blues, [25, 50, 99]); + assert_eq!(uncached_blues, blues); + } } diff --git a/crates/horizon-client/src/gfx/pack_stages.rs b/crates/horizon-client/src/gfx/pack_stages.rs new file mode 100644 index 000000000..87d22d07d --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_stages.rs @@ -0,0 +1,325 @@ +//! A Horizon shader pack on the GPU (docs/shader-packs.md): each `composite` +//! stage is one full-screen pass that reads the world's colour and depth and +//! the previous stage's output and writes its own target; the last target +//! goes to the screen through `world_post` (copy or FXAA) under the hand and +//! HUD. Only exists while a pack is selected. +use crate::shader_pack::{ShaderPack, VERTEX_ENTRY}; + +/// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`). +#[repr(C)] +#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)] +pub struct FrameUniform { + pub view: [[f32; 4]; 4], + pub projection: [[f32; 4]; 4], + pub inverse_view: [[f32; 4]; 4], + pub inverse_projection: [[f32; 4]; 4], + pub camera_position: [f32; 4], + pub resolution: [f32; 4], + pub time: [f32; 4], + pub sun: [f32; 4], + pub moon: [f32; 4], + pub sky_color: [f32; 4], + pub fog_color: [f32; 4], + pub fog: [f32; 4], + pub weather: [f32; 4], + pub camera_state: [f32; 4], + pub view_params: [f32; 4], + pub dimension: [f32; 4], +} + +struct Pass { + pipeline: wgpu::RenderPipeline, + scale: f32, + uniform: wgpu::Buffer, +} +/// A stage's output and the bindings that read the world into it. +struct Target { + size: [u32; 2], + view: wgpu::TextureView, + group: wgpu::BindGroup, +} + +pub struct PackStages { + pub id: String, + layout: wgpu::BindGroupLayout, + linear: wgpu::Sampler, + nearest: wgpu::Sampler, + passes: Vec, + format: wgpu::TextureFormat, + /// Built for this world target size. + targets: Vec, + /// `world_post`'s bindings of the last stage's output. + output: Option, + world_size: [u32; 2], + started: std::time::Instant, + frames: u32, +} + +impl PackStages { + /// The pipelines of a loaded (already validated) pack, or wgpu's error. + pub fn new( + device: &wgpu::Device, + format: wgpu::TextureFormat, + pack: &ShaderPack, + ) -> Result { + let texture = |binding, sample_type| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let float = wgpu::TextureSampleType::Float { filterable: true }; + let sampler = |binding, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(ty), + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack stage"), + entries: &[ + texture(0, float), + texture(1, wgpu::TextureSampleType::Depth), + texture(2, float), + sampler(3, wgpu::SamplerBindingType::Filtering), + sampler(4, wgpu::SamplerBindingType::NonFiltering), + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Shader pack stage"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let constants = pack.constants(); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let passes = pack + .stages + .iter() + .map(|stage| { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&stage.file), + source: wgpu::ShaderSource::Wgsl(stage.source.as_str().into()), + }); + // Only the overrides a stage declares may be passed to it. + let constants: Vec<(&str, f64)> = constants + .iter() + .copied() + .filter(|(key, _)| declares_override(&stage.source, key)) + .collect(); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&stage.file), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(VERTEX_ENTRY), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(&stage.entry), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &constants, + ..Default::default() + }, + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + Pass { + pipeline, + scale: stage.scale, + uniform: device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack frame"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + } + }) + .collect(); + if let Some(error) = pollster::block_on(scope.pop()) { + return Err(error.to_string()); + } + let sampler = |filter| { + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Shader pack"), + mag_filter: filter, + min_filter: filter, + ..Default::default() + }) + }; + Ok(Self { + id: pack.id.clone(), + layout, + linear: sampler(wgpu::FilterMode::Linear), + nearest: sampler(wgpu::FilterMode::Nearest), + passes, + format, + targets: Vec::new(), + output: None, + world_size: [0, 0], + started: std::time::Instant::now(), + frames: 0, + }) + } + + /// Run every stage over the world's `color` and `depth` (`size`) and + /// return `post`'s bindings of the last stage's output. + #[allow(clippy::too_many_arguments)] + pub fn run( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + color: &wgpu::TextureView, + depth: &wgpu::TextureView, + size: [u32; 2], + post: &super::world_post::Post, + mut uniform: FrameUniform, + ) -> &wgpu::BindGroup { + if self.world_size != size || self.targets.len() != self.passes.len() { + self.world_size = size; + self.targets.clear(); + for pass in &self.passes { + let target_size = size.map(|v| ((v as f32 * pass.scale).round() as u32).max(1)); + let view = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Shader pack stage"), + size: wgpu::Extent3d { + width: target_size[0], + height: target_size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); + let previous = self.targets.last().map_or(color, |t: &Target| &t.view); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack stage"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(color), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(depth), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(previous), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&self.linear), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&self.nearest), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: pass.uniform.as_entire_binding(), + }, + ], + }); + self.targets.push(Target { + size: target_size, + view, + group, + }); + } + let last = &self.targets.last().expect("a pack has a stage").view; + self.output = Some(post.bind(device, last)); + } + uniform.time[0] = self.started.elapsed().as_secs_f32(); + uniform.time[1] = self.frames as f32; + self.frames = self.frames.wrapping_add(1); + for (pass, target) in self.passes.iter().zip(&self.targets) { + let [w, h] = target.size.map(|v| v as f32); + uniform.resolution = [w, h, 1.0 / w, 1.0 / h]; + queue.write_buffer(&pass.uniform, 0, bytemuck::bytes_of(&uniform)); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: &target.view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Shader pack stage"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(&pass.pipeline); + render.set_bind_group(0, &target.group, &[]); + render.draw(0..3, 0..1); + } + self.output.as_ref().expect("bound with the targets") + } +} + +/// `override ` appears in the source (a declaration, not just a use). +fn declares_override(source: &str, key: &str) -> bool { + source.lines().any(|line| { + line.trim_start() + .strip_prefix("override") + .and_then(|rest| rest.trim_start().strip_prefix(key)) + .is_some_and(|rest| rest.trim_start().starts_with([':', '='])) + }) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_frame_uniform_matches_the_prelude() { + // 4 matrices and 12 vectors, as `struct Frame` in the prelude. + assert_eq!(std::mem::size_of::(), 4 * 64 + 12 * 16); + let prelude = crate::shader_pack::PRELUDE; + let body = prelude.split("struct Frame {").nth(1).unwrap(); + let body = &body[..body.find('}').unwrap()]; + assert_eq!(body.matches("mat4x4").count(), 4); + assert_eq!(body.matches("vec4").count(), 12); + } + #[test] + fn only_declared_overrides_are_passed() { + let source = + "override saturation: f32 = 1.0;\noverride vignette = true;\nlet x = saturation_2;"; + assert!(super::declares_override(source, "saturation")); + assert!(super::declares_override(source, "vignette")); + assert!(!super::declares_override(source, "saturation_2")); + assert!(!super::declares_override(source, "haze")); + } +} diff --git a/crates/horizon-client/src/gfx/world_post.rs b/crates/horizon-client/src/gfx/world_post.rs index bd067ec76..797ee03b7 100644 --- a/crates/horizon-client/src/gfx/world_post.rs +++ b/crates/horizon-client/src/gfx/world_post.rs @@ -1,7 +1,8 @@ //! Resolution scale and FXAA (Horizon settings): the world renders into its //! own target at the scaled size, then one full-screen pass copies or -//! anti-aliases it onto the screen, under the hand and HUD. With neither -//! setting on, the world renders straight to the screen as before. +//! anti-aliases it onto the screen, under the hand and HUD. A shader pack +//! also needs the target (its stages read the world's colour and depth). +//! With none of them on, the world renders straight to the screen as before. struct WorldTarget { size: [u32; 2], @@ -99,13 +100,14 @@ impl Post { } } /// The world's colour and depth targets this frame, or `None` to draw - /// it straight to the screen. + /// it straight to the screen. `pack`: a shader pack runs this frame. pub fn prepare( &mut self, device: &wgpu::Device, window: [u32; 2], + pack: bool, ) -> Option<(wgpu::TextureView, wgpu::TextureView)> { - if self.scale == 1.0 && !self.antialias { + if self.scale == 1.0 && !self.antialias && !pack { self.target = None; return None; } @@ -138,22 +140,9 @@ impl Post { let depth = texture( "Scaled world depth", wgpu::TextureFormat::Depth32Float, - wgpu::TextureUsages::RENDER_ATTACHMENT, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, ); - let group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("Horizon post"), - layout: &self.layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView(&color), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Sampler(&self.sampler), - }, - ], - }); + let group = self.bind(device, &color); self.target = Some(WorldTarget { size, color, @@ -165,9 +154,39 @@ impl Post { .as_ref() .map(|t| (t.color.clone(), t.depth.clone())) } + /// The world target's size, once `prepare` made one. + pub fn size(&self) -> Option<[u32; 2]> { + self.target.as_ref().map(|t| t.size) + } + /// Bindings that copy (or anti-alias) `view` onto the screen in `finish_with`. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon post"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + ], + }) + } /// Draw the scaled world onto `screen`. pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) { let Some(target) = &self.target else { return }; + self.finish_with(encoder, screen, &target.group); + } + /// Draw what `group` binds (`bind`) onto `screen`. + pub fn finish_with( + &self, + encoder: &mut wgpu::CommandEncoder, + screen: &wgpu::TextureView, + group: &wgpu::BindGroup, + ) { let attachments = [Some(wgpu::RenderPassColorAttachment { view: screen, resolve_target: None, @@ -187,7 +206,7 @@ impl Post { } else { &self.copy }); - pass.set_bind_group(0, &target.group, &[]); + pass.set_bind_group(0, group, &[]); pass.draw(0..3, 0..1); } } diff --git a/crates/horizon-client/src/gizmos.rs b/crates/horizon-client/src/gizmos.rs index 842f0be97..d4125710e 100644 --- a/crates/horizon-client/src/gizmos.rs +++ b/crates/horizon-client/src/gizmos.rs @@ -37,6 +37,36 @@ pub const DRAGON_PART: u32 = 0xFF3F_FF00; pub const STROKE_WIDTH: f32 = 2.5; impl Gizmos { + /// `DebugCrosshairRenderer`: the world axes one block in front of the + /// camera, `0.01 * gui_scale` long, X red, Y green, Z light blue, each a + /// 2 pixel line over a 4 pixel black one. Drawn on top, in that order. + pub fn debug_crosshair(&mut self, camera: [f64; 3], x_rot: f32, y_rot: f32, gui_scale: f32) { + let forward = view_vector(x_rot, y_rot); + let center: [f64; 3] = std::array::from_fn(|i| camera[i] + forward[i]); + let length = f64::from(0.01 * gui_scale); + let axes = [(0, 0xFFFF_0000), (1, 0xFF00_FF00), (2, 0xFF7F_7FFF)]; + let end = |axis: usize| { + let mut p = center; + p[axis] += length; + p + }; + for (axis, _) in axes { + self.on_top.push(Line { + start: center, + end: end(axis), + color: 0xFF00_0000, + width: 4.0, + }); + } + for (axis, color) in axes { + self.on_top.push(Line { + start: center, + end: end(axis), + color, + width: 2.0, + }); + } + } /// `Gizmos.line`. pub fn line(&mut self, start: [f64; 3], end: [f64; 3], color: u32, width: f32) { self.lines.push(Line { @@ -277,6 +307,35 @@ pub fn camera_relative(lines: &[Line], camera: [f64; 3], view: glam::Mat4) -> Ve mod tests { use super::*; + #[test] + fn debug_crosshair_is_the_world_axes_ahead_of_the_camera() { + let mut g = Gizmos::default(); + // Looking south (yaw 0) at GUI scale 2: one block towards +Z. + g.debug_crosshair([0.5, 64.0, 0.5], 0.0, 0.0, 2.0); + assert!(g.lines.is_empty()); + let ends: Vec<([f64; 3], u32, f32)> = + g.on_top.iter().map(|l| (l.end, l.color, l.width)).collect(); + assert_eq!(g.on_top[0].start, [0.5, 64.0, 1.5]); + // CROSSHAIR_SCALE * guiScale, in floats as vanilla scales. + let l = f64::from(0.01f32 * 2.0); + let (x, y, z) = ( + [0.5 + l, 64.0, 1.5], + [0.5, 64.0 + l, 1.5], + [0.5, 64.0, 1.5 + l], + ); + assert_eq!( + ends, + [ + (x, 0xFF00_0000, 4.0), + (y, 0xFF00_0000, 4.0), + (z, 0xFF00_0000, 4.0), + (x, 0xFFFF_0000, 2.0), + (y, 0xFF00_FF00, 2.0), + (z, 0xFF7F_7FFF, 2.0), + ] + ); + } + #[test] fn chunk_borders_match_the_renderer() { let mut g = Gizmos::default(); diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 5ef24247e..f10c6b3b3 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -117,6 +117,10 @@ pub struct Graphics { pub preset: Preset, /// Skip sections hidden behind closed ones (vanilla's occlusion graph). pub cave_culling: bool, + /// Hide shared leaf and mangrove-root faces, reducing foliage density. + pub cull_leaves: bool, + /// Skip drawing entities hidden behind opaque terrain. + pub entity_culling: bool, /// Meshed sections uploaded per frame; 0 uploads all that are ready. pub chunk_updates: u32, /// Section mesh bytes uploaded per frame, in KiB; 0 is unlimited. @@ -140,12 +144,17 @@ pub struct Graphics { /// or behind other windows, and half the worker threads. Off by default; /// it changes when frames are drawn, never what they show or the ticks. pub battery: bool, + /// The Horizon shader pack in `shaderpacks/` (its folder name); empty: + /// none, the vanilla picture (docs/shader-packs.md). + pub shader_pack: String, } impl Default for Graphics { fn default() -> Self { Self { preset: Preset::Custom, cave_culling: true, + cull_leaves: false, + entity_culling: false, chunk_updates: 0, upload_budget_kib: 0, sky: true, @@ -160,6 +169,7 @@ impl Default for Graphics { fxaa: false, advanced: false, battery: false, + shader_pack: String::new(), } } } @@ -188,6 +198,8 @@ impl Graphics { match key.trim() { "preset" => g.preset = Preset::parse(value), "caveCulling" => g.cave_culling = flag(g.cave_culling), + "cullLeaves" => g.cull_leaves = flag(g.cull_leaves), + "entityCulling" => g.entity_culling = flag(g.entity_culling), "chunkUpdates" => g.chunk_updates = number(g.chunk_updates).min(512), "uploadBudgetKiB" => g.upload_budget_kib = number(g.upload_budget_kib).min(65536), "sky" => g.sky = flag(g.sky), @@ -207,6 +219,7 @@ impl Graphics { "fxaa" => g.fxaa = flag(g.fxaa), "level" => g.advanced = value == "advanced", "batteryMode" => g.battery = flag(g.battery), + "shaderPack" => g.shader_pack = value.to_string(), "overlay" => { g.overlay = match value { "fps" => Overlay::Fps, @@ -221,9 +234,11 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\n", + "preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", self.preset.name(), bool_text(self.cave_culling), + bool_text(self.cull_leaves), + bool_text(self.entity_culling), self.chunk_updates, self.upload_budget_kib, bool_text(self.sky), @@ -245,6 +260,7 @@ impl Graphics { bool_text(self.fxaa), if self.advanced { "advanced" } else { "simple" }, bool_text(self.battery), + self.shader_pack, ) } pub fn save(&self, dir: &Path) { @@ -315,6 +331,8 @@ mod tests { let g = Graphics { preset: Preset::Balanced, cave_culling: false, + cull_leaves: true, + entity_culling: true, chunk_updates: 12, upload_budget_kib: 4096, sky: false, @@ -329,11 +347,12 @@ mod tests { fxaa: true, advanced: true, battery: true, + shader_pack: "horizon-sample".into(), }; assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(""), Graphics::default()); assert_eq!( - Graphics::parse("workers:abc\nsky:maybe\n"), + Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"), Graphics::default() ); } diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index d8196f478..c03041152 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -22,6 +22,8 @@ pub enum Level { pub enum H { Preset, CaveCulling, + CullLeaves, + EntityCulling, ChunkUpdates, UploadBudget, Sky, @@ -35,6 +37,7 @@ pub enum H { ResolutionScale, Antialiasing, BatteryMode, + ShaderPack, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -116,6 +119,16 @@ pub fn rows(level: Level) -> Vec { None, "Skips terrain hidden behind closed sections. Off costs a lot.", ), + h( + H::CullLeaves, + None, + "Hides shared leaf and mangrove root faces; foliage can look less dense.", + ), + h( + H::EntityCulling, + None, + "Hides models behind opaque blocks. Entities update. Off with custom packs.", + ), h( H::ChunkUpdates, Low, @@ -213,6 +226,11 @@ pub fn rows(level: Level) -> Vec { None, "Lowers the frame rate when minimised, or idle too.", ), + h( + H::ShaderPack, + High, + "Redraws the world with a pack from shaderpacks/. Off is vanilla.", + ), Row::Header("Preferences"), v(Opt::ViewBobbing, None, "Sways the view while walking."), v(Opt::ChunkFade, None, "Fades newly loaded chunks in."), @@ -276,6 +294,8 @@ impl H { match self { H::Preset => labelled("Preset", g.preset.label()), H::CaveCulling => labelled("Cave Culling", on_off(g.cave_culling)), + H::CullLeaves => labelled("Cull Leaves", on_off(g.cull_leaves)), + H::EntityCulling => labelled("Entity Culling", on_off(g.entity_culling)), H::ChunkUpdates => match g.chunk_updates { 0 => labelled("Chunk Updates", "Unlimited"), n => labelled("Chunk Updates", format!("{n} per frame")), @@ -304,6 +324,10 @@ impl H { H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)), H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }), H::BatteryMode => labelled("Battery Mode", on_off(g.battery)), + H::ShaderPack => match g.shader_pack.as_str() { + "" => labelled("Shader Pack", "Off"), + id => labelled("Shader Pack", id), + }, H::Overlay => labelled( "Performance Overlay", match g.overlay { @@ -342,6 +366,8 @@ impl H { let g = &mut s.horizon; match self { H::CaveCulling => g.cave_culling = !g.cave_culling, + H::CullLeaves => g.cull_leaves = !g.cull_leaves, + H::EntityCulling => g.entity_culling = !g.entity_culling, H::Sky => g.sky = !g.sky, H::Fog => g.fog = !g.fog, H::Weather => g.weather = !g.weather, @@ -349,6 +375,17 @@ impl H { H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back), H::Antialiasing => g.fxaa = !g.fxaa, H::BatteryMode => g.battery = !g.battery, + H::ShaderPack => { + // Off, then every pack in shaderpacks/ by folder name. + let dir = std::env::current_dir() + .unwrap_or_default() + .join(crate::shader_pack::DIR); + let mut all = vec![String::new()]; + all.extend(crate::shader_pack::list(&dir).into_iter().map(|(id, _)| id)); + let i = all.iter().position(|x| *x == g.shader_pack).unwrap_or(0); + let n = all.len(); + g.shader_pack = all[if back { (i + n - 1) % n } else { (i + 1) % n }].clone(); + } H::Pacing => { g.pacing = match g.pacing { Pacing::Efficient => Pacing::Precise, @@ -376,6 +413,8 @@ impl Item { let g = &s.horizon; Some(match self { Item::Horizon(H::CaveCulling) => g.cave_culling, + Item::Horizon(H::CullLeaves) => g.cull_leaves, + Item::Horizon(H::EntityCulling) => g.entity_culling, Item::Horizon(H::Sky) => g.sky, Item::Horizon(H::Fog) => g.fog, Item::Horizon(H::Weather) => g.weather, @@ -433,7 +472,13 @@ impl Item { let presetless = matches!( self, Item::Horizon( - H::Preset | H::Overlay | H::Pacing | H::PresentMode | H::Workers | H::BatteryMode + H::Preset + | H::Overlay + | H::Pacing + | H::PresentMode + | H::Workers + | H::BatteryMode + | H::ShaderPack ) | Item::Vanilla( Opt::GuiScale | Opt::Fullscreen @@ -825,6 +870,25 @@ mod tests { } } + #[test] + fn the_shader_pack_row_is_off_by_default_and_outside_presets() { + let mut s = Settings::default(); + let row = Item::Horizon(H::ShaderPack); + assert_eq!(row.label(&s).plain(), "Shader Pack: Off"); + assert!( + rows(Level::Advanced) + .iter() + .any(|r| matches!(r, Row::Setting(x) if x.item == row)) + ); + s.horizon.shader_pack = "horizon-sample".into(); + assert_eq!(row.label(&s).plain(), "Shader Pack: horizon-sample"); + // Picking a pack keeps the preset. + Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]); + let preset = s.horizon.preset; + row.cycle(&mut s, false, [854, 480]); + assert_eq!(s.horizon.preset, preset); + } + #[test] fn presets_set_vanilla_and_horizon_options() { let mut s = Settings::default(); @@ -850,4 +914,88 @@ mod tests { H::UploadBudget.set_slider(&mut s, 0.0); assert_eq!(s.horizon.upload_budget_kib, 0); } + + #[test] + fn cull_leaves_is_opt_in_and_toggles_from_advanced_graphics() { + let mut s = Settings::default(); + let item = Item::Horizon(H::CullLeaves); + assert_eq!(item.switch(&s), Some(false)); + assert_eq!(item.label(&s).plain(), "Cull Leaves: Off"); + for enabled in [false, true] { + s.horizon.cull_leaves = enabled; + for preset in Preset::ALL { + crate::graphics::apply_preset(preset, &mut s); + assert_eq!(s.horizon.cull_leaves, enabled); + } + } + + let mut ui = GraphicsUi::default(); + let size = (480.0, 4000.0); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); + let switch = widgets + .iter() + .find(|w| matches!(w.target, Target::Item(i) if i == item)) + .unwrap(); + let point = (switch.x + 1.0, switch.y + 1.0); + for enabled in [false, true] { + s.horizon.preset = Preset::Balanced; + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + ), + vec![Action::ButtonClick, Action::Changed] + ); + assert_eq!(item.switch(&s), Some(enabled)); + assert_eq!(s.horizon.preset, Preset::Custom); + } + assert_eq!(item.label(&s).plain(), "Cull Leaves: On"); + } + + #[test] + fn entity_culling_is_opt_in_and_toggles_from_advanced_graphics() { + let mut s = Settings::default(); + let item = Item::Horizon(H::EntityCulling); + assert_eq!(item.switch(&s), Some(false)); + assert_eq!(item.label(&s).plain(), "Entity Culling: Off"); + for enabled in [false, true] { + s.horizon.entity_culling = enabled; + for preset in Preset::ALL { + crate::graphics::apply_preset(preset, &mut s); + assert_eq!(s.horizon.entity_culling, enabled); + } + } + + let mut ui = GraphicsUi::default(); + let size = (480.0, 4000.0); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); + let switch = widgets + .iter() + .find(|w| matches!(w.target, Target::Item(i) if i == item)) + .unwrap(); + let point = (switch.x + 1.0, switch.y + 1.0); + for enabled in [false, true] { + s.horizon.preset = Preset::Balanced; + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + ), + vec![Action::ButtonClick, Action::Changed] + ); + assert_eq!(item.switch(&s), Some(enabled)); + assert_eq!(s.horizon.preset, Preset::Custom); + } + assert_eq!(item.label(&s).plain(), "Entity Culling: On"); + } } diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 1ed11ef54..e024d3634 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -180,11 +180,17 @@ impl Hub { /// Open a trading window for a guest (`Merchant.openTradingScreen`): /// its id, or None when the menu type is unknown. pub fn open_merchant_window(&mut self, conn: u32, title: Tag) -> Option { + self.open_window(conn, "minecraft:merchant", title) + } + + /// ServerPlayer.openMenu for a menu the game runs (merchant, crafting + /// table): the open container closes, a new window id opens this menu. + pub fn open_window(&mut self, conn: u32, menu: &str, title: Tag) -> Option { let kind = self .sync .builtin .get("minecraft:menu") - .and_then(|m| m.id("minecraft:merchant"))?; + .and_then(|m| m.id(menu))?; let i = self.guests.iter().position(|g| g.conn == conn)?; self.close_container_at(i); let g = &mut self.guests[i]; @@ -277,7 +283,7 @@ impl Hub { pub fn container_click( &mut self, conn: u32, - p: play::ContainerClick, + p: &play::ContainerClick, world: &mut World, rules: &dyn Rules, ) -> Vec { @@ -326,7 +332,34 @@ impl Hub { } else { self.guests[i].drag = drag; } - // Tell the client about every slot it got wrong, or that it did not claim. + self.answer_click(i, p, world, &changed); + drops + } + + /// A click on the inventory menu (window 0) the game applied itself + /// (the crafting grid): the client is corrected like after any click. + pub fn inventory_clicked( + &mut self, + conn: u32, + p: &play::ContainerClick, + world: &World, + changed: &[usize], + ) { + if let Some(i) = self.guests.iter().position(|g| g.conn == conn) { + self.answer_click(i, p, world, changed); + } + } + + /// After a click: tell the client about every slot it got wrong, or that + /// it did not claim, and the carried stack. + fn answer_click( + &mut self, + i: usize, + p: &play::ContainerClick, + world: &World, + changed: &[usize], + ) { + let in_menu = p.container != 0; let claimed: HashMap> = p .changed .iter() @@ -382,7 +415,6 @@ impl Hub { } else { self.guests[i].menu_sent = items; } - drops } /// Slot changes of open containers (AbstractContainerMenu.broadcastChanges). diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 49dec3f21..e58544bc6 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -80,6 +80,10 @@ pub struct Guest { pub offhand: Option, pub selected: usize, pub carried: Option, + /// The inventory menu's crafting grid (2x2) and its result + /// (`InventoryMenu.craftSlots`, `resultSlots`), which the game computes. + pub craft_grid: [Option; 4], + pub craft_result: Option, pub health: f32, pub food: i32, pub saturation: f32, @@ -95,6 +99,9 @@ pub struct Guest { pub inbox: VecDeque, pub joined_tick: u64, pub ticks: u64, + /// The moves accepted since the game last looked (movement, on ground), + /// for ServerPlayer.doCheckFallDamage. + pub moves: Vec<([f64; 3], bool)>, pub dead: bool, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, @@ -154,6 +161,8 @@ impl Guest { offhand: None, selected: 0, carried: None, + craft_grid: Default::default(), + craft_result: None, health: 20.0, food: 20, saturation: 5.0, @@ -168,6 +177,7 @@ impl Guest { inbox: VecDeque::new(), joined_tick: 0, ticks: 0, + moves: Vec::new(), dead: false, placed: false, menu: None, @@ -221,7 +231,8 @@ impl Guest { /// 45 off hand. pub fn menu_slot(&self, slot: usize) -> Option { match slot { - 0..=4 => None, + 0 => self.craft_result.clone(), + 1..=4 => self.craft_grid[slot - 1].clone(), 5..=8 => self.armor[slot - 5].clone(), 9..=35 => self.inventory.get(slot).cloned().flatten(), 36..=44 => self.inventory.get(slot - 36).cloned().flatten(), @@ -231,6 +242,8 @@ impl Guest { } pub fn set_menu_slot(&mut self, slot: usize, item: Option) { match slot { + 0 => self.craft_result = item, + 1..=4 => self.craft_grid[slot - 1] = item, 5..=8 => self.armor[slot - 5] = item, 9..=35 => self.inventory[slot] = item, 36..=44 => self.inventory[slot - 36] = item, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 2486fd1a5..8f4fc010e 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1394,9 +1394,7 @@ impl Hub { S::MovePlayerRot(p) => { self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags); } - S::MovePlayerStatus(p) => { - self.guests[i].on_ground = p.flags & 1 != 0; - } + S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags), S::PlayerLoaded(_) => self.guests[i].loaded = true, S::ChunkBatchReceived(p) => { let g = &mut self.guests[i]; @@ -1460,6 +1458,10 @@ impl Hub { g.previous_position = g.position; g.position = p; } + let moved = pos.map_or([0.0; 3], |_| { + [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]) + }); + g.moves.push((moved, flags & 1 != 0)); if let Some((yaw, pitch)) = rot && yaw.is_finite() && pitch.is_finite() diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1e6e99f0c..319f1fa50 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -47,10 +47,12 @@ pub mod data_cmd; pub mod datapack; pub mod debug_chart; pub mod debug_keys; +pub mod debug_overlay; pub mod effects; pub mod enchant; pub mod end_crystal; pub mod entities; +pub mod entity_culling; pub mod entity_nbt; pub mod environment; pub mod extras; @@ -101,6 +103,7 @@ pub mod mesher; pub mod minimap; pub mod mipmap; pub mod mobs; +pub mod mod_list; mod model_library; pub mod models; pub mod motion; diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 1f0b0b128..cb436a947 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -167,6 +167,8 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 { result } #[cfg(test)] +mod leaf_culling_tests; +#[cfg(test)] mod visibility_tests; #[derive(Clone, Copy, PartialEq, Eq)] enum Tint { @@ -208,6 +210,7 @@ struct Info { overlay: bool, /// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped. leaves: bool, + mangrove_roots: bool, blocks_flow: bool, ice: bool, sturdy: u8, @@ -368,6 +371,7 @@ impl MeshTables { legacy_solid: s.legacy_solid, overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"), leaves: s.has_class("LeavesBlock"), + mangrove_roots: s.has_class("MangroveRootsBlock"), blocks_flow: assets.blocks_fluid_flow.contains(&*s.name), ice: s.has_class("IceBlock"), sturdy: s.sturdy_full, @@ -596,6 +600,8 @@ pub struct Mesher<'a> { pub smooth_lighting: bool, /// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque. pub cutout_leaves: bool, + /// Cull shared leaf and mangrove-root faces, including transparent leaves. + pub cull_leaves: bool, } impl Mesher<'_> { /// `region[dz][dx]` are the chunks around the meshed column (centre 1,1). @@ -673,19 +679,22 @@ impl Mesher<'_> { for d in Direction::ALL { let [dx, dy, dz] = d.normal(); let neighbor = pad.blocks[pi(x + dx, y + dy, z + dz)]; - visible[d as usize] = self - .visibility - .should_render_face( - BlockStateId(id.into()), - BlockStateId(neighbor.into()), - d, - true, - ) - .unwrap_or(true); - // LeavesBlock.skipRendering with opaque leaves. - if !self.cutout_leaves && state.leaves && info[neighbor as usize].leaves { - visible[d as usize] = false; - } + let other = &info[neighbor as usize]; + // Adapted from CullLeaves (MIT); see THIRD_PARTY_NOTICES.md. + let shared_foliage = (state.leaves + && other.leaves + && (!self.cutout_leaves || self.cull_leaves)) + || (self.cull_leaves && state.mangrove_roots && other.mangrove_roots); + visible[d as usize] = !shared_foliage + && self + .visibility + .should_render_face( + BlockStateId(id.into()), + BlockStateId(neighbor.into()), + d, + true, + ) + .unwrap_or(true); } for (_, model) in &models { for face in &model.faces { diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs new file mode 100644 index 000000000..42ed2b8b6 --- /dev/null +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -0,0 +1,124 @@ +use super::*; +use horizon_assets::model::Direction as ModelDirection; + +#[test] +fn leaf_culling_removes_only_internal_leaf_and_root_faces() { + let root = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("horizon-resources.json").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let facts = BlockFacts::load(&root, assets.registry).unwrap(); + let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); + let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); + let biomes = Biomes::load(&root).unwrap(); + let state = |name| assets.registry.default_state(name).unwrap().0 as u16; + let oak = state("minecraft:oak_leaves"); + let birch = state("minecraft:birch_leaves"); + let roots = state("minecraft:mangrove_roots"); + let stone = state("minecraft:stone"); + let mesh = |blocks: &[([i32; 3], u16)], cull_leaves, cutout_leaves| { + let mut center = Chunk::empty(0, 0); + let mut east = Chunk::empty(1, 0); + for &([x, y, z], state) in blocks { + let chunk = if x < 16 { &mut center } else { &mut east }; + chunk.set(x, y, z, state); + } + let mut region = [[None; 3]; 3]; + region[1][1] = Some(¢er); + region[1][2] = Some(&east); + Mesher { + nether_shading: false, + assets: &assets, + tables: &tables, + biomes: &biomes, + visibility: visibility.clone(), + zoom: BiomeZoom::new(0), + blend_radius: 0, + smooth_lighting: false, + cutout_leaves, + cull_leaves, + } + .mesh(®ion, (0 - MIN_Y) / 16) + .solid + }; + + // Native leaves can contain unculled interior geometry as well as their + // outer faces. Select the touching cull group from the actual baked model, + // preserving every other quad and its full vertex attributes. + let without_face = |at: [i32; 3], id, direction| { + let vertices = mesh(&[(at, id)], false, true); + let models = assets + .model_catalog + .collect(BlockStateId(id.into()), BlockPos::new(at[0], at[1], at[2])) + .unwrap(); + let faces: Vec<_> = models.iter().flat_map(|(_, model)| &model.faces).collect(); + assert_eq!(vertices.len(), faces.len() * 4); + let retained: Vec<_> = vertices + .as_chunks::<4>() + .0 + .iter() + .zip(faces) + .filter(|(_, face)| face.quad.cull != Some(direction)) + .flat_map(|(quad, _)| quad.iter().copied()) + .collect(); + assert!(retained.len() < vertices.len(), "fixture has a cull group"); + retained + }; + + // Same-species leaves, mixed leaves and roots hide only their touching + // model groups. Disabling the option restores the isolated models. + for (a, b) in [(oak, oak), (oak, birch), (roots, roots)] { + let blocks = [([7, 7, 7], a), ([8, 7, 7], b)]; + let off = mesh(&blocks, false, true); + let on = mesh(&blocks, true, true); + assert_eq!( + off.len(), + mesh(&[blocks[0]], false, true).len() + mesh(&[blocks[1]], false, true).len() + ); + let mut retained = without_face(blocks[0].0, a, ModelDirection::East); + retained.extend(without_face(blocks[1].0, b, ModelDirection::West)); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&on), + bytemuck::cast_slice::<_, u8>(&retained) + ); + } + + // Roots do not join leaves into a single culling group. Ordinary opaque + // neighbors also keep their existing occlusion behavior. + for (a, b) in [(oak, roots), (roots, oak), (oak, stone)] { + let blocks = [([7, 7, 7], a), ([8, 7, 7], b)]; + let off = mesh(&blocks, false, true); + let on = mesh(&blocks, true, true); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&on), + bytemuck::cast_slice::<_, u8>(&off) + ); + } + + // Opaque leaves already hide internal leaf faces independently of this + // option, and a leaf beside air retains its complete baked model. + let pair = [([7, 7, 7], oak), ([8, 7, 7], birch)]; + assert_eq!( + mesh(&pair, false, false).len(), + mesh(&pair, true, false).len() + ); + let isolated = [([7, 7, 7], oak)]; + assert_eq!( + bytemuck::cast_slice::<_, u8>(&mesh(&isolated, false, true)), + bytemuck::cast_slice::<_, u8>(&mesh(&isolated, true, true)) + ); + + // The padding read must also remove the center chunk's internal face + // against a different leaf species in the neighboring chunk. + let boundary = [([15, 7, 7], oak), ([16, 7, 7], birch)]; + assert_eq!( + mesh(&boundary, false, true).len(), + mesh(&[boundary[0]], false, true).len() + ); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&mesh(&boundary, true, true)), + bytemuck::cast_slice::<_, u8>(&without_face(boundary[0].0, oak, ModelDirection::East)) + ); +} diff --git a/crates/horizon-client/src/mesher/visibility_tests.rs b/crates/horizon-client/src/mesher/visibility_tests.rs index c96793087..2f95c45cf 100644 --- a/crates/horizon-client/src/mesher/visibility_tests.rs +++ b/crates/horizon-client/src/mesher/visibility_tests.rs @@ -87,6 +87,7 @@ fn info(solid: bool) -> Info { legacy_solid: false, overlay: false, leaves: false, + mangrove_roots: false, blocks_flow: false, ice: false, sturdy: 0, diff --git a/crates/horizon-client/src/mipmap.rs b/crates/horizon-client/src/mipmap.rs index 98911e54f..33c99cdc3 100644 --- a/crates/horizon-client/src/mipmap.rs +++ b/crates/horizon-client/src/mipmap.rs @@ -31,6 +31,9 @@ impl Strategy { /// it has a fully transparent pixel and whether it is an `item/` sprite. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Settings { + /// Original square frame edge, before fitting the sprite into the array. + /// Zero means the supplied image is already at its native size. + pub native_size: u32, pub strategy: Strategy, pub alpha_cutoff_bias: f32, pub has_transparent: bool, @@ -45,6 +48,15 @@ pub struct Image { pub pixels: Vec<[u8; 4]>, } impl Image { + fn resized(&self, size: u32) -> Self { + Self { + width: size, + height: size, + pixels: (0..size * size) + .map(|i| self.get(i % size * self.width / size, i / size * self.height / size)) + .collect(), + } + } fn get(&self, x: u32, y: u32) -> [u8; 4] { self.pixels[(x + y * self.width) as usize] } @@ -263,17 +275,37 @@ fn darkened_alpha_blend(c: [[u8; 4]; 4]) -> [u8; 4] { } /// `MipmapGenerator.generateMipLevels` from the base image (`levels` mips -/// below it): `has_transparent` is `Transparency.hasTransparent` (a pixel -/// with zero alpha), `item` whether the sprite is under `item/` (its base -/// is left as is). -pub fn generate( - mut base: Image, - levels: u32, - strategy: Strategy, - alpha_cutoff_bias: f32, - has_transparent: bool, - item: bool, -) -> Vec { +/// below it). Array-only enlargement must not run extra alpha-coverage steps +/// before the sprite's native mip chain. +pub fn generate(base: Image, levels: u32, settings: Settings) -> Vec { + let native = settings.native_size; + if native.is_power_of_two() + && native < base.width + && base.width == base.height + && base.width.is_power_of_two() + { + let extra = (base.width / native).ilog2(); + let mut mips = + generate_native(base.resized(native), levels.saturating_sub(extra), settings); + let mut out: Vec<_> = (0..extra.min(levels + 1)) + .map(|level| mips[0].resized(base.width >> level)) + .collect(); + if levels >= extra { + out.append(&mut mips); + } + return out; + } + generate_native(base, levels, settings) +} + +fn generate_native(mut base: Image, levels: u32, settings: Settings) -> Vec { + let Settings { + strategy, + alpha_cutoff_bias, + has_transparent, + item, + .. + } = settings; let strategy = match strategy { Strategy::Auto if has_transparent => Strategy::Cutout, Strategy::Auto => Strategy::Mean, diff --git a/crates/horizon-client/src/mod_list.rs b/crates/horizon-client/src/mod_list.rs new file mode 100644 index 000000000..ba3d93cda --- /dev/null +++ b/crates/horizon-client/src/mod_list.rs @@ -0,0 +1,112 @@ +//! Which of the installed Horizon mods are on (`docs/mods.md`), kept in +//! `horizon-mods.txt` beside `options.txt` as `mod.:true` lines. Every +//! mod is off until the player turns it on in Options > Mods. +use std::{collections::BTreeSet, fs, path::Path}; + +pub const FILE: &str = "horizon-mods.txt"; +/// The folder holding `.hmod` files, beside `options.txt`. +pub const DIR: &str = "horizon-mods"; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ModList { + /// Ids of the mods the player turned on. + pub enabled: BTreeSet, + /// What the Mods page shows, filled by the game from the mods it found. + pub installed: Vec, +} + +/// One installed mod as the Mods page shows it. +#[derive(Clone, Debug, PartialEq)] +pub struct Installed { + pub id: String, + /// `Name 1.0` (the file name when the manifest is unreadable). + pub title: String, + pub description: String, + /// Why it is not running, when it failed. + pub problem: Option, + /// Loaded with `--dev-mod`: always on, reloaded when rebuilt. + pub dev: bool, +} + +impl ModList { + 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 enabled = text + .lines() + .filter_map(|l| l.split_once(':')) + .filter(|(_, v)| v.trim() == "true") + .filter_map(|(k, _)| k.trim().strip_prefix("mod.")) + .map(str::to_owned) + .collect(); + Self { + enabled, + installed: Vec::new(), + } + } + pub fn serialize(&self) -> String { + self.enabled + .iter() + .map(|id| format!("mod.{id}:true\n")) + .collect() + } + pub fn save(&self, dir: &Path) { + let path = dir.join(FILE); + if self.enabled.is_empty() && !path.exists() { + return; + } + let _ = fs::write(path, self.serialize()); + } + pub fn is_on(&self, i: usize) -> bool { + self.installed + .get(i) + .is_some_and(|m| m.dev || self.enabled.contains(&m.id)) + } + /// Turns installed mod `i` on or off (a dev mod stays on). + pub fn toggle(&mut self, i: usize) { + let Some(m) = self.installed.get(i).filter(|m| !m.dev) else { + return; + }; + if !self.enabled.remove(&m.id) { + self.enabled.insert(m.id.clone()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_ignores_the_rest() { + let list = ModList::parse("mod.coords_hud:true\nmod.other:false\nzoom:true\n"); + assert_eq!(list.enabled.iter().collect::>(), ["coords_hud"]); + assert_eq!(ModList::parse(&list.serialize()), list); + assert_eq!(ModList::default().serialize(), ""); + } + + #[test] + fn toggles_installed_mods_but_not_dev_ones() { + let installed = |id: &str, dev| Installed { + id: id.into(), + title: id.into(), + description: String::new(), + problem: None, + dev, + }; + let mut list = ModList { + installed: vec![installed("a", false), installed("b", true)], + ..Default::default() + }; + assert!(!list.is_on(0) && list.is_on(1)); + list.toggle(0); + list.toggle(1); + assert!(list.is_on(0) && list.is_on(1)); + assert_eq!(list.serialize(), "mod.a:true\n"); + list.toggle(0); + assert!(!list.is_on(0)); + } +} diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 0c81f6da2..60a5b2277 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -4,6 +4,8 @@ //! ServerStatusPinger to show the MOTD, player count and latency. use crate::hud::{HudAtlas, HudBatch, rgba}; use crate::lan::discovery::Scanner; +use crate::text::{DARK_GRAY, GRAY, Text, format_translation}; +use crate::title::confirm_top; use horizon_protocol::servers::{self, ServerEntry}; use std::{ collections::HashMap, @@ -17,14 +19,36 @@ use std::{ pub enum Ping { Pinging, Ok { - motd: String, - players: String, + /// The description component, styled (`sanitizeDescription`). + motd: Text, + /// Online and max players; None when the status has no `players`. + players: Option<(i64, i64)>, ms: u128, version: String, }, Failed(String), } +impl Ping { + /// ServerStatusPinger.formatPlayerCount: dark grey with grey numbers, + /// or `multiplayer.status.unknown` without a player count. + pub fn player_count(players: Option<(i64, i64)>) -> Text { + match players { + Some((online, max)) => Text::translate( + "multiplayer.status.player_count", + &[ + Text::colored(online.to_string(), GRAY), + Text::colored(max.to_string(), GRAY), + ], + ), + None => Text::translate("multiplayer.status.unknown", &[]), + } + .with_color(DARK_GRAY) + } +} type Pings = Arc>>; +/// Server icons by address as 64x64 RGBA (FaviconTexture), from servers.dat +/// and then from each ping's favicon. +type Icons = Arc>>>>; #[derive(Clone, Debug)] pub enum Screen { @@ -32,6 +56,7 @@ pub enum Screen { servers: Vec, selected: Option, pings: Pings, + icons: Icons, /// Worlds announced on the local network, listed after the servers. lan: Scanner, scroll: crate::ui::Scroll, @@ -46,6 +71,13 @@ pub enum Screen { Direct { address: String, }, + /// ConfirmScreen for Delete: the list it returns to, the server's name + /// and how many lines the warning took when last drawn. + ConfirmDelete { + list: Box, + name: String, + lines: std::cell::Cell, + }, /// Join a friend's world with its invite code (Horizon's own, reached /// from Horizon's multiplayer page). Friend { @@ -74,24 +106,63 @@ pub fn servers_file(saves: &Path) -> PathBuf { .parent() .map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat")) } -fn ping_all(servers: &[ServerEntry], pings: &Pings) { +/// `FaviconTexture.upload`: a PNG of exactly 64x64 pixels, else no icon. +fn icon_pixels(png: &[u8]) -> Option>> { + crate::hud::decode_bytes(png) + .ok() + .filter(|(w, h, _)| *w == 64 && *h == 64) + .map(|(_, _, p)| Arc::new(p)) +} +/// `ServerStatus.Favicon.CODEC`: a base64 PNG behind the data URL prefix. +fn favicon_bytes(json: &serde_json::Value) -> Option> { + let url = json["favicon"].as_str()?; + let base64 = url + .strip_prefix("data:image/png;base64,")? + .replace('\n', ""); + crate::skins::base64_decode(&base64) +} +fn ping_all(servers: &[ServerEntry], pings: &Pings, icons: &Icons, file: &Path) { for s in servers { let address = s.ip.clone(); pings.lock().unwrap().insert(address.clone(), Ping::Pinging); - let pings = pings.clone(); + let saved = s.icon.clone(); + if let Some(pixels) = saved + .as_deref() + .and_then(crate::skins::base64_decode) + .and_then(|png| icon_pixels(&png)) + { + icons.lock().unwrap().insert(address.clone(), pixels); + } + let (pings, icons, file) = (pings.clone(), icons.clone(), file.to_owned()); let _ = std::thread::Builder::new() .name("horizon-ping".into()) .spawn(move || { let result = match crate::net::ping(&address, Duration::from_secs(5)) { Ok((json, ms)) => { - let lang = Default::default(); - let motd = crate::net::json_text(&json["description"], &lang); - let players = format!( - "{}/{}", - json["players"]["online"].as_i64().unwrap_or(0), - json["players"]["max"].as_i64().unwrap_or(0) - ); + let motd = crate::component::to_text(&json["description"], &mut |s| { + Text::literal(s) + }); + let players = json["players"].as_object().map(|p| { + ( + p.get("online").and_then(|n| n.as_i64()).unwrap_or(0), + p.get("max").and_then(|n| n.as_i64()).unwrap_or(0), + ) + }); let version = json["version"]["name"].as_str().unwrap_or("?").to_owned(); + // A new favicon replaces the saved one (an invalid one + // clears it) and servers.dat is saved again. + if let Some(png) = favicon_bytes(&json) { + let encoded = crate::lan::base64(&png); + let pixels = icon_pixels(&png); + match &pixels { + Some(p) => icons.lock().unwrap().insert(address.clone(), p.clone()), + None => icons.lock().unwrap().remove(&address), + }; + let icon = pixels.map(|_| encoded); + if icon != saved { + save_icon(&file, &address, icon); + } + } Ping::Ok { motd, players, @@ -105,6 +176,33 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) { }); } } +/// Save the list after a move or delete, keeping the icons pings stored in +/// servers.dat since it was loaded. +fn save_servers(file: &Path, servers: &mut [ServerEntry]) { + let _guard = SAVING.lock(); + let saved = servers::load(file); + for entry in servers.iter_mut() { + if let Some(s) = saved.iter().find(|s| s.ip == entry.ip) { + entry.icon = s.icon.clone(); + } + } + let _ = servers::save(file, servers); +} +/// Held while servers.dat is read and written back. +static SAVING: Mutex<()> = Mutex::new(()); +/// Store `icon` on the entries for `address` (OnlineServerEntry.updateServerList). +fn save_icon(file: &Path, address: &str, icon: Option) { + let _guard = SAVING.lock(); + let mut list = servers::load(file); + let mut changed = false; + for entry in list.iter_mut().filter(|e| e.ip == address) { + changed |= entry.icon != icon; + entry.icon = icon.clone(); + } + if changed { + let _ = servers::save(file, &list); + } +} /// The address of list row `index`: the saved servers, then the LAN games. fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option { @@ -167,12 +265,106 @@ fn row_at( } rows(servers, lan).nth(index as usize) } +/// SelectableEntry's hover areas over the 32-pixel icon, relative to it. +fn over_right_half(x: f32, y: f32) -> bool { + (16.0..32.0).contains(&x) && (0.0..32.0).contains(&y) +} +fn over_top_left(x: f32, y: f32) -> bool { + (0.0..16.0).contains(&x) && (0.0..16.0).contains(&y) +} +fn over_bottom_left(x: f32, y: f32) -> bool { + (0.0..16.0).contains(&x) && (16.0..32.0).contains(&y) +} +/// The server's favicon in icon slot `slot`, else `misc/unknown_server`. +fn draw_server_icon( + atlas: &HudAtlas, + batch: &mut HudBatch, + pixels: Option<&[u8]>, + slot: usize, + x: f32, + y: f32, +) { + let sprite = format!("horizon/world-icon{}", slot % crate::hud::WORLD_ICON_SLOTS); + if let Some(pixels) = pixels + && let Some(rect) = atlas.sprites.get(&sprite) + { + batch.patches.push(crate::font::Patch { + x: (rect.u0 * atlas.width as f32).round() as u32, + y: (rect.v0 * atlas.height as f32).round() as u32, + width: 64, + height: 64, + rgba: pixels.to_vec(), + }); + batch.sprite_scaled(atlas, &sprite, x, y, 32.0, 32.0, u32::MAX); + } else { + batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); + } +} /// `LoadingDotsText.get`. fn loading_dots(millis: u128) -> &'static str { ["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize] } +fn ping_tooltip( + servers: &[ServerEntry], + pings: &HashMap, + size: (f32, f32), + scroll: f32, + cursor: (f32, f32), +) -> Option { + let Row::Server(i) = row_at(servers.len(), 0, cursor, size, scroll)? else { + return None; + }; + let (top, _, left) = list_area(size.0, size.1); + let x = left + 2.0 + ROW_WIDTH - 4.0 - 15.0; + let y = top + 4.0 - scroll.trunc() + i as f32 * ROW_HEIGHT; + if cursor.0 < x || cursor.0 >= x + 10.0 || cursor.1 < y || cursor.1 >= y + 8.0 { + return None; + } + Some(match pings.get(&servers[i].ip) { + Some(Ping::Ok { ms, .. }) => format_translation( + &crate::lang::get_or("multiplayer.status.ping", "%s ms"), + &[Text::literal(ms.to_string())], + ), + Some(Ping::Failed(_)) => Text::literal(crate::lang::get_or( + "multiplayer.status.no_connection", + "(no connection)", + )), + _ => Text::literal(crate::lang::get_or( + "multiplayer.status.pinging", + "Pinging...", + )), + }) +} + impl Screen { + /// Draw after the list and footer so the tooltip is neither clipped nor covered. + pub fn draw_tooltip(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) { + let Self::List { + servers, + pings, + lan, + scroll, + .. + } = self + else { + return; + }; + let size = (batch.width.ceil(), batch.height.ceil()); + let (top, bottom, _) = list_area(size.0, size.1); + let mut scroll = *scroll; + scroll.clamp( + top, + bottom, + content_height(servers.len(), lan.games().len()), + ); + if let Some(text) = + ping_tooltip(servers, &pings.lock().unwrap(), size, scroll.amount, cursor) + { + crate::ui::tooltip(batch, atlas, &[text], cursor); + } + } + /// The address of list row `row` (saved servers, then LAN games). pub fn address_of(&self, row: usize) -> Option { match self { @@ -183,11 +375,13 @@ impl Screen { pub fn list(saves: &Path) -> Self { let servers = servers::load(&servers_file(saves)); let pings: Pings = Arc::default(); - ping_all(&servers, &pings); + let icons: Icons = Arc::default(); + ping_all(&servers, &pings, &icons, &servers_file(saves)); Self::List { servers, selected: None, pings, + icons, lan: Scanner::start(), scroll: crate::ui::Scroll::default(), } @@ -284,6 +478,29 @@ impl Screen { 51, ), ], + // ConfirmScreen's two 150-wide buttons, 4 apart, under the message. + Self::ConfirmDelete { lines, .. } => { + let y = confirm_top(h, lines.get()) + 41.0 + lines.get() as f32 * 9.0; + let x = (w.ceil() / 2.0).floor(); + vec![ + b( + x - 152.0, + y, + 150.0, + &crate::lang::get_or("selectServer.deleteButton", "Delete"), + true, + 58, + ), + b( + x + 2.0, + y, + 150.0, + &crate::lang::get_or("gui.cancel", "Cancel"), + true, + 59, + ), + ] + } Self::Direct { address } => vec![ b( w / 2.0 - 100.0, @@ -343,32 +560,31 @@ impl Screen { } } } + /// An EditBox and its label: the label at `label_y` (one pixel in, in + /// 0xA0A0A0), the 200x20 box at `box_y`. fn field( atlas: &HudAtlas, batch: &mut HudBatch, label: &str, value: &str, - y: f32, + (label_y, box_y): (f32, f32), focused: bool, blink: bool, ) { - let w = batch.width; - crate::widgets::target_as( - [w / 2.0 - 100.0, y + 11.0, 200.0, 20.0], - crate::widgets::Kind::Field, - ); + let x = (batch.width.ceil() / 2.0).floor() - 100.0; + crate::widgets::target_as([x, box_y, 200.0, 20.0], crate::widgets::Kind::Field); batch.text( atlas, label, - w / 2.0 - 100.0, - y, + x + 1.0, + label_y, rgba(160, 160, 160, 255), true, ); batch.fill( atlas, - w / 2.0 - 100.0, - y + 11.0, + x, + box_y, 200.0, 20.0, if focused { @@ -377,14 +593,7 @@ impl Screen { rgba(160, 160, 160, 255) }, ); - batch.fill( - atlas, - w / 2.0 - 99.0, - y + 12.0, - 198.0, - 18.0, - rgba(0, 0, 0, 255), - ); + batch.fill(atlas, x + 1.0, box_y + 1.0, 198.0, 18.0, rgba(0, 0, 0, 255)); let shown = if focused && blink { format!("{value}_") } else { @@ -393,13 +602,13 @@ impl Screen { batch.text( atlas, &shown, - w / 2.0 - 96.0, - y + 17.0, + x + 4.0, + box_y + 6.0, rgba(224, 224, 224, 255), true, ); } - pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool, cursor: (f32, f32)) { let (w, h) = (batch.width, batch.height); crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { @@ -411,6 +620,7 @@ impl Screen { servers, selected, pings, + icons, lan, scroll, } => { @@ -437,6 +647,9 @@ impl Screen { crate::ui::list_background(batch, atlas, top, bottom, false); let first = batch.vertices.len(); let pings = pings.lock().unwrap(); + let icons = icons.lock().unwrap(); + // The row under the pointer (`isHovered`). + let hovered = row_at(servers.len(), games.len(), cursor, (w, h), scroll.amount); let millis = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_millis()); @@ -483,25 +696,18 @@ impl Screen { match row { Row::Server(k) => { let server = &servers[k]; - batch.sprite_scaled( - atlas, - "misc/unknown_server", - cx, - cy, - 32.0, - 32.0, - u32::MAX, - ); - batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false); + let icon = icons.get(&server.ip); + draw_server_icon(atlas, batch, icon.map(|p| p.as_slice()), i, cx, cy); + batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, true); // OnlineServerEntry: up to two lines of MOTD, the - // player count left of the status icon. - let (motd, status, motd_color, icon) = match pings.get(&server.ip) { + // player count left of the status icon, all with + // GuiGraphics.text's shadow. + let (motd, status, sprite) = match pings.get(&server.ip) { Some(Ping::Ok { motd, players, ms, .. }) => ( - motd.clone(), - players.clone(), - gray, + motd.resolve_legacy(), + Ping::player_count(*players), format!( "server_list/ping_{}", match ms { @@ -514,12 +720,9 @@ impl Screen { ), ), Some(Ping::Failed(_)) => ( - crate::lang::get_or( - "multiplayer.status.cannot_connect", - "Can't connect to server", - ), - String::new(), - rgba(255, 0, 0, 255), + Text::translate("multiplayer.status.cannot_connect", &[]) + .with_color(0xFF0000), + Text::empty(), "server_list/unreachable".to_owned(), ), _ => { @@ -527,50 +730,71 @@ impl Screen { let frame = (millis / 100 + i as u128 * 2) & 7; let frame = if frame > 4 { 8 - frame } else { frame }; ( - crate::lang::get_or( - "multiplayer.status.pinging", - "Pinging...", - ), - String::new(), - gray, + Text::translate("multiplayer.status.pinging", &[]), + Text::empty(), format!("server_list/pinging_{}", frame + 1), ) } }; - for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas) + for (n, line) in atlas + .font + .split(&motd, ROW_WIDTH - 4.0 - 32.0 - 2.0) .iter() .take(2) .enumerate() { - batch.text( + batch.text_styled( atlas, line, cx + 35.0, cy + 12.0 + 9.0 * n as f32, - motd_color, - false, + gray, + true, ); } let icon_x = cx + ROW_WIDTH - 4.0 - 15.0; batch.sprite_scaled( atlas, - &format!("gui/sprites/{icon}"), + &format!("gui/sprites/{sprite}"), icon_x, cy, 10.0, 8.0, u32::MAX, ); - if !status.is_empty() { - let sw = HudBatch::text_width(atlas, &status).ceil(); - batch.text( - atlas, - &status, - icon_x - sw - 5.0, - cy + 1.0, - gray, - false, - ); + let sw = atlas.font.width_text(&status).ceil(); + batch.text_styled( + atlas, + &status, + icon_x - sw - 5.0, + cy + 1.0, + gray, + true, + ); + // Hovering the row: the join arrow over the icon + // and the move arrows, each highlighted under + // the pointer. + if hovered == Some(row) { + let (rx, ry) = (cursor.0 - cx, cursor.1 - cy); + batch.fill(atlas, cx, cy, 32.0, 32.0, 0xA0909090); + for (sprite, shown, over) in [ + ("join", true, over_right_half(rx, ry)), + ("move_up", k > 0, over_top_left(rx, ry)), + ("move_down", k + 1 < servers.len(), over_bottom_left(rx, ry)), + ] { + if shown { + let lit = if over { "_highlighted" } else { "" }; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/server_list/{sprite}{lit}"), + cx, + cy, + 32.0, + 32.0, + u32::MAX, + ); + } + } } } Row::LanHeader => { @@ -633,38 +857,88 @@ impl Screen { 17.0, u32::MAX, ); - Self::field(atlas, batch, "Server Name", name, 53.0, *focus == 0, blink); + // ManageServerScreen: labels at 53 and 94, boxes at 66 and 106. + Self::field( + atlas, + batch, + "Server Name", + name, + (53.0, 66.0), + *focus == 0, + blink, + ); Self::field( atlas, batch, "Server Address", address, - 94.0, + (94.0, 106.0), *focus == 1, blink, ); } Self::Direct { address } => { - centered(batch, "Direct Connection", 20.0, u32::MAX); + // DirectJoinServerScreen: the title at 20, the label at 100 + // and the box at 116. + centered( + batch, + &crate::lang::get_or("selectServer.direct", "Direct Connection"), + 20.0, + u32::MAX, + ); Self::field( atlas, batch, - "Server Address", + &crate::lang::get_or("addServer.enterIp", "Server Address"), address, - 100.0 - 11.0, + (100.0, 116.0), true, blink, ); } + Self::ConfirmDelete { name, lines, .. } => { + // ConfirmScreen: the title, then the message wrapped to + // width - 50, centred as a block. + let warning = format_translation( + &crate::lang::get_or( + "selectServer.deleteWarning", + "'%s' will be lost forever! (A long time!)", + ), + &[Text::literal(name.clone())], + ); + let message = atlas.font.split(&warning, (w.ceil() - 50.0).max(1.0)); + lines.set(message.len()); + let top = confirm_top(h, message.len()); + centered( + batch, + &crate::lang::get_or( + "selectServer.deleteQuestion", + "Are you sure you want to remove this server?", + ), + top, + u32::MAX, + ); + for (i, line) in message.iter().enumerate() { + centered(batch, &line.plain(), top + 17.0 + i as f32 * 9.0, u32::MAX); + } + } Self::Friend { code, relay, focus } => { centered(batch, "Join a Friend", 20.0, u32::MAX); - Self::field(atlas, batch, "Invite Code", code, 53.0, *focus == 0, blink); + Self::field( + atlas, + batch, + "Invite Code", + code, + (53.0, 64.0), + *focus == 0, + blink, + ); Self::field( atlas, batch, "Relay (optional)", relay, - 94.0, + (94.0, 105.0), *focus == 1, blink, ); @@ -745,11 +1019,45 @@ impl Screen { }, Some(44), ) => { - if let Some(i) = selected.take() + // JoinMultiplayerScreen's Delete asks first (ConfirmScreen). + if let Some(name) = selected + .and_then(|i| servers.get(i)) + .map(|s| s.name.clone()) + { + let list = std::mem::replace( + self, + Self::Direct { + address: String::new(), + }, + ); + *self = Self::ConfirmDelete { + list: Box::new(list), + name, + lines: std::cell::Cell::new(1), + }; + } + } + // deleteCallback: yes removes the server and clears the + // selection; either answer returns to the list as it was. + (Self::ConfirmDelete { .. }, Some(id @ (58 | 59))) => { + let Self::ConfirmDelete { list, .. } = std::mem::replace( + self, + Self::Direct { + address: String::new(), + }, + ) else { + unreachable!() + }; + *self = *list; + if id == 58 + && let Self::List { + servers, selected, .. + } = self + && let Some(i) = selected.take() && i < servers.len() { servers.remove(i); - let _ = servers::save(&servers_file(saves), servers); + save_servers(&servers_file(saves), servers); } } (Self::List { .. }, Some(45)) => *self = Self::list(saves), @@ -771,9 +1079,34 @@ impl Screen { if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) { return Outcome::None; } + let row = row_at(servers.len(), games, (x, y), (w, h), scroll.amount); + // OnlineServerEntry.mouseClicked: the icon's right half joins, + // its left quarters move the server up or down (and keep it + // selected). + if let Some(Row::Server(k)) = row { + let row_top = top + 2.0 - scroll.amount.trunc() + k as f32 * ROW_HEIGHT; + let (rx, ry) = ((x - left - 2.0).floor(), (y - row_top - 2.0).floor()); + if over_right_half(rx, ry) { + *selected = Some(k); + return Outcome::Connect(servers[k].ip.clone()); + } + let to = if k > 0 && over_top_left(rx, ry) { + Some(k - 1) + } else if k + 1 < servers.len() && over_bottom_left(rx, ry) { + Some(k + 1) + } else { + None + }; + if let Some(to) = to { + servers.swap(k, to); + save_servers(&servers_file(saves), servers); + *selected = Some(to); + return Outcome::None; + } + } // Clicking a selected row again joins it; the LAN header // takes the click without anything to join. - let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) { + let index = match row { Some(Row::Server(k)) => Some(k), Some(Row::Lan(k)) => Some(servers.len() + k), Some(Row::LanHeader) => { @@ -830,8 +1163,16 @@ impl Screen { return Outcome::Connect(format!("{}{code}", crate::net::FRIEND)); } } - (Self::Edit { focus, .. } | Self::Friend { focus, .. }, None) => { - for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] { + (Self::Edit { .. } | Self::Friend { .. }, None) => { + let boxes = if matches!(self, Self::Edit { .. }) { + [66.0, 106.0] + } else { + [64.0, 105.0] + }; + let (Self::Edit { focus, .. } | Self::Friend { focus, .. }) = self else { + unreachable!() + }; + for (i, fy) in [(0u8, boxes[0]), (1, boxes[1])] { if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 { *focus = i; } @@ -958,6 +1299,17 @@ impl Screen { pub fn escape(&mut self, saves: &Path) -> bool { match self { Self::List { .. } => true, + // ConfirmScreen.keyPressed: Escape answers no. + Self::ConfirmDelete { list, .. } => { + let list = std::mem::replace( + &mut **list, + Self::Direct { + address: String::new(), + }, + ); + *self = list; + false + } _ => { *self = Self::list(saves); false @@ -993,6 +1345,62 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { mod tests { use super::*; + #[test] + fn ping_tooltip_follows_only_visible_status_bars_and_current_ping() { + let servers: Vec<_> = (0..6) + .map(|i| ServerEntry::new("Test", &format!("server{i}"))) + .collect(); + let mut pings = HashMap::new(); + let size = (427.0, 240.0); + let hover = |pings: &HashMap, scroll, cursor| { + ping_tooltip(&servers, pings, size, scroll, cursor).map(|t| t.plain()) + }; + // The first bar is at (349, 37), with a 10 by 8 hit area. + assert_eq!( + hover(&pings, 0.0, (349.0, 37.0)).as_deref(), + Some("Pinging...") + ); + pings.insert( + "server0".into(), + Ping::Ok { + motd: Text::empty(), + players: None, + ms: 42, + version: String::new(), + }, + ); + assert_eq!(hover(&pings, 0.0, (358.9, 44.9)).as_deref(), Some("42 ms")); + pings.insert("server1".into(), Ping::Pinging); + for cursor in [ + (348.9, 37.0), + (359.0, 37.0), + (349.0, 36.9), + (349.0, 45.0), + (100.0, 40.0), + (349.0, 32.0), + (349.0, 181.0), + ] { + assert!(hover(&pings, 0.0, cursor).is_none(), "{cursor:?}"); + } + // Scrolling moves the next row's bars into the same location. + assert_eq!( + hover(&pings, 36.0, (349.0, 37.0)).as_deref(), + Some("Pinging...") + ); + assert_eq!(hover(&pings, 5.0, (349.0, 34.0)).as_deref(), Some("42 ms")); + assert!(hover(&pings, 36.0, (349.0, 33.0)).is_none()); + assert!(hover(&pings, 0.0, (349.0, 179.0)).is_none()); + assert!(hover(&pings, 216.0, (349.0, 37.0)).is_none()); // LAN header + pings.insert( + "server0".into(), + Ping::Failed("private connection error".into()), + ); + assert_eq!( + hover(&pings, 0.0, (349.0, 37.0)).as_deref(), + Some("(no connection)") + ); + } + #[test] fn the_lan_header_follows_the_saved_servers() { let all: Vec = rows(2, 1).collect(); @@ -1033,4 +1441,168 @@ mod tests { ["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"] ); } + + #[test] + fn player_count_is_dark_gray_with_gray_numbers() { + assert_eq!( + Ping::player_count(Some((3, 20))).component(), + serde_json::json!({ + "translate": "multiplayer.status.player_count", + "with": [{"text": "3", "color": "gray"}, {"text": "20", "color": "gray"}], + "color": "dark_gray", + }) + ); + assert_eq!( + Ping::player_count(None).component(), + serde_json::json!({"translate": "multiplayer.status.unknown", "color": "dark_gray"}) + ); + } + + fn png(size: u32) -> Vec { + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, size, size); + encoder.set_color(png::ColorType::Rgba); + let mut writer = encoder.write_header().unwrap(); + writer + .write_image_data(&vec![200; (size * size * 4) as usize]) + .unwrap(); + writer.finish().unwrap(); + out + } + + #[test] + fn favicons_are_64_pixel_pngs_behind_the_data_url() { + let icon = png(64); + let encoded = crate::lan::base64(&icon); + let (a, b) = encoded.split_at(10); + let json = serde_json::json!({ "favicon": format!("data:image/png;base64,{a}\n{b}") }); + let bytes = favicon_bytes(&json).unwrap(); + assert_eq!(bytes, icon); + assert_eq!(icon_pixels(&bytes).unwrap().len(), 64 * 64 * 4); + // FaviconTexture refuses other sizes; other formats are not icons. + assert!(icon_pixels(&png(32)).is_none()); + assert!(favicon_bytes(&serde_json::json!({ "favicon": encoded })).is_none()); + } + + #[test] + fn icon_arrows_join_and_move_servers() { + let dir = std::env::temp_dir().join(format!("horizon-mp-arrows-{}", std::process::id())); + let saves = dir.join("saves"); + std::fs::create_dir_all(&saves).unwrap(); + let file = servers_file(&saves); + let names = ["a", "b", "c"]; + let list: Vec = names + .iter() + .map(|n| ServerEntry::new(n, &format!("127.0.0.1:{}", 1 + n.len()))) + .collect(); + servers::save(&file, &list).unwrap(); + let mut screen = Screen::list(&saves); + let size = (427.0, 240.0); + let order = |screen: &Screen| match screen { + Screen::List { + servers, selected, .. + } => ( + servers.iter().map(|s| s.name.clone()).collect::>(), + *selected, + ), + _ => unreachable!(), + }; + // 427x240: rows start at x 61, the first icon at (63, 37). + let (ix, iy) = (63.0, 37.0); + // The first server has no up arrow: its top-left quarter selects it. + assert!(matches!( + screen.click(None, ix + 4.0, iy + 4.0, size, &saves), + Outcome::None + )); + assert_eq!( + order(&screen), + (vec!["a".into(), "b".into(), "c".into()], Some(0)) + ); + // Bottom-left quarter: down, saved, and still selected. + screen.click(None, ix + 4.0, iy + 20.0, size, &saves); + assert_eq!( + order(&screen), + (vec!["b".into(), "a".into(), "c".into()], Some(1)) + ); + let saved: Vec = servers::load(&file).into_iter().map(|s| s.name).collect(); + assert_eq!(saved, ["b", "a", "c"]); + // Top-left quarter of the second row: back up. + screen.click(None, ix + 4.0, iy + ROW_HEIGHT + 4.0, size, &saves); + assert_eq!( + order(&screen), + (vec!["a".into(), "b".into(), "c".into()], Some(0)) + ); + // The right half joins at once. + match screen.click(None, ix + 20.0, iy + 2.0 * ROW_HEIGHT + 10.0, size, &saves) { + Outcome::Connect(address) => assert_eq!(address, list[2].ip), + _ => panic!("the join arrow connects"), + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn delete_asks_before_removing_the_server() { + let dir = std::env::temp_dir().join(format!("horizon-mp-delete-{}", std::process::id())); + let saves = dir.join("saves"); + std::fs::create_dir_all(&saves).unwrap(); + let file = servers_file(&saves); + let list = vec![ + ServerEntry::new("Keep", "127.0.0.1:2"), + ServerEntry::new("Gone", "127.0.0.1:3"), + ]; + servers::save(&file, &list).unwrap(); + let size = (427.0, 240.0); + let names = + || -> Vec { servers::load(&file).into_iter().map(|s| s.name).collect() }; + let mut screen = Screen::list(&saves); + let select = |screen: &mut Screen| { + if let Screen::List { selected, .. } = screen { + *selected = Some(1); + } + }; + select(&mut screen); + // Delete opens the ConfirmScreen: nothing is removed yet. + screen.click(Some(44), 0.0, 0.0, size, &saves); + assert!(matches!(&screen, Screen::ConfirmDelete { name, .. } if name == "Gone")); + let labels: Vec<(f32, f32, String, u8)> = screen + .buttons(size.0, size.1) + .into_iter() + .map(|b| (b.0, b.1, b.3, b.5)) + .collect(); + assert_eq!( + labels, + [ + (61.0, 135.0, "Delete".to_owned(), 58), + (215.0, 135.0, "Cancel".to_owned(), 59), + ] + ); + assert_eq!(names(), ["Keep", "Gone"]); + // Cancel and Escape return to the list with the selection kept. + screen.click(Some(59), 0.0, 0.0, size, &saves); + assert!(matches!( + &screen, + Screen::List { + selected: Some(1), + .. + } + )); + screen.click(Some(44), 0.0, 0.0, size, &saves); + assert!(!screen.escape(&saves)); + assert!(matches!( + &screen, + Screen::List { + selected: Some(1), + .. + } + )); + assert_eq!(names(), ["Keep", "Gone"]); + // Delete removes it, saves, and clears the selection. + screen.click(Some(44), 0.0, 0.0, size, &saves); + screen.click(Some(58), 0.0, 0.0, size, &saves); + assert!( + matches!(&screen, Screen::List { selected: None, servers, .. } if servers.len() == 1) + ); + assert_eq!(names(), ["Keep"]); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index 75cb85b55..bfaf05c9b 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -14,7 +14,7 @@ use crate::{ graphics_style::Cost, graphics_ui::{self, Item, Level}, hud::{HudAtlas, HudBatch}, - options_ui::{Event, Kind, Opt, OptionsUi, Page, apply_preset}, + options_ui::{self, Event, Kind, Opt, OptionsUi, Page, apply_preset}, settings::{SOUND_SOURCES, Settings}, ui_theme::{self as t, CONTROL, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, Ui, color, id}, }; @@ -34,6 +34,8 @@ pub enum HRow { Graphics(Item, Cost, &'static str), /// One of Horizon's extras (`extras`), off by default. Extra(extras::Item), + /// Installed mod `i` (`settings.mods.installed`) and its switch. + Mod(usize), } /// A sidebar section: name, description, rows. pub struct Section { @@ -101,6 +103,8 @@ pub const SECTIONS: &[Section] = &[ [ Opt::PadEnabled, Opt::PadVibration, + Opt::PadAdaptiveTriggers, + Opt::PadLightbar, Opt::PadLookSensitivity, Opt::PadToggleSneak, Opt::PadInvertX, @@ -184,6 +188,18 @@ pub const SECTIONS: &[Section] = &[ .collect() }, }, + Section { + name: "Mods", + blurb: "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on; check what it may do first.", + rows: |s| { + if s.mods.installed.is_empty() { + return vec![HRow::Header( + "No mods: put .hmod files in the horizon-mods folder", + )]; + } + (0..s.mods.installed.len()).map(HRow::Mod).collect() + }, + }, ]; const NAV: u64 = id("options.nav", 0); @@ -219,6 +235,7 @@ fn switch_value(opt: Opt, s: &Settings) -> Option { Opt::JapaneseGlyphs => s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled, Opt::PadVibration => s.controller.vibration, + Opt::PadAdaptiveTriggers => s.controller.adaptive_triggers, Opt::PadInvertX => s.controller.invert_x, Opt::PadInvertY => s.controller.invert_y, _ => return None, @@ -405,6 +422,20 @@ impl OptionsUi { ); } } + HRow::Mod(m) => { + let installed = &s.mods.installed[m]; + let cost = match (&installed.problem, installed.dev) { + (Some(_), _) => (3, "Stopped"), + (None, true) => (1, "Dev"), + (None, false) => (0, ""), + }; + let text = installed + .problem + .as_deref() + .unwrap_or(&installed.description); + ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0); + ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m)); + } HRow::Extra(item) => { let cy = y + ROW_H / 2.0; let id = ROW + i as u64; @@ -608,6 +639,10 @@ impl OptionsUi { item.cycle(&mut s.extras, right); events.push(Event::Changed); } + Some(HRow::Mod(m)) => { + s.mods.toggle(*m); + events.push(Event::Changed); + } _ => {} } } @@ -624,12 +659,7 @@ impl OptionsUi { /// settings go through `graphics_ui`. fn set_item_slider(item: Item, s: &mut Settings, v: f32) { match item { - Item::Vanilla(opt) => { - opt.set_slider(s, v); - if opt == Opt::Preset { - apply_preset(s); - } - } + Item::Vanilla(opt) => options_ui::set_slider(opt, s, v), Item::Horizon(_) => item.set_slider(s, v), } } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index ad89648e0..9da3a8bdf 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -71,6 +71,8 @@ pub enum Opt { /// Horizon's controller settings (`horizon-controller.txt`). PadEnabled, PadVibration, + PadAdaptiveTriggers, + PadLightbar, PadLookSensitivity, PadInvertX, PadInvertY, @@ -169,6 +171,8 @@ impl Opt { // Horizon's own options: English captions (no vanilla keys). Opt::PadEnabled => "Controller", Opt::PadVibration => "Vibration", + Opt::PadAdaptiveTriggers => "Adaptive Triggers", + Opt::PadLightbar => "Lightbar", Opt::PadLookSensitivity => "Look Sensitivity", Opt::PadInvertX => "Invert Look X", Opt::PadInvertY => "Invert Look Y", @@ -423,6 +427,7 @@ impl Opt { Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), Opt::PadEnabled => on_off(s.controller.enabled), Opt::PadVibration => on_off(s.controller.vibration), + Opt::PadAdaptiveTriggers => on_off(s.controller.adaptive_triggers), Opt::PadInvertX => on_off(s.controller.invert_x), Opt::PadInvertY => on_off(s.controller.invert_y), Opt::PadToggleSneak => tr(if s.controller.toggle_sneak { @@ -430,6 +435,11 @@ impl Opt { } else { "options.key.hold" }), + Opt::PadLightbar => Text::literal(match s.controller.lightbar { + gamepad::Lightbar::Health => "Health", + gamepad::Lightbar::Dimension => "Dimension", + gamepad::Lightbar::Off => "Off", + }), Opt::PadGlyphs => Text::literal(match s.controller.glyphs { GlyphStyle::Auto => "Auto", GlyphStyle::Xbox => "Xbox", @@ -566,9 +576,20 @@ impl Opt { Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled = !s.controller.enabled, Opt::PadVibration => s.controller.vibration = !s.controller.vibration, + Opt::PadAdaptiveTriggers => { + s.controller.adaptive_triggers = !s.controller.adaptive_triggers + } Opt::PadInvertX => s.controller.invert_x = !s.controller.invert_x, Opt::PadInvertY => s.controller.invert_y = !s.controller.invert_y, Opt::PadToggleSneak => s.controller.toggle_sneak = !s.controller.toggle_sneak, + Opt::PadLightbar => { + let all = gamepad::Lightbar::ALL; + let i = all + .iter() + .position(|l| *l == s.controller.lightbar) + .unwrap_or(0) as u8; + s.controller.lightbar = all[usize::from(next(i, 3))]; + } Opt::PadGlyphs => { let i = GlyphStyle::ALL .iter() @@ -601,32 +622,53 @@ const PRESETS: [&str; 4] = ["fast", "fancy", "fabulous", "custom"]; fn preset_index(p: &str) -> usize { PRESETS.iter().position(|x| *x == p).unwrap_or(1) } -/// GraphicsPreset.apply: quality options for Fast/Fancy/Fabulous. +/// A slider moved to `v` (OptionInstance.set): the graphics preset applies +/// its options when its value changes (`Options.applyGraphicsPreset`). +pub fn set_slider(opt: Opt, s: &mut Settings, v: f32) { + let preset = preset_index(&s.graphics_preset); + opt.set_slider(s, v); + if opt == Opt::Preset && preset_index(&s.graphics_preset) != preset { + apply_preset(s); + } +} +/// GraphicsPreset.apply: the options Fast, Fancy and Fabulous set (texture +/// filtering and anisotropy have no option here yet). pub fn apply_preset(s: &mut Settings) { + let fabulous = s.graphics_preset == "fabulous"; match s.graphics_preset.as_str() { "fast" => { + s.biome_blend = 1; + s.render_distance = 8; + s.prioritize_chunk_updates = 0; + s.simulation_distance = 6; + s.smooth_lighting = false; s.clouds = "fast".into(); s.particles = 1; + s.mipmap_levels = 2; s.entity_shadows = false; - s.biome_blend = 1; + s.entity_distance = 0.75; + s.menu_blur = 2; + s.cloud_range = 32; s.cutout_leaves = false; s.improved_transparency = false; - s.mipmap_levels = 2; s.weather_radius = 5; - s.cloud_range = 64; - s.entity_distance = 0.75; } "fancy" | "fabulous" => { + s.biome_blend = 2; + s.render_distance = if fabulous { 32 } else { 16 }; + s.prioritize_chunk_updates = 1; + s.simulation_distance = 12; + s.smooth_lighting = true; s.clouds = "true".into(); s.particles = 0; - s.entity_shadows = true; - s.biome_blend = 2; - s.cutout_leaves = true; - s.improved_transparency = s.graphics_preset == "fabulous"; s.mipmap_levels = 4; + s.entity_shadows = true; + s.entity_distance = if fabulous { 1.25 } else { 1.0 }; + s.menu_blur = 5; + s.cloud_range = if fabulous { 128 } else { 64 }; + s.cutout_leaves = true; + s.improved_transparency = fabulous; s.weather_radius = 10; - s.cloud_range = 128; - s.entity_distance = 1.0; } _ => {} } @@ -1028,6 +1070,8 @@ impl OptionsUi { rows.extend(pairs(&[ Opt::PadEnabled, Opt::PadVibration, + Opt::PadAdaptiveTriggers, + Opt::PadLightbar, Opt::PadLookSensitivity, Opt::PadToggleSneak, Opt::PadInvertX, @@ -1755,7 +1799,7 @@ impl OptionsUi { .iter() .find(|wd| matches!(&wd.kind, WKind::Slider { opt: o, .. } if *o == opt)) { - opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); + set_slider(opt, s, ui::slider_value(wd.x, wd.w, x)); events.push(Event::Changed); } return events; @@ -1838,10 +1882,7 @@ impl OptionsUi { } WKind::Slider { opt, .. } => { self.dragging = Some(opt); - opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); - if opt == Opt::Preset { - apply_preset(s); - } + set_slider(opt, s, ui::slider_value(wd.x, wd.w, x)); events.push(Event::Changed); } WKind::LanguageRow { code, .. } => { @@ -2125,6 +2166,63 @@ mod tests { } } + #[test] + fn classic_graphics_presets_set_the_distances() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Video); + let size = (480.0, 480.0); + let (widgets, _, _, _) = ui.layout(&s, size.0, size.1); + let preset = widgets + .iter() + .find(|wd| { + matches!( + wd.kind, + WKind::Slider { + opt: Opt::Preset, + .. + } + ) + }) + .expect("the Graphics preset slider is in classic Video Settings"); + // Dragging the slider across its range (GraphicsPreset.apply on each change). + let y = preset.y + 1.0; + let mut seen = Vec::new(); + ui.click( + &mut s, + &atlas, + preset.x + 1.0, + y, + size, + [854, 480], + false, + false, + ); + for step in 0..=20 { + let x = preset.x + preset.w * step as f32 / 20.0; + ui.click(&mut s, &atlas, x, y, size, [854, 480], true, false); + seen.push(( + s.graphics_preset.clone(), + s.render_distance, + s.simulation_distance, + s.cloud_range, + )); + } + ui.release(); + for expected in [ + ("fast", 8, 6, 32), + ("fancy", 16, 12, 64), + ("fabulous", 32, 12, 128), + ] { + assert!( + seen.iter() + .any(|(p, r, d, c)| (p.as_str(), *r, *d, *c) == expected), + "{expected:?} in {seen:?}" + ); + } + } + #[test] fn gui_scale_cycle_handles_reverse_and_out_of_range_saved_values() { for (framebuffer, force_unicode, max) in [ diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index b5778f40d..22c2b26ac 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2107,8 +2107,8 @@ pub struct Level { pub world_spawn: Option<[i32; 3]>, pub difficulty: String, pub hardcore: bool, - /// `allowCommands` chosen on the Create New World screen; unset keeps - /// the saved value (off for a new world). + /// `allowCommands`: read from `level.dat` or chosen on the Create New + /// World screen; unset is written as off. pub allow_commands: Option, /// Game rule values by name without namespace (`keep_inventory`, ...). pub game_rules: BTreeMap, @@ -2182,6 +2182,7 @@ impl Level { level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into()); level.hardcore = n(d.get("hardcore")) != 0; } + level.allow_commands = Some(n(data.get("allowCommands")) != 0); let mut rules: BTreeMap = GAME_RULES .iter() .map(|(k, v)| ((*k).to_owned(), *v)) diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 5e25e9679..34b945626 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -181,6 +181,8 @@ pub struct Settings { pub controller: crate::gamepad::PadSettings, /// Horizon's optional extras (`horizon-extras.txt`), all off by default. pub extras: crate::extras::Extras, + /// The Horizon mods turned on (`horizon-mods.txt`), all off by default. + pub mods: crate::mod_list::ModList, } impl Default for Settings { fn default() -> Self { @@ -253,6 +255,7 @@ impl Default for Settings { horizon: Default::default(), controller: Default::default(), extras: Default::default(), + mods: Default::default(), } } } @@ -301,17 +304,23 @@ impl Settings { .parent() .map(crate::extras::Extras::load) .unwrap_or_default(); + let mods = path + .parent() + .map(crate::mod_list::ModList::load) + .unwrap_or_default(); let settings = match fs::read(path) { Ok(bytes) => Self { horizon, controller, extras, + mods, ..Self::parse(&String::from_utf8_lossy(&bytes)) }, Err(_) => Self { horizon, controller, extras, + mods, ..Self::default() }, }; @@ -412,6 +421,7 @@ impl Settings { horizon: Default::default(), controller: Default::default(), extras: Default::default(), + mods: Default::default(), auto_jump: f.bool("autoJump"), language: f.string("lang"), force_unicode: f.bool("forceUnicodeFont"), @@ -546,6 +556,7 @@ impl Settings { self.horizon.save(dir); self.controller.save(dir); self.extras.save(dir); + self.mods.save(dir); } } /// Volume of a sound source (master excluded). diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index e59a2b6c5..d050e5fda 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -15,10 +15,39 @@ pub struct SpriteAnimation { frames: Arc>>, clip: Arc, } +/// What an animated sprite shows: `frame`, mixed `millis` thousandths of the +/// way towards `next` (0 for a single frame). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameBlend { + pub frame: usize, + pub next: usize, + pub millis: u32, +} impl SpriteAnimation { pub fn frame(&self, tick: u64) -> usize { self.clip.sample(tick).frame as usize } + /// `SpriteContents.AnimationState.drawToAtlas`: an animation with + /// `interpolate` mixes the frame with the next one by + /// `(int)(subFrame / time * 1000)` thousandths; others show the frame. + pub fn blend(&self, tick: u64) -> FrameBlend { + let sample = self.clip.sample(tick); + let frame = sample.frame as usize; + let next = sample.next_frame as usize; + if self.clip.interpolates() && sample.interpolation_millis > 0 && next != frame { + FrameBlend { + frame, + next, + millis: sample.interpolation_millis, + } + } else { + FrameBlend { + frame, + next: frame, + millis: 0, + } + } + } pub fn resized_pixels(&self, frame: usize, width: u32, height: u32) -> Vec { let source = self.pixels(frame); let side = (source.len() / 4).isqrt() as u32; @@ -223,6 +252,7 @@ impl Sprites { .and_then(|v| v.get("texture")) .and_then(|v| serde_json::from_str::(v.get()).ok()); self.mips.push(crate::mipmap::Settings { + native_size: side, strategy: texture .as_ref() .and_then(|t| t["mipmap_strategy"].as_str()) @@ -254,12 +284,16 @@ impl Sprites { #[cfg(test)] pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation { + test_clip(size, layer, r#"{"frametime":1,"frames":[0,1]}"#) +} +#[cfg(test)] +pub(crate) fn test_clip(size: u32, layer: u32, metadata: &str) -> SpriteAnimation { let frame = |blue: u8| { (0..size * size) .flat_map(|i| [(i % size) as u8, (i / size) as u8, blue, 255]) .collect() }; - let metadata = AnimationMetadata::from_json(r#"{"frametime":1,"frames":[0,1]}"#).unwrap(); + let metadata = AnimationMetadata::from_json(metadata).unwrap(); SpriteAnimation { layer, frames: Arc::new(vec![frame(0), frame(99)]), @@ -408,4 +442,27 @@ mod tests { assert_eq!(animation.frame(tick), frame); } } + + #[test] + fn interpolated_animations_blend_towards_the_next_frame() { + let animation = test_clip(16, 0, r#"{"frametime":4,"interpolate":true}"#); + let blend = |frame, next, millis| FrameBlend { + frame, + next, + millis, + }; + for (tick, expected) in [ + (0, blend(0, 0, 0)), + (1, blend(0, 1, 250)), + (3, blend(0, 1, 750)), + (4, blend(1, 1, 0)), + (5, blend(1, 0, 250)), + (8, blend(0, 0, 0)), + ] { + assert_eq!(animation.blend(tick), expected, "tick {tick}"); + } + let stepped = test_clip(16, 0, r#"{"frametime":4}"#); + assert_eq!(stepped.blend(1), blend(0, 0, 0)); + assert_eq!(stepped.blend(5), blend(1, 1, 0)); + } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 94dca0560..5ea173d73 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -81,6 +81,7 @@ struct MeshSettings { blend_radius: i32, smooth_lighting: bool, cutout_leaves: bool, + cull_leaves: bool, } enum Job { Generate(i32, i32), @@ -183,6 +184,7 @@ pub struct Streaming { /// The `ao` and `cutoutLeaves` options. pub smooth_lighting: bool, pub cutout_leaves: bool, + pub cull_leaves: bool, /// Incremental relighting of block edits on lit chunks (see `light::relight`). light_tables: Arc, /// Applied edits by sequence, replayed onto light jobs snapshotted before them. @@ -401,6 +403,7 @@ impl Streaming { blend_radius: settings.blend_radius, smooth_lighting: settings.smooth_lighting, cutout_leaves: settings.cutout_leaves, + cull_leaves: settings.cull_leaves, assets: &context.assets, tables: &context.tables, biomes: &context.biomes, @@ -454,6 +457,7 @@ impl Streaming { biome_blend: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, light_tables, light_log: Vec::new(), light_edit_sequence: 0, @@ -615,6 +619,9 @@ impl Streaming { pub fn is_lit(&self, x: i32, z: i32) -> bool { self.lit.contains(&(x, z)) } + pub fn is_meshing(&self, section: (i32, i32, i32)) -> bool { + self.meshing.contains_key(§ion) + } pub fn pending(&self) -> usize { self.shared.queue.lock().unwrap().len() } @@ -1005,6 +1012,7 @@ impl Streaming { blend_radius: self.biome_blend, smooth_lighting: self.smooth_lighting, cutout_leaves: self.cutout_leaves, + cull_leaves: self.cull_leaves, }, ), ); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index a514ed4bf..ce4016b27 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -27,7 +27,7 @@ const ROW_WIDTH: f32 = 270.0; fn edit_top(h: f32) -> f32 { ((h.ceil() - 234.0) / 2.0).floor() } -fn confirm_top(h: f32, lines: usize) -> f32 { +pub(crate) fn confirm_top(h: f32, lines: usize) -> f32 { ((h.ceil() - 61.0 - lines as f32 * 9.0) / 2.0).floor() } @@ -1020,6 +1020,7 @@ impl Title { atlas, batch, (self.started.elapsed().as_millis() / 300).is_multiple_of(2), + cursor, ), } for b in self.buttons(w, h) { @@ -1084,6 +1085,9 @@ impl Title { { self.create_tooltip(atlas, batch, cursor, name, *creative, options); } + if let Mode::Multiplayer(screen) = &self.mode { + screen.draw_tooltip(atlas, batch, cursor); + } if let Some((at, toast)) = &self.toast && at.elapsed().as_secs() < 5 { diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 23e3f7f6b..74edd5049 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -210,6 +210,7 @@ fn relit_columns_keep_every_mesh_current() { blend_radius: 2, smooth_lighting: true, cutout_leaves: true, + cull_leaves: false, assets: &context.assets, tables: &context.tables, biomes: &context.biomes, diff --git a/crates/horizon-dualsense/Cargo.toml b/crates/horizon-dualsense/Cargo.toml index 8e26f2e59..fe05b4f59 100644 --- a/crates/horizon-dualsense/Cargo.toml +++ b/crates/horizon-dualsense/Cargo.toml @@ -11,6 +11,8 @@ description = "The DualSense's output over HID: rumble, adaptive triggers, light # IOKit on macOS (opened shared, so gilrs keeps reading the pad), the HID API on Windows. hidapi = { version = "2.6.7", default-features = false, features = ["linux-static-hidraw", "macos-shared-device"] } log = "0.4" +# HD haptics through the pad's own audio device (USB). +cpal = "0.16" [lints] workspace = true diff --git a/crates/horizon-dualsense/examples/dualsense.rs b/crates/horizon-dualsense/examples/dualsense.rs index 90d62ebef..6c0ac6642 100644 --- a/crates/horizon-dualsense/examples/dualsense.rs +++ b/crates/horizon-dualsense/examples/dualsense.rs @@ -6,7 +6,7 @@ //! The pad's input report carries the triggers' active effect, and its accelerometer and gyro //! pick up the motors, so `rumble` measures the shake against the pad lying still. use horizon_dualsense::device::{DualSense, Link, State}; -use horizon_dualsense::{Output, TRIGGER_OFF, TriggerEffect}; +use horizon_dualsense::{Output, TRIGGER_OFF}; use std::time::{Duration, Instant}; /// Offsets in the input report's data, after the report ID (USB 0x01) or the ID and a tag byte @@ -223,13 +223,16 @@ fn leds(pad: &mut DualSense) { } fn triggers(pad: &mut DualSense) { - // Raw effects in the pad's own encoding (docs/controllers.md): resistance from zone 3 on at - // strength 6, then a weapon click between zones 2 and 6. - let feedback: TriggerEffect = [0x21, 0xf8, 0x03, 0x00, 0xda, 0xb6, 0x2d, 0, 0, 0, 0]; - let weapon: TriggerEffect = [0x25, 0x44, 0x00, 0x05, 0, 0, 0, 0, 0, 0, 0]; + use horizon_dualsense::trigger; + // The game's feels (docs/controllers.md "Adaptive triggers"); each holds two seconds so a + // hand on the pad can feel it. for (name, effect) in [ - ("feedback", feedback), - ("weapon", weapon), + ("bow drawn halfway", trigger::feedback(1, 4)), + ("bow drawn fully", trigger::feedback(1, 8)), + ("crossbow click", trigger::weapon(3, 6, 8)), + ("mining stone", trigger::vibration(1, 3, 30)), + ("mining obsidian", trigger::vibration(1, 5, 30)), + ("boost wall", trigger::feedback(4, 6)), ("off", TRIGGER_OFF), ] { write( @@ -240,9 +243,12 @@ fn triggers(pad: &mut DualSense) { ..Output::default() }, ); - std::thread::sleep(Duration::from_millis(100)); - print!(" {name:9}"); + std::thread::sleep(Duration::from_millis(150)); + print!(" {name:18}"); trigger_status(pad); + if effect != TRIGGER_OFF { + std::thread::sleep(Duration::from_millis(1850)); + } } } @@ -256,7 +262,7 @@ fn link() { } println!(" open over {:?} after {:?}", link.open(), start.elapsed()); link.set(State { - triggers: [TRIGGER_OFF, [0x25, 0x44, 0x00, 0x05, 0, 0, 0, 0, 0, 0, 0]], + triggers: [TRIGGER_OFF, horizon_dualsense::trigger::weapon(2, 6, 6)], lightbar: Some([0x8b, 0x5c, 0xf6]), player_leds: Some(0b00100), }); diff --git a/crates/horizon-dualsense/src/device.rs b/crates/horizon-dualsense/src/device.rs index 2ed168292..97c6ec72b 100644 --- a/crates/horizon-dualsense/src/device.rs +++ b/crates/horizon-dualsense/src/device.rs @@ -1,6 +1,8 @@ //! The pad over hidapi, and the thread that writes to it: writes block (a Bluetooth report can //! take milliseconds), so the game only hands over what the pad should do. -use crate::{Output, TRIGGER_OFF, TriggerEffect, Vibration, is_dualsense}; +use crate::{ + DEFAULT_LIGHTBAR, Output, PLAYER_1, TRIGGER_OFF, TriggerEffect, Vibration, is_dualsense, +}; use hidapi::{BusType, HidApi, HidDevice, HidResult}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; @@ -303,7 +305,13 @@ impl Writer { self.flush(); } if let Some(pad) = self.pad.as_mut() { - let _ = pad.write(&Output::release()); + // The lights go back to a host's defaults, if they were changed. + let release = Output { + lightbar: self.state.lightbar.map(|_| DEFAULT_LIGHTBAR), + player_leds: self.state.player_leds.map(|_| PLAYER_1), + ..Output::release() + }; + let _ = pad.write(&release); } } diff --git a/crates/horizon-dualsense/src/haptics.rs b/crates/horizon-dualsense/src/haptics.rs new file mode 100644 index 000000000..6aa9d5ab8 --- /dev/null +++ b/crates/horizon-dualsense/src/haptics.rs @@ -0,0 +1,149 @@ +//! HD haptics: on USB the DualSense is also a four-channel 48 kHz audio device, whose channels 3 +//! and 4 drive the left and right voice-coil actuators (1 and 2 are its speaker and headset). +//! Vibrations are synthesized as waveforms on those two channels; the first two stay silent. +//! Over Bluetooth there is no audio device, and the motors' emulation is used instead. +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use std::collections::VecDeque; +use std::f32::consts::TAU; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +const RATE: u32 = 48_000; +/// The frequencies the heavy and light parts of a vibration play at. +pub const HEAVY_HZ: f32 = 80.0; +pub const LIGHT_HZ: f32 = 200.0; +/// Fades between steps, so a level change doesn't click. +const RAMP: f32 = 0.004; + +/// The pad's audio output, playing the queued samples (left, right actuator). +pub struct Haptics { + queue: Arc>>, + _stream: cpal::Stream, +} + +impl Haptics { + /// The DualSense's audio device, if one is there with its four channels (USB). + pub fn open() -> Option { + let host = cpal::default_host(); + let device = host.output_devices().ok()?.find(is_dualsense)?; + let config = cpal::StreamConfig { + channels: 4, + sample_rate: cpal::SampleRate(RATE), + buffer_size: cpal::BufferSize::Default, + }; + let queue = Arc::new(Mutex::new(VecDeque::new())); + let source = queue.clone(); + let stream = device + .build_output_stream( + &config, + move |data: &mut [f32], _| { + let mut queue = source.lock().unwrap_or_else(|e| e.into_inner()); + for frame in data.chunks_mut(4) { + let [left, right] = queue.pop_front().unwrap_or_default(); + frame.copy_from_slice(&[0.0, 0.0, left, right]); + } + }, + |e| log::debug!("DualSense haptics: {e}"), + None, + ) + .map_err(|e| log::info!("Horizon: DualSense haptics unavailable: {e}")) + .ok()?; + stream.play().ok()?; + log::info!("DualSense HD haptics through its audio device"); + Some(Haptics { + queue, + _stream: stream, + }) + } + + /// Play a vibration (heavy and light levels, 0..1, each for a while), replacing the one + /// playing. + pub fn play(&self, steps: &[(f32, f32, Duration)]) { + let samples = waveform(steps); + let mut queue = self.queue.lock().unwrap_or_else(|e| e.into_inner()); + queue.clear(); + queue.extend(samples.into_iter().map(|v| [v, v])); + } + + /// Stop at once. + pub fn stop(&self) { + self.queue.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } +} + +fn is_dualsense(device: &cpal::Device) -> bool { + device.name().is_ok_and(|n| is_dualsense_name(&n)) + && device.supported_output_configs().is_ok_and(|mut configs| { + configs.any(|c| { + c.channels() >= 4 + && c.min_sample_rate().0 <= RATE + && c.max_sample_rate().0 >= RATE + && c.sample_format() == cpal::SampleFormat::F32 + }) + }) +} + +/// "DualSense Wireless Controller" on macOS; on Windows the endpoint is often just "Speakers +/// (Wireless Controller)" (DS5Windows' and dse-haptics' setup notes), a name the DualShock 4's +/// two-channel headset output shares, which the four channels rule out; ALSA names the card +/// "Controller". +fn is_dualsense_name(name: &str) -> bool { + name.contains("DualSense") + || name.contains("Wireless Controller") + || name.contains("CARD=Controller") +} + +/// The samples of a vibration: the heavy and light tones at each step's levels, with short +/// ramps between steps and to silence at the end. +pub fn waveform(steps: &[(f32, f32, Duration)]) -> Vec { + let ramp = (RAMP * RATE as f32) as usize; + let mut out = Vec::new(); + let mut level = [0.0f32; 2]; + let mut t = 0usize; + for &(heavy, light, length) in steps.iter().chain(&[(0.0, 0.0, Duration::ZERO)]) { + let target = [heavy.clamp(0.0, 1.0), light.clamp(0.0, 1.0)]; + let from = level; + let n = (length.as_secs_f32() * RATE as f32) as usize; + for i in 0..n.max(ramp) { + let k = (i as f32 / ramp as f32).min(1.0); + level = [0, 1].map(|j| from[j] + (target[j] - from[j]) * k); + let time = t as f32 / RATE as f32; + let v = + level[0] * (TAU * HEAVY_HZ * time).sin() + level[1] * (TAU * LIGHT_HZ * time).sin(); + out.push(v.clamp(-1.0, 1.0)); + t += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn device_names() { + assert!(is_dualsense_name("DualSense Wireless Controller")); + assert!(is_dualsense_name("Speakers (Wireless Controller)")); + assert!(is_dualsense_name( + "Speakers (2- DualSense Wireless Controller)" + )); + assert!(is_dualsense_name("plughw:CARD=Controller,DEV=0")); + assert!(!is_dualsense_name("MacBook Pro Speakers")); + assert!(!is_dualsense_name("hw:CARD=PCH,DEV=0")); + } + + #[test] + fn waveform_follows_the_steps() { + let w = waveform(&[(1.0, 0.0, Duration::from_millis(100))]); + // The step, then the ramp down. + assert_eq!(w.len(), 4800 + 192); + // Starts silent, reaches full strength, ends silent. + assert_eq!(w[0], 0.0); + let peak = w[1000..4800].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(peak > 0.99, "{peak}"); + assert!(w.last().unwrap().abs() < 0.01); + assert!(w.iter().all(|v| v.abs() <= 1.0)); + assert!(waveform(&[]).iter().all(|v| *v == 0.0)); + } +} diff --git a/crates/horizon-dualsense/src/lib.rs b/crates/horizon-dualsense/src/lib.rs index dd4823b26..438d8f6fe 100644 --- a/crates/horizon-dualsense/src/lib.rs +++ b/crates/horizon-dualsense/src/lib.rs @@ -7,6 +7,8 @@ //! and as report 0x31 over Bluetooth, where a sequence tag leads it and a CRC-32 (seeded with //! the byte 0xA2) closes it. pub mod device; +pub mod haptics; +pub mod trigger; pub use device::{Link, Transport}; @@ -59,6 +61,10 @@ const FLAG2_VIBRATION_V2: u8 = 1 << 2; const LIGHTBAR_LIGHT_OUT: u8 = 1 << 1; /// Player LEDs: switch at once instead of fading. pub const PLAYER_LEDS_INSTANT: u8 = 1 << 5; +/// The middle LED: player 1. +pub const PLAYER_1: u8 = 1 << 2; +/// The blue a host gives a first pad (`hid-playstation.c`), restored when Horizon lets go. +pub const DEFAULT_LIGHTBAR: [u8; 3] = [0, 0, 128]; /// An adaptive trigger's effect: a mode byte and ten parameters. pub type TriggerEffect = [u8; 11]; @@ -340,6 +346,15 @@ mod tests { assert_ne!(out.bluetooth(Vibration::V2, 1)[74..], r[74..]); } + #[test] + fn host_defaults() { + // hid-playstation.c: player 1 is BIT(2) ("--x--"), as SDL's first pattern 0x04; the + // blue it gives a pad; SDL's 0x20 switches LEDs without fading. + assert_eq!(PLAYER_1, 0x04); + assert_eq!(DEFAULT_LIGHTBAR, [0, 0, 128]); + assert_eq!(PLAYER_LEDS_INSTANT, 0x20); + } + #[test] fn dualsense_ids() { assert!(is_dualsense(0x054c, 0x0ce6)); diff --git a/crates/horizon-dualsense/src/trigger.rs b/crates/horizon-dualsense/src/trigger.rs new file mode 100644 index 000000000..973c3e30d --- /dev/null +++ b/crates/horizon-dualsense/src/trigger.rs @@ -0,0 +1,148 @@ +//! The adaptive triggers' effects in the pad's own encoding. A trigger's travel is cut into ten +//! zones (0 at rest, 9 fully pulled); an effect names the zones it acts in and a strength, 1..8, +//! for each, three bits per zone. Modes and packing as in Nielk1's TriggerEffectGenerator +//! (gist.github.com/Nielk1/6d54cc2c00d2201ccb8c2720ad7538db, rev. f73a299) and dualsensectl; +//! only the modes it calls official, which later firmware keeps. [`crate::TRIGGER_OFF`] frees +//! the trigger. +use crate::{TRIGGER_OFF, TriggerEffect}; + +const FEEDBACK: u8 = 0x21; +const WEAPON: u8 = 0x25; +const VIBRATION: u8 = 0x26; + +/// Zone bits and three-bit levels (`level - 1`) for the zones whose level isn't 0. +fn zones(levels: [u8; 10]) -> (u16, u32) { + let mut active = 0; + let mut values = 0; + for (i, level) in levels.into_iter().enumerate() { + if level > 0 { + active |= 1 << i; + values |= u32::from(level.min(8) - 1) << (3 * i); + } + } + (active, values) +} + +fn zoned(mode: u8, levels: [u8; 10]) -> TriggerEffect { + let (active, values) = zones(levels); + let mut e = [0; 11]; + e[0] = mode; + e[1..3].copy_from_slice(&active.to_le_bytes()); + e[3..7].copy_from_slice(&values.to_le_bytes()); + e +} + +/// Resistance in each zone, 0 (none) to 8; it holds wherever the trigger is. +pub fn resistance(levels: [u8; 10]) -> TriggerEffect { + zoned(FEEDBACK, levels) +} + +/// Even resistance from zone `start` (0..9) to the end of the travel, at `strength` (1..8). +pub fn feedback(start: u8, strength: u8) -> TriggerEffect { + resistance(std::array::from_fn(|i| { + if i >= usize::from(start) { + strength.clamp(1, 8) + } else { + 0 + } + })) +} + +/// A gun trigger: resistance from zone `start` that gives way with a click at zone `end` +/// (`2 <= start < end <= 8`), at `strength` (1..8). +pub fn weapon(start: u8, end: u8, strength: u8) -> TriggerEffect { + let start = start.clamp(2, 7); + let end = end.clamp(start + 1, 8); + let mut e = [0; 11]; + e[0] = WEAPON; + e[1..3].copy_from_slice(&((1u16 << start) | (1u16 << end)).to_le_bytes()); + e[3] = strength.clamp(1, 8) - 1; + e +} + +/// A buzz from zone `start` (0..9) on, at `amplitude` (1..8) and `frequency` Hz; at 0 Hz, +/// nothing (as Nielk1's factory). +pub fn vibration(start: u8, amplitude: u8, frequency: u8) -> TriggerEffect { + if frequency == 0 { + return TRIGGER_OFF; + } + let mut e = zoned( + VIBRATION, + std::array::from_fn(|i| { + if i >= usize::from(start) { + amplitude.clamp(1, 8) + } else { + 0 + } + }), + ); + e[9] = frequency; + e +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn feedback_bytes() { + // Zones 3..9 at strength 6 (stored as 5, three bits each). + assert_eq!( + feedback(3, 6), + [0x21, 0xf8, 0x03, 0x00, 0xda, 0xb6, 0x2d, 0, 0, 0, 0] + ); + assert_eq!(feedback(0, 1), [0x21, 0xff, 0x03, 0, 0, 0, 0, 0, 0, 0, 0]); + // Out-of-range strengths are clamped. + assert_eq!(feedback(0, 0), feedback(0, 1)); + assert_eq!(feedback(0, 9), feedback(0, 8)); + } + + #[test] + fn resistance_per_zone() { + let e = resistance([0, 0, 1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(u16::from_le_bytes([e[1], e[2]]), 0b11_1111_1100); + let values = u32::from_le_bytes([e[3], e[4], e[5], e[6]]); + for zone in 2..10 { + assert_eq!((values >> (3 * zone)) & 7, zone - 2); + } + } + + #[test] + fn weapon_bytes() { + assert_eq!( + weapon(2, 6, 6), + [0x25, 0x44, 0x00, 0x05, 0, 0, 0, 0, 0, 0, 0] + ); + // The click is always past the start. + assert_eq!(weapon(7, 3, 8)[1..3], [0x80, 0x01]); + } + + #[test] + fn vibration_bytes() { + let e = vibration(8, 2, 30); + assert_eq!(e[..3], [0x26, 0x00, 0x03]); + assert_eq!( + u32::from_le_bytes([e[3], e[4], e[5], e[6]]), + 1 << 24 | 1 << 27 + ); + assert_eq!(e[9], 30); + } + + #[test] + fn reference_examples() { + // DSX++'s README, Weapon {2, 6, 8}: zones 2 and 6, strength 8 stored as 7. + assert_eq!( + weapon(2, 6, 8), + [0x25, 0x44, 0x00, 0x07, 0, 0, 0, 0, 0, 0, 0] + ); + // dualsensectl's wiki, `weapon 2 3 8`. + assert_eq!(weapon(2, 3, 8)[1..4], [0x0c, 0x00, 0x07]); + // DSX++'s README, Vibration {2, 8, 20}: zones 2..9, amplitude 8 (stored 7) in each + // zone's three bits, the frequency in byte 9. + assert_eq!( + vibration(2, 8, 20), + [0x26, 0xfc, 0x03, 0xc0, 0xff, 0xff, 0x3f, 0, 0, 20, 0] + ); + assert_eq!(vibration(2, 8, 0), TRIGGER_OFF); + } +} diff --git a/docs/agent-control.md b/docs/agent-control.md index d2f13cb34..2f9ce377e 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -233,4 +233,6 @@ is not under control. Each PR adds its tests: unit tests next to the code, and scenarios in `tools/agent_control_e2e.py` (`survival`, `ui`, `options`, `events`; CLI and MCP) and `tools/launcher_mcp_e2e.py`, which drive the real game offscreen on macOS or on a virtual -screen on Linux. +screen on Linux. `tools/lan_e2e.py` runs two games at once, a host that opens its world to LAN +and a guest that joins it, and checks from both sides what a guest sees and can do (player +list, own model, armour, name tags, chest lids, crafting, fall damage). diff --git a/docs/controllers.md b/docs/controllers.md index 8fd58274c..4e3d82a75 100644 --- a/docs/controllers.md +++ b/docs/controllers.md @@ -219,6 +219,8 @@ exactly vanilla's, so a vanilla client can share the game folder. ``` enabled:true vibration:true +adaptiveTriggers:true +lightbar:health lookSensitivity:0.5 invertX:false invertY:false @@ -232,7 +234,7 @@ bind_pad.hotbarNext:rb ``` Only bindings that differ from the defaults are written. The controls -options get a Controller page: on/off, vibration, look sensitivity, invert +options get a Controller page: on/off, vibration, adaptive triggers, lightbar, look sensitivity, invert X/Y, deadzones, glyph style, sneak toggle, and a binding list like the key binds screen (pick an action, press a button; conflicts marked as vanilla does; reset). @@ -247,7 +249,7 @@ sensitivity, slower while scoping with a spyglass. Vibration (on by default, off in the options): taking damage (stronger with the damage), a block broken, an explosion nearby (scaled by distance), a totem of undying. Short, low-intensity pulses, as on Bedrock. A DualSense gets them -through its own output report (below), on every OS. Other pads go through +shaped, through its own output report (below), on every OS. Other pads go through gilrs force feedback: Linux (evdev force feedback, including Steam Input's virtual pad) and Windows support it; macOS gilrs has no force feedback, so it is silently skipped there. @@ -323,6 +325,134 @@ shared, so gilrs keeps reading the same pad), the HID API on Windows. shake while the motors run (`watch` logs the shake while the game drives the pad). +### Adaptive triggers + +On by default with a DualSense ("Adaptive Triggers" in the controller +options, `adaptiveTriggers:`). Each trigger feels the action bound to it, so +rebinding moves the feel along: with the default mapping that is L2 for +`key.use` and R2 for `key.attack`. + +| While | Trigger | Effect (zones 0..9, strength 1..8) | Feel | +|---|---|---|---| +| Drawing a bow | use | feedback from zone 2, strength 1 rising to 6 with the draw (`BowItem.getPowerForTime`) | the string's tension builds; letting go frees the trigger at once | +| Charging a trident | use | the same, at 6 after the 10 ticks a throw needs | | +| Loading a crossbow | use | the same, at 6 when it is loaded | | +| Holding a loaded crossbow | use | weapon: from two zones before the press zone to the press zone, strength 8 | a gun trigger: a hard catch that breaks with a click as it fires | +| Gliding with a rocket, riding a pig or a strider with its stick | use | weapon, the same zones, strength 5 | a lighter catch: pulling through it is the boost | +| A shield in the use hand (raised or ready) | use | feedback from zone 2, strength 3 | its weight | +| That shield disabled by an axe | use | feedback from zone 1, strength 8 | the trigger locks until the shield recovers | +| Mining (survival) | attack | vibration from zone 1: amplitude 2 (dirt) to 5 (obsidian) of 8, 40 Hz on sand and dirt, 30 on stone, 20 on wood, deepslate and ores, 10 on obsidian | a grit that gets heavier and slower on harder blocks; none on blocks that break at once | + +The press zone is where Horizon presses the trigger's action: the trigger +threshold (0.4 by default) times ten, kept between 3 and 8, so with the +defaults a crossbow catches from zone 2 and breaks at zone 4, as its bolt +leaves. This assumes the ten zones split the travel evenly, as dualsensectl +documents them (0 at rest, 9 fully pressed); it is not measured. + +Everything else, and every menu, the pause screen, a window without focus, +another pad being the active one, and controllers turned off, leaves the +triggers free; quitting frees them too. `pad status` shows the effects in +use. + +Why these values, from what shipped games do and what the community +documents (none of it measured on Horizon's pad yet): + +- **Only the official modes.** Off 0x05, feedback 0x21, weapon 0x25 and + vibration 0x26 are the modes Nielk1's notes call official and expected in + future firmware; bow 0x22, galloping 0x23 and machine 0x27 "might be + removed", and the low "simple" modes (0x01, 0x02) that pydualsense and + DualSense-Windows send are leftovers. The bow mode's snap-back would suit a + bow, but a firmware update could take it away. +- **Bows build tension.** Kena: Bridge of Spirits and Astro's Playroom use + the triggers to make you feel the bow being drawn (PlayStation Blog's + DualSense round-up, as reported by + [GameSpot](https://www.gamespot.com/articles/sony-reveals-how-ps5s-dualsense-controller-works-with-ratchet-clank-returnal-scarlet-nexus-and-more/1100-6491469/)). Minecraft holds the draw for + as long as you like, so the tension stops at 6 of 8 (dualsensectl: 1 is + "almost no resistance", 8 the maximum), and starts after the first two + zones so the press that starts the draw stays light. +- **A loaded crossbow is a gun trigger.** The developer note GameSpot quotes + describes a bazooka whose resistance "will cause the trigger to catch at the + input position just before the bullet is fired, and as you continue to pull + the trigger, the bullet will fire and release the tension": the weapon + effect does exactly that, and Horizon moves its breaking point onto the + threshold so the click is the shot. DSX community presets use the same + shape (DSX++'s example `Weapon {2, 6, 8}`; dualsensectl's + `weapon 2 3 8` "resists strongly and lets go almost immediately"). + Returnal and Ratchet & Clank: Rift Apart use a half-press stop to split two + actions on one trigger; Minecraft has one action per trigger, so Horizon + doesn't. +- **Boosts click lighter.** A rocket or a pig's carrot fires on the pull, so + it gets a catch that gives way rather than a wall that never does (strength + 5, below the crossbow's 8). +- **A disabled shield locks the trigger**, as Deathloop locks R2 halfway + when a gun jams, "to give to the player an immediate feedback even before + the animation plays out" (its director, Dinga Bakaba, in + [Destructoid's report](https://www.destructoid.com/when-a-gun-jams-in-deathloop-the-ps5-controllers-triggers-will-lock-up/)): + the shield can't be raised, and the finger feels why. +- **Mining is a texture.** The vibration mode buzzes the trigger at a given + rate; reWASD's preset uses 30 Hz and its "rifle" 2..20 Hz. Softer blocks + get a finer, faster grit, harder ones a slower, heavier chug, never above + 5 of 8, since the attack trigger is held for seconds. + +### Vibration shapes and HD haptics + +Each event plays a short shape rather than one flat block: a hit opens at +full strength for 50 ms and dies away in two steps, an explosion rolls on for +half a second, a totem swells, a broken block is a 35 ms tick. Over HID they +drive the motors' emulation (the compatible-vibration bytes). Measured on the +pad, that emulation has inertia: after a full-strength step it takes about +half a second to settle, so short shapes blur. + +The DualSense has no motors, but two voice-coil actuators, and on USB it is +also a four-channel 48 kHz audio device whose channels 3 and 4 drive them +(1 and 2 are its speaker and headset). Played there as waveforms (an 80 Hz +tone for the heavy part, 200 Hz for the light one, 4 ms ramps between steps, +channels 1 and 2 silent), the same shapes come out crisp. Per OS: + +| | USB | Bluetooth | +|---|---|---| +| macOS | the pad lists as a 4-channel CoreAudio output ("DualSense Wireless Controller", seen on the Mac mini by dualsense-1); cpal opens it by name | no audio device | +| Linux | snd-usb-audio exposes the card "Controller" with 4 channels; cpal opens it through ALSA (`plughw:CARD=Controller`), which fails while PipeWire or PulseAudio holds the card, as desktops do: then the motors' emulation stays | no audio device | +| Windows | a WASAPI endpoint named "Wireless Controller" (or "DualSense Wireless Controller"), stereo until its speaker setup is set to Quadraphonic in the Sound control panel (`mmsys.cpl`, Configure); until then Horizon finds no 4-channel output and keeps the motors | no audio device | + +The audio haptics play only while the pad is out of its rumble emulation: +any report with the rumble flags (flags 0, bits 0 and 1) silences them until +a report without them (SDL: "Leaving emulated rumble bits off will restore +audio haptics"; nondebug/dualsense and +[dse-haptics](https://github.com/iranran666/dse-haptics) arm them with an +all-zero report 0x02). While HD haptics are open the motors stay at zero, so +every report Horizon sends, starting with the one at opening, keeps them +armed; that first report also clears the attenuation a PS5 may have left. +The frame layout `[0, 0, left, right]` at 48 kHz is the one +[KytyPS5 #843](https://github.com/KytyPS5/KytyPS5/pull/843) plays on +Windows. + +Over Bluetooth the haptics travel as 8-bit 3 kHz samples in vendor output +report 0x32, reverse-engineered by +[SAxense](https://github.com/egormanga/SAxense) and since used by DSX 3.2 +and [dualsense-bt-haptics](https://github.com/awalol/dualsense-bt-haptics); +it needs Bluetooth output, which only Linux gets (see above), and isn't +done: there the motors' emulation is used. HD haptics are opt-in for now +(`HORIZON_DUALSENSE_HAPTICS=1`) until they are confirmed on a real pad; +games started for tests (`HORIZON_NO_AUDIO`) never open them, and the pad's +audio device is only ever opened by name, never the system's default output. + +### Lightbar and player LEDs + +"Lightbar: Health / Dimension / Off" in the controller options +(`lightbar:`, health by default). Health runs from green at full through +amber at half to red; Dimension is blue in the Overworld, orange in the +Nether, violet in the End. Both at half brightness (the pad's full light is +glaring); menus keep the last colour. The player LEDs show player 1 (the +middle LED). Off leaves both to the pad. When Horizon lets go of the pad, a +lightbar or LEDs it changed go back to a host's defaults: blue (0, 0, 128) +and the middle LED, as Linux's driver gives a first pad (neither SDL nor +the kernel resets anything when it lets go; Horizon does, so the pad never +keeps a game's colour or a stiff trigger). The microphone's mute LED is +never touched (flags 1, bit 0 stays clear): whatever the system set +stays. Over Bluetooth the colour waits for the pad's connection +animation (see "DualSense output"). Verified against the references only. + Byte layout from public references, read for facts; no code is copied from them (the kernel and dualsensectl are GPL): @@ -331,8 +461,10 @@ them (the kernel and dualsensectl are GPL): | SDL [`SDL_hidapi_ps5.c`](https://github.com/libsdl-org/SDL/blob/6defbc0129b5ba90bab3f6c67bbc1e9329e24ff1/src/joystick/hidapi/SDL_hidapi_ps5.c) and [`SDL_hints.h`](https://github.com/libsdl-org/SDL/blob/6defbc0129b5ba90bab3f6c67bbc1e9329e24ff1/include/SDL3/SDL_hints.h) (zlib) | `6defbc0` | the 47-byte block, rumble flags and stop, 0x0224, legacy at half, LED reset and the Bluetooth animation clock, USB report length 48, the enhanced-mode switch | | Linux [`hid-playstation.c`](https://github.com/torvalds/linux/blob/045958acaa75205b31578cb22c4345e28dd2e4bf/drivers/hid/hid-playstation.c) (GPL) | `045958a` | valid flags, the Bluetooth sequence and tag 0x10, CRC seed 0xA2, `dualsense_reset_leds`, `use_vibration_v2` from 2.21, player LED patterns, the default blue | | [dualsensectl](https://github.com/nowrep/dualsensectl/blob/d3ae2fa272e1bf9a5c08a0ded3f374b40f7c73ac/main.c) (GPL) | `d3ae2fa` | trigger valid bits (flags 0 bits 2, 3), `reduce_motor_power` (byte 36) and its flag, the trigger effect packing | +| Nielk1's [TriggerEffectGenerator](https://gist.github.com/Nielk1/6d54cc2c00d2201ccb8c2720ad7538db/f73a299fdc52f43be84d39e62734192ad82bb393) (MIT) | rev. `f73a299` | the trigger modes (official 0x05, 0x21, 0x25, 0x26) and their zone packing | | [pydualsense](https://github.com/flok/pydualsense/blob/01445f5ed6ba/pydualsense/pydualsense.py) (MIT) | `01445f5` | sets the attenuation flag with 0 on every report | | [nondebug/dualsense](https://github.com/nondebug/dualsense) | `b87450e` | an all-zero report 0x02 leaves rumble emulation for the audio haptics | +| [KytyPS5 #843](https://github.com/KytyPS5/KytyPS5/pull/843), [dse-haptics](https://github.com/iranran666/dse-haptics), [SAxense](https://github.com/egormanga/SAxense) | read 2026-10-15 | the 4-channel layout, the Windows and Linux device names and setup, the Bluetooth haptics report | Verified on hardware (USB, dualsense-1, Mac mini): the motors with the V2 flags (the IMU shook, and settled after a stop that then still sent the diff --git a/docs/release-flow.md b/docs/release-flow.md index f494bf538..f1015a31f 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -143,7 +143,7 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f `tools/release_train.py notes` writes them from the same pull requests: -- the title, `Horizon 2026.10.15.1: `, features first, newest first; +- the title, `Horizon 2026.10.15.01: ` (a day's later releases count .01, .02…, two digits so GitHub's releases page, which sorts them as text, keeps them in order), 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); @@ -177,7 +177,7 @@ While paused, runs still decide and say why in their summary; `force=true` still A bad release is withdrawn by turning it back into a draft: ```sh -gh release edit v2026.10.15.1 --draft +gh release edit v2026.10.15.01 --draft ``` Launchers list only published releases: the previous version becomes the newest one again, launchers that diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 868d4fc76..4a281729d 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2673,6 +2673,7 @@ dependencies = [ "self-replace", "serde", "serde_json", + "sha1", "tar", "ureq", "winresource", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index dadff4db1..8f5873f87 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -12,6 +12,8 @@ gpui = "0.2.2" ureq = { version = "2", features = ["json", "tls"], default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" +# Checks the client jar and the version file found in other launchers' folders (sources.rs). +sha1 = "0.10" pulldown-cmark = { version = "0.12", default-features = false } flate2 = "1" tar = { version = "0.4", default-features = false } diff --git a/launcher/src/account.rs b/launcher/src/account.rs index 1b3bd42d5..44fa96cb6 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -422,6 +422,12 @@ fn profile(ep: &Endpoints, token: &str) -> Result { }) } +/// Whether the signed-in account still owns Minecraft: Java Edition, asked again now: the +/// launcher downloads the game's files only for an owner (sources.rs). +pub fn owns_minecraft(ep: &Endpoints, secrets: &Secrets) -> Result { + owns_game(ep, &secrets.minecraft_token) +} + /// What the keychain keeps for one account. #[derive(Clone, serde::Serialize, serde::Deserialize)] pub struct Secrets { diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs index 925b78195..5aea5dd12 100644 --- a/launcher/src/account/tests.rs +++ b/launcher/src/account/tests.rs @@ -275,6 +275,21 @@ fn refresh_only_when_the_token_runs_out() { ); } +#[test] +fn ownership_is_asked_again_with_the_saved_token() { + let secrets = |token: &str| Secrets { + refresh_token: "ms-refresh-1".into(), + minecraft_token: token.into(), + minecraft_expires_at: now() + 7200, + xuid: None, + }; + let (m, ep) = mock(|_| {}); + assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(true)); + assert_eq!(m.lock().unwrap().log.len(), 1); + let (_, ep) = mock(|m| m.owns_game = false); + assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(false)); +} + #[test] fn refusals_have_messages() { let tokens = || MsTokens { diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 00c0db163..898364040 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1,6 +1,7 @@ //! Everything that is not UI: GitHub, installs, resource preparation, the game's processes and //! updates. The GUI, the CLI and the MCP server all go through this module. Functions here //! block; the GUI runs them on threads and reads their messages. +use crate::{account, mojang, sources}; use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; @@ -594,17 +595,14 @@ fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> { .collect() } -/// The official launcher's game directory, where horizon-prepare looks by default. +/// The official launcher's game directory, else the first other launcher's found +/// (sources.rs); preparing looks in all of them anyway. pub fn default_minecraft_dir() -> Option { - let home = dirs::home_dir()?; - let dir = if cfg!(target_os = "macos") { - home.join("Library/Application Support/minecraft") - } else if cfg!(windows) { - dirs::config_dir()?.join(".minecraft") - } else { - home.join(".minecraft") - }; - dir.is_dir().then_some(dir) + let folders = sources::Folders::current()?; + sources::known_folders(sources::Os::current(), &folders) + .into_iter() + .map(|(_, dir)| dir) + .find(|dir| dir.is_dir()) } fn found(program: &str, arg: &str) -> bool { @@ -644,23 +642,102 @@ fn preparer_binary(dir: &Path) -> Option { binary.is_file().then_some(binary) } +/// Downloads the pinned version from Mojang into `dir` when the signed-in account owns +/// Minecraft (asked again now), else says what signing in would do, as the last line of the +/// not-found error. +fn download_for_owner( + pins: &sources::Pins, + dir: &Path, + fetch: sources::Fetch, + log: &dyn Fn(String), +) -> Result<(), String> { + let v = &pins.version; + let owner = (|| -> Result, String> { + let ep = account::Endpoints::live(); + let mut accounts = account::Accounts::load(); + let Some((a, secrets)) = account::session_for_launch(&ep, account::store(), &mut accounts)? + else { + return Ok(None); + }; + Ok(Some((a.name, account::owns_minecraft(&ep, &secrets)?))) + })(); + match owner { + Ok(Some((name, true))) => { + log(format!( + "{name} owns Minecraft: downloading {v} from Mojang" + )); + let os = match sources::Os::current() { + sources::Os::Linux => "linux", + sources::Os::MacOs => "osx", + sources::Os::Windows => "windows", + }; + mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| { + format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}") + }) + } + Ok(Some((name, false))) => Err(format!( + "\n • {name}, the signed-in account, doesn't own Minecraft: Java Edition, so Horizon \ + can't download it." + )), + Ok(None) => Err(format!( + "\n • Or sign in with the Microsoft account that owns Minecraft: Horizon then \ + downloads {v} from Mojang itself." + )), + Err(e) => Err(format!( + "\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \ + checked: {e}" + )), + } +} + /// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same /// steps: the player's own launcher install, the server jar from that version's own json, and -/// Java (and Python, for versions before horizon-prepare). -pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result { +/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder +/// to prepare from: `minecraft`, or the files another launcher keeps, linked into the official +/// launcher's layout (sources.rs). +pub fn preparer( + tag: &str, + minecraft: &Path, + log: &dyn Fn(String), +) -> Result<(Preparer, PathBuf), String> { let version = game_version(tag); let dir = version_dir(tag); let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?; + let minecraft = if reused { + minecraft.to_path_buf() + } else { + let pins = read_json(&dir.join("research-lock.json")) + .and_then(|lock| sources::Pins::read(&lock)) + .ok_or("The version's research-lock.json doesn't pin the Minecraft files")?; + let own = data_dir().join("minecraft"); + let mut known = vec![("Horizon's own download", own.clone())]; + known.extend( + sources::Folders::current() + .map(|f| sources::known_folders(sources::Os::current(), &f)) + .unwrap_or_default(), + ); + let fetch = |url: &str| -> Result, String> { + let mut body = Vec::new(); + get(url)? + .into_reader() + .read_to_end(&mut body) + .map_err(|e| e.to_string())?; + Ok(body) + }; + let linked = data_dir().join("linked-minecraft"); + match sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)? { + sources::Resolved::Folder(dir) => dir, + sources::Resolved::NotFound(checked) => { + let not_found = sources::not_found(&version, &checked); + download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?; + own + } + } + }; let manifest = minecraft .join("versions") .join(&version) .join(format!("{version}.json")); - 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 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 @@ -707,20 +784,21 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result
 Result
,
         /// The installed version (default: the selected one)
@@ -299,7 +300,8 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
         Cmd::Prepare { minecraft, version } => {
             let tag = backend::resolve_version(version.as_deref())?;
             let minecraft = backend::minecraft_dir(minecraft)?;
-            let preparer = backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
+            let (preparer, minecraft) =
+                backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
             backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
             match preparer {
                 backend::Preparer::Process(cmd) => attached(cmd)?,
diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs
index 5c8afcb33..5df6a7cbb 100644
--- a/launcher/src/lib.rs
+++ b/launcher/src/lib.rs
@@ -2,4 +2,6 @@
 pub mod account;
 pub mod backend;
 pub mod desktop;
+pub mod mojang;
+pub mod sources;
 pub mod telemetry;
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index b066ecc6d..cc66aa08e 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -501,9 +501,15 @@ impl Launcher {
                             if let (None, Some(started)) = (&error, self.prepare_started.take()) {
                                 self.perf.record_since("launcher.prepare_ms", started);
                             }
+                            // A preparer process's exit status says little, so its last line
+                            // follows; the launcher's own errors are full sentences already.
                             self.prepare_error = error.map(|e| {
-                                let tail =
-                                    self.prepare_log.iter().rev().find(|l| !l.trim().is_empty());
+                                let tail = self
+                                    .prepare_log
+                                    .iter()
+                                    .rev()
+                                    .find(|l| !l.trim().is_empty())
+                                    .filter(|_| e.starts_with("Exited with"));
                                 tail.map_or(e.clone(), |t| format!("{e}: {t}"))
                             });
                         }
@@ -632,8 +638,8 @@ impl Launcher {
                 let _ = tx.send(Msg::Line(Job::Prepare, line));
             };
             let result = backend::preparer(&tag, &minecraft, &log)
-                .inspect(|_| backend::sounds(&tag, &minecraft, &log))
-                .and_then(|p| match p {
+                .inspect(|(_, minecraft)| backend::sounds(&tag, minecraft, &log))
+                .and_then(|(p, _)| match p {
                     backend::Preparer::Process(cmd) => {
                         backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
                     }
@@ -1436,7 +1442,7 @@ impl Launcher {
         let minecraft = self.settings.minecraft_dir.as_deref().map_or_else(
             || {
                 div()
-                    .child("Not found. Choose the official launcher's game folder.")
+                    .child("Not found. Choose the folder where your launcher keeps Minecraft.")
                     .into_any_element()
             },
             |p| {
diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs
index f02cb6f56..82304923f 100644
--- a/launcher/src/mcp.rs
+++ b/launcher/src/mcp.rs
@@ -32,7 +32,7 @@ fn tools() -> Value {
         { "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.",
           "inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } },
         { "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher and Java 25; versions before horizon-prepare also need Python 3.10+). Can take several minutes; returns the end of the log.",
-          "inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The official launcher's game folder. Default: the launcher's setting, else the platform default." } } } },
+          "inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher. Default: the launcher's setting, then every launcher's default folder." } } } },
         { "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world.",
           "inputSchema": { "type": "object", "properties": { "version": version,
             "world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
@@ -120,7 +120,7 @@ impl Session {
                 let tag = backend::resolve_version(arg_str(args, "version"))?;
                 let minecraft =
                     backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
-                let preparer = backend::preparer(&tag, &minecraft, &|_| {})?;
+                let (preparer, minecraft) = backend::preparer(&tag, &minecraft, &|_| {})?;
                 let sound = std::cell::RefCell::new(Vec::new());
                 backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line));
                 let (result, tail) = match preparer {
diff --git a/launcher/src/mojang.rs b/launcher/src/mojang.rs
new file mode 100644
index 000000000..dbe2aa7fb
--- /dev/null
+++ b/launcher/src/mojang.rs
@@ -0,0 +1,194 @@
+//! The player's own download of the pinned version from Mojang, for a signed-in account that
+//! owns Minecraft: Java Edition (#434), as other launchers get it: the version JSON, the client
+//! jar, this system's libraries and the assets (the sounds), each checked against its sha1,
+//! in the official launcher's layout in the launcher's data folder. sources.rs then finds them
+//! there like any launcher's. Nothing of Mojang's is part of Horizon.
+
+use crate::sources::{fetch_checked, fetch_manifest, sha1_file, write_file, Fetch, Pins};
+use serde_json::Value;
+use std::fs;
+use std::path::{Component, Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
+use std::sync::Mutex;
+use std::time::Duration;
+
+const OBJECTS: &str = "https://resources.download.minecraft.net";
+
+/// One file to download.
+struct File {
+    url: String,
+    sha1: String,
+    path: PathBuf,
+}
+
+/// Downloads the pinned version into `dir`, `jobs` files at a time; files already there and
+/// whole are kept. An asset that fails is a line in the log (the game is then partly silent),
+/// anything else an error.
+pub fn download(
+    pins: &Pins,
+    dir: &Path,
+    os: &str,
+    jobs: usize,
+    fetch: Fetch,
+    log: &dyn Fn(String),
+) -> Result<(), String> {
+    let v = &pins.version;
+    let versions = dir.join("versions").join(v);
+    let manifest = versions.join(format!("{v}.json"));
+    fetch_manifest(pins, &manifest, fetch, log)?;
+    let manifest = read_json(&manifest)?;
+    let client = &manifest["downloads"]["client"];
+    let mut game = vec![File {
+        url: text(client, "url")?,
+        sha1: pins.client_sha1.clone(),
+        path: versions.join(format!("{v}.jar")),
+    }];
+    let libraries = manifest["libraries"]
+        .as_array()
+        .ok_or("The version file has no libraries")?;
+    for library in libraries.iter().filter(|l| allowed(l, os)) {
+        let artifact = &library["downloads"]["artifact"];
+        if artifact.is_null() {
+            continue;
+        }
+        game.push(File {
+            url: text(artifact, "url")?,
+            sha1: text(artifact, "sha1")?,
+            path: dir
+                .join("libraries")
+                .join(relative(&text(artifact, "path")?)?),
+        });
+    }
+    log(format!(
+        "Downloading Minecraft {v} from Mojang: the game and {} libraries",
+        game.len() - 1
+    ));
+    fetch_all(&game, jobs, fetch, log)?;
+    let index = &manifest["assetIndex"];
+    let index = File {
+        url: text(index, "url")?,
+        sha1: text(index, "sha1")?,
+        path: dir
+            .join("assets/indexes")
+            .join(relative(&format!("{}.json", text(index, "id")?))?),
+    };
+    let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, log)
+        .and_then(|_| objects(&read_json(&index.path)?, dir))
+        .and_then(|objects| {
+            log(format!("Downloading the sounds ({} files)", objects.len()));
+            fetch_all(&objects, jobs, fetch, log)
+        });
+    if let Err(e) = assets {
+        log(format!("The sounds could not all be downloaded: {e}"));
+    }
+    Ok(())
+}
+
+fn read_json(path: &Path) -> Result {
+    let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
+    serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+fn text(v: &Value, key: &str) -> Result {
+    v[key]
+        .as_str()
+        .map(String::from)
+        .ok_or_else(|| format!("The version file has no {key} in {v}"))
+}
+
+/// A path from the version file, refused if it could leave the folder.
+fn relative(path: &str) -> Result {
+    let safe = !path.contains('\\')
+        && Path::new(path)
+            .components()
+            .all(|c| matches!(c, Component::Normal(_)));
+    safe.then(|| PathBuf::from(path))
+        .ok_or_else(|| format!("Unsafe path {path:?} in the version file"))
+}
+
+/// Whether a library's rules let this system (`osx`, `windows`, `linux`) use it: the last
+/// rule that matches decides.
+fn allowed(library: &Value, os: &str) -> bool {
+    let Some(rules) = library["rules"].as_array() else {
+        return true;
+    };
+    rules
+        .iter()
+        .rfind(|rule| rule["os"]["name"].as_str().is_none_or(|name| name == os))
+        .is_some_and(|rule| rule["action"] == "allow")
+}
+
+/// The asset index's objects, once each.
+fn objects(index: &Value, dir: &Path) -> Result, String> {
+    let objects = index["objects"]
+        .as_object()
+        .ok_or("The asset index has no objects")?;
+    let mut hashes: Vec<&str> = objects
+        .values()
+        .filter_map(|o| o["hash"].as_str())
+        .collect();
+    hashes.sort_unstable();
+    hashes.dedup();
+    hashes
+        .into_iter()
+        .map(|hash| {
+            if hash.len() != 40 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
+                return Err(format!("Bad asset hash {hash:?} in the asset index"));
+            }
+            let path = format!("{}/{hash}", &hash[..2]);
+            Ok(File {
+                url: format!("{OBJECTS}/{path}"),
+                sha1: hash.to_string(),
+                path: dir.join("assets/objects").join(path),
+            })
+        })
+        .collect()
+}
+
+/// Downloads the files not already there, `jobs` at a time, with a line every few seconds;
+/// stops at the first error.
+fn fetch_all(
+    files: &[File],
+    jobs: usize,
+    fetch: Fetch,
+    log: &dyn Fn(String),
+) -> Result<(), String> {
+    let next = AtomicUsize::new(0);
+    let done = AtomicUsize::new(0);
+    let failed = Mutex::new(None);
+    std::thread::scope(|scope| {
+        let workers: Vec<_> = (0..jobs.clamp(1, files.len().max(1)))
+            .map(|_| {
+                scope.spawn(|| {
+                    while let Some(file) = files.get(next.fetch_add(1, Relaxed)) {
+                        if failed.lock().unwrap().is_some() {
+                            break;
+                        }
+                        if sha1_file(&file.path).as_ref() != Some(&file.sha1) {
+                            let got = fetch_checked(fetch, &file.url, &file.sha1)
+                                .map_err(|e| format!("{} {e}", file.url))
+                                .and_then(|body| write_file(&file.path, &body));
+                            if let Err(e) = got {
+                                failed.lock().unwrap().get_or_insert(e);
+                            }
+                        }
+                        done.fetch_add(1, Relaxed);
+                    }
+                })
+            })
+            .collect();
+        let mut waited = 0;
+        while !workers.iter().all(|w| w.is_finished()) {
+            std::thread::sleep(Duration::from_millis(100));
+            waited += 1;
+            if waited % 50 == 0 {
+                log(format!("{} of {} files", done.load(Relaxed), files.len()));
+            }
+        }
+    });
+    failed.into_inner().unwrap().map_or(Ok(()), Err)
+}
+
+#[cfg(test)]
+#[path = "mojang_tests.rs"]
+mod tests;
diff --git a/launcher/src/mojang_tests.rs b/launcher/src/mojang_tests.rs
new file mode 100644
index 000000000..b50a77a93
--- /dev/null
+++ b/launcher/src/mojang_tests.rs
@@ -0,0 +1,232 @@
+//! A download from a mock of Mojang's servers serving small fake files (never Mojang's).
+use super::*;
+use crate::sources::{resolve, sha1_hex, Resolved};
+use std::collections::HashMap;
+
+const CLIENT: &[u8] = b"fake client jar";
+const COMMON: &[u8] = b"a library every system uses";
+const LINUX: &[u8] = b"a linux native";
+const SOUND: &[u8] = b"a fake ogg";
+const LANG: &[u8] = b"{}";
+
+/// The fake version file, asset index and files, by URL.
+fn mojang() -> (Pins, HashMap>) {
+    let artifact = |name: &str, data: &[u8]| {
+        serde_json::json!({
+            "path": format!("org/fake/{name}/1/{name}-1.jar"),
+            "sha1": sha1_hex(data),
+            "url": format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar"),
+        })
+    };
+    let index = serde_json::json!({"objects": {
+        "minecraft/sounds/a.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
+        "minecraft/sounds/same.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
+        "minecraft/lang/fr_fr.json": {"hash": sha1_hex(LANG), "size": LANG.len()},
+    }})
+    .to_string();
+    let manifest = serde_json::json!({
+        "id": "26.3",
+        "assetIndex": {"id": "34", "sha1": sha1_hex(index.as_bytes()),
+                       "url": "https://piston-meta.mojang.com/v1/packages/i/34.json"},
+        "downloads": {"client": {"sha1": sha1_hex(CLIENT), "url": "https://piston-data.mojang.com/client.jar"}},
+        "libraries": [
+            {"name": "org.fake:common:1", "downloads": {"artifact": artifact("common", COMMON)}},
+            {"name": "org.fake:linux:1", "downloads": {"artifact": artifact("linux", LINUX)},
+             "rules": [{"action": "allow", "os": {"name": "linux"}}]},
+            {"name": "org.fake:not-osx:1", "downloads": {"artifact": artifact("not-osx", COMMON)},
+             "rules": [{"action": "allow"}, {"action": "disallow", "os": {"name": "osx"}}]},
+            {"name": "org.fake:windows:1", "downloads": {"artifact": artifact("windows", b"w")},
+             "rules": [{"action": "allow", "os": {"name": "windows"}}]},
+        ],
+    })
+    .to_string();
+    let pins = Pins::read(&serde_json::json!({"minecraft": {
+        "version": "26.3",
+        "client_sha1": sha1_hex(CLIENT),
+        "manifest_sha1": sha1_hex(manifest.as_bytes()),
+    }}))
+    .unwrap();
+    let object = |data: &[u8]| {
+        let hash = sha1_hex(data);
+        format!("{OBJECTS}/{}/{hash}", &hash[..2])
+    };
+    let lib =
+        |name: &str| format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar");
+    let files = HashMap::from([
+        (
+            format!(
+                "https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
+                sha1_hex(manifest.as_bytes())
+            ),
+            manifest.into_bytes(),
+        ),
+        (
+            "https://piston-data.mojang.com/client.jar".into(),
+            CLIENT.to_vec(),
+        ),
+        (lib("common"), COMMON.to_vec()),
+        (lib("linux"), LINUX.to_vec()),
+        (lib("not-osx"), COMMON.to_vec()),
+        (lib("windows"), b"w".to_vec()),
+        (
+            "https://piston-meta.mojang.com/v1/packages/i/34.json".into(),
+            index.into_bytes(),
+        ),
+        (object(SOUND), SOUND.to_vec()),
+        (object(LANG), LANG.to_vec()),
+    ]);
+    (pins, files)
+}
+
+struct Server {
+    files: HashMap>,
+    asked: Mutex>,
+}
+
+impl Server {
+    fn fetch(&self, url: &str) -> Result, String> {
+        self.asked.lock().unwrap().push(url.to_string());
+        self.files
+            .get(url)
+            .cloned()
+            .ok_or_else(|| format!("{url} answered 404"))
+    }
+
+    fn asked(&self) -> Vec {
+        std::mem::take(&mut *self.asked.lock().unwrap())
+    }
+}
+
+fn scratch(name: &str) -> PathBuf {
+    let dir = std::env::temp_dir().join(format!("horizon-mojang-{name}-{}", std::process::id()));
+    let _ = fs::remove_dir_all(&dir);
+    dir
+}
+
+#[test]
+fn an_owner_gets_the_official_layout_with_this_systems_libraries() {
+    let (pins, files) = mojang();
+    let server = Server {
+        files,
+        asked: Mutex::new(Vec::new()),
+    };
+    let dir = scratch("layout");
+    let logged = Mutex::new(Vec::new());
+    download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|line| {
+        logged.lock().unwrap().push(line)
+    })
+    .unwrap();
+    assert_eq!(
+        fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(),
+        CLIENT
+    );
+    let libraries = dir.join("libraries/org/fake");
+    assert_eq!(
+        fs::read(libraries.join("common/1/common-1.jar")).unwrap(),
+        COMMON
+    );
+    assert_eq!(
+        fs::read(libraries.join("linux/1/linux-1.jar")).unwrap(),
+        LINUX
+    );
+    assert!(libraries.join("not-osx/1/not-osx-1.jar").is_file());
+    assert!(!libraries.join("windows").exists());
+    let hash = sha1_hex(SOUND);
+    assert_eq!(
+        fs::read(dir.join("assets/objects").join(&hash[..2]).join(&hash)).unwrap(),
+        SOUND
+    );
+    assert!(dir.join("assets/indexes/34.json").is_file());
+    let asked = server.asked();
+    // The sound two names share is fetched once; nothing is fetched twice.
+    assert_eq!(asked.len(), 8, "{asked:#?}");
+    assert!(!asked.iter().any(|u| u.contains("windows")));
+    assert_eq!(
+        logged.lock().unwrap()[1],
+        "Downloading Minecraft 26.3 from Mojang: the game and 3 libraries"
+    );
+
+    // Found like any launcher's folder, as it is; a second download fetches nothing.
+    let found = resolve(
+        &dir,
+        &pins,
+        &[],
+        &scratch("unused"),
+        &|url| server.fetch(url),
+        &|_| {},
+    );
+    assert_eq!(found, Ok(Resolved::Folder(dir.clone())));
+    download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|_| {}).unwrap();
+    assert_eq!(server.asked(), Vec::::new());
+    fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn macos_skips_what_its_rules_disallow() {
+    let (pins, files) = mojang();
+    let server = Server {
+        files,
+        asked: Mutex::new(Vec::new()),
+    };
+    let dir = scratch("osx");
+    download(&pins, &dir, "osx", 2, &|url| server.fetch(url), &|_| {}).unwrap();
+    let libraries = dir.join("libraries/org/fake");
+    assert!(libraries.join("common/1/common-1.jar").is_file());
+    assert!(!libraries.join("linux").exists());
+    assert!(!libraries.join("not-osx").exists());
+    fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn a_file_that_is_not_the_pinned_one_stops_the_download() {
+    let (pins, mut files) = mojang();
+    files.insert(
+        "https://piston-data.mojang.com/client.jar".into(),
+        b"something else".to_vec(),
+    );
+    let server = Server {
+        files,
+        asked: Mutex::new(Vec::new()),
+    };
+    let dir = scratch("bad-jar");
+    let error = download(&pins, &dir, "linux", 2, &|url| server.fetch(url), &|_| {}).unwrap_err();
+    assert!(
+        error.starts_with("https://piston-data.mojang.com/client.jar is not the one Horizon pins"),
+        "{error}"
+    );
+    assert!(!dir.join("versions/26.3/26.3.jar").exists());
+    fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn missing_sounds_are_a_line_in_the_log_not_an_error() {
+    let (pins, mut files) = mojang();
+    let hash = sha1_hex(SOUND);
+    files.remove(&format!("{OBJECTS}/{}/{hash}", &hash[..2]));
+    let server = Server {
+        files,
+        asked: Mutex::new(Vec::new()),
+    };
+    let dir = scratch("no-sound");
+    let logged = Mutex::new(Vec::new());
+    download(&pins, &dir, "linux", 1, &|url| server.fetch(url), &|line| {
+        logged.lock().unwrap().push(line)
+    })
+    .unwrap();
+    assert!(dir.join("versions/26.3/26.3.jar").is_file());
+    let last = logged.lock().unwrap().last().cloned().unwrap();
+    assert!(
+        last.starts_with("The sounds could not all be downloaded:")
+            && last.ends_with("answered 404"),
+        "{last}"
+    );
+    fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn version_file_paths_stay_in_the_folder() {
+    assert!(relative("org/fake/a.jar").is_ok());
+    for bad in ["../a.jar", "/etc/a", "a/../../b", "a\\b"] {
+        assert!(relative(bad).is_err(), "{bad}");
+    }
+}
diff --git a/launcher/src/sources.rs b/launcher/src/sources.rs
new file mode 100644
index 000000000..aafdb51e4
--- /dev/null
+++ b/launcher/src/sources.rs
@@ -0,0 +1,449 @@
+//! Where the player's own Minecraft files are: the folder they chose, the official launcher's,
+//! or another launcher's (Prism Launcher, MultiMC, Modrinth App, ATLauncher, GDLauncher), #434.
+//! horizon-prepare reads the official launcher's layout and pins the version JSON's own sha1, so
+//! files found elsewhere are linked into that layout in the launcher's data folder, with the
+//! pinned version JSON from Mojang when the other launcher keeps its own rewrite of it.
+
+use serde_json::Value;
+use sha1::{Digest, Sha1};
+use std::fs;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+/// What a version's research-lock.json pins about the game files.
+pub struct Pins {
+    pub version: String,
+    pub client_sha1: String,
+    /// The version JSON's sha1, then the earlier ones Mojang republished.
+    pub manifests: Vec,
+}
+
+impl Pins {
+    pub fn read(lock: &Value) -> Option {
+        let game = &lock["minecraft"];
+        let text = |key: &str| game[key].as_str().map(String::from);
+        let mut manifests = vec![text("manifest_sha1")?];
+        if let Some(list) = game["accepted_manifest_sha1"].as_array() {
+            manifests.extend(list.iter().filter_map(Value::as_str).map(String::from));
+        }
+        Some(Pins {
+            version: text("version")?,
+            client_sha1: text("client_sha1")?,
+            manifests,
+        })
+    }
+
+    fn manifest_accepted(&self, path: &Path) -> bool {
+        sha1_file(path).is_some_and(|sha1| self.manifests.contains(&sha1))
+    }
+}
+
+/// A launcher's copy of the pinned version.
+#[derive(Debug, PartialEq)]
+pub struct Found {
+    /// The folder holding the launcher's `libraries` and `assets`.
+    pub base: PathBuf,
+    /// The client jar, checked against the pin.
+    pub client: PathBuf,
+    /// The launcher's version JSON when it is one Horizon pins.
+    pub manifest: Option,
+}
+
+impl Found {
+    /// Whether `base` is in the official launcher's layout, so horizon-prepare reads it as is.
+    fn official_layout(&self, version: &str) -> bool {
+        let dir = self.base.join("versions").join(version);
+        self.client == dir.join(format!("{version}.jar"))
+            && self.manifest == Some(dir.join(format!("{version}.json")))
+    }
+}
+
+pub struct Folders {
+    pub home: PathBuf,
+    /// `dirs::data_dir()`: ~/.local/share (XDG_DATA_HOME), ~/Library/Application Support,
+    /// %APPDATA%.
+    pub data: PathBuf,
+    /// `dirs::config_dir()`: ~/.config (XDG_CONFIG_HOME), the same as `data` elsewhere.
+    pub config: PathBuf,
+}
+
+impl Folders {
+    pub fn current() -> Option {
+        Some(Folders {
+            home: dirs::home_dir()?,
+            data: dirs::data_dir()?,
+            config: dirs::config_dir()?,
+        })
+    }
+}
+
+#[derive(Clone, Copy, PartialEq)]
+pub enum Os {
+    Linux,
+    MacOs,
+    Windows,
+}
+
+impl Os {
+    pub fn current() -> Os {
+        if cfg!(target_os = "macos") {
+            Os::MacOs
+        } else if cfg!(windows) {
+            Os::Windows
+        } else {
+            Os::Linux
+        }
+    }
+}
+
+const OFFICIAL: &str = "the official launcher";
+
+/// Every launcher's default game folder on `os`, the official launcher's first. MultiMC on
+/// macOS and Windows has none (it lives where it was unzipped): it is chosen by hand.
+pub fn known_folders(os: Os, f: &Folders) -> Vec<(&'static str, PathBuf)> {
+    let flatpak = |app: &str, rest: &str| f.home.join(".var/app").join(app).join(rest);
+    let mut list = match os {
+        Os::Linux => vec![
+            (OFFICIAL, f.home.join(".minecraft")),
+            (OFFICIAL, flatpak("com.mojang.Minecraft", ".minecraft")),
+            ("Prism Launcher", f.data.join("PrismLauncher")),
+            (
+                "Prism Launcher",
+                flatpak("org.prismlauncher.PrismLauncher", "data/PrismLauncher"),
+            ),
+            ("MultiMC", f.data.join("multimc")),
+            ("Modrinth App", f.data.join("ModrinthApp")),
+            (
+                "Modrinth App",
+                flatpak("com.modrinth.ModrinthApp", "data/ModrinthApp"),
+            ),
+            ("ATLauncher", f.data.join("atlauncher")),
+            (
+                "ATLauncher",
+                flatpak("com.atlauncher.ATLauncher", "data/atlauncher"),
+            ),
+        ],
+        Os::MacOs => vec![
+            (OFFICIAL, f.data.join("minecraft")),
+            ("Prism Launcher", f.data.join("PrismLauncher")),
+            ("MultiMC", f.data.join("MultiMC")),
+            ("Modrinth App", f.data.join("ModrinthApp")),
+            ("ATLauncher", f.data.join("ATLauncher")),
+        ],
+        Os::Windows => vec![
+            (OFFICIAL, f.data.join(".minecraft")),
+            ("Prism Launcher", f.data.join("PrismLauncher")),
+            ("Modrinth App", f.data.join("ModrinthApp")),
+            ("ATLauncher", f.data.join("ATLauncher")),
+        ],
+    };
+    // Names every system shares: the Modrinth App before its rename, GDLauncher and its
+    // previous version (GDLauncher Next).
+    list.extend([
+        ("Modrinth App", f.data.join("com.modrinth.theseus")),
+        ("GDLauncher", f.data.join("gdlauncher_carbon")),
+        ("GDLauncher", f.config.join("gdlauncher_next")),
+    ]);
+    list
+}
+
+/// The client jar's path in a Maven repository: `com.mojang:minecraft:26.3:client` is
+/// `com/mojang/minecraft/26.3/minecraft-26.3-client.jar`.
+pub fn maven_path(name: &str) -> Option {
+    let (name, extension) = name.split_once('@').unwrap_or((name, "jar"));
+    let parts: Vec<&str> = name.split(':').collect();
+    let (group, artifact, version) = match parts[..] {
+        [group, artifact, version] | [group, artifact, version, _] => (group, artifact, version),
+        _ => return None,
+    };
+    let classifier = parts.get(3).map(|c| format!("-{c}")).unwrap_or_default();
+    let unsafe_part = |p: &str| p.is_empty() || p.contains(['/', '\\']) || p.contains("..");
+    if parts.iter().any(|p| unsafe_part(p)) || unsafe_part(extension) {
+        return None;
+    }
+    Some(format!(
+        "{}/{artifact}/{version}/{artifact}-{version}{classifier}.{extension}",
+        group.replace('.', "/")
+    ))
+}
+
+/// The client jar Prism Launcher's and MultiMC's metadata name (`meta/net.minecraft/.json`,
+/// their own format, `mainJar` a Maven name in `libraries`).
+fn meta_client_jar(base: &Path, version: &str) -> Option {
+    let meta = fs::read_to_string(base.join(format!("meta/net.minecraft/{version}.json"))).ok()?;
+    let meta: Value = serde_json::from_str(&meta).ok()?;
+    maven_path(meta["mainJar"]["name"].as_str()?).map(|path| format!("libraries/{path}"))
+}
+
+/// Where launchers keep the client jar, relative to the folder holding their `libraries`.
+fn client_jars(base: &Path, version: &str) -> Vec {
+    let v = version;
+    let mut jars: Vec = meta_client_jar(base, v).into_iter().collect();
+    for jar in [
+        // The official launcher; the Modrinth App, in meta/.
+        format!("versions/{v}/{v}.jar"),
+        // Prism Launcher and MultiMC.
+        format!("libraries/com/mojang/minecraft/{v}/minecraft-{v}-client.jar"),
+        // ATLauncher and GDLauncher.
+        format!("libraries/net/minecraft/client/{v}/client-{v}.jar"),
+    ] {
+        if !jars.contains(&jar) {
+            jars.push(jar);
+        }
+    }
+    jars
+}
+
+pub(crate) fn sha1_file(path: &Path) -> Option {
+    let mut file = fs::File::open(path).ok()?;
+    let mut hash = Sha1::new();
+    let mut buffer = vec![0; 1 << 20];
+    loop {
+        match file.read(&mut buffer).ok()? {
+            0 => break,
+            n => hash.update(&buffer[..n]),
+        }
+    }
+    Some(hash.finalize().iter().map(|b| format!("{b:02x}")).collect())
+}
+
+/// The pinned version in one launcher folder, or what the folder lacks. The folder holding
+/// `libraries` is the folder itself or its `meta` (Modrinth App), `data` (GDLauncher) or
+/// `datastore` (GDLauncher Next).
+pub fn find(dir: &Path, pins: &Pins) -> Result {
+    if !dir.is_dir() {
+        return Err("the folder doesn't exist".into());
+    }
+    let v = &pins.version;
+    let mut other = None;
+    let bases = [dir.to_path_buf()]
+        .into_iter()
+        .chain(["meta", "data", "datastore"].map(|sub| dir.join(sub)));
+    for base in bases {
+        for jar in client_jars(&base, v) {
+            let client = base.join(&jar);
+            if !client.is_file() {
+                continue;
+            }
+            if sha1_file(&client).as_ref() != Some(&pins.client_sha1) {
+                other.get_or_insert(client);
+                continue;
+            }
+            let manifest = base.join(format!("versions/{v}/{v}.json"));
+            let manifest = pins.manifest_accepted(&manifest).then_some(manifest);
+            return Ok(Found {
+                base,
+                client,
+                manifest,
+            });
+        }
+    }
+    Err(match other {
+        Some(jar) => format!(
+            "{} is not the {v} release Horizon was made for",
+            jar.strip_prefix(dir).unwrap_or(&jar).display()
+        ),
+        None => format!("no Minecraft {v} client jar"),
+    })
+}
+
+/// The error when no folder has the pinned version: every folder looked in with what it
+/// lacks, and what the player can do about it (#419).
+pub fn not_found(version: &str, checked: &[(PathBuf, String)]) -> String {
+    let mut text = format!("Minecraft {version} was not found. Horizon looked in:");
+    for (dir, missing) in checked {
+        text += &format!("\n  {} ({missing})", dir.display());
+    }
+    text += &format!(
+        "\nTo fix it:\n  \
+         • Play {version} once in the official Minecraft launcher, or in Prism Launcher, MultiMC, \
+         the Modrinth App, ATLauncher or GDLauncher, then prepare again.\n  \
+         • Or choose the folder where your launcher keeps Minecraft {version} (Minecraft folder › \
+         Choose… in the launcher, --minecraft on the command line)."
+    );
+    text
+}
+
+/// Fetches a URL's body (from several threads for a download).
+pub type Fetch<'a> = &'a (dyn Fn(&str) -> Result, String> + Sync);
+
+/// Where the pinned version is.
+#[derive(Debug, PartialEq)]
+pub enum Resolved {
+    /// A folder in the official launcher's layout.
+    Folder(PathBuf),
+    /// In none of these folders; each with what it lacks.
+    NotFound(Vec<(PathBuf, String)>),
+}
+
+/// A Minecraft folder in the official launcher's layout holding the pinned version: the
+/// chosen folder when it is one, else the files found in the chosen folder (or a folder above
+/// it: a launcher's instance folder may be chosen) or any launcher's default folder, linked into
+/// `linked`.
+pub fn resolve(
+    chosen: &Path,
+    pins: &Pins,
+    known: &[(&'static str, PathBuf)],
+    linked: &Path,
+    fetch: Fetch,
+    log: &dyn Fn(String),
+) -> Result {
+    let mut checked = Vec::new();
+    let mut found = None;
+    for dir in chosen.ancestors().take(4) {
+        match find(dir, pins) {
+            Ok(f) => {
+                found = Some(("the chosen folder", f));
+                break;
+            }
+            Err(missing) if dir == chosen => checked.push((dir.to_path_buf(), missing)),
+            Err(_) => {}
+        }
+    }
+    let same = |a: &Path, b: &Path| a == b || fs::canonicalize(a).ok() == fs::canonicalize(b).ok();
+    for (name, dir) in known.iter().filter(|(_, d)| d.is_dir() && !same(d, chosen)) {
+        if found.is_some() {
+            break;
+        }
+        match find(dir, pins) {
+            Ok(f) => found = Some((name, f)),
+            Err(missing) => checked.push((dir.clone(), format!("{name}: {missing}"))),
+        }
+    }
+    let Some((name, found)) = found else {
+        return Ok(Resolved::NotFound(checked));
+    };
+    log(format!(
+        "Using Minecraft {} from {name} ({})",
+        pins.version,
+        found.base.display()
+    ));
+    if found.official_layout(&pins.version) {
+        return Ok(Resolved::Folder(found.base));
+    }
+    link_official_layout(&found, pins, linked, fetch, log)?;
+    Ok(Resolved::Folder(linked.to_path_buf()))
+}
+
+/// The pinned version JSON at `path`, from piston-meta (by its sha1) unless it is there.
+pub(crate) fn fetch_manifest(
+    pins: &Pins,
+    path: &Path,
+    fetch: Fetch,
+    log: &dyn Fn(String),
+) -> Result<(), String> {
+    if pins.manifest_accepted(path) {
+        return Ok(());
+    }
+    let (v, sha1) = (&pins.version, &pins.manifests[0]);
+    log(format!("Downloading the {v} version file from Mojang"));
+    let url = format!("https://piston-meta.mojang.com/v1/packages/{sha1}/{v}.json");
+    let body =
+        fetch_checked(fetch, &url, sha1).map_err(|e| format!("Mojang's {v} version file {e}"))?;
+    write_file(path, &body)
+}
+
+pub(crate) fn sha1_hex(data: &[u8]) -> String {
+    Sha1::digest(data)
+        .iter()
+        .map(|b| format!("{b:02x}"))
+        .collect()
+}
+
+/// A download checked against its sha1; the error says how it differs.
+pub(crate) fn fetch_checked(fetch: Fetch, url: &str, sha1: &str) -> Result, String> {
+    let body = fetch(url)?;
+    match sha1_hex(&body) {
+        actual if actual == sha1 => Ok(body),
+        actual => Err(format!("is not the one Horizon pins (sha1 {actual})")),
+    }
+}
+
+/// Writes a file whole: a partial one never takes its place.
+pub(crate) fn write_file(path: &Path, data: &[u8]) -> Result<(), String> {
+    let error = |e: std::io::Error| format!("{}: {e}", path.display());
+    fs::create_dir_all(path.parent().unwrap()).map_err(error)?;
+    let partial = path.with_file_name(format!(
+        "{}.partial",
+        path.file_name().unwrap().to_string_lossy()
+    ));
+    fs::write(&partial, data)
+        .and_then(|_| fs::rename(&partial, path))
+        .map_err(error)
+}
+
+/// Links a launcher's files into the official layout in `linked`: the client jar as
+/// `versions//.jar`, its `libraries` and `assets`, and the pinned version JSON, the
+/// launcher's own when it keeps it, else Mojang's.
+fn link_official_layout(
+    found: &Found,
+    pins: &Pins,
+    linked: &Path,
+    fetch: Fetch,
+    log: &dyn Fn(String),
+) -> Result<(), String> {
+    let v = &pins.version;
+    let versions = linked.join("versions").join(v);
+    fs::create_dir_all(&versions).map_err(|e| format!("{}: {e}", versions.display()))?;
+    let manifest = versions.join(format!("{v}.json"));
+    if let Some(source) = &found.manifest {
+        fs::copy(source, &manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
+    } else {
+        fetch_manifest(pins, &manifest, fetch, log)?;
+    }
+    link(&found.client, &versions.join(format!("{v}.jar")))?;
+    for dir in ["libraries", "assets"] {
+        let source = found.base.join(dir);
+        let target = linked.join(dir);
+        if source.is_dir() {
+            link(&source, &target)?;
+        } else {
+            unlink(&target)?;
+        }
+    }
+    Ok(())
+}
+
+/// Removes a link left by an earlier preparation; never a real folder's contents.
+fn unlink(path: &Path) -> Result<(), String> {
+    if fs::symlink_metadata(path).is_err() {
+        return Ok(());
+    }
+    // A Windows junction, or a directory symlink, is removed as a directory.
+    fs::remove_file(path)
+        .or_else(|_| fs::remove_dir(path))
+        .map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// `link` pointing at `target`, replacing an earlier one.
+fn link(target: &Path, link: &Path) -> Result<(), String> {
+    unlink(link)?;
+    make_link(target, link).map_err(|e| format!("{} → {}: {e}", link.display(), target.display()))
+}
+
+#[cfg(unix)]
+fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
+    std::os::unix::fs::symlink(target, link)
+}
+
+/// Symlinks need developer mode on Windows: a junction for a folder, a hard link for a file.
+#[cfg(windows)]
+fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
+    if !target.is_dir() {
+        return fs::hard_link(target, link).or_else(|_| fs::copy(target, link).map(|_| ()));
+    }
+    let status = std::process::Command::new("cmd")
+        .args(["/C", "mklink", "/J"])
+        .arg(link)
+        .arg(target)
+        .stdout(std::process::Stdio::null())
+        .status()?;
+    match status.success() {
+        true => Ok(()),
+        false => Err(std::io::Error::other("mklink /J failed")),
+    }
+}
+
+#[cfg(test)]
+#[path = "sources_tests.rs"]
+mod tests;
diff --git a/launcher/src/sources_tests.rs b/launcher/src/sources_tests.rs
new file mode 100644
index 000000000..f603aaf0a
--- /dev/null
+++ b/launcher/src/sources_tests.rs
@@ -0,0 +1,406 @@
+//! Each launcher's layout, rebuilt with small fake files (never Mojang's).
+use super::*;
+use std::cell::RefCell;
+use std::sync::Mutex;
+
+const CLIENT: &[u8] = b"fake 26.3 client jar";
+const MANIFEST: &[u8] = br#"{"id": "26.3", "fake": true}"#;
+
+fn pins() -> Pins {
+    Pins::read(&serde_json::json!({ "minecraft": {
+        "version": "26.3",
+        "client_sha1": sha1_hex(CLIENT),
+        "manifest_sha1": sha1_hex(MANIFEST),
+        "accepted_manifest_sha1": [sha1_hex(b"an earlier one")],
+    }}))
+    .unwrap()
+}
+
+/// A scratch folder, removed at the end.
+struct Scratch(PathBuf);
+
+impl Scratch {
+    fn new(name: &str) -> Scratch {
+        let dir =
+            std::env::temp_dir().join(format!("horizon-sources-{name}-{}", std::process::id()));
+        let _ = fs::remove_dir_all(&dir);
+        fs::create_dir_all(&dir).unwrap();
+        Scratch(dir)
+    }
+
+    fn write(&self, path: &str, data: &[u8]) -> PathBuf {
+        let path = self.0.join(path);
+        fs::create_dir_all(path.parent().unwrap()).unwrap();
+        fs::write(&path, data).unwrap();
+        path
+    }
+
+    /// A launcher folder: the client jar at `jar`, a library and a sound under `base`.
+    fn launcher(&self, root: &str, base: &str, jar: &str) -> PathBuf {
+        let base = if base.is_empty() {
+            root.to_string()
+        } else {
+            format!("{root}/{base}")
+        };
+        self.write(&format!("{base}/{jar}"), CLIENT);
+        self.write(&format!("{base}/libraries/org/lib/1/lib-1.jar"), b"lib");
+        self.write(&format!("{base}/assets/indexes/30.json"), b"{}");
+        self.0.join(root)
+    }
+}
+
+impl Drop for Scratch {
+    fn drop(&mut self) {
+        let _ = fs::remove_dir_all(&self.0);
+    }
+}
+
+/// Mojang's piston-meta, serving `body` and counting the requests.
+struct Mojang {
+    body: Vec,
+    urls: Mutex>,
+}
+
+impl Mojang {
+    fn new(body: &[u8]) -> Mojang {
+        Mojang {
+            body: body.to_vec(),
+            urls: Mutex::new(Vec::new()),
+        }
+    }
+
+    fn fetch(&self, url: &str) -> Result, String> {
+        self.urls.lock().unwrap().push(url.to_string());
+        Ok(self.body.clone())
+    }
+}
+
+fn resolve_with(
+    chosen: &Path,
+    known: &[(&'static str, PathBuf)],
+    linked: &Path,
+    mojang: &Mojang,
+) -> Result {
+    match resolve(
+        chosen,
+        &pins(),
+        known,
+        linked,
+        &|url| mojang.fetch(url),
+        &|_| {},
+    )? {
+        Resolved::Folder(dir) => Ok(dir),
+        Resolved::NotFound(checked) => Err(not_found("26.3", &checked)),
+    }
+}
+
+/// The linked folder is the official layout, pointing at the launcher's files.
+fn assert_linked(linked: &Path, base: &Path, jar: &str) {
+    let v = linked.join("versions/26.3");
+    assert_eq!(fs::read(v.join("26.3.jar")).unwrap(), CLIENT);
+    assert_eq!(fs::read(v.join("26.3.json")).unwrap(), MANIFEST);
+    assert_eq!(
+        fs::canonicalize(v.join("26.3.jar")).unwrap(),
+        fs::canonicalize(base.join(jar)).unwrap()
+    );
+    assert_eq!(
+        fs::read(linked.join("libraries/org/lib/1/lib-1.jar")).unwrap(),
+        b"lib"
+    );
+    assert!(linked.join("assets/indexes/30.json").is_file());
+}
+
+#[test]
+fn maven_names_become_repository_paths() {
+    assert_eq!(
+        maven_path("com.mojang:minecraft:26.3:client").as_deref(),
+        Some("com/mojang/minecraft/26.3/minecraft-26.3-client.jar")
+    );
+    assert_eq!(
+        maven_path("org.lwjgl:lwjgl:3.3.3").as_deref(),
+        Some("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
+    );
+    assert_eq!(
+        maven_path("net.example:thing:1.0@zip").as_deref(),
+        Some("net/example/thing/1.0/thing-1.0.zip")
+    );
+    for bad in ["minecraft", "a:b", "a:b:c:d:e", "a:..:1", "a:b/c:1", "a::1"] {
+        assert_eq!(maven_path(bad), None, "{bad}");
+    }
+}
+
+#[test]
+fn the_official_layout_is_used_as_it_is() {
+    let s = Scratch::new("official");
+    let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
+    s.write(".minecraft/versions/26.3/26.3.json", MANIFEST);
+    let mojang = Mojang::new(b"");
+    let got = resolve_with(&dir, &[], &s.0.join("linked"), &mojang).unwrap();
+    assert_eq!(got, dir);
+    assert!(mojang.urls.lock().unwrap().is_empty());
+    assert!(!s.0.join("linked").exists());
+}
+
+#[test]
+fn an_official_folder_with_an_unknown_version_file_gets_the_pinned_one() {
+    let s = Scratch::new("republished");
+    let dir = s.launcher(".minecraft", "", "versions/26.3/26.3.jar");
+    s.write(".minecraft/versions/26.3/26.3.json", b"{\"id\": \"26.3\"}");
+    let linked = s.0.join("linked");
+    let mojang = Mojang::new(MANIFEST);
+    assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
+    assert_linked(&linked, &dir, "versions/26.3/26.3.jar");
+}
+
+#[test]
+fn prism_launcher_and_multimc_are_read_through_their_metadata() {
+    let s = Scratch::new("prism");
+    let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
+    let dir = s.launcher("PrismLauncher", "", jar);
+    // Prism's own version format: no `downloads.server`, the client a Maven name.
+    s.write(
+        "PrismLauncher/meta/net.minecraft/26.3.json",
+        br#"{"formatVersion": 1, "uid": "net.minecraft", "version": "26.3",
+            "mainJar": {"name": "com.mojang:minecraft:26.3:client",
+                        "downloads": {"artifact": {"sha1": "x", "size": 20}}}}"#,
+    );
+    let linked = s.0.join("linked");
+    let mojang = Mojang::new(MANIFEST);
+    assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
+    assert_linked(&linked, &dir, jar);
+    assert_eq!(
+        *mojang.urls.lock().unwrap(),
+        [format!(
+            "https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
+            sha1_hex(MANIFEST)
+        )]
+    );
+    // A second preparation keeps the version file it has.
+    resolve_with(&dir, &[], &linked, &mojang).unwrap();
+    assert_eq!(mojang.urls.lock().unwrap().len(), 1);
+}
+
+#[test]
+fn a_main_jar_elsewhere_is_found_from_the_metadata() {
+    let s = Scratch::new("meta-jar");
+    let dir = s.launcher(
+        "multimc",
+        "",
+        "libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar",
+    );
+    s.write(
+        "multimc/meta/net.minecraft/26.3.json",
+        br#"{"mainJar": {"name": "com.mojang:minecraft:26.3:x"}}"#,
+    );
+    let found = find(&dir, &pins()).unwrap();
+    assert_eq!(
+        found.client,
+        dir.join("libraries/com/mojang/minecraft/26.3/minecraft-26.3-x.jar")
+    );
+}
+
+#[test]
+fn the_modrinth_app_atlauncher_and_gdlauncher_are_found() {
+    for (root, base, jar) in [
+        ("ModrinthApp", "meta", "versions/26.3/26.3.jar"),
+        (
+            "atlauncher",
+            "",
+            "libraries/net/minecraft/client/26.3/client-26.3.jar",
+        ),
+        (
+            "gdlauncher_carbon",
+            "data",
+            "libraries/net/minecraft/client/26.3/client-26.3.jar",
+        ),
+        (
+            "gdlauncher_next",
+            "datastore",
+            "libraries/net/minecraft/client/26.3/client-26.3.jar",
+        ),
+    ] {
+        let s = Scratch::new(root);
+        let dir = s.launcher(root, base, jar);
+        // The Modrinth App rewrites the version file: not the pinned one, so Mojang's is used.
+        s.write(
+            &format!("{root}/meta/versions/26.3/26.3.json"),
+            b"{\"id\":\"26.3\"}",
+        );
+        let linked = s.0.join("linked");
+        let mojang = Mojang::new(MANIFEST);
+        assert_eq!(
+            resolve_with(&dir, &[], &linked, &mojang).unwrap(),
+            linked,
+            "{root}"
+        );
+        assert_linked(&linked, &dir.join(base), jar);
+    }
+}
+
+#[test]
+fn an_instance_folder_may_be_chosen() {
+    let s = Scratch::new("instance");
+    let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
+    let dir = s.launcher("PrismLauncher", "", jar);
+    let instance = dir.join("instances/26.3/minecraft");
+    fs::create_dir_all(&instance).unwrap();
+    let linked = s.0.join("linked");
+    let got = resolve_with(&instance, &[], &linked, &Mojang::new(MANIFEST)).unwrap();
+    assert_eq!(got, linked);
+    assert_linked(&linked, &dir, jar);
+}
+
+#[test]
+fn the_known_folders_are_searched_after_the_chosen_one() {
+    let s = Scratch::new("known");
+    let empty = s.0.join(".minecraft");
+    fs::create_dir_all(empty.join("versions")).unwrap();
+    let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
+    let prism = s.launcher("PrismLauncher", "", jar);
+    let known = [
+        (OFFICIAL, empty.clone()),
+        ("Modrinth App", s.0.join("ModrinthApp")),
+        ("Prism Launcher", prism.clone()),
+    ];
+    let linked = s.0.join("linked");
+    let logged = RefCell::new(Vec::new());
+    let mojang = Mojang::new(MANIFEST);
+    let got = resolve(
+        &empty,
+        &pins(),
+        &known,
+        &linked,
+        &|url| mojang.fetch(url),
+        &|line| logged.borrow_mut().push(line),
+    );
+    assert_eq!(got.unwrap(), Resolved::Folder(linked.clone()));
+    assert_linked(&linked, &prism, jar);
+    assert_eq!(
+        logged.borrow()[0],
+        format!(
+            "Using Minecraft 26.3 from Prism Launcher ({})",
+            prism.display()
+        )
+    );
+}
+
+#[test]
+fn relinking_follows_the_launcher_the_files_now_come_from() {
+    let s = Scratch::new("relink");
+    let prism_jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
+    let prism = s.launcher("PrismLauncher", "", prism_jar);
+    let linked = s.0.join("linked");
+    let mojang = Mojang::new(MANIFEST);
+    resolve_with(&prism, &[], &linked, &mojang).unwrap();
+    let modrinth = s.0.join("ModrinthApp");
+    s.write("ModrinthApp/meta/versions/26.3/26.3.jar", CLIENT);
+    resolve_with(&modrinth, &[], &linked, &mojang).unwrap();
+    assert_eq!(
+        fs::canonicalize(linked.join("versions/26.3/26.3.jar")).unwrap(),
+        fs::canonicalize(modrinth.join("meta/versions/26.3/26.3.jar")).unwrap()
+    );
+    // The Modrinth App folder has no libraries or assets: the old links are gone, and the
+    // folders they pointed at are untouched.
+    assert!(fs::symlink_metadata(linked.join("libraries")).is_err());
+    assert!(prism.join("libraries/org/lib/1/lib-1.jar").is_file());
+}
+
+#[test]
+fn nothing_found_lists_every_folder_and_what_it_lacks() {
+    let s = Scratch::new("nothing");
+    let chosen = s.0.join("chosen");
+    let wrong = s.0.join("PrismLauncher");
+    s.write(
+        "PrismLauncher/libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar",
+        b"another release",
+    );
+    let empty = s.0.join("ModrinthApp");
+    fs::create_dir_all(&empty).unwrap();
+    let known = [
+        ("Prism Launcher", wrong.clone()),
+        ("Modrinth App", empty.clone()),
+        ("ATLauncher", s.0.join("atlauncher")),
+    ];
+    let mojang = Mojang::new(MANIFEST);
+    let error = resolve_with(&chosen, &known, &s.0.join("linked"), &mojang).unwrap_err();
+    let expected = format!(
+        "Minecraft 26.3 was not found. Horizon looked in:\n  \
+         {} (the folder doesn't exist)\n  \
+         {} (Prism Launcher: libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar is \
+         not the 26.3 release Horizon was made for)\n  \
+         {} (Modrinth App: no Minecraft 26.3 client jar)\nTo fix it:\n",
+        chosen.display(),
+        wrong.display(),
+        empty.display()
+    );
+    assert!(error.starts_with(&expected), "{error}");
+    assert!(error.contains("Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher"));
+    // A launcher that isn't installed isn't listed.
+    assert!(!error.contains("atlauncher"));
+    assert!(mojang.urls.lock().unwrap().is_empty());
+}
+
+#[test]
+fn a_version_file_that_is_not_the_pinned_one_is_refused() {
+    let s = Scratch::new("bad-download");
+    let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar";
+    let dir = s.launcher("PrismLauncher", "", jar);
+    let linked = s.0.join("linked");
+    let error = resolve_with(&dir, &[], &linked, &Mojang::new(b"{}")).unwrap_err();
+    assert!(error.contains("not the one Horizon pins"), "{error}");
+    assert!(!linked.join("versions/26.3/26.3.json").exists());
+}
+
+#[test]
+fn each_system_has_its_launcher_folders() {
+    let linux = Folders {
+        home: "/home/r".into(),
+        data: "/home/r/.local/share".into(),
+        config: "/home/r/.config".into(),
+    };
+    let folders = |os, f: &Folders| -> Vec {
+        known_folders(os, f)
+            .into_iter()
+            .map(|(name, dir)| format!("{name}: {}", dir.display()).replace('\\', "/"))
+            .collect()
+    };
+    let got = folders(Os::Linux, &linux);
+    for expected in [
+        "the official launcher: /home/r/.minecraft",
+        "Prism Launcher: /home/r/.local/share/PrismLauncher",
+        "Prism Launcher: /home/r/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher",
+        "MultiMC: /home/r/.local/share/multimc",
+        "Modrinth App: /home/r/.local/share/ModrinthApp",
+        "Modrinth App: /home/r/.var/app/com.modrinth.ModrinthApp/data/ModrinthApp",
+        "ATLauncher: /home/r/.local/share/atlauncher",
+        "GDLauncher: /home/r/.local/share/gdlauncher_carbon",
+        "GDLauncher: /home/r/.config/gdlauncher_next",
+    ] {
+        assert!(got.iter().any(|g| g == expected), "{expected} in {got:#?}");
+    }
+    assert!(got[0].starts_with("the official launcher"));
+    let mac = Folders {
+        home: "/Users/r".into(),
+        data: "/Users/r/Library/Application Support".into(),
+        config: "/Users/r/Library/Application Support".into(),
+    };
+    let got = folders(Os::MacOs, &mac);
+    assert_eq!(
+        got[0],
+        "the official launcher: /Users/r/Library/Application Support/minecraft"
+    );
+    assert!(
+        got.contains(&"Prism Launcher: /Users/r/Library/Application Support/PrismLauncher".into())
+    );
+    let windows = Folders {
+        home: "C:/Users/r".into(),
+        data: "C:/Users/r/AppData/Roaming".into(),
+        config: "C:/Users/r/AppData/Roaming".into(),
+    };
+    let got = folders(Os::Windows, &windows);
+    assert_eq!(
+        got[0],
+        "the official launcher: C:/Users/r/AppData/Roaming/.minecraft"
+    );
+    assert!(got.contains(&"ATLauncher: C:/Users/r/AppData/Roaming/ATLauncher".into()));
+}
diff --git a/tests/test_release_train.py b/tests/test_release_train.py
index fef887f3c..1240334b0 100644
--- a/tests/test_release_train.py
+++ b/tests/test_release_train.py
@@ -39,8 +39,13 @@ class ReleaseTrainTests(unittest.TestCase):
     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")
+        self.assertEqual(train.next_game_tag(["v2026.10.15"], today), "v2026.10.15.01")
+        self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.01", "v2026.10.15.02"], today), "v2026.10.15.03")
+        # Unpadded tags from before the change still count, and the next one sorts after them as text too.
+        self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.9", "v2026.10.15.20"], today), "v2026.10.15.21")
+        self.assertEqual(train.next_game_tag(["v2026.10.15", "v2026.10.15.08"], today), "v2026.10.15.09")
+        tags = ["v2026.10.15.09", "v2026.10.15.10", "v2026.10.15"]
+        self.assertEqual(sorted(tags), sorted(tags, key=train.tag_key))
 
     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"]
diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py
new file mode 100755
index 000000000..a78948dd0
--- /dev/null
+++ b/tools/lan_e2e.py
@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+"""LAN multiplayer end to end: a host opens its world to LAN and a guest joins, both real games.
+
+Two Horizon clients run side by side under horizon-ctl, each in its own scratch folder. The host
+creates a survival world and opens it to LAN with commands allowed; the guest connects to it by
+address. The script then checks, from both sides, what a guest's game used to get wrong (#366):
+
+- tab:       the guest's player list holds the host and the guest, under their own names;
+- self:      the guest's own model exists (third person, inventory preview);
+- armour:    each side draws the other player in that player's own armour;
+- nametags:  each side draws the other player's name above them;
+- chest:     a chest the guest opens opens on the guest's screen, its lid opens on both sides and
+             closes on both when the guest closes it;
+- crafting:  the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
+- damage:    a guest in survival takes fall damage.
+
+Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
+both sides go to --out (host-*.png, guest-*.png).
+
+    python3 tools/lan_e2e.py                          # build with the fast profile, run every check
+    python3 tools/lan_e2e.py --bin-dir target/fast    # prebuilt binaries
+    python3 tools/lan_e2e.py --check chest --check tab
+
+Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on
+macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1).
+"""
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from agent_control_e2e import Cli, Failed, game_env  # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[1]
+GUEST_NAME = 'Guest'
+CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage']
+
+
+class Game:
+    """One client: its scratch folder, its socket and a CLI driver."""
+
+    def __init__(self, name, ctl, resources):
+        self.name = name
+        self.work = Path(tempfile.mkdtemp(prefix=f'hzlan-{name}-'))
+        (self.work / '.local/horizon-client').mkdir(parents=True)
+        os.symlink(resources, self.work / '.local/horizon-client/26.3')
+        self.socket = self.work / 'c.sock'
+        env = game_env(os.environ.get('VSCREEN', 'lan-e2e'))
+        env['HORIZON_HOME'] = str(self.work / 'home')
+        self.d = Cli(ctl, self.socket, self.work, env)
+        self.d.name = name
+
+    def __call__(self, tool, **args):
+        return self.d(tool, **args)
+
+    def raw(self, *words):
+        """A game command horizon-ctl has no table entry for (lan, connect): the words as typed."""
+        result = subprocess.run(self.d.base + [str(w) for w in words], cwd=self.work, env=self.d.env,
+                                capture_output=True, text=True, timeout=600)
+        lines = result.stdout.strip().splitlines()
+        reply = json.loads(lines[-1]) if lines else {'error': result.stderr.strip()}
+        print(f'[{self.name}] {list(words)} -> {json.dumps(reply)[:400]}')
+        if result.returncode or 'error' in reply:
+            raise Failed(f'{" ".join(map(str, words))}: {reply}')
+        return reply
+
+    def shot(self, out, label):
+        path = out / f'{self.name}-{label}.png'
+        self.d('screenshot', path=path)
+        return path
+
+    def wait(self, ticks):
+        self.d('wait', ticks=ticks)
+
+    def close(self):
+        try:
+            self.d('quit')
+        except Exception:
+            pass
+        time.sleep(2)
+        log = self.socket.with_suffix('.log')
+        return log.read_text(errors='replace') if log.exists() else ''
+
+
+def remote(guest):
+    """The guest's view of the server (`status`'s server part)."""
+    return guest('status')['server']
+
+
+def back_to_game(game):
+    """Close whatever screen a failed check left open, without opening the pause menu."""
+    try:
+        if game('state').get('screen') not in (None, 'playing'):
+            game.raw('key', 'esc', 'tap')
+            game.wait(2)
+    except Failed:
+        pass
+
+
+def pos_of(game):
+    return game('state')['player']['position']
+
+
+def face_each_other(host, guest):
+    """Put the guest 3 blocks east of the host, both looking at the other's head."""
+    hx, hy, hz = pos_of(host)
+    guest('command', command=f'tp @s {hx + 3:.2f} {hy:.2f} {hz:.2f}')
+    guest.wait(30)
+    host.raw('look-at', f'{hx + 3:.2f}', f'{hy + 1.6:.2f}', f'{hz:.2f}')
+    guest.raw('look-at', f'{hx:.2f}', f'{hy + 1.6:.2f}', f'{hz:.2f}')
+    host.wait(10)
+
+
+def check_tab(host, guest, out):
+    players = remote(guest)['players']
+    names = sorted(p['name'] if isinstance(p, dict) else str(p) for p in players)
+    assert names == sorted([host.player, GUEST_NAME]), f'guest tab list: {players}, host {host.player}'
+    guest.raw('key', 'tab', 'down')
+    guest.wait(5)
+    guest.shot(out, 'tab')
+    guest.raw('key', 'tab', 'up')
+    return names
+
+
+def check_self(host, guest, out):
+    guest.raw('key', 'f5', 'tap')
+    guest.wait(10)
+    guest.shot(out, 'self-third-person')
+    status = guest('state')
+    guest.raw('key', 'f5', 'tap')
+    guest.raw('key', 'f5', 'tap')
+    guest.raw('key', 'e', 'tap')
+    guest.raw('wait-for', 'screen', 'inventory')
+    guest.shot(out, 'self-inventory')
+    model = remote(guest).get('player_model')
+    guest.raw('key', 'esc', 'tap')
+    assert model, f'the guest has no player model: {status.get("camera")}'
+    return 'model drawn'
+
+
+def check_armour(host, guest, out):
+    host('command', command='item replace entity @s armor.head with minecraft:golden_helmet')
+    host('command', command='item replace entity @s armor.chest with minecraft:golden_chestplate')
+    guest('command', command='item replace entity @s armor.chest with minecraft:diamond_chestplate')
+    guest('command', command='item replace entity @s armor.legs with minecraft:diamond_leggings')
+    face_each_other(host, guest)
+    host.shot(out, 'armour')
+    guest.shot(out, 'armour')
+    seen = host.raw('lan', 'status')['guests'][0].get('model_armor')
+    assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \
+        f'the host draws the guest in {seen}'
+    host_gear = [e for e in remote(guest).get('player_equipment', [])]
+    assert any('golden_chestplate' in json.dumps(e) for e in host_gear), f'the guest sees the host in {host_gear}'
+    return 'each in their own'
+
+
+def check_nametags(host, guest, out):
+    face_each_other(host, guest)
+    h = host('status').get('name_tags') or []
+    g = guest('status').get('name_tags') or []
+    host.shot(out, 'nametags')
+    guest.shot(out, 'nametags')
+    assert GUEST_NAME in h, f'host draws name tags {h}'
+    assert host.player in g, f'guest draws name tags {g}'
+    return {'host': h, 'guest': g}
+
+
+def lid(game, pos):
+    return game.raw('block', *pos).get('lid', 0.0)
+
+
+def check_chest(host, guest, out):
+    x, y, z = (int(v // 1) for v in pos_of(guest))
+    chest = (x, y, z + 2)
+    guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
+    guest.wait(10)
+    guest.raw('interact', *chest)
+    screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
+    guest.wait(20)
+    opened = {'guest': lid(guest, chest), 'host': lid(host, chest)}
+    host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5)
+    host.wait(2)
+    host.shot(out, 'chest-open')
+    guest.shot(out, 'chest-open')
+    guest.raw('key', 'esc', 'tap')
+    guest.wait(20)
+    closed = {'guest': lid(guest, chest), 'host': lid(host, chest)}
+    host.shot(out, 'chest-closed')
+    assert screen, 'no container screen on the guest'
+    assert opened['guest'] > 0.9 and opened['host'] > 0.9, f'lid while open: {opened}'
+    assert closed['guest'] < 0.1 and closed['host'] < 0.1, f'lid after closing: {closed}'
+    return {'open': opened, 'closed': closed}
+
+
+def check_crafting(host, guest, out):
+    guest('command', command='clear @s')
+    guest('command', command='give @s minecraft:oak_log 1')
+    guest.wait(10)
+    guest.raw('key', 'e', 'tap')
+    guest.raw('wait-for', 'screen', 'inventory')
+    inv = guest('inventory')
+    slot = next(s['slot'] for s in inv['hotbar'] if s and s.get('item') == 'minecraft:oak_log')
+    # Horizon's slot ids (click-slot): the hotbar is 0-8, the grid 100-108, the result 200.
+    guest.raw('click-slot', slot)
+    guest.raw('click-slot', 100)
+    guest.wait(5)
+    result = [s for s in guest('screen').get('slots', []) if s.get('slot') == 200]
+    guest.shot(out, 'crafting-grid')
+    guest.raw('click-slot', 200, 'shift')
+    guest.wait(5)
+    guest.raw('key', 'esc', 'tap')
+    guest.wait(5)
+    planks = guest('inventory')['counts'].get('minecraft:oak_planks', 0)
+    assert planks == 4, f'crafted {planks} planks (result slot: {result})'
+    x, y, z = (int(v // 1) for v in pos_of(guest))
+    table = (x, y, z - 2)
+    guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table')
+    guest.wait(10)
+    guest.raw('interact', *table)
+    guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10)
+    size = guest('screen').get('craft_size')
+    assert size == 3, f'the crafting table opened a {size}x{size} grid'
+    # Two planks one above the other in the 3x3 grid: four sticks.
+    slot = next(s['slot'] for s in guest('inventory')['hotbar'] if s and s.get('item') == 'minecraft:oak_planks')
+    guest.raw('click-slot', slot)
+    guest.raw('click-slot', 100, 'right')
+    guest.raw('click-slot', 103, 'right')
+    guest.raw('click-slot', slot)
+    guest.wait(5)
+    guest.shot(out, 'crafting-table')
+    guest.raw('click-slot', 200, 'shift')
+    guest.wait(5)
+    guest.raw('key', 'esc', 'tap')
+    guest.wait(5)
+    counts = guest('inventory')['counts']
+    assert counts.get('minecraft:stick') == 4 and counts.get('minecraft:oak_planks') == 2, f'after the table: {counts}'
+    return {'planks': planks, 'table': counts}
+
+
+def check_damage(host, guest, out):
+    guest('command', command='gamemode survival')
+    guest.wait(10)
+    before = remote(guest)['health']
+    x, y, z = pos_of(guest)
+    guest('command', command=f'tp @s {x:.2f} {y + 12:.2f} {z:.2f}')
+    guest.wait(50)
+    after = remote(guest)['health']
+    guest.shot(out, 'damage')
+    assert after < before, f'health {before} -> {after} after a 12-block fall'
+    # Into water: the fall does no damage.
+    x, y, z = pos_of(guest)
+    guest('command', command=f'setblock {int(x // 1)} {int(y // 1)} {int(z // 1)} minecraft:water')
+    guest('command', command=f'tp @s {x:.2f} {y + 12:.2f} {z:.2f}')
+    guest.wait(50)
+    water = remote(guest)['health']
+    assert water >= after, f'health {after} -> {water} after falling into water'
+    return {'before': before, 'after': after, 'water': water}
+
+
+CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
+             'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage}
+
+
+def run(ctl, out, resources, checks):
+    host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
+    results = {}
+    try:
+        host('launch', wait=False, offscreen=sys.platform == 'darwin')
+        host.raw('open', 'Lan', 5)
+        host('wait_ready', seconds=400)
+        host('command', command='time set day')
+        # An open stone floor around the host, so the players see each other and nothing is in the way.
+        host('command', command='fill ~-8 ~-1 ~-8 ~8 ~-1 ~8 minecraft:stone')
+        host('command', command='fill ~-8 ~ ~-8 ~8 ~6 ~8 minecraft:air')
+        host('command', command='gamerule spawn_mobs false')
+        port = host.raw('lan', 'open', 0, 'commands')['port']
+        host.player = host.raw('lan', 'status').get('host', 'Player')  # the host's profile name
+        guest('launch', wait=False, offscreen=sys.platform == 'darwin')
+        guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME)
+        guest.raw('wait-for', 'loaded', '--timeout', 300)
+        guest.wait(40)
+        face_each_other(host, guest)
+        host.shot(out, 'joined')
+        guest.shot(out, 'joined')
+        for name in checks:
+            try:
+                results[name] = {'pass': True, 'detail': CHECK_FNS[name](host, guest, out)}
+            except (Failed, AssertionError, StopIteration, KeyError) as e:
+                results[name] = {'pass': False, 'detail': repr(e)}
+                for g in (host, guest):
+                    back_to_game(g)
+            print(f'[lan] {name}: {"PASS" if results[name]["pass"] else "FAIL"} {results[name]["detail"]}')
+    finally:
+        logs = {g.name: g.close() for g in (guest, host)}
+        for name, text in logs.items():
+            (out / f'{name}.log').write_text(text)
+        for g in (host, guest):
+            shutil.rmtree(g.work, ignore_errors=True)
+    return results
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+    parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
+    parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)')
+    parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here')
+    args = parser.parse_args()
+    if args.bin_dir:
+        bins = Path(args.bin_dir).resolve()
+    else:
+        subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
+                       cwd=ROOT, check=True)
+        meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT,
+                                         capture_output=True, text=True, check=True).stdout)
+        bins = Path(meta['target_directory']) / 'fast'
+    resources = (ROOT / '.local/horizon-client/26.3').resolve()
+    if not (resources / 'horizon-resources.json').exists():
+        sys.exit(f'no prepared resources in {resources}')
+    out = Path(args.out)
+    out.mkdir(parents=True, exist_ok=True)
+    results = run(bins / 'horizon-ctl', out, resources, args.check or CHECKS)
+    print(json.dumps(results, indent=1))
+    sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/tools/package_native_client.py b/tools/package_native_client.py
index 92498436a..70f8c64ac 100644
--- a/tools/package_native_client.py
+++ b/tools/package_native_client.py
@@ -102,6 +102,8 @@ def main():
     archive = args.out / f'{name}.tar.gz'
     with tarfile.open(archive, 'w:gz', compresslevel=1) as tar:
         tar.add(args.binary, 'horizon/horizon-client')
+        tar.add(ROOT / 'LICENSE', 'horizon/LICENSE')
+        tar.add(ROOT / 'THIRD_PARTY_NOTICES.md', 'horizon/THIRD_PARTY_NOTICES.md')
         ctl = args.binary.with_name('horizon-ctl')  # built with --bins: scripts and agents play through it
         if ctl.is_file():
             tar.add(ctl, 'horizon/horizon-ctl')
diff --git a/tools/release_train.py b/tools/release_train.py
index c74b46b76..a1af28449 100644
--- a/tools/release_train.py
+++ b/tools/release_train.py
@@ -11,7 +11,7 @@ of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that
 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
+Game releases are tagged vYYYY.MM.DD, then .01, .02 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.
@@ -92,12 +92,15 @@ def tag_key(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)."""
+    """vYYYY.MM.DD, or .01, .02... when that day already has a tag (drafts and rolled-back releases included).
+
+    The counter has two digits because GitHub's releases page sorts a day's tags as text: .9 went above .18.
+    Every reader compares the numbers as integers, so the unpadded tags from before still order correctly."""
     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}"
+    return f"{day}.{max(int(tag.split('.')[3]) if tag.count('.') == 3 else 0 for tag in taken) + 1:02d}"
 
 
 def next_launcher_tag(tags, minor):
diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py
index a9a718340..068fba3d4 100644
--- a/tools/test_save_roundtrip_parity.py
+++ b/tools/test_save_roundtrip_parity.py
@@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir):
     if launch.returncode:
         sys.exit('horizon failed to launch: ' + launch.stdout + launch.stderr)
     steps = [['wait-ready', '240']]
-    steps += [['chat', f'/gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()]
+    steps += [['command', f'gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()]
     steps += [['save-all'], ['quit']]
     for step in steps:
         result = subprocess.run(ctl + step, cwd=destination, env=env, capture_output=True, text=True)
diff --git a/tools/test_world_reopen_parity.py b/tools/test_world_reopen_parity.py
new file mode 100644
index 000000000..381927013
--- /dev/null
+++ b/tools/test_world_reopen_parity.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Leaving a world and opening it again keeps its entities as they were (#374).
+
+Vanilla's integrated server unloads every entity with the level when the player saves
+and quits (`MinecraftServer.stopServer`), so a world reopened in the same session holds
+each entity once. Horizon kept non-mob entities (minecarts, boats, armor stands...) in
+memory after Save and Quit to Title; opening the world loaded them again from disk and
+the next save wrote both copies, doubling them each time, until the game crawled.
+
+The game runs offscreen (macOS) or on the virtual screen (Linux) with a control socket:
+a minecart is summoned beside the player (seed 7 also has mineshaft chest minecarts in
+view), then the world is closed through the pause menu and reopened from the title three
+times. The minecarts must be the same ones each time, each once.
+
+  test_world_reopen_parity.py [--bin-dir DIR] [--keep]
+"""
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
+RUN = ROOT / '.local' / 'world-reopen'
+CYCLES = 3
+
+
+def game_env():
+    """macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity)."""
+    env = dict(os.environ, HORIZON_NO_AUDIO='1')
+    if sys.platform == 'darwin':
+        return env, ['--offscreen']
+    subprocess.run(['vscreen', 'up'], check=False, capture_output=True)
+    text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout
+    env.pop('DISPLAY', None)
+    for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
+        env[match.group(1)] = match.group(2)
+    return env, []
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+    parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build them with the fast profile)')
+    parser.add_argument('--keep', action='store_true', help='keep the run folder')
+    args = parser.parse_args()
+    bin_dir = Path(args.bin_dir).resolve() if args.bin_dir else None
+    if bin_dir is None:
+        subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], cwd=ROOT, check=True)
+        bin_dir = ROOT / os.environ.get('CARGO_TARGET_DIR', 'target') / 'fast'
+    shutil.rmtree(RUN, ignore_errors=True)
+    RUN.mkdir(parents=True)
+    socket = Path(tempfile.mkdtemp(prefix='hzro')) / 'control.sock'  # sockets need short paths
+    env, extra = game_env()
+
+    def ctl(*words, check=True):
+        result = subprocess.run([str(bin_dir / 'horizon-ctl'), '--socket', str(socket), '--timeout', '600', *words],
+                                cwd=RUN, env=env, capture_output=True, text=True)
+        if check and result.returncode:
+            sys.exit(f'horizon-ctl {" ".join(words)} failed: {result.stdout}{result.stderr}')
+        return json.loads(result.stdout) if result.stdout.strip().startswith('{') else result.stdout
+
+    def carts():
+        found = ctl('status')['carts']
+        return sorted((c['kind'], *(round(v, 1) for v in c['position'])) for c in found)
+
+    ctl('launch', '--resources', str(RESOURCES), '--world', 'reopen', '--seed', '7', '--creative',
+        '--render-distance', '4', *extra)
+    failures = 0
+    try:
+        ctl('wait-ready', '300')
+        ctl('command', 'summon minecraft:minecart ~2 ~ ~2')
+        ctl('wait', '20')
+        expected = carts()
+        print('minecarts:', len(expected))
+        if not any(kind == 'minecraft:minecart' for kind, *_ in expected):
+            sys.exit(f'the summoned minecart is not there: {expected}')
+        for cycle in range(1, CYCLES + 1):
+            ctl('pause')
+            ctl('click-button', 'Save and Quit to Title')
+            ctl('wait-for', 'screen', 'title', '--timeout', '120')
+            ctl('open', 'reopen')
+            ctl('wait-for', 'loaded', '--timeout', '300')
+            ctl('wait', '20')
+            got = carts()
+            ok = got == expected
+            failures += not ok
+            print(f'reopen {cycle}: {len(got)} minecarts', 'ok' if ok else f'FAIL (expected {len(expected)})')
+    finally:
+        ctl('quit', check=False)
+        if not args.keep and not failures:
+            shutil.rmtree(RUN, ignore_errors=True)
+    print('world reopen:', 'PASS' if not failures else f'{failures} FAILED')
+    sys.exit(1 if failures else 0)
+
+
+if __name__ == '__main__':
+    main()