From 88efc73ac156e72a18a2786889595784ec9ab27a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:52:25 +0200 Subject: [PATCH 01/24] Mesh biome tints through the zoomed biome and honour lighting options The section mesher blended biome colours over quart cells at the section's mid-height. It now follows ClientLevel.calculateBlockTint: each tinted block averages the colours of the biomes BiomeManager picks (the eight-corner zoom with the client's hashed seed) over the biomeBlendRadius square at the block's own height, computed lazily per layer and column. The ao and cutoutLeaves options are honoured too: flat lighting, skipped faces between opaque leaves and a vertex layer flag that makes the terrain shader ignore leaf alpha. The section mesh parity gate gained biome-blend scenes (random zoom seeds, radii 0 to 7, all 67 biomes, real Biome colour resolvers through a BiomeManager in the Java oracle) and option scenes; all 1.0M quads of the 112 scenes match the client. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/section_mesh_fixture.rs | 60 ++++- crates/horizon-client/src/game.rs | 13 +- crates/horizon-client/src/game/remote.rs | 2 + crates/horizon-client/src/mesher.rs | 216 +++++++++++++----- crates/horizon-client/src/streaming.rs | 49 +++- crates/horizon-client/src/terrain.wgsl | 7 +- docs/parity/meshing.md | 37 ++- .../parity/VanillaSectionMeshOracle.java | 75 +++++- tools/test_section_mesh_parity.py | 75 +++++- 9 files changed, 435 insertions(+), 99 deletions(-) diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index 1ac0e094d..d4c710fbc 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -4,12 +4,13 @@ #![forbid(unsafe_code)] use horizon_client::{ assets::Assets, - biome::{Biomes, GrassModifier}, + biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, - mesher::{MeshTables, Mesher, Vertex}, + mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex}, models, }; +use horizon_core::biome::BiomeZoom; use horizon_world::registry::BlockStateId; use serde_json::{Value, json}; use std::{ @@ -48,17 +49,23 @@ fn scene( assets: &Assets, tables: &MeshTables, biomes: &mut Biomes, + pristine: &[BiomeInfo], names: &BTreeMap, elapsed: &mut Duration, ) -> Result { let colors = &row["colors"]; let color = |k: &str| -> Result { Ok(int(&colors[k])? as u32 & 0xFF_FFFF) }; - for biome in &mut biomes.list { - biome.grass = color("grass")?; - biome.modifier = GrassModifier::None; - biome.foliage = color("foliage")?; - biome.dry_foliage = color("dry_foliage")?; - biome.water = color("water")?; + // Scenes without a biome field give every biome the same constant colours; + // the others use the real biome definitions. + biomes.list = pristine.to_vec(); + if row.get("biomes").is_none() { + for biome in &mut biomes.list { + biome.grass = color("grass")?; + biome.modifier = GrassModifier::None; + biome.foliage = color("foliage")?; + biome.dry_foliage = color("dry_foliage")?; + biome.water = color("water")?; + } } let default = row["light"].as_array().ok_or("missing default light")?; let packed = |sky: i32, block: i32| (sky << 4 | block) as u8; @@ -89,6 +96,24 @@ fn scene( values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?); } } + let (mut zoom, mut blend_radius) = (BiomeZoom::new(0), 2); + let smooth_lighting = row["smooth"].as_bool().unwrap_or(true); + let cutout_leaves = row["cutout_leaves"].as_bool().unwrap_or(true); + if let Some(field) = row.get("biomes") { + zoom = BiomeZoom::new(field["seed"].as_i64().ok_or("missing biome seed")?); + blend_radius = int(&field["radius"])?; + let default = biomes.id(field["default"].as_str().ok_or("missing default biome")?); + for chunk in &mut chunks { + Arc::make_mut(&mut chunk.biomes).fill(default); + } + for cell in field["cells"].as_array().ok_or("missing biome cells")? { + let (qx, qy, qz) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?); + let i = chunk_index(qx * 4, qz * 4)?; + let slot = ((qy - MIN_Y / 4) * 16 + (qz & 3) * 4 + (qx & 3)) as usize; + Arc::make_mut(&mut chunks[i].biomes)[slot] = + biomes.id(cell[3].as_str().ok_or("biome name")?); + } + } let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|z| std::array::from_fn(|x| Some(&chunks[z * 3 + x]))); let mut mesher = Mesher { @@ -97,6 +122,10 @@ fn scene( tables, biomes: &*biomes, visibility: tables.visibility.clone(), + zoom, + blend_radius, + smooth_lighting, + cutout_leaves, }; let section_y = int(&row["section_y"])?; let started = Instant::now(); @@ -109,7 +138,9 @@ fn scene( return Err("partial quad".into()); } for quad in vertices { - let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?; + let sprite = names + .get(&(quad[0].layer & !OPAQUE_LAYER)) + .ok_or("unknown sprite layer")?; if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) { return Err("quad mixes sprite layers".into()); } @@ -150,6 +181,7 @@ fn main() -> Result<()> { .iter() .map(|(name, layer)| (*layer, name.as_str())) .collect(); + let pristine = biomes.list.clone(); let mut output = BufWriter::new(fs::File::create(&args[2])?); if args[1] == "facts" { // The per-state facts the mesher derives, in the oracle's order and positions. @@ -175,7 +207,15 @@ fn main() -> Result<()> { let (mut elapsed, mut sections) = (Duration::ZERO, 0u32); for line in BufReader::new(fs::File::open(&args[1])?).lines() { let row: Value = serde_json::from_str(&line?)?; - let result = scene(&row, &assets, &tables, &mut biomes, &names, &mut elapsed)?; + let result = scene( + &row, + &assets, + &tables, + &mut biomes, + &pristine, + &names, + &mut elapsed, + )?; serde_json::to_writer(&mut output, &result)?; output.write_all(b"\n")?; sections += 1; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b8f4a8529..262b23d32 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -97,7 +97,11 @@ use horizon_client::{ vanillagen::VanillaTerrain, world::World, }; -use horizon_core::{geometry::Direction, position::BlockPos}; +use horizon_core::{ + biome::{BiomeZoom, obfuscate_seed}, + geometry::Direction, + position::BlockPos, +}; use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_world::{ block_collision::BlockCollisionRegistry, @@ -4768,6 +4772,10 @@ impl Game<'_> { ) }; streaming.radius = self.settings.render_distance; + streaming.biome_blend = self.settings.biome_blend; + streaming.smooth_lighting = self.settings.smooth_lighting; + streaming.cutout_leaves = self.settings.cutout_leaves; + streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; Ok((streaming, save)) @@ -6019,6 +6027,9 @@ impl Game<'_> { } fn apply_settings(&mut self) { self.streaming.radius = self.settings.render_distance; + 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.audio.master = self.settings.master_volume; horizon_client::hud::GUI_SCALE.store( self.settings.gui_scale, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d0d821410..1e9f59167 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -420,6 +420,8 @@ impl Game<'_> { .is_none_or(|r| r.dimension.has_skylight); self.streaming.sky_light = has_sky; self.streaming.nether_shading = self.dim == Dim::Nether; + // The seed in SpawnInfo is already the hashed one the client's BiomeManager holds. + self.streaming.biome_zoom = horizon_core::biome::BiomeZoom::new(spawn.seed); self.player = None; self.apply_settings(); } diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 368c92518..63a929074 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -12,7 +12,9 @@ use crate::{ chunk::{Chunk, MIN_Y}, models::catalog::BakedFace, }; -use horizon_core::{geometry::Direction, position::BlockPos, random::position_seed}; +use horizon_core::{ + biome::BiomeZoom, geometry::Direction, position::BlockPos, random::position_seed, +}; use horizon_world::{ block_render::FaceVisibility, fluid::{FluidKind, FluidState}, @@ -161,6 +163,8 @@ struct Info { legacy_solid: bool, /// `HalfTransparentBlock`/`LeavesBlock`: water sides show the overlay sprite. overlay: bool, + /// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped. + leaves: bool, blocks_flow: bool, ice: bool, sturdy: u8, @@ -313,6 +317,7 @@ impl MeshTables { offset, legacy_solid: s.legacy_solid, overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"), + leaves: s.has_class("LeavesBlock"), blocks_flow: assets.blocks_fluid_flow.contains(&*s.name), ice: s.has_class("IceBlock"), sturdy: s.sturdy_full, @@ -396,57 +401,113 @@ impl Padded { Self { blocks, light } } } +/// Set on a vertex's sprite layer when its texture alpha must be ignored. +pub const OPAQUE_LAYER: u32 = 1 << 31; +const UNSET: u32 = u32::MAX; +const NO_BIOME: u16 = u16::MAX; +/// The `ColorResolver`s `ClientLevel` caches block tints for. #[derive(Clone, Copy)] -struct Colors { - grass: [u32; 256], - tall_upper: [u32; 256], - foliage: [u32; 256], - dry: [u32; 256], - water: [u32; 256], +enum Resolver { + Grass, + Foliage, + Dry, + Water, } -fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y: i32) -> Colors { - // Vanilla blends over a (2r+1)^2 area; r = 2 is the default option. - const R: i32 = 2; - let biome_at = |x: i32, z: i32| -> u16 { - region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize] - .map_or(0, |c| c.biome(x & 15, y, z & 15)) - }; - let mut colors = Colors { - grass: [0; 256], - tall_upper: [0; 256], - foliage: [0; 256], - dry: [0; 256], - water: [0; 256], - }; - let avg = |f: &dyn Fn(u16, i32, i32) -> u32, x: i32, z: i32| -> u32 { - let (mut r, mut g, mut b) = (0, 0, 0); - for dz in -R..=R { - for dx in -R..=R { - let c = f(biome_at(x + dx, z + dz), x + dx, z + dz); - r += c >> 16 & 255; - g += c >> 8 & 255; - b += c & 255; - } - } - let n = ((2 * R + 1) * (2 * R + 1)) as u32; - (r / n) << 16 | (g / n) << 8 | (b / n) - }; - for z in 0..16 { - for x in 0..16 { - let i = (z * 16 + x) as usize; - let (wx, wz) = (cx * 16 + x, cz * 16 + z); - colors.grass[i] = avg( - &|b, dx, dz| biomes.grass(b, f64::from(wx + dx - x), f64::from(wz + dz - z)), - x, - z, - ); - colors.tall_upper[i] = colors.grass[i]; - colors.foliage[i] = avg(&|b, _, _| biomes.get(b).foliage, x, z); - colors.dry[i] = avg(&|b, _, _| biomes.get(b).dry_foliage, x, z); - colors.water[i] = avg(&|b, _, _| biomes.get(b).water, x, z); +/// Biome tints of one block layer: the zoomed biome of every block of the +/// layer plus the blend radius around it, and the blended colours per column. +struct Layer { + zoomed: Vec, + colors: [[u32; 256]; 4], +} +/// `ClientLevel.calculateBlockTint` behind a per-layer `BlockTintCache`: each +/// block averages the colours of the biomes `BiomeManager.getBiome` picks (the +/// eight-corner zoom) over a `(2r+1)^2` square at the block's own height. +/// Layers and columns are only computed when a tinted block asks for them. +struct Tints<'a> { + region: &'a [[Option<&'a Chunk>; 3]; 3], + biomes: &'a Biomes, + zoom: BiomeZoom, + radius: i32, + plains: u16, + /// Chunk x, chunk z and the section's lowest block y. + origin: [i32; 3], + layers: [Option>; 16], +} +impl<'a> Tints<'a> { + fn new( + region: &'a [[Option<&'a Chunk>; 3]; 3], + biomes: &'a Biomes, + zoom: BiomeZoom, + radius: i32, + origin: [i32; 3], + ) -> Self { + Self { + region, + biomes, + zoom, + radius: radius.clamp(0, 7), + plains: biomes.id("minecraft:plains"), + origin, + layers: Default::default(), } } - colors + /// The blended tint of block `(x, y, z)` (section-local x/z, y in 0..16). + fn get(&mut self, resolver: Resolver, x: i32, y: i32, z: i32) -> u32 { + let r = self.radius; + let dim = (16 + 2 * r) as usize; + let layer = self.layers[y as usize].get_or_insert_with(|| { + Box::new(Layer { + zoomed: vec![NO_BIOME; dim * dim], + colors: [[UNSET; 256]; 4], + }) + }); + let slot = (z * 16 + x) as usize; + let cached = layer.colors[resolver as usize][slot]; + if cached != UNSET { + return cached; + } + let [cx, cz, base_y] = self.origin; + let (bx, by, bz) = (cx * 16, base_y + y, cz * 16); + let (mut red, mut green, mut blue) = (0, 0, 0); + for dz in -r..=r { + for dx in -r..=r { + let cell = ((z + dz + r) as usize) * dim + (x + dx + r) as usize; + let mut biome = layer.zoomed[cell]; + if biome == NO_BIOME { + // BiomeManager.getBiome over the loaded chunks (plains + // where there is none). + let q = self + .zoom + .quart_at_block(BlockPos::new(bx + x + dx, by, bz + z + dz)); + let (rx, rz) = ((q[0] >> 2) - cx + 1, (q[2] >> 2) - cz + 1); + biome = if (0..3).contains(&rx) && (0..3).contains(&rz) { + self.region[rz as usize][rx as usize].map_or(self.plains, |c| { + c.biome((q[0] & 3) * 4, q[1] * 4, (q[2] & 3) * 4) + }) + } else { + self.plains + }; + layer.zoomed[cell] = biome; + } + let c = match resolver { + Resolver::Grass => { + self.biomes + .grass(biome, f64::from(bx + x + dx), f64::from(bz + z + dz)) + } + Resolver::Foliage => self.biomes.get(biome).foliage, + Resolver::Dry => self.biomes.get(biome).dry_foliage, + Resolver::Water => self.biomes.get(biome).water, + }; + red += c >> 16 & 255; + green += c >> 8 & 255; + blue += c & 255; + } + } + let n = ((2 * r + 1) * (2 * r + 1)) as u32; + let color = (red / n) << 16 | (green / n) << 8 | (blue / n); + layer.colors[resolver as usize][slot] = color; + color + } } /// Packs 8-bit RGB into the vertex's RGBA8 (red in the low byte), opaque. fn pack_rgb([r, g, b]: [u32; 3]) -> u32 { @@ -464,6 +525,14 @@ pub struct Mesher<'a> { pub tables: &'a MeshTables, pub biomes: &'a Biomes, pub visibility: FaceVisibility, + /// The client's biome zoom (the hashed world seed `BiomeManager` holds). + pub zoom: BiomeZoom, + /// The `biomeBlendRadius` option, 0 to 7. + pub blend_radius: i32, + /// The `ao` option: smooth lighting for models that allow it. + pub smooth_lighting: bool, + /// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque. + pub cutout_leaves: bool, } impl Mesher<'_> { /// `region[dz][dx]` are the chunks around the meshed column (centre 1,1). @@ -477,7 +546,13 @@ impl Mesher<'_> { let pad = Padded::new(region, sy); out.visibility = visibility(&pad, &self.tables.info); let base_y = MIN_Y + sy * 16; - let colors = blend(region, self.biomes, center.x, center.z, base_y + 8); + let mut tints = Tints::new( + region, + self.biomes, + self.zoom, + self.blend_radius, + [center.x, center.z, base_y], + ); let info = &self.tables.info; for y in 0..16 { for z in 0..16 { @@ -502,7 +577,7 @@ impl Mesher<'_> { continue; } if state.fluid.kind() != FluidKind::Empty { - let water = colors.water[(z * 16 + x) as usize]; + let water = tints.get(Resolver::Water, x, y, z); let nether = self.nether_shading; fluid::tesselate(self.tables, nether, &pad, water, &mut out, [x, y, z]); } @@ -522,7 +597,7 @@ impl Mesher<'_> { let Some((_, first)) = models.first() else { continue; }; - let ao = state.emission == 0 && first.ambient_occlusion; + let ao = self.smooth_lighting && state.emission == 0 && first.ambient_occlusion; let origin = match offset(state, world.x, world.z) { Some(o) => [ x as f32 + o[0] as f32, @@ -544,13 +619,26 @@ impl Mesher<'_> { 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; + } } for (_, model) in &models { for face in &model.faces { if face.quad.cull.is_some_and(|d| !visible[d as usize]) { continue; } - self.face(&pad, &colors, &mut out, [x, y, z], origin, face, ao, state); + self.face( + &pad, + &mut tints, + &mut out, + [x, y, z], + origin, + face, + ao, + state, + ); } } } @@ -559,18 +647,17 @@ impl Mesher<'_> { out } /// `BlockColors` tint source `index`, or `None` for an untinted (-1) layer. - fn tint(state: &Info, index: i32, colors: &Colors, x: i32, z: i32) -> Option { + fn tint(state: &Info, index: i32, tints: &mut Tints, [x, y, z]: [i32; 3]) -> Option { if index < 0 || index >= i32::from(state.tint_count) { return None; } - let column = (z * 16 + x) as usize; Some(match state.tints[(index as usize).min(1)] { Tint::None => return None, - Tint::Grass => colors.grass[column], - Tint::TallGrassUpper => colors.tall_upper[column], - Tint::Foliage => colors.foliage[column], - Tint::DryFoliage => colors.dry[column], - Tint::Water => colors.water[column], + Tint::Grass => tints.get(Resolver::Grass, x, y, z), + Tint::TallGrassUpper => tints.get(Resolver::Grass, x, y, z), + Tint::Foliage => tints.get(Resolver::Foliage, x, y, z), + Tint::DryFoliage => tints.get(Resolver::Dry, x, y, z), + Tint::Water => tints.get(Resolver::Water, x, y, z), Tint::Constant(c) => c, Tint::Redstone(p) => redstone_color(p), Tint::Stem(age) => { @@ -583,7 +670,7 @@ impl Mesher<'_> { fn face( &self, pad: &Padded, - colors: &Colors, + tints: &mut Tints, out: &mut SectionMesh, pos: [i32; 3], origin: [f32; 3], @@ -608,7 +695,7 @@ impl Mesher<'_> { }; ([lighting::gray(directional); 4], [coords; 4]) }; - let tint = Self::tint(state, q.tint_index, colors, pos[0], pos[2]); + let tint = Self::tint(state, q.tint_index, tints, pos); let target = if face.translucent { &mut out.translucent } else { @@ -624,7 +711,12 @@ impl Mesher<'_> { target.push(Vertex { pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], uv: q.uv[i], - layer: face.layer, + // Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout. + layer: if !self.cutout_leaves && state.leaves { + face.layer | OPAQUE_LAYER + } else { + face.layer + }, color: pack_rgb(rgb), light: pack_coords(lighting::with_emission(coords[i], q.light_emission)), }); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index c43e82e69..98aec9924 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -8,6 +8,7 @@ use crate::{ mesher::{MeshTables, Mesher, Region, SectionMesh, borrow}, world::World, }; +use horizon_core::biome::BiomeZoom; use std::{ collections::{BinaryHeap, HashMap, HashSet}, sync::{ @@ -40,12 +41,21 @@ pub trait ChunkGenerator: Send + Sync + 'static { fn decorate(&self, _worker: &mut Self::Worker, _region: &mut [Proto; 9]) {} fn finish(&self, proto: Proto) -> Chunk; } +/// Per-job mesher inputs that change with the dimension or the options. +#[derive(Clone, Copy)] +struct MeshSettings { + nether: bool, + zoom: BiomeZoom, + blend_radius: i32, + smooth_lighting: bool, + cutout_leaves: bool, +} enum Job { Generate(i32, i32), Decorate(i32, i32, Box<[Proto; 9]>), Finish(Proto), Light(i32, i32, Box, u64, bool), - Mesh(i32, i32, i32, Box, u64, bool), + Mesh(i32, i32, i32, Box, u64, MeshSettings), } pub enum Done { Generated(Chunk), @@ -109,6 +119,12 @@ pub struct Streaming { /// Dimension flags: sky light, Nether face shading. pub sky_light: bool, pub nether_shading: bool, + /// `BiomeManager`'s zoom seed (the hashed world seed) and `biomeBlendRadius`. + pub biome_zoom: BiomeZoom, + pub biome_blend: i32, + /// The `ao` and `cutoutLeaves` options. + pub smooth_lighting: bool, + pub cutout_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. @@ -153,6 +169,10 @@ impl Streaming { let mut worker = generator.worker(); let mut mesher = Mesher { nether_shading: false, + zoom: BiomeZoom::new(0), + blend_radius: 2, + smooth_lighting: true, + cutout_leaves: true, assets: &context.assets, tables: &context.tables, biomes: &context.biomes, @@ -187,8 +207,12 @@ impl Streaming { light_chunk(&borrow(®ion), &context.light, sky), seq, ), - Job::Mesh(x, sy, z, region, seq, nether) => { - mesher.nether_shading = nether; + Job::Mesh(x, sy, z, region, seq, settings) => { + mesher.nether_shading = settings.nether; + mesher.zoom = settings.zoom; + mesher.blend_radius = settings.blend_radius; + mesher.smooth_lighting = settings.smooth_lighting; + mesher.cutout_leaves = settings.cutout_leaves; Done::Meshed(x, sy, z, mesher.mesh(&borrow(®ion), sy), seq) } }; @@ -221,6 +245,10 @@ impl Streaming { paused: false, sky_light: true, nether_shading: false, + biome_zoom: BiomeZoom::new(0), + biome_blend: 2, + smooth_lighting: true, + cutout_leaves: true, light_tables, light_log: Vec::new(), light_edit_sequence: 0, @@ -554,7 +582,20 @@ impl Streaming { self.meshing.insert((x, sy, z), self.sequence); self.submit( self.distance(x, z) * 4 + if first { 2 } else { 0 }, - Job::Mesh(x, sy, z, region, self.sequence, self.nether_shading), + Job::Mesh( + x, + sy, + z, + region, + self.sequence, + MeshSettings { + nether: self.nether_shading, + zoom: self.biome_zoom, + blend_radius: self.biome_blend, + smooth_lighting: self.smooth_lighting, + cutout_leaves: self.cutout_leaves, + }, + ), ); } (uploads, removed) diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 02c79db05..806d5e845 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -59,12 +59,13 @@ fn apply_fog(color: vec4, spherical: f32, cylindrical: f32) -> vec4 { return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } @fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4 { - let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color; - if color.a < 0.5 { discard; } + // Bit 31 of the layer marks opaque leaves (forceOpaque): no alpha cutout. + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color; + if color.a < 0.5 && (in.layer & 0x80000000u) == 0u { discard; } return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical); } @fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4 { - let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color; + let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color; if color.a < 0.01 { discard; } return apply_fog(color, in.spherical, in.cylindrical); } diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md index 841ca30a3..919c67891 100644 --- a/docs/parity/meshing.md +++ b/docs/parity/meshing.md @@ -24,7 +24,8 @@ emit for the same scenes. loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`, `load_visibility`, `MeshTables`), builds the same blocks and light in real client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the - scene constants and runs `Mesher::mesh`. + scene constants (or, for the biome-blend scenes, keeps the real biome + definitions and fills the chunks' quart biome arrays) and runs `Mesher::mesh`. - **Comparison**: quads are matched as multisets per scene, keyed by sprite, render-layer class (translucent vs. solid/cutout) and geometry rounded to 1/1000 after binary32 normalisation, with a winding-preserving rotation. @@ -37,7 +38,7 @@ emit for the same scenes. overlay classes (`HalfTransparentBlock`/`LeavesBlock`), tint source counts and `getOffset` at five columns. -The corpus (94 sections, ~842k quads, ~206k of them fluid quads) has full +The corpus (112 sections, ~1.0M quads, ~206k of them fluid quads) has full cubes in open air, corners, cavities and overhangs; slabs, stairs, walls, fences, panes, bars, torches, flowers and grasses with XZ/XYZ offsets, tall plants, tinted blocks (grass, leaves, stems, redstone, lily pad, petals, leaf @@ -50,6 +51,27 @@ sculk sensor, glow lichen); Nether shading; every block's default state; every `RenderShape.MODEL` state of the registry on a sparse grid; and dense random scenes mixing all model states with fluids under propagated or random light. +Biome tint blending is compared against the client's real +`ClientLevel.calculateBlockTint`: the oracle builds a `BiomeManager` (the +eight-corner zoom with a random hashed seed) over a fixed noise-biome map of +real `Biome` objects from the registry bootstrap (colormap sampling, colour +overrides, the dark-forest and swamp grass modifiers), initialises +`GrassColor`/`FoliageColor`/`DryFoliageColor` from the jar's colormaps, and +averages the resolver over the blend radius at each block's own height. The +`biome_blend_r*` scenes (radius 0, 1, 2, 3, 5, 7) put tinted blocks (grass, +leaves, water, leaf litter, cane, ferns, vines) at four heights on every +column of a Voronoi patchwork of 16 common biomes that shifts with height; +the `biome_each_*` scenes cover all 67 biomes. Option scenes (`options_*`) +cover flat lighting (`ao` off), opaque leaves (`cutoutLeaves` off, which +`SectionCompiler` draws in the solid layer and `LeavesBlock.skipRendering` +joins) and both together. + +With `biomeBlendRadius` 0 the client takes the resolver's colour as is. Biome +colours given as plain RGB (all water colours, most grass/foliage overrides) +have alpha 0 there, so the client's tinted vertices come out fully +transparent, which the terrain shader would discard. Horizon keeps them +opaque and the gate compares RGB for radius-0 scenes. + ## Running ```sh @@ -112,15 +134,14 @@ gate. ## What remains different or untested -- Biome tint blending: vanilla blends `BiomeManager`'s zoomed biome at each - block's own height; Horizon blends its quart biome cells at the section's - mid-height. The gate uses one constant colour per resolver, so this is not - compared. +- Changing `biomeBlendRadius`, `ao` or `cutoutLeaves` in the options does not + remesh resident sections; new and edited sections use the new values. - Model variant seeds: `DoublePlantBlock`, `DoorBlock` and `AbstractBedBlock` override `getSeed`; Horizon seeds every block from its own position. No vanilla block among those has weighted variants, so output is unaffected. -- Settings: only smooth lighting on and cutout ("fancy") leaves are covered; - Horizon has no flat-lighting or opaque-leaves modes. +- Opaque leaves: the vertex layer carries a flag (`OPAQUE_LAYER`) that makes + the terrain shader ignore the texture's alpha; the shader side is not + compared (GPU pixels). - Layers: vanilla's solid and cutout layers are compared as one class because Horizon draws both in its opaque pass. - Not compared: block entities and their renderers, animated sprite frames, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java index 548275cbe..8845fad89 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java @@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.function.Function; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.BiomeColors; import net.minecraft.client.renderer.block.*; @@ -29,6 +30,14 @@ import net.minecraft.world.level.CardinalLighting; import net.minecraft.world.level.ColorResolver; import net.minecraft.world.level.EmptyBlockGetter; import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.DryFoliageColor; +import net.minecraft.world.level.FoliageColor; +import net.minecraft.world.level.GrassColor; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.ARGB; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; @@ -100,6 +109,12 @@ public final class VanillaSectionMeshOracle { return (T) value; } } + private static int[] colormap(String name) throws IOException { + try (var input = VanillaSectionMeshOracle.class.getResourceAsStream("/assets/minecraft/textures/colormap/" + name + ".png"); + var image = NativeImage.read(input)) { + return image.makePixelArray(); + } + } private static String resource(String path) throws IOException { try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) { return input == null ? null : new String(input.readAllBytes(), StandardCharsets.UTF_8); @@ -139,12 +154,47 @@ public final class VanillaSectionMeshOracle { return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker)); } } + /** ClientLevel.calculateBlockTint over a BiomeManager with a fixed noise-biome map: + * quart cells listed in the scene, a default elsewhere in the 3x3 chunk region and + * plains outside it (chunks that are not loaded). */ + private static final class TintBiomes { + final BiomeManager manager; final int radius; + final Map> cells = new HashMap<>(); + final Holder dflt, plains; + TintBiomes(JsonObject o, HolderLookup.RegistryLookup lookup) { + radius = o.get("radius").getAsInt(); + Function> named = name -> lookup.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(name))); + plains = named.apply("minecraft:plains"); + dflt = named.apply(o.get("default").getAsString()); + for (var item : o.getAsJsonArray("cells")) { + var c = item.getAsJsonArray(); + cells.put(BlockPos.asLong(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), named.apply(c.get(3).getAsString())); + } + manager = new BiomeManager((qx, qy, qz) -> { + if (qx < -4 || qx >= 8 || qz < -4 || qz >= 8) return plains; + return cells.getOrDefault(BlockPos.asLong(qx, Math.max(-16, Math.min(79, qy)), qz), dflt); + }, o.get("seed").getAsLong()); + } + int tint(BlockPos pos, ColorResolver resolver) { + if (radius == 0) return resolver.getColor(manager.getBiome(pos).value(), pos.getX(), pos.getZ()); + int count = (radius * 2 + 1) * (radius * 2 + 1); + int red = 0, green = 0, blue = 0; + var cursor = new Cursor3D(pos.getX() - radius, pos.getY(), pos.getZ() - radius, pos.getX() + radius, pos.getY(), pos.getZ() + radius); + var next = new BlockPos.MutableBlockPos(); + while (cursor.advance()) { + next.set(cursor.nextX(), cursor.nextY(), cursor.nextZ()); + int color = resolver.getColor(manager.getBiome(next).value(), next.getX(), next.getZ()); + red += ARGB.red(color); green += ARGB.green(color); blue += ARGB.blue(color); + } + return ARGB.color(red / count, green / count, blue / count); + } + } private static long key(int x, int y, int z) { return BlockPos.asLong(x, y, z); } /** A fixed region: listed blocks over air, listed light over a default. */ private static final class Scene implements BlockAndTintGetter { final Map blocks = new HashMap<>(); final Map light = new HashMap<>(); - int[] defaultLight; boolean nether; int grass, foliage, dry, water; + int[] defaultLight; boolean nether; int grass, foliage, dry, water; TintBiomes biomes; public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; } public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; } public int getBrightness(LightLayer layer, BlockPos pos) { @@ -152,6 +202,7 @@ public final class VanillaSectionMeshOracle { return layer == LightLayer.SKY ? value[0] : value[1]; } public int getBlockTint(BlockPos pos, ColorResolver resolver) { + if (biomes != null) return biomes.tint(pos, resolver); int rgb = resolver == BiomeColors.GRASS_COLOR_RESOLVER ? grass : resolver == BiomeColors.FOLIAGE_COLOR_RESOLVER ? foliage : resolver == BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER ? dry : resolver == BiomeColors.WATER_COLOR_RESOLVER ? water : -1; if (rgb == -1) throw new AssertionError("unexpected colour resolver"); @@ -165,7 +216,7 @@ public final class VanillaSectionMeshOracle { } private static final class Recorder { final List quads = new ArrayList<>(); - List pending; BlockPos block; String kind, layer, sprite; + List pending; boolean forceSolid; BlockPos block; String kind, layer, sprite; void vertex(float x, float y, float z, int color, float u, float v, int light) { if (pending == null) pending = new ArrayList<>(); pending.add(new Object[]{x, y, z, u, v, color, light}); @@ -176,7 +227,7 @@ public final class VanillaSectionMeshOracle { } } private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); } - private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) { + private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids, HolderLookup.RegistryLookup biomeLookup) { var scene = new Scene(); var light = row.getAsJsonArray("light"); scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()}; @@ -184,6 +235,7 @@ public final class VanillaSectionMeshOracle { var colors = row.getAsJsonObject("colors"); scene.grass = colors.get("grass").getAsInt(); scene.foliage = colors.get("foliage").getAsInt(); scene.dry = colors.get("dry_foliage").getAsInt(); scene.water = colors.get("water").getAsInt(); + if (row.has("biomes")) scene.biomes = new TintBiomes(row.getAsJsonObject("biomes"), biomeLookup); for (var item : row.getAsJsonArray("blocks")) { var b = item.getAsJsonArray(); scene.blocks.put(key(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()), Block.stateById(b.get(3).getAsInt())); @@ -194,10 +246,13 @@ public final class VanillaSectionMeshOracle { } var recorder = new Recorder(); BlockModelLighter.enableCaching(); - var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault()); + boolean smooth = !row.has("smooth") || row.get("smooth").getAsBoolean(); + boolean cutoutLeaves = !row.has("cutout_leaves") || row.get("cutout_leaves").getAsBoolean(); + LeavesBlock.setCutoutLeaves(cutoutLeaves); + var renderer = new ModelBlockRenderer(smooth, true, BlockColors.createDefault()); var fluidRenderer = new FluidRenderer(fluids); BlockQuadOutput output = (x, y, z, quad, instance) -> { - recorder.kind = "model"; recorder.layer = layer(quad.materialInfo().layer()); + recorder.kind = "model"; recorder.layer = recorder.forceSolid ? "solid" : layer(quad.materialInfo().layer()); recorder.sprite = quad.materialInfo().sprite().contents().name().toString(); int emission = quad.materialInfo().lightEmission(); int slot = Arrays.asList(FLUID_SPRITES).indexOf(recorder.sprite); @@ -233,9 +288,8 @@ public final class VanillaSectionMeshOracle { }, state, fluid); } if (state.getRenderShape() == RenderShape.MODEL) { - renderer.tesselateBlock(ModelBlockRenderer.forceOpaque(true, state) ? (x, y, z, quad, instance) -> { - throw new AssertionError("cutout leaves are enabled"); - } : output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()), + recorder.forceSolid = ModelBlockRenderer.forceOpaque(cutoutLeaves, state); + renderer.tesselateBlock(output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()), scene, pos, state, models.get(state), state.getSeed(pos)); } } @@ -244,6 +298,7 @@ public final class VanillaSectionMeshOracle { return map("name", row.get("name").getAsString(), "quads", recorder.quads); } private static BlockColors COLORS; + private static HolderLookup.RegistryLookup biomeLookup; /** Per-state facts the Rust mesher derives from prepared resources. */ private static Object facts(BlockState state, int id) { var level = EmptyBlockGetter.INSTANCE; @@ -266,6 +321,7 @@ public final class VanillaSectionMeshOracle { net.minecraft.server.Bootstrap.bootStrap(); VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject()); LeavesBlock.setCutoutLeaves(true); + GrassColor.init(colormap("grass")); FoliageColor.init(colormap("foliage")); DryFoliageColor.init(colormap("dry_foliage")); COLORS = BlockColors.createDefault(); if (args[0].equals("facts")) { try (var output = Files.newBufferedWriter(Path.of(args[1]))) { @@ -288,10 +344,11 @@ public final class VanillaSectionMeshOracle { var atlas = new SpriteLoader.Preparations(16, 16, 0, missing, Map.of(), CompletableFuture.completedFuture(null)); var materials = new Materials(atlas); var models = new Models(blocks, materials); + biomeLookup = net.minecraft.data.registries.VanillaRegistries.createWorldLookup().lookupOrThrow(Registries.BIOME); var fluidModels = FluidStateModelSet.bake(materials); var fluids = new FluidStateModelSet(fluidModels, fluidModels.values().iterator().next()); try (var output = Files.newBufferedWriter(Path.of(args[1]))) { - for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids))); output.newLine(); } + for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids, biomeLookup))); output.newLine(); } } } } diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py index 4c6fff704..22362bd79 100644 --- a/tools/test_section_mesh_parity.py +++ b/tools/test_section_mesh_parity.py @@ -29,6 +29,7 @@ except ImportError: import test_model_baking_parity as baking BUILD = lab.ROOT / 'target/section-mesh-parity' +RESOURCES = lab.LOCAL / 'horizon-client' / '26.3' SECTION_Y = 0 COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4} POSITION_TOLERANCE = 1e-4 @@ -71,6 +72,8 @@ class Scene: self.blocks = {} self.light_override = {} self.noise = None + self.biomes = None + self.options = {} def put(self, x, y, z, name, **properties): self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties) @@ -130,8 +133,38 @@ class Scene: return result def row(self): - return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0], - 'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()} + row = {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0], + 'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()} + if self.biomes is not None: + row['biomes'] = self.biomes + row.update(self.options) + return row + + def tinted_columns(self): + """Every tint source at several heights over the section's 16x16 footprint.""" + names = [('grass_block', {}), ('short_grass', {}), ('oak_leaves', {}), ('water', {}), ('leaf_litter', {'segment_amount': 2}), + ('sugar_cane', {}), ('fern', {}), ('vine', {'north': True}), ('mangrove_leaves', {}), ('jungle_leaves', {})] + for x in range(16): + for z in range(16): + for layer, y in enumerate((1, 5, 9, 13)): + name, properties = names[(x * 5 + z * 3 + layer) % len(names)] + self.put(x, y, z, 'stone') + self.put(x, y + 1, z, name, **properties) + if name == 'water': + self.put(x, y + 2, z, 'water') + + def biome_field(self, seed, radius, names, default='plains'): + """Noise-biome quart cells: a Voronoi patchwork that shifts with height.""" + rng = random.Random(seed) + sites = [[(rng.uniform(-4, 8), rng.uniform(-4, 8), rng.choice(names)) for _ in range(9)] for _ in range(10)] + cells = [] + for qy in range(-3, 8): + layer = sites[(qy + 3) // 2 % len(sites)] + for qx in range(-4, 8): + for qz in range(-4, 8): + best = min(layer, key=lambda site: (site[0] - qx) ** 2 + (site[1] - qz) ** 2) + cells.append([qx, qy, qz, 'minecraft:' + best[2]]) + self.biomes = {'seed': rng.randrange(-2 ** 63, 2 ** 63), 'radius': radius, 'default': 'minecraft:' + default, 'cells': cells} def corpus(states, full=True): @@ -306,6 +339,38 @@ def corpus(states, full=True): s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids)) if seed % 2: s.noise = seed + # Biome tint blending: BiomeManager's zoomed biome at each block's own height, averaged + # over the blend radius, for real biome colours (colormaps, overrides, modifiers). + biome_names = sorted(path.stem for path in (RESOURCES / 'data/minecraft/worldgen/biome').glob('*.json')) + common = ['plains', 'swamp', 'dark_forest', 'desert', 'jungle', 'badlands', 'mangrove_swamp', 'warm_ocean', 'snowy_plains', + 'birch_forest', 'cherry_grove', 'pale_garden', 'savanna', 'taiga', 'old_growth_pine_taiga', 'lush_caves'] + for i, radius in enumerate((2, 0, 1, 3, 5, 7)): + s = scene(f'biome_blend_r{radius}') + s.floor(0) + s.tinted_columns() + s.biome_field(0x42494F4D + i, radius, common) + for i in range(0, len(biome_names), 8): + s = scene(f'biome_each_{i // 8}') + s.tinted_columns() + s.biome_field(0x45414348 + i, 2, biome_names[i:i + 8], biome_names[i]) + # Options: flat lighting (ao off) and opaque leaves (cutoutLeaves off) alone and together. + leaves = ['oak_leaves', 'spruce_leaves', 'birch_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves', + 'azalea_leaves', 'flowering_azalea_leaves', 'mangrove_leaves', 'cherry_leaves', 'pale_oak_leaves'] + option_palette = ['stone', 'glass', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy', 'short_grass', + 'glowstone', 'oak_fence', 'ice', 'oak_log', 'tinted_glass', 'slime_block', 'honey_block'] + leaves * 2 + for i, options in enumerate(({'smooth': False}, {'cutout_leaves': False}, {'smooth': False, 'cutout_leaves': False})): + rng = random.Random(0x4F505453 + i) + s = scene(f'options_{i}', nether=i == 2) + s.options = options + s.floor(0) + for x in range(-1, 17): + for y in range(1, 17): + for z in range(-1, 17): + if rng.random() < 0.5: + name = rng.choice(option_palette) + s.put(x, y, z, rng.choice(states.by_name['minecraft:' + name])) + if i: + s.noise = i s = scene('cubes_nether', nether=True) s.floor(3, 'netherrack') s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks') @@ -337,6 +402,7 @@ def light(coords): def compare(scene, client, rust, states, report, limit): + blend_zero = scene.get('biomes', {}).get('radius') == 0 blocks = {tuple(b[:3]): b[3] for b in scene['blocks']} def describe(quad, rotation): v = quad['vertices'] @@ -377,6 +443,11 @@ def compare(scene, client, rust, states, report, limit): if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)): problems.add('uv') cp, cq = channels(p[5]), channels(q[5]) + if blend_zero and cp[3] == 0 and cq[3] == 255: + # With biomeBlendRadius 0 the client uses the resolver's colour as is, + # and biome colours given as plain RGB have alpha 0: tinted vertices come + # out fully transparent. Horizon keeps them opaque; RGB is compared. + cp[3] = 255 if cp != cq: problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding') if light(p[6]) != light(q[6]): From 69c7fd925eb22cd41f0105222e75822bdf03480a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:04:56 +0200 Subject: [PATCH 02/24] Port every crafting recipe type and test recipes against vanilla The crafting module now matches shapeless recipes with a full bipartite assignment, shrinks shaped patterns like ShapedRecipePattern, keeps result components (suspicious stew effects), and implements the transmute, dye, imbue (tipped arrow), book cloning, firework rocket/star/fade, decorated pot, repair item, map extending, banner duplicate and shield decoration recipes with vanilla's matching and assembly. Crafting remainders now follow Item.craftRemainder only and are placed on the grid by recipe, so cloned books and duplicated banners stay. Stacks gain dyed colour, firework explosion, pot decorations, bundle contents, stew effects and map post-processing components, and their NBT now matches the codecs (defaults omitted, templates without count 1). A banner whose first layer was a rhombus was mistaken for the raid banner; that is fixed. tools/test_recipe_parity.py drives vanilla's RecipeManager (new VanillaRecipeOracle) and the Rust recipe_fixture over 50k generated crafting, cooking, stonecutting and smithing cases and compares matches, results and remainders as canonical NBT; all match. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/examples/recipe_fixture.rs | 91 ++ crates/horizon-client/src/crafting.rs | 1365 ++++++++++++++--- crates/horizon-client/src/game.rs | 16 +- .../src/game/machines/crafter.rs | 2 +- crates/horizon-client/src/item_data.rs | 346 ++++- crates/horizon-client/src/items.rs | 30 +- crates/horizon-client/src/recipe_book.rs | 2 +- .../dev/horizonlab/parity/ParityData.java | 132 ++ .../parity/VanillaRecipeOracle.java | 140 ++ tools/interaction_lab.py | 71 + tools/test_recipe_parity.py | 303 ++++ 11 files changed, 2233 insertions(+), 265 deletions(-) create mode 100644 crates/horizon-client/examples/recipe_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java create mode 100644 tools/interaction_lab.py create mode 100644 tools/test_recipe_parity.py diff --git a/crates/horizon-client/examples/recipe_fixture.rs b/crates/horizon-client/examples/recipe_fixture.rs new file mode 100644 index 000000000..e68258e4d --- /dev/null +++ b/crates/horizon-client/examples/recipe_fixture.rs @@ -0,0 +1,91 @@ +//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's +//! tab-separated commands (craft, cook, stonecut, smith) and prints one line +//! per command in the oracle's format. +//! +//! usage: recipe_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + crafting::Recipes, + enchant::Enchantments, + item_data::{canon_stack, parse_stack}, + items::Items, + stations::StationRecipes, +}; +use std::{fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let stations = StationRecipes::load(root, &items); + let enchantments = Enchantments::load(root); + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split('\t').collect(); + let stack = |i: usize| parse_stack(f[i]); + let text = match f[0] { + "craft" => { + let n: usize = f[1].parse()?; + let mut grid = Vec::new(); + for i in 0..n * n { + grid.push(stack(2 + i)?); + } + match recipes.find(&grid, n) { + None => "none".to_owned(), + Some((id, result)) => { + let rest = recipes.remainders(id, &grid, n); + let rest: Vec = rest + .iter() + .enumerate() + .filter_map(|(i, s)| { + Some(format!("{i}={}", canon_stack(Some(s.as_ref()?)))) + }) + .collect(); + format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";")) + } + } + } + "cook" => match stack(2)?.and_then(|s| { + recipes + .cook(&format!("minecraft:{}", f[1]), &s) + .map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time)) + }) { + None => "none".to_owned(), + Some((id, result, xp, time)) => { + format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result))) + } + }, + "stonecut" => match stack(1)? { + None => String::new(), + Some(s) => stations + .stonecutter(&s) + .iter() + .map(|r| { + format!( + "{}={}", + r.id.trim_start_matches("minecraft:"), + canon_stack(Some(&r.result)) + ) + }) + .collect::>() + .join(";"), + }, + "smith" => { + let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?); + match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) { + None => "none".to_owned(), + Some(r) => canon_stack(Some(&r)), + } + } + other => return Err(format!("unknown command {other}").into()), + }; + out.push_str(&text); + out.push('\n'); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index aa434a556..cf2e43f03 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1,13 +1,28 @@ //! Crafting and cooking recipes from the pinned data pack: shaped patterns -//! (placed anywhere in the grid, optionally mirrored as in -//! `ShapedRecipePattern.matches`), shapeless ingredient sets, and furnace-type -//! cooking lookups. +//! (`ShapedRecipePattern.matches`), shapeless recipes (a bipartite match of +//! ingredients to stacks, as `StackedContents.canCraft`), the special and +//! transmuting crafting recipes (`CustomRecipe` and friends), and +//! furnace-type cooking lookups. use crate::{ Result, + item_data::StackData, items::{ItemStack, Items}, + particles::{FireworkExplosion, FireworkShape}, }; +use horizon_world::nbt::Tag; use serde_json::Value; -use std::{collections::HashSet, fs, path::Path, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + fs, + path::Path, + sync::Arc, +}; + +/// `DyeColor.getFireworkColor` in dye order (white to black). +const FIREWORK_COLORS: [u32; 16] = [ + 15_790_320, 15_435_844, 12_801_229, 6_719_955, 14_602_026, 4_312_372, 14_188_952, 4_408_131, + 11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019, +]; /// A set of accepted items (expanded from an item, list or tag). #[derive(Clone, Debug)] @@ -41,22 +56,124 @@ impl Ingredient { self.0.contains(&*stack.item) } } +/// A recipe result: `ItemStackTemplate` (`id`, `count`, `components`), with the +/// id optional for the transmuting recipes that keep the input's item. +#[derive(Clone, Debug)] +pub struct Template { + pub item: Option>, + pub count: u32, + pub damage: u32, + pub extra: Option>, +} +impl Template { + fn parse(v: &Value) -> Option { + let (damage, extra) = match v.get("components") { + Some(c) => crate::item_data::decode_components(Some(&json_tag(c))), + None => (0, None), + }; + Some(Self { + item: v["id"].as_str().map(Arc::from), + count: v["count"].as_u64().unwrap_or(1) as u32, + damage, + extra, + }) + } + /// `ItemStackTemplate.create`. + pub fn create(&self) -> ItemStack { + ItemStack { + item: self + .item + .clone() + .unwrap_or_else(|| Arc::from("minecraft:air")), + count: self.count, + damage: self.damage, + extra: self.extra.clone(), + } + } + /// `TransmuteRecipe.createWithOriginalComponents`: the input's component + /// patch on the result item, then the template's own components over it. + fn over(&self, input: &ItemStack, extra_count: u32) -> ItemStack { + let mut out = ItemStack { + item: self.item.clone().unwrap_or_else(|| input.item.clone()), + count: self.count + extra_count, + damage: input.damage, + extra: input.extra.clone(), + }; + if self.damage > 0 { + out.damage = self.damage; + } + if let Some(over) = &self.extra { + overlay(out.data_mut(), over); + } + out.tidy(); + out + } +} +/// `DataComponentPatch` application: every component the overlay sets wins. +fn overlay(dst: &mut StackData, src: &StackData) { + let none = StackData::default(); + macro_rules! field { + ($($f:ident),*) => {$( + if src.$f != none.$f { + dst.$f = src.$f.clone(); + } + )*}; + } + field!( + enchantments, + stored_enchantments, + repair_cost, + custom_name, + potion, + trim, + container, + charged, + fireworks, + map_id, + writable_pages, + written, + banner_patterns, + base_color, + ominous_banner, + ominous_amplifier, + dyed_color, + firework_explosion, + pot_decorations, + bundle_contents, + stew_effects, + map_post_processing + ); +} +/// A JSON recipe value as the NBT a component codec reads. +fn json_tag(v: &Value) -> Tag { + match v { + Value::Null => Tag::End, + Value::Bool(b) => Tag::Byte(i8::from(*b)), + Value::Number(n) => match n.as_i64() { + Some(i) => i32::try_from(i).map_or(Tag::Long(i), Tag::Int), + None => Tag::Double(n.as_f64().unwrap_or(0.0).to_bits()), + }, + Value::String(s) => Tag::String(s.as_str().into()), + Value::Array(a) => Tag::List(a.iter().map(json_tag).collect()), + Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), json_tag(v)))), + } +} #[derive(Clone, Debug)] pub enum Recipe { Shaped { width: usize, height: usize, cells: Vec>, - result: ItemStack, + result: Template, }, Shapeless { ingredients: Vec, - result: ItemStack, + result: Template, }, - /// `BannerDuplicateRecipe` and `ShieldDecorationRecipe`. + /// The recipes with code of their own. Special(Special), } -/// The banner-copying custom recipes. +/// The custom and transmuting crafting recipes. #[derive(Clone, Debug)] pub enum Special { /// A patterned banner and a blank one of the same colour copy the patterns. @@ -67,70 +184,481 @@ pub enum Special { target: Ingredient, result: String, }, + /// `TransmuteRecipe`: one input, 1..8 materials; shulker box and bundle + /// dyeing, map cloning. + Transmute { + input: Ingredient, + material: Ingredient, + min: usize, + max: usize, + add_count: bool, + result: Template, + }, + /// `DyeRecipe`: dyed armour. + Dye { + target: Ingredient, + dye: Ingredient, + result: Template, + }, + /// `ImbueRecipe`: tipped arrows. + Imbue { + source: Ingredient, + material: Ingredient, + result: Template, + }, + /// `BookCloningRecipe`. + BookCloning { + source: Ingredient, + material: Ingredient, + min: i32, + max: i32, + result: Template, + }, + /// `FireworkRocketRecipe`. + FireworkRocket { + shell: Ingredient, + fuel: Ingredient, + star: Ingredient, + result: Template, + }, + /// `FireworkStarRecipe`. + FireworkStar { + dye: Ingredient, + fuel: Ingredient, + trail: Ingredient, + twinkle: Ingredient, + shapes: Vec<(FireworkShape, Ingredient)>, + result: Template, + }, + /// `FireworkStarFadeRecipe`. + FireworkStarFade { + dye: Ingredient, + target: Ingredient, + result: Template, + }, + /// `MapExtendingRecipe`: a map ringed by paper, when its scale is under 4. + MapExtending { + map: Ingredient, + material: Ingredient, + result: Template, + }, + /// `DecoratedPotRecipe`: four sherds or bricks. + DecoratedPot { + back: Ingredient, + left: Ingredient, + right: Ingredient, + front: Ingredient, + result: Template, + }, + /// `RepairItemRecipe`: two damaged items of one kind. + RepairItem, +} +/// `CraftingInput`: the occupied bounding box of the grid. +pub struct Input<'a> { + pub width: usize, + pub height: usize, + /// Position of the box in the grid. + pub left: usize, + pub top: usize, + cells: Vec>, +} +impl<'a> Input<'a> { + /// `CraftingInput.ofPositioned`; None for an empty grid. + pub fn of(grid: &'a [Option], size: usize) -> Option { + let occupied: Vec<(usize, usize)> = (0..size * size) + .filter(|&i| grid.get(i).is_some_and(|c| c.is_some())) + .map(|i| (i % size, i / size)) + .collect(); + let (x0, x1) = ( + occupied.iter().map(|p| p.0).min()?, + occupied.iter().map(|p| p.0).max()?, + ); + let (y0, y1) = ( + occupied.iter().map(|p| p.1).min()?, + occupied.iter().map(|p| p.1).max()?, + ); + let (width, height) = (x1 - x0 + 1, y1 - y0 + 1); + let cells = (0..width * height) + .map(|i| grid[(y0 + i / width) * size + x0 + i % width].as_ref()) + .collect(); + Some(Self { + width, + height, + left: x0, + top: y0, + cells, + }) + } + pub fn get(&self, x: usize, y: usize) -> Option<&'a ItemStack> { + self.cells.get(y * self.width + x).copied().flatten() + } + /// The non-empty stacks in slot order. + pub fn stacks(&self) -> Vec<&'a ItemStack> { + self.cells.iter().flatten().copied().collect() + } + pub fn count(&self) -> usize { + self.cells.iter().flatten().count() + } +} +/// What recipes need to know about an item. +#[derive(Clone, Debug, Default)] +struct Facts { + /// Index into the dye colours when the item has the `dye` component. + dye: Option, + max_damage: u32, + max_stack: u32, + remainder: Option>, +} +/// The tables recipes consult. +pub struct Context<'a> { + recipes: &'a Recipes, + /// A filled map's scale, when its data is known. + pub map_scale: &'a dyn Fn(i32) -> Option, +} +impl Context<'_> { + fn facts(&self, stack: &ItemStack) -> Option<&Facts> { + self.recipes.facts.get(&stack.item) + } + /// `itemStack.has(DataComponents.DYE)`. + fn dye(&self, stack: &ItemStack) -> Option { + self.facts(stack).and_then(|f| f.dye) + } + fn max_stack(&self, item: &str) -> u32 { + self.recipes.facts.get(item).map_or(64, |f| f.max_stack) + } } impl Special { - /// `matches` + `assemble` over the non-empty stacks of the grid. - fn assemble(&self, stacks: &[&ItemStack]) -> Option { + /// `Recipe.matches`. + fn matches(&self, ctx: &Context, input: &Input) -> bool { use crate::banner; - if stacks.len() != 2 { - return None; - } + let stacks = input.stacks(); match self { - Self::BannerDuplicate { - banner: ing, - result, - } => { - let color = banner::banner_color(&stacks[0].item)?; - let mut source = None; - let mut target = false; - for s in stacks { - if !ing.test(s) || banner::banner_color(&s.item)? != color { - return None; + Self::BannerDuplicate { banner: ing, .. } => { + if stacks.len() != 2 { + return false; + } + let mut color = None; + let (mut target, mut source) = (false, false); + for s in &stacks { + let Some(this) = banner::banner_color(&s.item).filter(|_| ing.test(s)) else { + return false; + }; + match color { + None => color = Some(this), + Some(c) if c != this => return false, + _ => {} } let layers = banner::layers(s).len(); if layers > banner::MAX_LAYERS { - return None; + return false; } - if layers > 0 { - if source.is_some() { - return None; - } - source = Some(*s); - } else { - if target { - return None; - } - target = true; + let seen = if layers > 0 { &mut source } else { &mut target }; + if *seen { + return false; } + *seen = true; } - let source = source.filter(|_| target)?; - // TransmuteRecipe.createWithOriginalComponents: the source's components. - Some(ItemStack { - item: Arc::from(result.as_str()), - count: 1, - ..(*source).clone() - }) + source && target } Self::ShieldDecoration { banner: ing, target: tgt, - result, + .. } => { - let (mut patterned, mut clear) = (None, None); - for s in stacks { + if stacks.len() != 2 { + return false; + } + let (mut patterned, mut clear) = (false, false); + for s in &stacks { if ing.test(s) && banner::banner_color(&s.item).is_some() { - if patterned.is_some() { - return None; + if patterned { + return false; } - patterned = Some(*s); + patterned = true; } else { - if !tgt.test(s) || clear.is_some() || !banner::layers(s).is_empty() { - return None; + if !tgt.test(s) || clear || !banner::layers(s).is_empty() { + return false; } - clear = Some(*s); + clear = true; } } - let (banner_stack, shield) = (patterned?, clear?); + patterned && clear + } + Self::Transmute { + input: base, + material, + min, + max, + add_count, + result, + } => { + let n = stacks.len(); + if n < min + 1 || n > max + 1 { + return false; + } + let mut found: Option<&ItemStack> = None; + let mut materials = 0; + for s in &stacks { + if base.test(s) { + if found.is_some() { + return false; + } + found = Some(s); + } else { + if !material.test(s) { + return false; + } + materials += 1; + if materials > *max { + return false; + } + } + } + let Some(found) = found else { + return false; + }; + if materials < *min || materials > *max { + return false; + } + let count = if *add_count { + materials as u32 + result.count + } else { + result.count + }; + if count != 1 { + return true; + } + let made = result.over(found, 0); + made.count <= ctx.max_stack(&made.item) && !made.same_item_same_components(found) + } + Self::Dye { target, dye, .. } => { + if stacks.len() < 2 { + return false; + } + let (mut has_target, mut has_dyes) = (false, false); + for s in &stacks { + if target.test(s) { + if has_target { + return false; + } + has_target = true; + } else { + if !dye.test(s) || ctx.dye(s).is_none() { + return false; + } + has_dyes = true; + } + } + has_dyes && has_target + } + Self::Imbue { + source, material, .. + } => { + if input.width != 3 || input.height != 3 || stacks.len() != 9 { + return false; + } + (0..3).all(|y| { + (0..3).all(|x| { + let ing = if x == 1 && y == 1 { source } else { material }; + input.get(x, y).is_some_and(|s| ing.test(s)) + }) + }) + } + Self::BookCloning { + source, + material, + min, + max, + .. + } => { + if stacks.len() < 2 { + return false; + } + let (mut has_material, mut has_source) = (false, false); + for s in &stacks { + if source.test(s) { + let Some(book) = s.data().and_then(|d| d.written.as_ref()) else { + return false; + }; + let generation = i32::from(book.generation); + if generation < *min || generation > *max || has_source { + return false; + } + has_source = true; + } else { + if !material.test(s) { + return false; + } + has_material = true; + } + } + has_source && has_material + } + Self::FireworkRocket { + shell, fuel, star, .. + } => { + if stacks.len() < 2 { + return false; + } + let mut has_shell = false; + let mut fuels = 0; + for s in &stacks { + if shell.test(s) { + if has_shell { + return false; + } + has_shell = true; + } else if fuel.test(s) { + fuels += 1; + if fuels > 3 { + return false; + } + } else if !star.test(s) { + return false; + } + } + has_shell && fuels >= 1 + } + Self::FireworkStar { + dye, + fuel, + trail, + twinkle, + shapes, + .. + } => { + if stacks.len() < 2 { + return false; + } + let (mut has_fuel, mut has_dye, mut has_shape) = (false, false, false); + let (mut has_trail, mut has_twinkle) = (false, false); + for s in &stacks { + if twinkle.test(s) { + if has_twinkle { + return false; + } + has_twinkle = true; + } else if trail.test(s) { + if has_trail { + return false; + } + has_trail = true; + } else if fuel.test(s) { + if has_fuel { + return false; + } + has_fuel = true; + } else if dye.test(s) && ctx.dye(s).is_some() { + has_dye = true; + } else { + if !shapes.iter().any(|(_, ing)| ing.test(s)) || has_shape { + return false; + } + has_shape = true; + } + } + has_fuel && has_dye + } + Self::FireworkStarFade { dye, target, .. } => { + if stacks.len() < 2 { + return false; + } + let (mut has_dye, mut has_target) = (false, false); + for s in &stacks { + if dye.test(s) && ctx.dye(s).is_some() { + has_dye = true; + } else { + if !target.test(s) || has_target { + return false; + } + has_target = true; + } + } + has_target && has_dye + } + Self::MapExtending { map, material, .. } => { + if input.width != 3 || input.height != 3 || stacks.len() != 9 { + return false; + } + let ring = (0..3).all(|y| { + (0..3).all(|x| { + let ing = if x == 1 && y == 1 { map } else { material }; + input.get(x, y).is_some_and(|s| ing.test(s)) + }) + }); + if !ring { + return false; + } + stacks + .iter() + .find_map(|s| s.data().and_then(|d| d.map_id)) + .and_then(|id| (ctx.map_scale)(id)) + .is_some_and(|scale| scale < 4) + } + Self::DecoratedPot { + back, + left, + right, + front, + .. + } => { + input.width == 3 + && input.height == 3 + && stacks.len() == 4 + && input.get(1, 0).is_some_and(|s| back.test(s)) + && input.get(0, 1).is_some_and(|s| left.test(s)) + && input.get(2, 1).is_some_and(|s| right.test(s)) + && input.get(1, 2).is_some_and(|s| front.test(s)) + } + Self::RepairItem => Self::repair_pair(ctx, &stacks).is_some(), + } + } + /// `RepairItemRecipe.getItemsToCombine`. + fn repair_pair<'a>( + ctx: &Context, + stacks: &[&'a ItemStack], + ) -> Option<(&'a ItemStack, &'a ItemStack)> { + let [first, second] = stacks else { + return None; + }; + let durable = |s: &ItemStack| ctx.facts(s).is_some_and(|f| f.max_damage > 0); + (second.item == first.item + && first.count == 1 + && second.count == 1 + && durable(first) + && durable(second)) + .then_some((*first, *second)) + } + /// `Recipe.assemble`; None is the empty stack. + fn assemble(&self, ctx: &Context, input: &Input) -> Option { + use crate::banner; + let stacks = input.stacks(); + let made = match self { + Self::BannerDuplicate { result, .. } => { + let source = stacks + .iter() + .find(|s| (1..=banner::MAX_LAYERS).contains(&banner::layers(s).len()))?; + // TransmuteRecipe.createWithOriginalComponents: the source's components. + ItemStack { + item: Arc::from(result.as_str()), + count: 1, + ..(**source).clone() + } + } + Self::ShieldDecoration { + banner: ing, + target, + result, + } => { + let (mut banner_stack, mut shield) = (None, None); + for s in &stacks { + if ing.test(s) && banner::banner_color(&s.item).is_some() { + banner_stack = Some(*s); + } else if target.test(s) { + shield = Some(*s); + } + } + let (banner_stack, shield) = (banner_stack?, shield?); let mut out = ItemStack { item: Arc::from(result.as_str()), count: 1, @@ -139,11 +667,258 @@ impl Special { let data = out.data_mut(); data.banner_patterns = banner::layers(banner_stack).to_vec(); data.base_color = banner::banner_color(&banner_stack.item).map(Arc::from); - Some(out) + out } - } + Self::Transmute { + input: base, + material, + add_count, + result, + .. + } => { + if *add_count { + let mut materials = 0; + let mut found = None; + for s in &stacks { + if base.test(s) { + found = Some(*s); + } else if material.test(s) { + materials += 1; + } + } + result.over(found?, materials) + } else { + let s = stacks.iter().find(|s| base.test(s))?; + result.over(s, 0) + } + } + Self::Dye { + target, + dye, + result, + } => { + let mut dyes = Vec::new(); + let mut target_stack: Option<&ItemStack> = None; + for s in &stacks { + if target.test(s) { + if target_stack.is_some() { + return None; + } + target_stack = Some(s); + } else { + if !dye.test(s) { + return None; + } + // getOrDefault(DYE, WHITE) + dyes.push(ctx.dye(s).unwrap_or(0)); + } + } + let target_stack = target_stack?; + if dyes.is_empty() { + return None; + } + let current = target_stack.data().and_then(|d| d.dyed_color); + let mut out = result.over(target_stack, 0); + out.data_mut().dyed_color = Some(apply_dyes(current, &dyes)); + out + } + Self::Imbue { result, .. } => { + let source = input.get(1, 1)?; + let mut out = result.create(); + out.data_mut().potion = source.data().and_then(|d| d.potion.clone()); + out + } + Self::BookCloning { + source, + material, + result, + .. + } => { + let mut copies = 0u32; + let mut book: Option<&ItemStack> = None; + for s in &stacks { + if source.test(s) && s.data().is_some_and(|d| d.written.is_some()) { + if book.is_some() { + return None; + } + book = Some(s); + } else { + if !material.test(s) { + return None; + } + copies += 1; + } + } + let book = book?; + // count - 1 can be -1 when no material was seen; matches() ensures one. + let mut out = result.over(book, copies.saturating_sub(1)); + if let Some(w) = out.data_mut().written.as_mut() { + w.generation += 1; + } + out + } + Self::FireworkRocket { + fuel, star, result, .. + } => { + let mut explosions = Vec::new(); + let mut fuels = 0u8; + for s in &stacks { + if fuel.test(s) { + fuels += 1; + } else if star.test(s) + && let Some(e) = s.data().and_then(|d| d.firework_explosion.clone()) + { + explosions.push(e); + } + } + let mut out = result.create(); + // A rocket's prototype is one flight and no explosions. + if fuels != 1 || !explosions.is_empty() { + out.data_mut().fireworks = Some((fuels, explosions)); + } + out + } + Self::FireworkStar { + dye, + trail, + twinkle, + shapes, + result, + .. + } => { + let mut shape = FireworkShape::SmallBall; + let (mut has_twinkle, mut has_trail) = (false, false); + let mut colors = Vec::new(); + for s in &stacks { + if let Some((found, _)) = shapes.iter().find(|(_, ing)| ing.test(s)) { + shape = *found; + } else if twinkle.test(s) { + has_twinkle = true; + } else if trail.test(s) { + has_trail = true; + } else if dye.test(s) { + colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]); + } + } + let mut out = result.create(); + out.data_mut().firework_explosion = Some(FireworkExplosion { + shape, + colors, + fade: Vec::new(), + trail: has_trail, + twinkle: has_twinkle, + }); + out + } + Self::FireworkStarFade { + dye, + target, + result, + } => { + let mut colors = Vec::new(); + let mut target_stack = None; + for s in &stacks { + if dye.test(s) { + colors.push(FIREWORK_COLORS[ctx.dye(s).unwrap_or(0)]); + } else if target.test(s) { + target_stack = Some(*s); + } + } + let target_stack = target_stack?; + if colors.is_empty() { + return None; + } + let mut out = result.over(target_stack, 0); + let explosion = out + .data_mut() + .firework_explosion + .get_or_insert_with(FireworkExplosion::default); + explosion.fade = colors; + out + } + Self::MapExtending { result, .. } => { + let map = stacks + .iter() + .find(|s| s.data().is_some_and(|d| d.map_id.is_some()))?; + let mut out = result.over(map, 0); + out.data_mut().map_post_processing = Some(1); + out + } + Self::DecoratedPot { result, .. } => { + let side = |x, y| { + input.get(x, y).map(|s| ItemStack { + count: 1, + ..s.clone() + }) + }; + let mut out = result.create(); + let sides = [side(1, 0), side(0, 1), side(2, 1), side(1, 2)]; + if !crate::item_data::all_bricks(&sides) { + out.data_mut().pot_decorations = Some(Box::new(sides)); + } + out + } + Self::RepairItem => { + let (first, second) = Self::repair_pair(ctx, &stacks)?; + let max = |s: &ItemStack| ctx.facts(s).map_or(0, |f| f.max_damage) as i64; + let durability = max(first).max(max(second)); + let remaining = (max(first) - i64::from(first.damage)) + + (max(second) - i64::from(second.damage)) + + durability * 5 / 100; + let mut out = ItemStack::new(&first.item, 1); + out.damage = (durability - remaining).max(0) as u32; + // Only the curses of both survive, at the higher level. + let (a, b) = ( + first.crafting_enchantments(), + second.crafting_enchantments(), + ); + let mut curses: Vec<(Arc, u32)> = Vec::new(); + for (id, level) in a.iter().chain(b.iter()) { + if !ctx.recipes.curses.contains(&**id) { + continue; + } + match curses.iter_mut().find(|(c, _)| c == id) { + Some((_, l)) => *l = (*l).max(*level), + None => curses.push((id.clone(), *level)), + } + } + out.set_crafting_enchantments(curses); + out + } + }; + let mut made = made; + made.tidy(); + // ItemStackTemplate.validate: oversized stacks become empty. + (made.count > 0 && made.count <= ctx.max_stack(&made.item)).then_some(made) } } +/// `DyedItemColor.applyDyes` over dye indexes. +fn apply_dyes(current: Option, dyes: &[usize]) -> i32 { + let (mut r, mut g, mut b, mut intensity, mut n) = (0i32, 0i32, 0i32, 0i32, 0i32); + let mut add = |rgb: u32| { + let (red, green, blue) = ( + (rgb >> 16 & 255) as i32, + (rgb >> 8 & 255) as i32, + (rgb & 255) as i32, + ); + intensity += red.max(green.max(blue)); + r += red; + g += green; + b += blue; + n += 1; + }; + if let Some(c) = current { + add(c as u32); + } + for d in dyes { + add(crate::block_entity_render::DYES[*d].1); + } + let (red, green, blue) = (r / n, g / n, b / n); + let average = intensity as f32 / n as f32; + let result = red.max(green.max(blue)) as f32; + let scale = |c: i32| (c as f32 * average / result) as i32; + scale(red) << 16 | scale(green) << 8 | scale(blue) +} #[derive(Clone, Debug)] pub struct Cooking { /// The recipe's file name (its id without namespace). @@ -161,21 +936,84 @@ pub struct Recipes { pub crafting: Vec<(String, Recipe)>, pub cooking: Vec, /// `category` and `group` of each crafting recipe, by file name. - pub meta: std::collections::HashMap, + pub meta: HashMap, + facts: HashMap, Facts>, + /// The `#minecraft:curse` enchantments. + curses: HashSet, } -fn result(v: &Value) -> Option { - Some(ItemStack { - item: Arc::from(v["id"].as_str()?), - count: v["count"].as_u64().unwrap_or(1) as u32, - damage: 0, - extra: None, +/// `MinMaxBounds.Ints` as (min, max) with the given defaults. +fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { + match v { + Some(Value::Number(n)) => { + let n = n.as_i64().unwrap_or(default.0); + (n, n) + } + Some(o @ Value::Object(_)) => ( + o["min"].as_i64().unwrap_or(open.0), + o["max"].as_i64().unwrap_or(open.1), + ), + _ => default, + } +} +/// `Util.isSymmetrical` is not needed: both orientations are tried. +/// `ShapedRecipePattern.shrink`: the pattern without empty border rows and columns. +fn shrink(pattern: &[Vec]) -> Vec> { + let rows: Vec<&Vec> = pattern + .iter() + .skip_while(|r| r.iter().all(|c| *c == ' ')) + .collect(); + let mut rows: Vec> = rows.into_iter().cloned().collect(); + while rows.last().is_some_and(|r| r.iter().all(|c| *c == ' ')) { + rows.pop(); + } + let left = rows + .iter() + .filter_map(|r| r.iter().position(|c| *c != ' ')) + .min(); + let right = rows + .iter() + .filter_map(|r| r.iter().rposition(|c| *c != ' ')) + .max(); + match (left, right) { + (Some(l), Some(r)) => rows.iter().map(|row| row[l..=r].to_vec()).collect(), + _ => Vec::new(), + } +} +/// A perfect matching of the ingredients to distinct stacks (`StackedContents.canCraft`). +fn matches_all(ingredients: &[Ingredient], stacks: &[&ItemStack]) -> bool { + fn augment( + i: usize, + ingredients: &[Ingredient], + stacks: &[&ItemStack], + owner: &mut [Option], + seen: &mut [bool], + ) -> bool { + for s in 0..stacks.len() { + if seen[s] || !ingredients[i].test(stacks[s]) { + continue; + } + seen[s] = true; + if owner[s].is_none_or(|o| augment(o, ingredients, stacks, owner, seen)) { + owner[s] = Some(i); + return true; + } + } + false + } + if ingredients.len() != stacks.len() { + return false; + } + let mut owner = vec![None; stacks.len()]; + (0..ingredients.len()).all(|i| { + let mut seen = vec![false; stacks.len()]; + augment(i, ingredients, stacks, &mut owner, &mut seen) }) } impl Recipes { pub fn load(root: &Path, items: &Items) -> Result { let mut crafting = Vec::new(); let mut cooking = Vec::new(); - let mut meta = std::collections::HashMap::new(); + let mut meta = HashMap::new(); let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? .flatten() .map(|e| e.path()) @@ -191,7 +1029,10 @@ impl Recipes { let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); - match v["type"].as_str().unwrap_or("") { + let ing = |k: &str| Ingredient::parse(&v[k], items); + let result = || Template::parse(&v["result"]); + let special = |recipe: Option| recipe.map(Recipe::Special); + let parsed: Option = match v["type"].as_str().unwrap_or("") { "minecraft:crafting_shaped" => { let pattern: Vec> = v["pattern"] .as_array() @@ -199,14 +1040,14 @@ impl Recipes { .flatten() .filter_map(|r| r.as_str().map(|s| s.chars().collect())) .collect(); + let pattern = shrink(&pattern); let height = pattern.len(); - let width = pattern.iter().map(Vec::len).max().unwrap_or(0); + let width = pattern.first().map_or(0, Vec::len); let mut cells = Vec::with_capacity(width * height); - let mut ok = true; + let mut ok = height > 0; for row in &pattern { - for x in 0..width { - let c = row.get(x).copied().unwrap_or(' '); - if c == ' ' { + for c in row { + if *c == ' ' { cells.push(None); } else { match Ingredient::parse(&v["key"][c.to_string()], items) { @@ -216,16 +1057,14 @@ impl Recipes { } } } - if let (true, Some(result)) = (ok, result(&v["result"])) { - crafting.push(( - name, - Recipe::Shaped { - width, - height, - cells, - result, - }, - )); + match (ok, result()) { + (true, Some(result)) => Some(Recipe::Shaped { + width, + height, + cells, + result, + }), + _ => None, } } "minecraft:crafting_shapeless" => { @@ -235,73 +1074,168 @@ impl Recipes { .flatten() .map(|i| Ingredient::parse(i, items)) .collect(); - if let (Some(ingredients), Some(result)) = (ingredients, result(&v["result"])) { - crafting.push(( - name, - Recipe::Shapeless { - ingredients, - result, - }, - )); + match (ingredients, result()) { + (Some(ingredients), Some(result)) => Some(Recipe::Shapeless { + ingredients, + result, + }), + _ => None, } } - "minecraft:crafting_special_bannerduplicate" => { - if let (Some(banner), Some(id)) = ( - Ingredient::parse(&v["banner"], items), - v["result"]["id"].as_str(), - ) { - crafting.push(( - name, - Recipe::Special(Special::BannerDuplicate { - banner, - result: id.to_owned(), - }), + "minecraft:crafting_special_bannerduplicate" => special( + ing("banner") + .zip(v["result"]["id"].as_str()) + .map(|(banner, id)| Special::BannerDuplicate { + banner, + result: id.to_owned(), + }), + ), + "minecraft:crafting_special_shielddecoration" => special( + ing("banner") + .zip(ing("target")) + .zip(v["result"]["id"].as_str()) + .map(|((banner, target), id)| Special::ShieldDecoration { + banner, + target, + result: id.to_owned(), + }), + ), + "minecraft:crafting_transmute" => special((|| { + let (min, max) = bounds(v.get("material_count"), (1, 1), (1, 8)); + Some(Special::Transmute { + input: ing("input")?, + material: ing("material")?, + min: min.clamp(1, 8) as usize, + max: max.clamp(1, 8) as usize, + add_count: v["add_material_count_to_result"].as_bool().unwrap_or(false), + result: result()?, + }) + })()), + "minecraft:crafting_dye" => special((|| { + Some(Special::Dye { + target: ing("target")?, + dye: ing("dye")?, + result: result()?, + }) + })()), + "minecraft:crafting_imbue" => special((|| { + Some(Special::Imbue { + source: ing("source")?, + material: ing("material")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_bookcloning" => special((|| { + let (min, max) = bounds(v.get("allowed_generations"), (0, 1), (0, 2)); + Some(Special::BookCloning { + source: ing("source")?, + material: ing("material")?, + min: min as i32, + max: max as i32, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_rocket" => special((|| { + Some(Special::FireworkRocket { + shell: ing("shell")?, + fuel: ing("fuel")?, + star: ing("star")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_star" => special((|| { + let mut shapes = Vec::new(); + for (shape, value) in v["shapes"].as_object()? { + shapes.push(( + FireworkShape::from_name(shape), + Ingredient::parse(value, items)?, )); } - } - "minecraft:crafting_special_shielddecoration" => { - if let (Some(banner), Some(target), Some(id)) = ( - Ingredient::parse(&v["banner"], items), - Ingredient::parse(&v["target"], items), - v["result"]["id"].as_str(), - ) { - crafting.push(( - name, - Recipe::Special(Special::ShieldDecoration { - banner, - target, - result: id.to_owned(), - }), - )); - } - } + Some(Special::FireworkStar { + dye: ing("dye")?, + fuel: ing("fuel")?, + trail: ing("trail")?, + twinkle: ing("twinkle")?, + shapes, + result: result()?, + }) + })()), + "minecraft:crafting_special_firework_star_fade" => special((|| { + Some(Special::FireworkStarFade { + dye: ing("dye")?, + target: ing("target")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_mapextending" => special((|| { + Some(Special::MapExtending { + map: ing("map")?, + material: ing("material")?, + result: result()?, + }) + })()), + "minecraft:crafting_decorated_pot" => special((|| { + Some(Special::DecoratedPot { + back: ing("back")?, + left: ing("left")?, + right: ing("right")?, + front: ing("front")?, + result: result()?, + }) + })()), + "minecraft:crafting_special_repairitem" => special(Some(Special::RepairItem)), kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" | "minecraft:campfire_cooking") => { - if let (Some(ingredient), Some(result)) = ( - Ingredient::parse(&v["ingredient"], items), - result(&v["result"]), - ) { + if let (Some(ingredient), Some(result)) = (ing("ingredient"), result()) { cooking.push(Cooking { - id: name, + id: name.clone(), category: text("category"), group: text("group"), kind: kind.to_owned(), ingredient, - result, + result: result.create(), experience: v["experience"].as_f64().unwrap_or(0.0) as f32, time: v["cookingtime"].as_u64().unwrap_or(200) as u32, }); } + None } - _ => {} + _ => None, + }; + if let Some(recipe) = parsed { + crafting.push((name, recipe)); } } + let facts = items + .items + .iter() + .map(|(id, info)| { + ( + id.clone(), + Facts { + dye: info.dye.as_deref().and_then(|d| { + crate::block_entity_render::DYES + .iter() + .position(|(name, _)| *name == d) + }), + max_damage: info.max_damage, + max_stack: info.max_stack, + remainder: info.crafting_remainder.as_deref().map(Arc::from), + }, + ) + }) + .collect(); + let curses = crate::items::load_tags(root, "enchantment")? + .remove("minecraft:curse") + .unwrap_or_default(); Ok(Self { crafting, cooking, meta, + facts, + curses, }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -310,31 +1244,28 @@ impl Recipes { } /// `craft` with the matched recipe's id (the file name without namespace). pub fn find(&self, grid: &[Option], size: usize) -> Option<(&str, ItemStack)> { - // Trim to the occupied bounding box. - let occupied: Vec<(usize, usize)> = (0..size * size) - .filter(|&i| grid[i].is_some()) - .map(|i| (i % size, i / size)) - .collect(); - if occupied.is_empty() { - return None; - } - let (x0, x1) = ( - occupied.iter().map(|p| p.0).min()?, - occupied.iter().map(|p| p.0).max()?, - ); - let (y0, y1) = ( - occupied.iter().map(|p| p.1).min()?, - occupied.iter().map(|p| p.1).max()?, - ); - let (w, h) = (x1 - x0 + 1, y1 - y0 + 1); - let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); + self.find_with(grid, size, &|_| None) + } + /// `RecipeManager.getRecipeFor(CRAFTING, ...)` with a lookup for the scale + /// of a filled map (map extending reads the map's saved data). + pub fn find_with( + &self, + grid: &[Option], + size: usize, + map_scale: &dyn Fn(i32) -> Option, + ) -> Option<(&str, ItemStack)> { + let input = Input::of(grid, size)?; + let ctx = Context { + recipes: self, + map_scale, + }; for (name, recipe) in &self.crafting { - match recipe { + let result = match recipe { Recipe::Special(special) => { - let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); - if let Some(result) = special.assemble(&stacks) { - return Some((name, result)); + if !special.matches(&ctx, &input) { + continue; } + special.assemble(&ctx, &input) } Recipe::Shaped { width, @@ -342,14 +1273,17 @@ impl Recipes { cells, result, } => { - if *width != w || *height != h { + if *width != input.width + || *height != input.height + || cells.iter().flatten().count() != input.count() + { continue; } let matches = |mirror: bool| { - (0..h).all(|y| { - (0..w).all(|x| { - let rx = if mirror { w - 1 - x } else { x }; - match (&cells[y * w + rx], cell(x, y)) { + (0..*height).all(|y| { + (0..*width).all(|x| { + let rx = if mirror { width - 1 - x } else { x }; + match (&cells[y * width + rx], input.get(x, y)) { (None, None) => true, (Some(i), Some(s)) => i.test(s), _ => false, @@ -357,60 +1291,76 @@ impl Recipes { }) }) }; - if matches(false) || matches(true) { - return Some((name, result.clone())); + if !(matches(false) || matches(true)) { + continue; } + Some(result.create()) } Recipe::Shapeless { ingredients, result, } => { - let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); - if stacks.len() != ingredients.len() { + if !matches_all(ingredients, &input.stacks()) { continue; } - // Greedy bipartite matching is sufficient for vanilla's ingredient sets. - let mut used = vec![false; stacks.len()]; - let ok = ingredients.iter().all(|ingredient| { - if let Some(i) = - (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) - { - used[i] = true; - true - } else { - false - } - }); - if ok { - return Some((name, result.clone())); - } + Some(result.create()) } - } + }; + return result.map(|r| (name.as_str(), r)); } None } - /// `Recipe.getRemainingItems` per grid cell: an item's crafting remainder - /// (buckets, bottles), and the patterned banner a duplicate keeps. + /// `Recipe.getRemainingItems` placed on the `size`x`size` grid: an item's + /// crafting remainder (buckets, bottles), the patterned banner a duplicate + /// keeps and the written book a clone keeps. pub fn remainders( &self, - items: &Items, + recipe: &str, grid: &[Option], - result: &ItemStack, + size: usize, ) -> Vec> { - grid.iter() - .map(|cell| { - let s = cell.as_ref()?; - if let Some(rem) = items.get(&s.item).and_then(|i| i.remainder.as_deref()) { - return Some(ItemStack::new(rem, 1)); + let mut out = vec![None; size * size]; + let Some(input) = Input::of(grid, size) else { + return out; + }; + let kind = self + .crafting + .iter() + .find(|(n, _)| n == recipe) + .map(|(_, r)| r); + for (i, cell) in input.cells.iter().enumerate() { + let Some(s) = cell else { continue }; + let at = (input.top + i / input.width) * size + input.left + i % input.width; + let rest = self + .facts + .get(&s.item) + .and_then(|f| f.remainder.as_deref()) + .map(|r| ItemStack::new(r, 1)); + if rest.is_some() { + out[at] = rest; + continue; + } + let copy = ItemStack { + count: 1, + ..(*s).clone() + }; + match kind { + Some(Recipe::Special(Special::BannerDuplicate { .. })) + if !crate::banner::layers(s).is_empty() => + { + out[at] = Some(copy); } - (result.item.ends_with("_banner") && !crate::banner::layers(s).is_empty()).then( - || ItemStack { - count: 1, - ..s.clone() - }, - ) - }) - .collect() + // BookCloningRecipe stops at the first copied book. + Some(Recipe::Special(Special::BookCloning { .. })) + if s.data().is_some_and(|d| d.written.is_some()) => + { + out[at] = Some(copy); + break; + } + _ => {} + } + } + out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking @@ -432,6 +1382,26 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + fn run(special: &Special, cells: &[ItemStack]) -> Option { + let recipes = Recipes { + crafting: Vec::new(), + cooking: Vec::new(), + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + }; + let ctx = Context { + recipes: &recipes, + map_scale: &|_| None, + }; + let mut grid: Vec> = cells.iter().cloned().map(Some).collect(); + grid.resize(9, None); + let input = Input::of(&grid, 3)?; + special + .matches(&ctx, &input) + .then(|| special.assemble(&ctx, &input)) + .flatten() + } #[test] fn banner_duplicate_copies_the_patterns_of_the_same_colour() { let recipe = Special::BannerDuplicate { @@ -440,14 +1410,14 @@ mod tests { }; let source = patterned("minecraft:white_banner"); let blank = ItemStack::new("minecraft:white_banner", 1); - let out = recipe.assemble(&[&source, &blank]).expect("copy"); + let out = run(&recipe, &[source.clone(), blank.clone()]).expect("copy"); assert_eq!(out.data().unwrap().banner_patterns.len(), 1); // Two blanks, or two patterned banners, do not match. - assert!(recipe.assemble(&[&blank, &blank]).is_none()); - assert!(recipe.assemble(&[&source, &source]).is_none()); + assert!(run(&recipe, &[blank.clone(), blank.clone()]).is_none()); + assert!(run(&recipe, &[source.clone(), source.clone()]).is_none()); // Another colour is not in the recipe's ingredient. let other = ItemStack::new("minecraft:red_banner", 1); - assert!(recipe.assemble(&[&source, &other]).is_none()); + assert!(run(&recipe, &[source, other]).is_none()); } #[test] fn shield_decoration_needs_a_bare_shield() { @@ -458,11 +1428,26 @@ mod tests { }; let banner = patterned("minecraft:red_banner"); let shield = ItemStack::new("minecraft:shield", 1); - let out = recipe.assemble(&[&banner, &shield]).expect("decorated"); + let out = run(&recipe, &[banner.clone(), shield]).expect("decorated"); let data = out.data().unwrap(); assert_eq!(data.base_color.as_deref(), Some("red")); assert_eq!(data.banner_patterns.len(), 1); // A shield that already has patterns cannot be decorated again. - assert!(recipe.assemble(&[&banner, &out]).is_none()); + assert!(run(&recipe, &[banner, out]).is_none()); + } + #[test] + fn shapeless_matching_assigns_each_stack_one_ingredient() { + let any = ingredient(&["a", "b"]); + let only_a = ingredient(&["a"]); + let (a, b) = (ItemStack::new("a", 1), ItemStack::new("b", 1)); + // Greedy matching would give `a` to the first ingredient and fail. + assert!(matches_all(&[any.clone(), only_a.clone()], &[&a, &b])); + assert!(!matches_all(&[only_a.clone(), only_a], &[&a, &b])); + assert!(!matches_all(&[any], &[&a, &b])); + } + #[test] + fn dyes_blend_like_dyed_item_color() { + // One red dye on an undyed item gives the dye's own colour. + assert_eq!(apply_dyes(None, &[14]), 0xB02E26); } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b66937e3b..e8d7eb2e4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3185,9 +3185,17 @@ impl Game<'_> { } } fn craft_result(&self) -> Option { + self.craft_recipe().map(|(_, result)| result) + } + /// The recipe id and result of the crafting grid. + fn craft_recipe(&self) -> Option<(String, ItemStack)> { let n = self.craft_size; let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); - self.res.recipes.craft(&grid, n) + let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale); + self.res + .recipes + .find_with(&grid, n, &scale) + .map(|(name, result)| (name.to_owned(), result)) } fn draw_inventory(&mut self, batch: &mut HudBatch) { if self.draw_station(batch) { @@ -3484,13 +3492,13 @@ impl Game<'_> { if slot == 200 { // ResultSlot: take the crafted stack and consume one of each ingredient. let mut crafted = 0; - while let Some(result) = self.craft_result() { + while let Some((recipe, result)) = self.craft_recipe() { let made = (result.item.clone(), result.count); let cells = self.craft_size * self.craft_size; let remainders = self.res.recipes.remainders( - &self.res.items, + &recipe, &self.craft_grid[..cells], - &result, + self.craft_size, ); if shift { if self.give(result).is_some() { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 0d1432526..470424c44 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -125,7 +125,7 @@ impl Game<'_> { true, horizon_world::level::flags::UPDATE_CLIENTS, ); - let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result); + let remainders = self.res.recipes.remainders(&recipe, &grid, 3); self.crafter_eject(key, facing, result, &recipe); for rest in remainders.into_iter().flatten() { self.crafter_eject(key, facing, rest, &recipe); diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 21273d804..e4329a140 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -44,6 +44,18 @@ pub struct StackData { pub ominous_banner: bool, /// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0). pub ominous_amplifier: Option, + /// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB). + pub dyed_color: Option, + /// `minecraft:firework_explosion` (a firework star). + pub firework_explosion: Option, + /// `minecraft:pot_decorations`: back, left, right, front sherds. + pub pot_decorations: Option; 4]>>, + /// `minecraft:bundle_contents`. + pub bundle_contents: Vec, + /// `minecraft:suspicious_stew_effects`: (effect id, duration). + pub stew_effects: Vec<(Arc, i32)>, + /// `minecraft:map_post_processing`: 0 lock, 1 scale. + pub map_post_processing: Option, } /// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers. pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ @@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option { } } +/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted). +fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag { + let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect()); + let mut fields = vec![("shape", Tag::String(e.shape.name().into()))]; + if !e.colors.is_empty() { + fields.push(("colors", colors(&e.colors))); + } + if !e.fade.is_empty() { + fields.push(("fade_colors", colors(&e.fade))); + } + if e.trail { + fields.push(("has_trail", Tag::Byte(1))); + } + if e.twinkle { + fields.push(("has_twinkle", Tag::Byte(1))); + } + Tag::compound(fields) +} +fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion { + let ints = |t: Option<&Tag>| match t { + Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(), + Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(), + _ => Vec::new(), + }; + crate::particles::FireworkExplosion { + shape: crate::particles::FireworkShape::from_name( + e.get("shape") + .and_then(string) + .as_deref() + .map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)), + ), + colors: ints(e.get("colors")), + fade: ints(e.get("fade_colors")), + trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0, + twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0, + } +} +/// An `ItemStackTemplate`: `{id, count?, components?}`. +fn template_tag(stack: &ItemStack) -> Tag { + let mut entries = vec![("id", Tag::String((&*stack.item).into()))]; + if stack.count != 1 { + entries.push(("count", Tag::Int(stack.count as i32))); + } + if let Some(components) = encode_components(stack) { + entries.push(("components", components)); + } + Tag::compound(entries) +} +/// The pot prototype's decorations: a brick on every side. +pub fn all_bricks(sides: &[Option; 4]) -> bool { + sides.iter().all(|s| { + s.as_ref() + .is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none()) + }) +} +fn template_from(tag: &Tag) -> Option { + match tag { + Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)), + _ => { + let id = tag.get("id").and_then(string)?; + let (damage, extra) = decode_components(tag.get("components")); + Some(ItemStack { + item: Arc::from(id.as_str()), + count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32, + damage, + extra, + }) + } + } +} +/// Sorted-key, type-annotated text of a tag (the differential harnesses +/// print the same form from the vanilla side). +pub fn canon_tag(tag: &Tag) -> String { + fn list(out: &mut String, prefix: &str, items: impl Iterator) { + out.push_str(prefix); + out.push_str(&items.collect::>().join(",")); + out.push(']'); + } + fn go(tag: &Tag, out: &mut String) { + use std::fmt::Write as _; + match tag { + Tag::End => {} + Tag::Byte(v) => write!(out, "{v}b").unwrap(), + Tag::Short(v) => write!(out, "{v}s").unwrap(), + Tag::Int(v) => write!(out, "{v}").unwrap(), + Tag::Long(v) => write!(out, "{v}L").unwrap(), + Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(), + Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(), + Tag::String(s) => write!( + out, + "\"{}\"", + s.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ) + .unwrap(), + Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())), + Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)), + Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)), + Tag::List(items) => { + out.push('['); + for (i, t) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + go(t, out); + } + out.push(']'); + } + Tag::Compound(map) => { + let mut keys: Vec<(String, &Tag)> = + map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect(); + keys.sort_by(|a, b| a.0.cmp(&b.0)); + out.push('{'); + for (i, (k, v)) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&k); + out.push(':'); + go(v, out); + } + out.push('}'); + } + } + } + let mut out = String::new(); + go(tag, &mut out); + out +} +/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none. +pub fn canon_stack(stack: Option<&ItemStack>) -> String { + stack.map_or_else( + || "-".to_owned(), + |s| canon_tag(&crate::save::item_to_nbt(s)), + ) +} +/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-". +pub fn parse_stack(snbt: &str) -> Result, String> { + if snbt == "-" { + return Ok(None); + } + let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?; + Ok(crate::save::item_from_nbt(&tag)) +} /// The `components` compound for a stack, or None when every component is default. pub fn encode_components(stack: &ItemStack) -> Option { components_tag(stack.damage, stack.data()) @@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { .collect(); entries.push(( "minecraft:written_book_content", - Tag::compound([ - ("title", raw(Tag::String(w.title.as_str().into()))), - ("author", Tag::String(w.author.as_str().into())), - ("generation", Tag::Int(i32::from(w.generation))), - ("pages", Tag::List(pages)), - ("resolved", Tag::Byte(1)), - ]), + Tag::compound({ + let mut fields = vec![ + ("title", raw(Tag::String(w.title.as_str().into()))), + ("author", Tag::String(w.author.as_str().into())), + ("pages", Tag::List(pages)), + ]; + if w.generation != 0 { + fields.push(("generation", Tag::Int(i32::from(w.generation)))); + } + fields + }), )); } if let Some((flight, explosions)) = &d.fireworks { - let list = explosions - .iter() - .map(|e| { - Tag::compound([ - ("shape", Tag::String(e.shape.name().into())), - ( - "colors", - Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()), - ), - ( - "fade_colors", - Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()), - ), - ("has_trail", Tag::Byte(i8::from(e.trail))), - ("has_twinkle", Tag::Byte(i8::from(e.twinkle))), - ]) - }) - .collect(); + let mut fields = Vec::new(); + if *flight != 0 { + fields.push(("flight_duration", Tag::Byte(*flight as i8))); + } + if !explosions.is_empty() { + fields.push(( + "explosions", + Tag::List(explosions.iter().map(explosion_tag).collect()), + )); + } + entries.push(("minecraft:fireworks", Tag::compound(fields))); + } + if let Some(e) = &d.firework_explosion { + entries.push(("minecraft:firework_explosion", explosion_tag(e))); + } + if let Some(color) = d.dyed_color { + entries.push(("minecraft:dyed_color", Tag::Int(color))); + } + if let Some(sides) = &d.pot_decorations { + let mut sherds = Vec::new(); + for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) { + if let Some(stack) = side { + sherds.push((*name, template_tag(stack))); + } + } + entries.push(("minecraft:pot_decorations", Tag::compound(sherds))); + } + if !d.bundle_contents.is_empty() { entries.push(( - "minecraft:fireworks", - Tag::compound([ - ("flight_duration", Tag::Byte(*flight as i8)), - ("explosions", Tag::List(list)), - ]), + "minecraft:bundle_contents", + Tag::List(d.bundle_contents.iter().map(template_tag).collect()), + )); + } + if !d.stew_effects.is_empty() { + entries.push(( + "minecraft:suspicious_stew_effects", + Tag::List( + d.stew_effects + .iter() + .map(|(id, duration)| { + Tag::compound([ + ("id", Tag::String((&**id).into())), + ("duration", Tag::Int(*duration)), + ]) + }) + .collect(), + ), + )); + } + if let Some(mode) = d.map_post_processing { + entries.push(( + "minecraft:map_post_processing", + Tag::String(if mode == 0 { "lock" } else { "scale" }.into()), )); } if !d.charged.is_empty() { @@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { .map(|(slot, stack)| { Tag::compound([ ("slot", Tag::Int(i32::from(*slot))), - ("item", crate::save::item_to_nbt(stack)), + ("item", template_tag(stack)), ]) }) .collect(); @@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, }), - fireworks: c.get("minecraft:fireworks").map(|f| { - let flight = f - .get("flight_duration") - .and_then(int) - .unwrap_or(0) - .clamp(0, 255) as u8; - let ints = |t: Option<&Tag>| match t { - Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(), - _ => Vec::new(), - }; - let explosions = match f.get("explosions") { - Some(Tag::List(list)) => list - .iter() - .map(|e| crate::particles::FireworkExplosion { - shape: crate::particles::FireworkShape::from_name( - e.get("shape") - .and_then(string) - .as_deref() - .unwrap_or("small_ball"), - ), - colors: ints(e.get("colors")), - fade: ints(e.get("fade_colors")), - trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0, - twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0, - }) - .collect(), - _ => Vec::new(), - }; - (flight, explosions) - }), + fireworks: c + .get("minecraft:fireworks") + .map(|f| { + let flight = f + .get("flight_duration") + .and_then(int) + .unwrap_or(0) + .clamp(0, 255) as u8; + let explosions = match f.get("explosions") { + Some(Tag::List(list)) => list.iter().map(explosion_from).collect(), + _ => Vec::new(), + }; + (flight, explosions) + }) + .filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())), + firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from), + dyed_color: c + .get("minecraft:dyed_color") + .and_then(int) + .map(|v| v as i32), + pot_decorations: c + .get("minecraft:pot_decorations") + .map(|p| { + let side = |name: &str| p.get(name).and_then(template_from); + Box::new([side("back"), side("left"), side("right"), side("front")]) + }) + .filter(|sides| !all_bricks(sides)), + bundle_contents: match c.get("minecraft:bundle_contents") { + Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(), + _ => Vec::new(), + }, + stew_effects: match c.get("minecraft:suspicious_stew_effects") { + Some(Tag::List(list)) => list + .iter() + .filter_map(|e| { + Some(( + Arc::from(e.get("id").and_then(string)?.as_str()), + e.get("duration").and_then(int).unwrap_or(160) as i32, + )) + }) + .collect(), + _ => Vec::new(), + }, + map_post_processing: match c.get("minecraft:map_post_processing") { + Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")), + Some(t) => int(t).map(|v| v.clamp(0, 1) as u8), + None => None, + }, charged: match c.get("minecraft:charged_projectiles") { Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(), _ => Vec::new(), @@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, - ominous_banner: matches!( - c.get("minecraft:banner_patterns"), - Some(Tag::List(layers)) if layers.first().is_some_and(|l| - l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus")) - ), + ominous_banner: c + .get("minecraft:item_name") + .and_then(|n| n.get("translate")) + .and_then(string) + .as_deref() + == Some("block.minecraft.ominous_banner") + && matches!( + c.get("minecraft:banner_patterns"), + Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()), ominous_amplifier: c .get("minecraft:ominous_bottle_amplifier") .and_then(int) diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index c7eb83aae..bd0d44f92 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -60,7 +60,20 @@ pub struct ItemInfo { pub equip_sound: Option, /// `jukebox_playable`: the jukebox song it plays. pub jukebox_song: Option, + /// `crafting_remainder`: what stays in the grid when the item is used in a recipe. + pub crafting_remainder: Option, + /// `dye`: the dye colour name (dyes, and anything else with the component). + pub dye: Option, } +/// `Item.Properties.craftRemainder` (not a data component, so not in the +/// default-component report): what an item leaves in the grid when crafted with. +pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [ + ("minecraft:water_bucket", "minecraft:bucket"), + ("minecraft:lava_bucket", "minecraft:bucket"), + ("minecraft:milk_bucket", "minecraft:bucket"), + ("minecraft:dragon_breath", "minecraft:glass_bottle"), + ("minecraft:honey_bottle", "minecraft:glass_bottle"), +]; /// A reduction of `blocks_attacks.damage_reductions`. #[derive(Clone, Debug)] pub struct BlockReduction { @@ -264,8 +277,6 @@ fn entity_spec(tags: &HashMap>, spec: &str) -> HashSet Result { - let raw: BTreeMap = - serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { let default = registry.default_state(&s.name); @@ -275,6 +286,16 @@ impl Items { .or_insert(BlockStateId(i as u32)); } } + Self::load_with(root, &block_for_item) + } + /// Every item's default components and the tags, without the block <-> + /// item mapping (for headless tools that never place blocks). + pub fn catalog(root: &Path) -> Result { + Self::load_with(root, &HashMap::new()) + } + fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result { + let raw: BTreeMap = + serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let entity_tags = load_tags(root, "entity_type")?; let mut items = HashMap::new(); let mut order = Vec::new(); @@ -352,6 +373,11 @@ impl Items { .as_str() .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), + dye: c["minecraft:dye"].as_str().map(str::to_owned), + crafting_remainder: CRAFT_REMAINDERS + .iter() + .find(|(item, _)| *item == name) + .map(|(_, rest)| (*rest).to_owned()), use_speed: c["minecraft:use_effects"]["speed_multiplier"] .as_f64() .unwrap_or(0.2) as f32, diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 50edd8329..4aeb50f7c 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -287,7 +287,7 @@ impl Book { category: crafting_category(&category), group: group(&grp), display, - result: result.clone(), + result: result.create(), }); } for c in &recipes.cooking { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java new file mode 100644 index 000000000..09d75a7d8 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java @@ -0,0 +1,132 @@ +package dev.horizonlab.parity; + +import java.lang.reflect.Field; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.*; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.RegistryOps; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +/** + * Shared set-up for the interaction/inventory parity oracles: the vanilla data + * pack loaded into registries (as the server does), an NBT registry ops, a + * stand-in ServerLevel that only answers registryAccess, and canonical text + * for item stacks and NBT so both sides print comparable lines. + */ +public final class ParityData { + public static HolderLookup.Provider lookup; + public static RegistryAccess access; + public static RegistryOps ops; + public static ServerLevel level; + + public static void init() throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + access = loaded.layers().compositeAccess(); + ops = RegistryOps.create(NbtOps.INSTANCE, lookup); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + Object unsafe = unsafeField.get(null); + level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class); + Field registryAccess = Level.class.getDeclaredField("registryAccess"); + registryAccess.setAccessible(true); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess); + unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access); + } + + /** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */ + public static ItemStack stack(String snbt) throws Exception { + if (snbt.equals("-")) return ItemStack.EMPTY; + Tag tag = TagParser.parseCompoundFully(snbt); + return ItemStack.CODEC.parse(ops, tag).getOrThrow(); + } + + public static String canon(ItemStack stack) { + if (stack == null || stack.isEmpty()) return "-"; + Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow(); + return canon(tag); + } + + /** Sorted-key, type-annotated text of an NBT tag. */ + public static String canon(Tag tag) { + StringBuilder out = new StringBuilder(); + canon(tag, out); + return out.toString(); + } + + private static void canon(Tag tag, StringBuilder out) { + switch (tag) { + case ByteTag t -> out.append(t.value()).append('b'); + case ShortTag t -> out.append(t.value()).append('s'); + case IntTag t -> out.append(t.value()); + case LongTag t -> out.append(t.value()).append('L'); + case FloatTag t -> out.append(t.value()).append('f'); + case DoubleTag t -> out.append(t.value()).append('d'); + case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"'); + case ByteArrayTag t -> { + out.append("[B;"); + byte[] a = t.getAsByteArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case IntArrayTag t -> { + out.append("[I;"); + int[] a = t.getAsIntArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case LongArrayTag t -> { + out.append("[L;"); + long[] a = t.getAsLongArray(); + for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]); + out.append(']'); + } + case ListTag t -> { + out.append('['); + for (int i = 0; i < t.size(); i++) { + if (i > 0) out.append(','); + canon(t.get(i), out); + } + out.append(']'); + } + case CompoundTag t -> { + out.append('{'); + boolean first = true; + for (String key : new TreeSet<>(t.keySet())) { + if (!first) out.append(','); + first = false; + out.append(key).append(':'); + canon(t.get(key), out); + } + out.append('}'); + } + default -> throw new IllegalStateException(tag.toString()); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java new file mode 100644 index 000000000..f35cd5337 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeOracle.java @@ -0,0 +1,140 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.*; + +/** + * Original oracle: vanilla's RecipeManager over the data pack's recipes. + * Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty): + * craft N cells..., cook TYPE stack, stonecut stack, smith template base addition. + * "dump" prints every crafting recipe's ingredient item lists for the generator. + */ +public final class VanillaRecipeOracle { + static RecipeManager recipes; + + public static void main(String[] args) throws Exception { + ParityData.init(); + recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + if (args[0].equals("dump")) { + dump(Path.of(args[1])); + return; + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + String result; + try { + result = run(line.split("\t", -1)); + } catch (Exception e) { + result = "error"; + } + out.println(result); + } + } + } + + static String run(String[] f) throws Exception { + switch (f[0]) { + case "craft": { + int n = Integer.parseInt(f[1]); + List items = new ArrayList<>(); + for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i])); + var positioned = CraftingInput.ofPositioned(n, n, items); + var input = positioned.input(); + if (input.isEmpty()) return "none"; + var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null); + if (found.isEmpty()) return "none"; + var recipe = found.get().value(); + var result = recipe.assemble(input); + var rest = recipe.getRemainingItems(input); + StringJoiner joiner = new StringJoiner(";"); + for (int i = 0; i < rest.size(); i++) { + if (rest.get(i).isEmpty()) continue; + int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width(); + joiner.add(at + "=" + ParityData.canon(rest.get(i))); + } + return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner; + } + case "cook": { + RecipeType type = switch (f[1]) { + case "smelting" -> RecipeType.SMELTING; + case "blasting" -> RecipeType.BLASTING; + case "smoking" -> RecipeType.SMOKING; + default -> RecipeType.CAMPFIRE_COOKING; + }; + return cook(type, ParityData.stack(f[2])); + } + case "stonecut": { + var stack = ParityData.stack(f[1]); + StringJoiner joiner = new StringJoiner(";"); + for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) { + var holder = entry.recipe().recipe().get(); + joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack)))); + } + return joiner.toString(); + } + case "smith": { + var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3])); + var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null); + if (found.isEmpty()) return "none"; + return ParityData.canon(found.get().value().assemble(input)); + } + default: + throw new IllegalArgumentException(f[0]); + } + } + + static String cook(RecipeType type, ItemStack stack) { + if (stack.isEmpty()) return "none"; + var input = new SingleRecipeInput(stack); + var found = recipes.getRecipeFor(type, input, null); + if (found.isEmpty()) return "none"; + var recipe = found.get().value(); + return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime(); + } + + static String items(Ingredient ingredient) { + if (ingredient == null) return "[]"; + StringBuilder row = new StringBuilder("["); + var items = ingredient.items().toList(); + for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"'); + return row.append(']').toString(); + } + + static void dump(Path path) throws Exception { + try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) { + for (var holder : recipes.getRecipes()) { + var recipe = holder.value(); + if (recipe instanceof SmithingRecipe smithing) { + out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName() + + "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient()) + + ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}"); + continue; + } + if (recipe.getType() != RecipeType.CRAFTING) continue; + var info = recipe.placementInfo(); + StringBuilder row = new StringBuilder(); + row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":["); + for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i)); + row.append("],\"ingredients\":["); + boolean firstIngredient = true; + for (var ingredient : info.ingredients()) { + row.append(firstIngredient ? "" : ",").append('['); + firstIngredient = false; + var items = ingredient.items().toList(); + for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"'); + row.append(']'); + } + row.append("]}"); + out.println(row); + } + } + } +} diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py new file mode 100644 index 000000000..19cbd44bd --- /dev/null +++ b/tools/interaction_lab.py @@ -0,0 +1,71 @@ +"""Shared plumbing for the interaction/inventory differential harnesses +(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity): +compile and run a vanilla Java oracle headlessly, run the matching Rust +example, and report differing lines grouped by a key.""" +import json +import os +from pathlib import Path +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +RESOURCES = lab.LOCAL / 'horizon-client' / '26.3' +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' + + +def work_dir(name): + path = lab.LOCAL / name + path.mkdir(parents=True, exist_ok=True) + return path + + +class Vanilla: + """Compiles oracles against the pinned server jar and runs them.""" + + def __init__(self, work): + self.lock, self.jars, self.libraries = base.verify_artifacts() + self.work = work + self.classes = work / 'classes' + self.classes.mkdir(exist_ok=True) + self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries])) + + def compile(self, *oracles): + sources = [PARITY / (name + '.java') for name in oracles] + subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', + '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], check=True) + + def run(self, oracle, *args, heap='2G'): + subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps, + 'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True) + + +def cargo_example(package, example, *args, profile=None): + command = ['cargo', 'run', '-q', '-j3'] + if profile: + command += ['--profile', profile] + command += ['-p', package, '--example', example, '--', *map(str, args)] + subprocess.run(command, check=True, cwd=lab.ROOT) + + +def compare(cases, native_path, rust_path, key, describe=None, limit=3): + """Print differing cases grouped by key(case, native_line); returns the count.""" + native = Path(native_path).read_text().split('\n') + rust = Path(rust_path).read_text().split('\n') + if len(native) != len(rust): + print(f'line counts differ: native {len(native)} rust {len(rust)}') + groups = {} + for case, a, b in zip(cases, native, rust): + if a != b: + groups.setdefault(key(case, a), []).append((case, a, b)) + describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case)) + total = sum(len(v) for v in groups.values()) + for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): + print(f'{name}: {len(entries)} differing') + for case, a, b in entries[:limit]: + print(f' case {describe(case)}\n native {a}\n rust {b}') + print(f'{len(cases) - total}/{len(cases)} cases match') + return total diff --git a/tools/test_recipe_parity.py b/tools/test_recipe_parity.py new file mode 100644 index 000000000..5f96e164e --- /dev/null +++ b/tools/test_recipe_parity.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager. + +The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and +answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture) +answers the same commands from horizon_client::crafting and ::stations. +Crafting cases are built from every recipe's own ingredients (placed at random +offsets, mirrored, perturbed) plus focused generators for the special recipes +(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and +random grids. Results are compared as canonical ItemStack NBT, with the +matched recipe id and the crafting remainders. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] +POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision'] +SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst'] + + +def quote(text): + return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"' + + +def stack(item, count=1, **components): + """SNBT of an ItemStack.CODEC compound; component values are SNBT text.""" + body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items())) + comp = f',components:{{{body}}}' if body else '' + return f'{{id:{quote(item)},count:{count}{comp}}}' + + +def colors(rng, n=None): + n = rng.randrange(0, 4) if n is None else n + return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']' + + +def explosion(rng): + return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}' + % (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2))) + + +class Gen: + def __init__(self, rng, items, recipes, patterns): + self.rng = rng + self.items = items + self.recipes = recipes + self.patterns = patterns + self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')] + + def layers(self, n=None): + n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n + return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']' + + def book(self, generation=None): + g = self.rng.randrange(4) if generation is None else generation + return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g) + + def stack(self, item, count=None, rich=0.5): + """A stack of the item, with the components that apply to it.""" + rng = self.rng + info = self.items.get(item, {}) + count = rng.choice([1, 1, 1, 2, 3]) if count is None else count + c = {} + if rng.random() < rich: + if info.get('minecraft:max_damage') and rng.random() < 0.7: + c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1)) + if info.get('minecraft:max_damage') and rng.random() < 0.3: + c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking'])) + if item.endswith('_banner'): + c['banner_patterns'] = self.layers() + if item == 'minecraft:shield': + if rng.random() < 0.3: + c['banner_patterns'] = self.layers(rng.randrange(1, 3)) + c['base_color'] = quote(rng.choice(DYES)) + if item == 'minecraft:written_book': + return self.book() + if item == 'minecraft:firework_star': + c['firework_explosion'] = explosion(rng) + if item == 'minecraft:firework_rocket': + c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng)) + if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'): + c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS)) + if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',): + if rng.random() < 0.6: + c['dyed_color'] = str(rng.randrange(1 << 24)) + if item.endswith('shulker_box'): + c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64) + if item.endswith('_bundle') or item == 'minecraft:bundle': + c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64) + if item == 'minecraft:filled_map': + c['map_id'] = str(rng.randrange(1, 5)) + return stack(item, count, **c) + + def plain(self, item): + return self.stack(item, rich=0.3) + + +def place(rng, cells, size): + """Cells (stack list) at random free positions of a size x size grid.""" + grid = ['-'] * (size * size) + spots = rng.sample(range(size * size), len(cells)) + for spot, cell in zip(spots, cells): + grid[spot] = cell + return grid + + +def place_box(rng, width, height, cells, size): + """A width x height pattern at a random offset of the grid.""" + x0 = rng.randrange(size - width + 1) + y0 = rng.randrange(size - height + 1) + grid = ['-'] * (size * size) + for i, cell in enumerate(cells): + grid[(y0 + i // width) * size + x0 + i % width] = cell + return grid + + +def craft_case(grid, size): + return 'craft\t%d\t%s' % (size, '\t'.join(grid)) + + +def recipe_cases(g, count_per): + rng = g.rng + for recipe in g.recipes: + if 'slots' not in recipe or not recipe['ingredients']: + continue + ingredients = recipe['ingredients'] + slots = recipe['slots'] + shaped = recipe['kind'] == 'ShapedRecipe' + if shaped: + width = recipe['width'] + height = len(slots) // width + for variant in range(count_per): + pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients] + if shaped: + cells = ['-' if s < 0 else pick[s] for s in slots] + if variant % 3 == 1: # mirrored + cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)] + size = rng.choice([s for s in (2, 3) if s >= max(width, height)]) + grid = place_box(rng, width, height, cells, size) + else: + size = 3 if len(pick) > 4 else rng.choice([2, 3]) + grid = place(rng, pick, size) + yield craft_case(grid, size) + # Perturbations: drop one, swap one for a stranger, add one, shift a count. + if variant < 2: + filled = [i for i, c in enumerate(grid) if c != '-'] + broken = list(grid) + broken[rng.choice(filled)] = '-' + yield craft_case(broken, size) + broken = list(grid) + broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])) + yield craft_case(broken, size) + free = [i for i, c in enumerate(grid) if c == '-'] + if free: + broken = list(grid) + broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])) + yield craft_case(broken, size) + + +def special_cases(g, n): + rng = g.rng + items = g.items + banners = [f'minecraft:{d}_banner' for d in DYES] + dyes = [f'minecraft:{d}_dye' for d in DYES] + armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor'] + boxes = [k for k in items if k.endswith('shulker_box')] + bundles = [k for k in items if k.endswith('bundle')] + skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')] + for _ in range(n): + size = rng.choice([2, 3]) + # banner duplicate / shield decoration + a, b = rng.choice(banners), rng.choice(banners) + yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size) + yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size) + # book cloning + books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))] + if rng.random() < 0.2: + books.append(g.book()) + yield craft_case(place(rng, books, 3), 3) + # fireworks + star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge', + 'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)])) + for _ in range(rng.randrange(1, 7))] + star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))] + yield craft_case(place(rng, star[:9], 3), 3) + fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))] + yield craft_case(place(rng, fade, 3), 3) + rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \ + [g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))] + yield craft_case(place(rng, rocket[:9], 3), 3) + # armour dyeing, with leftovers + dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))] + yield craft_case(place(rng, dye_cells[:9], 3), 3) + # repair + tool = rng.choice(g.durable) + pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)] + yield craft_case(place(rng, pair, size), size) + # shulker boxes and bundles + yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size) + multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))] + yield craft_case(place(rng, multi, 3), 3) + # decorated pots + sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd'] + pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-'] + if rng.random() < 0.2: + pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick') + yield craft_case(pot, 3) + yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3) + # tipped arrows + ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9 + ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0) + yield craft_case(ring, 3) + # map cloning + maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))] + yield craft_case(place(rng, maps, 3), 3) + # mixed junk of the interesting items + pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star', + 'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle', + 'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick'] + junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))] + yield craft_case(place(rng, junk, 3), 3) + + +def smithing_cases(g): + rng = g.rng + for recipe in g.recipes: + if recipe['kind'].startswith('Smithing'): + for _ in range(24): + pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-' + yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition')) + yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))) + # Armour with a trim already on it. + trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}'] + for recipe in g.recipes: + if recipe['kind'] == 'SmithingTrimRecipe': + for trim in trims: + base = rng.choice(recipe['base']) + yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition']))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--variants', type=int, default=6) + parser.add_argument('--specials', type=int, default=1500) + parser.add_argument('--random', type=int, default=4000) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('recipe-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaRecipeOracle') + vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl') + recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()] + # Shaped recipes: widths come from the data pack. + for recipe in recipes: + path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json') + data = json.loads(path.read_text()) + if recipe['kind'] == 'ShapedRecipe': + rows = [row.rstrip() for row in data['pattern']] + left = min(len(row) - len(row.lstrip()) for row in rows if row) + recipe['width'] = max(len(row) for row in rows) - left + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + rng = random.Random(args.seed) + g = Gen(rng, items, recipes, patterns) + cases = list(recipe_cases(g, args.variants)) + cases += list(special_cases(g, args.specials)) + pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air'] + interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick', + 'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket'] + for _ in range(args.random): + size = rng.choice([2, 3]) + cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))] + cases.append(craft_case(place(rng, cells, size), size)) + for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']: + for item in [i for i in items if i != 'minecraft:air']: + cases.append('cook\t%s\t%s' % (kind, stack(item))) + for item in [i for i in items if i != 'minecraft:air']: + cases.append('stonecut\t' + stack(item)) + cases += list(smithing_cases(g)) + (work / 'cases.txt').write_text(''.join(c + '\n' for c in cases)) + vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt') + lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt') + + def key(case, native_line): + kind = case.split('\t')[0] + return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0] + + def describe(case): + return case if len(case) < 1200 else case[:1200] + '...' + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From 7cfb90538e3675f7f3127a97be0646d1fc0de6e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:06:43 +0200 Subject: [PATCH 03/24] WIP: options, timer, mouse (to be squashed) --- .../examples/game_loop_probe.rs | 263 +++++++ .../horizon-client/examples/options_probe.rs | 32 + crates/horizon-client/src/clock.rs | 337 ++++++-- crates/horizon-client/src/game.rs | 85 ++- crates/horizon-client/src/java_text.rs | 613 +++++++++++++++ crates/horizon-client/src/key_names.rs | 265 +++++++ crates/horizon-client/src/keybinds.rs | 26 + crates/horizon-client/src/keymapping.rs | 110 +++ crates/horizon-client/src/lib.rs | 7 + crates/horizon-client/src/mouse.rs | 283 +++++++ crates/horizon-client/src/options_file.rs | 717 ++++++++++++++++++ crates/horizon-client/src/options_fixes.rs | 319 ++++++++ crates/horizon-client/src/settings.rs | 435 +++++------ crates/horizon-client/src/window.rs | 226 ++++++ .../parity/VanillaGameLoopOracle.java | 377 +++++++++ .../parity/VanillaOptionsOracle.java | 63 ++ .../parity/VanillaOptionsTableExporter.java | 119 +++ tools/oracle_harness.py | 118 +++ tools/test_options_parity.py | 185 +++++ 19 files changed, 4268 insertions(+), 312 deletions(-) create mode 100644 crates/horizon-client/examples/game_loop_probe.rs create mode 100644 crates/horizon-client/examples/options_probe.rs create mode 100644 crates/horizon-client/src/java_text.rs create mode 100644 crates/horizon-client/src/key_names.rs create mode 100644 crates/horizon-client/src/keymapping.rs create mode 100644 crates/horizon-client/src/mouse.rs create mode 100644 crates/horizon-client/src/options_file.rs create mode 100644 crates/horizon-client/src/options_fixes.rs create mode 100644 crates/horizon-client/src/window.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsTableExporter.java create mode 100644 tools/oracle_harness.py create mode 100644 tools/test_options_parity.py diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/game_loop_probe.rs new file mode 100644 index 000000000..f73b63a93 --- /dev/null +++ b/crates/horizon-client/examples/game_loop_probe.rs @@ -0,0 +1,263 @@ +#![forbid(unsafe_code)] +//! Runs the JSON-lines scenarios of tools/test_game_loop_parity.py through the +//! Rust timer, tick-rate manager, window, mouse and key-mapping code. +use horizon_client::{ + Result, + clock::{ServerTickRateManager, Timer}, + keymapping::KeyState, + mouse::{LookOptions, MouseLook, Rotation}, + window::{self, FrameContext, InactivityFpsLimit}, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn fl(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn db(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn fb(v: f32) -> String { + format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }) +} +fn dbs(v: f64) -> String { + format!( + "{:016x}", + if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + } + ) +} +fn b(v: &Value) -> bool { + v.as_bool().unwrap() +} + +fn timer(c: &Value, out: &mut impl Write) -> Result<()> { + let mut timer = Timer::new(fl(&c["tps"]), c["start"].as_i64().unwrap()); + writeln!(out, "timer")?; + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + let mut result = String::new(); + match name { + "adv" => { + let mspt = if op[2].is_null() { 0.0 } else { fl(&op[2]) }; + let ticks = timer.advance_game_time(op[1].as_i64().unwrap(), |d| { + if mspt == 0.0 { d } else { java_max(d, mspt) } + }); + result = format!(" {ticks}"); + } + "real" => timer.advance_real_time(op[1].as_i64().unwrap()), + "pause" => timer.update_pause_state(b(&op[1])), + "frozen" => timer.update_frozen_state(b(&op[1])), + _ => panic!("{name}"), + } + writeln!( + out, + "{name}{result} {} {} {} {}", + fb(timer.game_time_delta_ticks()), + fb(timer.game_time_delta_partial_tick(false)), + fb(timer.game_time_delta_partial_tick(true)), + fb(timer.realtime_delta_ticks()) + )?; + } + Ok(()) +} + +/// Math.max(float, float). +fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() & b.to_bits()) + } else if a >= b { + a + } else { + b + } +} + +fn rate(c: &Value, out: &mut impl Write) -> Result<()> { + let mut m = ServerTickRateManager::default(); + writeln!(out, "rate")?; + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + let mut result = String::new(); + let mut report = None; + match name { + "rate" => m.set_tick_rate(fl(&op[1])), + "freeze" => m.base.set_frozen(b(&op[1])), + "step" => result = format!(" {}", m.step_game_if_paused(op[1].as_i64().unwrap() as i32)), + "stopstep" => result = format!(" {}", m.stop_stepping()), + "sprint" => result = format!(" {}", m.request_game_to_sprint(op[1].as_i64().unwrap() as i32)), + "check" => { + let (run, r) = m.check_should_sprint_this_tick(op[1].as_i64().unwrap()); + result = format!(" {run}"); + report = r; + } + "end" => m.end_tick_work(op[1].as_i64().unwrap()), + "stopsprint" => { + report = m.stop_sprinting(); + result = format!(" {}", report.is_some()); + } + "tick" => m.base.tick(), + _ => panic!("{name}"), + } + let tail = report.map_or(String::new(), |r| { + format!(" report {} {}", r.ticks_per_second, r.milliseconds_per_tick) + }); + writeln!( + out, + "{name}{result} | {} {} {} {} {} {} {} {}{tail}", + fb(m.base.tickrate()), + m.base.nanoseconds_per_tick(), + fb(m.base.milliseconds_per_tick()), + m.base.runs_normally(), + m.base.is_stepping_forward(), + m.base.frozen_ticks_to_run(), + m.base.is_frozen(), + m.is_sprinting() + )?; + } + Ok(()) +} + +fn scale(c: &Value, out: &mut impl Write) -> Result<()> { + let i = |k: &str| c[k].as_i64().unwrap() as i32; + let fbsize = [i("w"), i("h")]; + let scale = window::calculate_scale(fbsize, i("max"), b(&c["uni"])); + let [gw, gh] = window::gui_scaled_size(fbsize, scale); + writeln!( + out, + "scale {scale} {gw} {gh} {} {}", + dbs(window::scaled_pos(db(&c["x"]), gw, i("sw"))), + dbs(window::scaled_pos(db(&c["y"]), gh, i("sh"))) + )?; + Ok(()) +} + +fn limit(c: &Value, out: &mut impl Write) -> Result<()> { + let ctx = FrameContext { + inactivity: if b(&c["afk"]) { InactivityFpsLimit::Afk } else { InactivityFpsLimit::Minimized }, + iconified: b(&c["iconified"]), + focused: b(&c["focused"]), + exclusive_fullscreen: false, + now_ms: c["ago"].as_i64().unwrap(), + latest_input_ms: 0, + has_level: b(&c["level"]), + has_screen: b(&c["screen"]), + has_overlay: b(&c["overlay"]), + }; + let reason = window::throttle_reason(ctx); + let name = match reason { + window::ThrottleReason::None => "NONE", + window::ThrottleReason::WindowIconified => "WINDOW_ICONIFIED", + window::ThrottleReason::LongAfk => "LONG_AFK", + window::ThrottleReason::ShortAfk => "SHORT_AFK", + window::ThrottleReason::OutOfLevelMenu => "OUT_OF_LEVEL_MENU", + }; + writeln!( + out, + "limit {name} {} {}", + window::framerate_limit(c["opt"].as_i64().unwrap() as i32, ctx), + window::heavily_throttled(reason) + )?; + Ok(()) +} + +fn mouse(c: &Value, out: &mut impl Write) -> Result<()> { + let look = LookOptions { + sensitivity: db(&c["sens"]), + smooth_camera: b(&c["smooth"]), + scoping: b(&c["scoping"]), + invert_x: b(&c["ix"]), + invert_y: b(&c["iy"]), + }; + let (active, grabbed) = (b(&c["active"]), b(&c["grabbed"])); + let mut handler = MouseLook::default(); + let mut rotation = Rotation { x_rot: 0.0, y_rot: 0.0, x_rot_o: 0.0, y_rot_o: 0.0 }; + writeln!(out, "mouse")?; + for op in c["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "move" => handler.on_move(db(&op[1]), db(&op[2]), db(&op[3]), db(&op[4]), active, grabbed), + "ignore" => handler.set_ignore_first_move(), + "frame" => { + if let Some((xo, yo)) = handler.handle_accumulated_movement(db(&op[1]), active, grabbed, look) { + rotation.turn(xo, yo); + } + writeln!( + out, + "frame {} {} {} {}", + fb(rotation.x_rot), + fb(rotation.y_rot), + fb(rotation.x_rot_o), + fb(rotation.y_rot_o) + )?; + } + other => panic!("{other}"), + } + } + Ok(()) +} + +fn scroll(c: &Value, out: &mut impl Write) -> Result<()> { + let mut handler = MouseLook::default(); + let mut slot = c["slot"].as_i64().unwrap() as i32; + writeln!(out, "scroll")?; + for op in c["ops"].as_array().unwrap() { + if let Some((wheel, _)) = handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), db(&c["sens"])) { + slot = horizon_client::mouse::ScrollWheelHandler::next_selection(f64::from(wheel), slot, 9); + } + writeln!(out, "{slot}")?; + } + Ok(()) +} + +fn key(c: &Value, out: &mut impl Write) -> Result<()> { + let mut state = if b(&c["toggle"]) { + KeyState::toggle(b(&c["restore"]), b(&c["keyboard"])) + } else { + KeyState::plain() + }; + let mut option = false; + writeln!(out, "key")?; + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + let mut result = String::new(); + match name { + "option" => option = b(&op[1]), + "down" => state.set_down(b(&op[1]), option), + "release" => state.release(option), + "restore" => result = format!(" {}", state.should_restore_state_on_screen_closed(option)), + "click" => state.click(), + "consume" => result = format!(" {}", state.consume_click()), + "ingame" => result = format!(" {}", state.should_set_on_ingame_focus(option)), + _ => panic!("{name}"), + } + writeln!(out, "{name}{result} {}", state.is_down)?; + } + Ok(()) +} + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let mut out = BufWriter::new(File::create(&args[1])?); + for line in BufReader::new(File::open(&args[0])?).lines() { + let c: Value = serde_json::from_str(&line?)?; + match c["t"].as_str().unwrap() { + "timer" => timer(&c, &mut out)?, + "rate" => rate(&c, &mut out)?, + "scale" => scale(&c, &mut out)?, + "limit" => limit(&c, &mut out)?, + "mouse" => mouse(&c, &mut out)?, + "scroll" => scroll(&c, &mut out)?, + "key" => key(&c, &mut out)?, + other => panic!("{other}"), + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/options_probe.rs b/crates/horizon-client/examples/options_probe.rs new file mode 100644 index 000000000..1cdf8c8fb --- /dev/null +++ b/crates/horizon-client/examples/options_probe.rs @@ -0,0 +1,32 @@ +#![forbid(unsafe_code)] +//! Loads and saves option files like `Options.load`/`save`, for the +//! differential harness (tools/test_options_parity.py). +use horizon_client::{Result, keybinds, options_file::OptionsFile}; +use std::{fs, io::Write}; + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let mut names: Vec<_> = fs::read_dir(&args[0])? + .map(|e| e.map(|e| e.path())) + .collect::>()?; + names.sort(); + let mut out = fs::File::create(&args[1])?; + let mut first = true; + for path in names { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let file = if name == "absent.txt" { + OptionsFile::default() + } else { + OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?)) + }; + write!(out, "== {name}\n{}", file.serialize())?; + if first { + first = false; + writeln!(out, "== keys")?; + for (name, key, category) in keybinds::MAPPINGS { + writeln!(out, "{name} {key} {category} {}", keybinds::is_toggle(name))?; + } + } + } + Ok(()) +} diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 874fec656..f5cd91f8e 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -1,63 +1,304 @@ -//! Fixed-rate development simulation driver. Rendering consumes elapsed time; -//! a per-frame work cap retains its backlog instead of dropping simulation time. -use std::time::Duration; +//! `DeltaTracker.Timer` and the tick-rate managers of 26.3: how real +//! milliseconds turn into game ticks, partial ticks and real-time deltas, and +//! the `/tick` freeze, step and sprint state. -pub const TICK: Duration = Duration::from_millis(50); -#[derive(Default)] -pub struct FixedStep { - pending: Duration, +/// `DeltaTracker.Timer`: float arithmetic on integer milliseconds, exactly as +/// the client does it. +#[derive(Clone, Debug)] +pub struct Timer { + delta_ticks: f32, + delta_tick_residual: f32, + realtime_delta_ticks: f32, + paused_delta_tick_residual: f32, + last_ms: i64, + last_ui_ms: i64, + ms_per_tick: f32, + paused: bool, + frozen: bool, } -impl FixedStep { - pub fn advance(&mut self, elapsed: Duration) -> u32 { - self.pending += elapsed; - let steps = (self.pending.as_nanos() / TICK.as_nanos()).min(10) as u32; - self.pending -= TICK * steps; - steps + +impl Timer { + pub fn new(ticks_per_second: f32, current_ms: i64) -> Self { + Self { + delta_ticks: 0.0, + delta_tick_residual: 0.0, + realtime_delta_ticks: 0.0, + paused_delta_tick_residual: 0.0, + last_ms: current_ms, + last_ui_ms: current_ms, + ms_per_tick: 1000.0 / ticks_per_second, + paused: false, + frozen: false, + } } - pub fn reset(&mut self) { - self.pending = Duration::ZERO; + + /// `advanceGameTime`: the whole ticks to run now. `target_mspt` maps the + /// default milliseconds per tick to the target in force (the tick-rate + /// manager's, when the level runs normally). The caller runs at most ten. + pub fn advance_game_time(&mut self, current_ms: i64, target_mspt: impl FnOnce(f32) -> f32) -> i32 { + self.delta_ticks = (current_ms - self.last_ms) as f32 / target_mspt(self.ms_per_tick); + self.last_ms = current_ms; + self.delta_tick_residual += self.delta_ticks; + let ticks = self.delta_tick_residual as i32; + self.delta_tick_residual -= ticks as f32; + ticks } - pub fn fraction(&self) -> f64 { - (self.pending.as_secs_f64() / TICK.as_secs_f64()).min(1.0) + + /// `advanceRealTime`. + pub fn advance_real_time(&mut self, current_ms: i64) { + self.realtime_delta_ticks = (current_ms - self.last_ui_ms) as f32 / self.ms_per_tick; + self.last_ui_ms = current_ms; + } + + /// `updatePauseState`. + pub fn update_pause_state(&mut self, pause: bool) { + if pause { + if !self.paused { + self.paused_delta_tick_residual = self.delta_tick_residual; + } + self.paused = true; + } else { + if self.paused { + self.delta_tick_residual = self.paused_delta_tick_residual; + } + self.paused = false; + } + } + + /// `updateFrozenState`. + pub fn update_frozen_state(&mut self, frozen: bool) { + self.frozen = frozen; + } + + pub fn game_time_delta_ticks(&self) -> f32 { + self.delta_ticks + } + + /// `getGameTimeDeltaPartialTick`. + pub fn game_time_delta_partial_tick(&self, ignore_frozen_game: bool) -> f32 { + if !ignore_frozen_game && self.frozen { + 1.0 + } else if self.paused { + self.paused_delta_tick_residual + } else { + self.delta_tick_residual + } + } + + /// `getRealtimeDeltaTicks`. + pub fn realtime_delta_ticks(&self) -> f32 { + if self.realtime_delta_ticks > 7.0 { + 0.5 + } else { + self.realtime_delta_ticks + } + } +} + +const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000; +const NANOSECONDS_PER_MILLISECOND: i64 = 1_000_000; + +/// `TickRateManager`. +#[derive(Clone, Debug)] +pub struct TickRateManager { + tickrate: f32, + nanoseconds_per_tick: i64, + frozen_ticks_to_run: i32, + run_game_elements: bool, + is_frozen: bool, +} + +impl Default for TickRateManager { + fn default() -> Self { + Self { + tickrate: 20.0, + nanoseconds_per_tick: NANOSECONDS_PER_SECOND / 20, + frozen_ticks_to_run: 0, + run_game_elements: true, + is_frozen: false, + } + } +} + +impl TickRateManager { + /// `setTickRate` (`Math.max(rate, 1.0F)`, NaN propagates). + pub fn set_tick_rate(&mut self, rate: f32) { + self.tickrate = if rate.is_nan() || rate > 1.0 { rate } else { 1.0 }; + self.nanoseconds_per_tick = (NANOSECONDS_PER_SECOND as f64 / f64::from(self.tickrate)) as i64; + } + pub fn tickrate(&self) -> f32 { + self.tickrate + } + pub fn milliseconds_per_tick(&self) -> f32 { + self.nanoseconds_per_tick as f32 / NANOSECONDS_PER_MILLISECOND as f32 + } + pub fn nanoseconds_per_tick(&self) -> i64 { + self.nanoseconds_per_tick + } + pub fn runs_normally(&self) -> bool { + self.run_game_elements + } + pub fn is_stepping_forward(&self) -> bool { + self.frozen_ticks_to_run > 0 + } + pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) { + self.frozen_ticks_to_run = ticks; + } + pub fn frozen_ticks_to_run(&self) -> i32 { + self.frozen_ticks_to_run + } + pub fn set_frozen(&mut self, frozen: bool) { + self.is_frozen = frozen; + } + pub fn is_frozen(&self) -> bool { + self.is_frozen + } + /// `tick`: decides whether game elements run this tick. + pub fn tick(&mut self) { + self.run_game_elements = !self.is_frozen || self.frozen_ticks_to_run > 0; + if self.frozen_ticks_to_run > 0 { + self.frozen_ticks_to_run -= 1; + } + } + /// `isEntityFrozen` for an entity that is not (and does not carry) a player. + pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool { + !self.runs_normally() && !is_player_or_carries_player + } +} + +/// What `/tick sprint` reports when it ends. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SprintReport { + pub ticks_per_second: i32, + pub milliseconds_per_tick: String, +} + +/// `ServerTickRateManager`: the freeze, step and sprint state kept by the +/// server (the broadcasts to clients are the caller's concern). +#[derive(Clone, Debug, Default)] +pub struct ServerTickRateManager { + pub base: TickRateManager, + remaining_sprint_ticks: i64, + sprint_tick_start_time: i64, + sprint_time_spend: i64, + scheduled_current_sprint_ticks: i64, + previous_is_frozen: bool, +} + +impl ServerTickRateManager { + pub fn is_sprinting(&self) -> bool { + self.scheduled_current_sprint_ticks > 0 + } + /// `stepGameIfPaused`. + pub fn step_game_if_paused(&mut self, ticks: i32) -> bool { + if !self.base.is_frozen() { + return false; + } + self.base.set_frozen_ticks_to_run(ticks); + true + } + /// `stopStepping`. + pub fn stop_stepping(&mut self) -> bool { + if self.base.frozen_ticks_to_run() > 0 { + self.base.set_frozen_ticks_to_run(0); + true + } else { + false + } + } + /// `stopSprinting`. + pub fn stop_sprinting(&mut self) -> Option { + if self.remaining_sprint_ticks > 0 { + Some(self.finish_tick_sprint()) + } else { + None + } + } + /// `requestGameToSprint`: true when an earlier sprint was interrupted. + pub fn request_game_to_sprint(&mut self, time: i32) -> bool { + let interrupted = self.remaining_sprint_ticks > 0; + self.sprint_time_spend = 0; + self.scheduled_current_sprint_ticks = i64::from(time); + self.remaining_sprint_ticks = i64::from(time); + self.previous_is_frozen = self.base.is_frozen(); + self.base.set_frozen(false); + interrupted + } + fn finish_tick_sprint(&mut self) -> SprintReport { + let completed_ticks = self.scheduled_current_sprint_ticks - self.remaining_sprint_ticks; + let milliseconds_to_complete = + (self.sprint_time_spend.max(1)) as f64 / NANOSECONDS_PER_MILLISECOND as f64; + let ticks_per_second = (1000.0 * completed_ticks as f64 / milliseconds_to_complete) as i32; + let per_tick = if completed_ticks == 0 { + f64::from(self.base.milliseconds_per_tick()) + } else { + milliseconds_to_complete / completed_ticks as f64 + }; + self.scheduled_current_sprint_ticks = 0; + self.sprint_time_spend = 0; + self.remaining_sprint_ticks = 0; + self.base.set_frozen(self.previous_is_frozen); + SprintReport { + ticks_per_second, + milliseconds_per_tick: crate::java_text::format_fixed2(per_tick), + } + } + /// `checkShouldSprintThisTick`: whether to run this tick without waiting, + /// plus the report when the sprint just finished. + pub fn check_should_sprint_this_tick(&mut self, now_ns: i64) -> (bool, Option) { + if !self.base.run_game_elements { + (false, None) + } else if self.remaining_sprint_ticks > 0 { + self.sprint_tick_start_time = now_ns; + self.remaining_sprint_ticks -= 1; + (true, None) + } else { + (false, Some(self.finish_tick_sprint())) + } + } + /// `endTickWork`. + pub fn end_tick_work(&mut self, now_ns: i64) { + self.sprint_time_spend += now_ns - self.sprint_tick_start_time; + } + /// `setTickRate`. + pub fn set_tick_rate(&mut self, rate: f32) { + self.base.set_tick_rate(rate); } } #[cfg(test)] mod tests { use super::*; + #[test] - fn render_schedules_preserve_ticks_and_stall_backlog() { - for schedule in [&[7, 13, 18, 12][..], &[50][..], &[1, 999, 2700, 300][..]] { - let mut clock = FixedStep::default(); - let mut elapsed = Duration::ZERO; - let mut ticks = 0; - for _ in 0..100 { - for &ms in schedule { - let frame = Duration::from_millis(ms); - elapsed += frame; - let count = clock.advance(frame); - assert!(count <= 10); - ticks += count; - } - } - loop { - let count = clock.advance(Duration::ZERO); - ticks += count; - if count == 0 { - break; - } - } - assert_eq!(u128::from(ticks), elapsed.as_nanos() / TICK.as_nanos()); - } + fn timer_carries_fractions_and_caps_nothing_itself() { + let mut t = Timer::new(20.0, 0); + assert_eq!(t.advance_game_time(49, |d| d), 0); + assert_eq!(t.advance_game_time(50, |d| d), 1); + assert_eq!(t.advance_game_time(1050, |d| d), 20); } #[test] - fn pause_discards_only_explicitly_reset_time() { - let mut clock = FixedStep::default(); - assert_eq!(clock.advance(Duration::from_millis(49)), 0); - assert_eq!(clock.advance(Duration::from_millis(1)), 1); - assert_eq!(clock.advance(Duration::from_millis(24)), 0); - clock.reset(); - assert_eq!(clock.advance(Duration::from_millis(26)), 0); - assert_eq!(clock.advance(Duration::from_millis(24)), 1); + fn pause_restores_the_residual() { + let mut t = Timer::new(20.0, 0); + t.advance_game_time(25, |d| d); + t.update_pause_state(true); + t.advance_game_time(1000, |d| d); + assert_eq!(t.game_time_delta_partial_tick(false), 0.5); + t.update_pause_state(false); + assert_eq!(t.game_time_delta_partial_tick(false), 0.5); + } + #[test] + fn frozen_step_runs_exactly_the_requested_ticks() { + let mut m = ServerTickRateManager::default(); + m.base.set_frozen(true); + m.base.tick(); + assert!(!m.base.runs_normally()); + assert!(m.step_game_if_paused(2)); + for _ in 0..2 { + m.base.tick(); + assert!(m.base.runs_normally()); + } + m.base.tick(); + assert!(!m.base.runs_normally()); } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b8f4a8529..ab53005c5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -72,7 +72,7 @@ use horizon_client::{ biome::Biomes, blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, - clock::FixedStep, + clock::{ServerTickRateManager, Timer}, collisions, containers::{BlockEntity, Providers}, crafting::Recipes, @@ -472,7 +472,11 @@ struct Game<'a> { options: Options, player: Option, spawn: Option, - clock: FixedStep, + clock: Timer, + /// `/tick` freeze, step and sprint state (TickRateManager). + tick_rate: ServerTickRateManager, + /// Minecraft.pause: a single-player screen that pauses the game is open. + pause: bool, previous_position: Vec3, eye: f32, previous_eye: f32, @@ -2227,7 +2231,8 @@ impl Game<'_> { self.apply_equipment(); self.eye = 1.62; self.previous_eye = 1.62; - self.clock.reset(); + let now = self.started.elapsed().as_millis() as i64; + self.clock = Timer::new(20.0, now); Ok(()) } fn tick(&mut self) -> Result<()> { @@ -2235,15 +2240,21 @@ impl Game<'_> { return self.tick_remote(); } self.ticks += 1; - self.world.game_time += 1; - if self.ui.rules.bool("advance_weather") { - self.world.weather.tick(&mut self.world.random); + // TickRateManager: a frozen level only ticks players (and what they ride). + let frozen = !self.tick_rate.base.runs_normally(); + if !frozen { + self.world.game_time += 1; + if self.ui.rules.bool("advance_weather") { + self.world.weather.tick(&mut self.world.random); + } + self.tick_weather_effects(); } - self.tick_weather_effects(); if self.ticks.is_multiple_of(6000) { self.save_game()?; } - self.advance_clock(); + if !frozen { + self.advance_clock(); + } if self.use_delay > 0 { self.use_delay -= 1; } @@ -2448,31 +2459,37 @@ impl Game<'_> { self.tick_burning(); self.tick_using(); self.titles.tick(); - self.tick_paintings(); - self.tick_item_frames(); - self.tick_armor_stands(); - self.tick_boats(); - self.tick_carts(); - self.tick_thunder(); - self.tick_lecterns(); - self.tick_maps(); - self.tick_bolts(); - self.tick_fishing(); - self.tick_tridents(); - self.tick_rockets(); + if !frozen { + self.tick_paintings(); + self.tick_item_frames(); + self.tick_armor_stands(); + self.tick_boats(); + self.tick_carts(); + self.tick_thunder(); + self.tick_lecterns(); + self.tick_maps(); + self.tick_bolts(); + self.tick_fishing(); + self.tick_tridents(); + self.tick_rockets(); + } self.tick_mining()?; - self.tick_items(); - self.spawn_loaded_entities(); - self.tick_mobs()?; + if !frozen { + self.tick_items(); + self.spawn_loaded_entities(); + self.tick_mobs()?; + } self.tick_experience(); self.tick_hand(); self.tick_sleep(); self.tick_portal()?; self.tick_end()?; self.postprocess_chunks()?; - self.tick_blocks()?; - self.tick_falling()?; - self.tick_tnt()?; + if !frozen { + self.tick_blocks()?; + self.tick_falling()?; + self.tick_tnt()?; + } if let Some(p) = &self.player { // Player.aiStep bob and Entity.walkDist (0.6 per block). let (dx, dz) = ( @@ -2490,8 +2507,10 @@ impl Game<'_> { }; self.bob.1 += (target - self.bob.1) * 0.4; } - self.tick_block_entities()?; - self.tick_brewing_stands()?; + if !frozen { + self.tick_block_entities()?; + self.tick_brewing_stands()?; + } if let Some(r) = &self.renderer { let eye = self.player.as_ref().map(|p| { [ @@ -2502,7 +2521,9 @@ impl Game<'_> { }); self.res.block_entity_render.tick(r.block_entities(), eye); } - self.tick_particles(); + if !frozen { + self.tick_particles(); + } if self.right && self.use_delay == 0 && self.screen == Screen::Playing { self.use_item()?; self.use_delay = 4; @@ -6614,7 +6635,7 @@ impl Game<'_> { else { return Ok(false); }; - let alpha = self.clock.fraction(); + let alpha = f64::from(self.clock.game_time_delta_partial_tick(false)); let (camera, underwater, view_yaw, view_pitch) = match &self.player { Some(p) => { let (a, b) = (self.previous_position, p.position); @@ -7564,7 +7585,9 @@ pub fn run() -> Result<()> { options, player: None, spawn: None, - clock: FixedStep::default(), + clock: Timer::new(20.0, 0), + tick_rate: ServerTickRateManager::default(), + pause: false, previous_position: Vec3::ZERO, eye: 1.62, previous_eye: 1.62, diff --git a/crates/horizon-client/src/java_text.rs b/crates/horizon-client/src/java_text.rs new file mode 100644 index 000000000..25eecf67e --- /dev/null +++ b/crates/horizon-client/src/java_text.rs @@ -0,0 +1,613 @@ +//! Java text conventions the vanilla option files depend on: shortest-digit +//! `Double.toString`/`Float.toString`, Gson's HTML-safe string escaping and a +//! reader for Gson's lenient JSON (`JsonParser.parseString`). + +/// Digits and decimal exponent of the shortest round-trip form. +fn shortest(text: &str) -> (String, i32) { + // `{:e}` yields "d.ddde-5" or "de5". + let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0")); + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + (digits, exponent.parse().unwrap_or(0)) +} + +fn render(negative: bool, digits: &str, exponent: i32) -> String { + let mut out = String::new(); + if negative { + out.push('-'); + } + let digits = if digits.is_empty() { "0" } else { digits }; + if (-3..7).contains(&exponent) { + if exponent >= 0 { + let int_len = exponent as usize + 1; + if digits.len() <= int_len { + out.push_str(digits); + out.extend(std::iter::repeat_n('0', int_len - digits.len())); + out.push_str(".0"); + } else { + out.push_str(&digits[..int_len]); + out.push('.'); + out.push_str(&digits[int_len..]); + } + } else { + out.push_str("0."); + out.extend(std::iter::repeat_n('0', (-exponent - 1) as usize)); + out.push_str(digits); + } + } else { + out.push_str(&digits[..1]); + out.push('.'); + if digits.len() > 1 { + out.push_str(&digits[1..]); + } else { + out.push('0'); + } + out.push('E'); + out.push_str(&exponent.to_string()); + } + out +} + +/// `Double.toString`. +pub fn double_to_string(value: f64) -> String { + if value.is_nan() { + return "NaN".into(); + } + if value.is_infinite() { + return if value < 0.0 { "-Infinity" } else { "Infinity" }.into(); + } + if value == 0.0 { + return if value.is_sign_negative() { + "-0.0" + } else { + "0.0" + } + .into(); + } + let (digits, exponent) = shortest(&format!("{:e}", value.abs())); + render(value < 0.0, &digits, exponent) +} + +/// `Float.toString`. +pub fn float_to_string(value: f32) -> String { + if value.is_nan() { + return "NaN".into(); + } + if value.is_infinite() { + return if value < 0.0 { "-Infinity" } else { "Infinity" }.into(); + } + if value == 0.0 { + return if value.is_sign_negative() { + "-0.0" + } else { + "0.0" + } + .into(); + } + let (digits, exponent) = shortest(&format!("{:e}", value.abs())); + render(value < 0.0, &digits, exponent) +} + +/// Gson's default (HTML-safe) JSON string literal. +pub fn gson_string(value: &str) -> String { + let mut out = String::from("\""); + for c in value.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + '<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' => { + out.push_str(&format!("\\u{:04x}", c as u32)); + } + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// A parsed JSON element as Gson models it. +#[derive(Clone, Debug, PartialEq)] +pub enum Json { + Null, + Bool(bool), + /// The number's source text (`LazilyParsedNumber`). + Number(String), + String(String), + Array(Vec), + Object, +} + +impl Json { + /// `Number.intValue()` of a `LazilyParsedNumber`: `Integer.parseInt`, else + /// `BigDecimal.intValue()` (truncate, keep the low 32 bits). + pub fn int_value(text: &str) -> i32 { + let (negative, body) = match text.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, text), + }; + let (mantissa, exponent) = match body.split_once(['e', 'E']) { + Some((m, e)) => ( + m, + e.strip_prefix('+').unwrap_or(e).parse::().unwrap_or(0), + ), + None => (body, 0), + }; + let (int_part, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let digits: Vec = int_part + .chars() + .chain(fraction.chars()) + .filter_map(|c| c.to_digit(10)) + .collect(); + // value = digits * 10^scale; truncating drops digits below the point. + let scale = exponent - fraction.len() as i64; + let keep = if scale >= 0 { + digits.len() + } else { + digits + .len() + .saturating_sub(scale.unsigned_abs().min(usize::MAX as u64) as usize) + }; + let mut v: u32 = 0; + for d in &digits[..keep] { + v = v.wrapping_mul(10).wrapping_add(*d); + } + if scale > 0 { + // v * 10^scale modulo 2^32 by repeated squaring. + let (mut base, mut power, mut e) = (10u32, 1u32, scale as u64); + while e > 0 { + if e & 1 == 1 { + power = power.wrapping_mul(base); + } + base = base.wrapping_mul(base); + e >>= 1; + } + v = v.wrapping_mul(power); + } + let v = v as i32; + if negative { v.wrapping_neg() } else { v } + } + /// `Number.doubleValue()`. + pub fn double_value(text: &str) -> f64 { + text.parse::().unwrap_or(0.0) + } +} + +/// A syntax error aborts the whole options load, as in vanilla. +#[derive(Debug)] +pub struct SyntaxError; + +struct Reader { + chars: Vec, + pos: usize, +} + +fn is_literal(c: char) -> bool { + !matches!( + c, + '/' | '\\' + | ';' + | '#' + | '=' + | '{' + | '}' + | '[' + | ']' + | ':' + | ',' + | ' ' + | '\t' + | '\u{c}' + | '\r' + | '\n' + ) +} + +impl Reader { + fn peek_char(&self) -> Option { + self.chars.get(self.pos).copied() + } + /// `nextNonWhitespace` with lenient comments; `None` at the end. + fn skip(&mut self) -> Result, SyntaxError> { + loop { + match self.peek_char() { + None => return Ok(None), + Some(' ' | '\t' | '\r' | '\n') => self.pos += 1, + Some('#') => self.line_comment(), + Some('/') => match self.chars.get(self.pos + 1) { + Some('/') => self.line_comment(), + Some('*') => { + self.pos += 2; + loop { + match (self.peek_char(), self.chars.get(self.pos + 1)) { + (Some('*'), Some('/')) => { + self.pos += 2; + break; + } + (Some(_), _) => self.pos += 1, + (None, _) => return Err(SyntaxError), + } + } + } + _ => return Ok(Some('/')), + }, + Some(c) => return Ok(Some(c)), + } + } + } + fn line_comment(&mut self) { + while let Some(c) = self.peek_char() { + self.pos += 1; + if c == '\n' || c == '\r' { + break; + } + } + } + fn quoted(&mut self, quote: char) -> Result { + self.pos += 1; + let mut out = String::new(); + loop { + let c = self.peek_char().ok_or(SyntaxError)?; + self.pos += 1; + if c == quote { + return Ok(out); + } + if c != '\\' { + out.push(c); + continue; + } + let e = self.peek_char().ok_or(SyntaxError)?; + self.pos += 1; + match e { + 'u' => { + let mut v = 0u32; + for _ in 0..4 { + let d = self.peek_char().ok_or(SyntaxError)?; + self.pos += 1; + v = v * 16 + d.to_digit(16).ok_or(SyntaxError)?; + } + // Lone surrogates cannot be represented; keep the replacement. + out.push(char::from_u32(v).unwrap_or('\u{fffd}')); + } + 't' => out.push('\t'), + 'b' => out.push('\u{8}'), + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 'f' => out.push('\u{c}'), + '\n' | '\'' | '"' | '\\' | '/' => out.push(e), + _ => return Err(SyntaxError), + } + } + } + fn literal(&mut self) -> String { + let start = self.pos; + while self.peek_char().is_some_and(is_literal) { + self.pos += 1; + } + self.chars[start..self.pos].iter().collect() + } + /// JSON number grammar with Gson's leading-zero rule. + fn is_number(text: &str) -> bool { + let b: Vec = text.chars().collect(); + let mut i = 0; + if b.first() == Some(&'-') { + i += 1; + } + match b.get(i) { + Some('0') => { + i += 1; + } + Some(c) if c.is_ascii_digit() => { + while b.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + _ => return false, + } + if b.get(i) == Some(&'.') { + i += 1; + if !b.get(i).is_some_and(char::is_ascii_digit) { + return false; + } + while b.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + if matches!(b.get(i), Some('e' | 'E')) { + i += 1; + if matches!(b.get(i), Some('+' | '-')) { + i += 1; + } + if !b.get(i).is_some_and(char::is_ascii_digit) { + return false; + } + while b.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + i == b.len() + } + fn keyword(text: &str, word: &str) -> bool { + text.len() == word.len() && text.eq_ignore_ascii_case(word) + } + fn value(&mut self) -> Result { + let c = self.skip()?.ok_or(SyntaxError)?; + match c { + '"' | '\'' => Ok(Json::String(self.quoted(c)?)), + '[' => { + self.pos += 1; + let mut items = Vec::new(); + loop { + match self.skip()?.ok_or(SyntaxError)? { + ']' => { + self.pos += 1; + // A trailing separator leaves an implicit null. + return Ok(Json::Array(items)); + } + ',' | ';' => { + self.pos += 1; + items.push(Json::Null); + continue; + } + _ => {} + } + items.push(self.value()?); + match self.skip()?.ok_or(SyntaxError)? { + ']' => { + self.pos += 1; + return Ok(Json::Array(items)); + } + ',' | ';' => self.pos += 1, + _ => return Err(SyntaxError), + } + } + } + '{' => { + self.pos += 1; + loop { + match self.skip()?.ok_or(SyntaxError)? { + '}' => { + self.pos += 1; + return Ok(Json::Object); + } + '"' | '\'' => { + let q = self.skip()?.ok_or(SyntaxError)?; + self.quoted(q)?; + } + c if is_literal(c) => { + self.literal(); + } + _ => return Err(SyntaxError), + } + match self.skip()?.ok_or(SyntaxError)? { + ':' => self.pos += 1, + '=' => { + self.pos += 1; + if self.peek_char() == Some('>') { + self.pos += 1; + } + } + _ => return Err(SyntaxError), + } + self.value()?; + match self.skip()?.ok_or(SyntaxError)? { + '}' => { + self.pos += 1; + return Ok(Json::Object); + } + ',' | ';' => self.pos += 1, + _ => return Err(SyntaxError), + } + } + } + ']' | '}' | ',' | ';' | ':' | '=' | '\\' | '/' => Err(SyntaxError), + _ => { + let text = self.literal(); + if text.is_empty() { + return Err(SyntaxError); + } + if Self::keyword(&text, "true") { + Ok(Json::Bool(true)) + } else if Self::keyword(&text, "false") { + Ok(Json::Bool(false)) + } else if Self::keyword(&text, "null") { + Ok(Json::Null) + } else if Self::is_number(&text) { + Ok(Json::Number(text)) + } else { + Ok(Json::String(text)) + } + } + } + } +} + +/// `JsonParser.parseString`: one lenient value and nothing after it. +pub fn parse_lenient(text: &str) -> Result { + let text = text.strip_prefix(")]}'\n").unwrap_or(text); + let mut reader = Reader { + chars: text.chars().collect(), + pos: 0, + }; + if reader.skip()?.is_none() { + return Ok(Json::Null); + } + let value = reader.value()?; + // The trailing check runs after Gson restored its legacy-strict mode: + // only whitespace may follow the value. + if value != Json::Null + && reader.chars[reader.pos..] + .iter() + .any(|c| !matches!(c, ' ' | '\t' | '\r' | '\n')) + { + return Err(SyntaxError); + } + Ok(value) +} + +impl Reader { + /// Next non-whitespace char in strict mode (comments are errors). + fn strict_skip(&mut self) -> Option { + while matches!(self.peek_char(), Some(' ' | '\t' | '\r' | '\n')) { + self.pos += 1; + } + self.peek_char() + } +} + +/// `Gson.getAdapter(List).read` on a strict `JsonReader` +/// (`GsonHelper.fromNullableJson`): `Ok(None)` for `null`, an error for +/// anything Gson rejects, including an empty document. +pub fn parse_strict_string_list(text: &str) -> Result>, SyntaxError> { + let mut r = Reader { + chars: text.chars().collect(), + pos: 0, + }; + match r.strict_skip().ok_or(SyntaxError)? { + 'n' => { + let word = r.literal(); + if word == "null" { + Ok(None) + } else { + Err(SyntaxError) + } + } + '[' => { + r.pos += 1; + let mut items = Vec::new(); + if r.strict_skip().ok_or(SyntaxError)? == ']' { + return Ok(Some(items)); + } + loop { + let c = r.strict_skip().ok_or(SyntaxError)?; + match c { + '"' => items.push(r.quoted('"')?), + '-' | '0'..='9' => { + let word = r.literal(); + if !Reader::is_number(&word) { + return Err(SyntaxError); + } + items.push(word); + } + 't' | 'f' | 'n' => { + let word = r.literal(); + match word.as_str() { + "true" | "false" => items.push(word), + "null" => {} + _ => return Err(SyntaxError), + } + } + _ => return Err(SyntaxError), + } + match r.strict_skip().ok_or(SyntaxError)? { + ',' => r.pos += 1, + ']' => return Ok(Some(items)), + _ => return Err(SyntaxError), + } + } + } + _ => Err(SyntaxError), + } +} + +/// `String.format(Locale.ROOT, "%.f", value)`: Java rounds the shortest +/// round-trip decimal expansion half-up (so 1.005 gives 1.01). +pub fn format_fixed(value: f64, decimals: usize) -> String { + if value.is_nan() { + return "NaN".into(); + } + if value.is_infinite() { + return if value < 0.0 { "-Infinity" } else { "Infinity" }.into(); + } + let negative = value.is_sign_negative(); + let (digits, exponent) = if value == 0.0 { + ("0".to_owned(), 0) + } else { + shortest(&format!("{:e}", value.abs())) + }; + let mut int_part: Vec = Vec::new(); + let mut frac: Vec = Vec::new(); + let d: Vec = digits.bytes().map(|b| b - b'0').collect(); + let point = exponent + 1; // digits before the decimal point + if point <= 0 { + int_part.push(0); + frac.extend(std::iter::repeat_n(0, (-point) as usize)); + frac.extend(&d); + } else { + let point = point as usize; + for i in 0..point { + int_part.push(d.get(i).copied().unwrap_or(0)); + } + if d.len() > point { + frac.extend(&d[point..]); + } + } + let round_up = frac.get(decimals).is_some_and(|&x| x >= 5); + frac.truncate(decimals); + frac.resize(decimals, 0); + if round_up { + let mut carry = true; + for x in frac.iter_mut().rev().chain(int_part.iter_mut().rev()) { + if !carry { + break; + } + if *x == 9 { + *x = 0; + } else { + *x += 1; + carry = false; + } + } + if carry { + int_part.insert(0, 1); + } + } + let mut out = String::new(); + if negative { + out.push('-'); + } + out.extend(int_part.iter().map(|&x| (b'0' + x) as char)); + if decimals > 0 { + out.push('.'); + out.extend(frac.iter().map(|&x| (b'0' + x) as char)); + } + out +} + +/// `%.2f`. +pub fn format_fixed2(value: f64) -> String { + format_fixed(value, 2) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn java_number_text() { + assert_eq!(double_to_string(1.0), "1.0"); + assert_eq!(double_to_string(0.5), "0.5"); + assert_eq!(double_to_string(0.0001), "1.0E-4"); + assert_eq!(double_to_string(0.001), "0.001"); + assert_eq!(double_to_string(1234567.0), "1234567.0"); + assert_eq!(double_to_string(12345678.0), "1.2345678E7"); + assert_eq!(double_to_string(100.0), "100.0"); + assert_eq!(float_to_string(0.15), "0.15"); + assert_eq!(float_to_string(1.0e10), "1.0E10"); + assert_eq!(double_to_string(-2.5), "-2.5"); + } + #[test] + fn lenient_json() { + assert_eq!(parse_lenient("0.5").unwrap(), Json::Number("0.5".into())); + assert_eq!(parse_lenient("fast").unwrap(), Json::String("fast".into())); + assert_eq!(parse_lenient("TRUE").unwrap(), Json::Bool(true)); + assert_eq!(parse_lenient("007").unwrap(), Json::String("007".into())); + assert!(parse_lenient("1 2").is_err()); + assert!(parse_lenient("\"abc").is_err()); + assert_eq!(parse_lenient(" ").unwrap(), Json::Null); + assert_eq!(gson_string("a=b"), "\"a\\u003db\""); + } +} diff --git a/crates/horizon-client/src/key_names.rs b/crates/horizon-client/src/key_names.rs new file mode 100644 index 000000000..c6ba9d634 --- /dev/null +++ b/crates/horizon-client/src/key_names.rs @@ -0,0 +1,265 @@ +//! InputConstants key tables of 26.3 (SDL scancodes), generated from the +//! pinned client by `VanillaOptionsTableExporter`. + +/// Keyboard keys: (SDL scancode, key name). +pub const KEYBOARD: &[(i32, &str)] = &[ + (0, "key.keyboard.unknown"), + (4, "key.keyboard.a"), + (5, "key.keyboard.b"), + (6, "key.keyboard.c"), + (7, "key.keyboard.d"), + (8, "key.keyboard.e"), + (9, "key.keyboard.f"), + (10, "key.keyboard.g"), + (11, "key.keyboard.h"), + (12, "key.keyboard.i"), + (13, "key.keyboard.j"), + (14, "key.keyboard.k"), + (15, "key.keyboard.l"), + (16, "key.keyboard.m"), + (17, "key.keyboard.n"), + (18, "key.keyboard.o"), + (19, "key.keyboard.p"), + (20, "key.keyboard.q"), + (21, "key.keyboard.r"), + (22, "key.keyboard.s"), + (23, "key.keyboard.t"), + (24, "key.keyboard.u"), + (25, "key.keyboard.v"), + (26, "key.keyboard.w"), + (27, "key.keyboard.x"), + (28, "key.keyboard.y"), + (29, "key.keyboard.z"), + (30, "key.keyboard.1"), + (31, "key.keyboard.2"), + (32, "key.keyboard.3"), + (33, "key.keyboard.4"), + (34, "key.keyboard.5"), + (35, "key.keyboard.6"), + (36, "key.keyboard.7"), + (37, "key.keyboard.8"), + (38, "key.keyboard.9"), + (39, "key.keyboard.0"), + (40, "key.keyboard.enter"), + (41, "key.keyboard.escape"), + (42, "key.keyboard.backspace"), + (43, "key.keyboard.tab"), + (44, "key.keyboard.space"), + (45, "key.keyboard.minus"), + (46, "key.keyboard.equal"), + (47, "key.keyboard.left.bracket"), + (48, "key.keyboard.right.bracket"), + (49, "key.keyboard.backslash"), + (50, "key.keyboard.world.2"), + (51, "key.keyboard.semicolon"), + (52, "key.keyboard.apostrophe"), + (53, "key.keyboard.grave.accent"), + (54, "key.keyboard.comma"), + (55, "key.keyboard.period"), + (56, "key.keyboard.slash"), + (57, "key.keyboard.caps.lock"), + (58, "key.keyboard.f1"), + (59, "key.keyboard.f2"), + (60, "key.keyboard.f3"), + (61, "key.keyboard.f4"), + (62, "key.keyboard.f5"), + (63, "key.keyboard.f6"), + (64, "key.keyboard.f7"), + (65, "key.keyboard.f8"), + (66, "key.keyboard.f9"), + (67, "key.keyboard.f10"), + (68, "key.keyboard.f11"), + (69, "key.keyboard.f12"), + (70, "key.keyboard.print.screen"), + (71, "key.keyboard.scroll.lock"), + (72, "key.keyboard.pause"), + (73, "key.keyboard.insert"), + (74, "key.keyboard.home"), + (75, "key.keyboard.page.up"), + (76, "key.keyboard.delete"), + (77, "key.keyboard.end"), + (78, "key.keyboard.page.down"), + (79, "key.keyboard.right"), + (80, "key.keyboard.left"), + (81, "key.keyboard.down"), + (82, "key.keyboard.up"), + (83, "key.keyboard.num.lock"), + (84, "key.keyboard.keypad.divide"), + (85, "key.keyboard.keypad.multiply"), + (86, "key.keyboard.keypad.subtract"), + (87, "key.keyboard.keypad.add"), + (88, "key.keyboard.keypad.enter"), + (89, "key.keyboard.keypad.1"), + (90, "key.keyboard.keypad.2"), + (91, "key.keyboard.keypad.3"), + (92, "key.keyboard.keypad.4"), + (93, "key.keyboard.keypad.5"), + (94, "key.keyboard.keypad.6"), + (95, "key.keyboard.keypad.7"), + (96, "key.keyboard.keypad.8"), + (97, "key.keyboard.keypad.9"), + (98, "key.keyboard.keypad.0"), + (99, "key.keyboard.keypad.period"), + (100, "key.keyboard.world.1"), + (101, "key.keyboard.application"), + (102, "key.keyboard.power"), + (103, "key.keyboard.keypad.equal"), + (104, "key.keyboard.f13"), + (105, "key.keyboard.f14"), + (106, "key.keyboard.f15"), + (107, "key.keyboard.f16"), + (108, "key.keyboard.f17"), + (109, "key.keyboard.f18"), + (110, "key.keyboard.f19"), + (111, "key.keyboard.f20"), + (112, "key.keyboard.f21"), + (113, "key.keyboard.f22"), + (114, "key.keyboard.f23"), + (115, "key.keyboard.f24"), + (116, "key.keyboard.execute"), + (117, "key.keyboard.help"), + (118, "key.keyboard.menu"), + (119, "key.keyboard.select"), + (120, "key.keyboard.stop"), + (121, "key.keyboard.again"), + (122, "key.keyboard.undo"), + (123, "key.keyboard.cut"), + (124, "key.keyboard.copy"), + (125, "key.keyboard.paste"), + (126, "key.keyboard.find"), + (127, "key.keyboard.mute"), + (128, "key.keyboard.volume.up"), + (129, "key.keyboard.volume.down"), + (133, "key.keyboard.keypad.comma"), + (134, "key.keyboard.keypad.equals.as400"), + (135, "key.keyboard.international1"), + (136, "key.keyboard.international2"), + (137, "key.keyboard.international3"), + (138, "key.keyboard.international4"), + (139, "key.keyboard.international5"), + (140, "key.keyboard.international6"), + (141, "key.keyboard.international7"), + (142, "key.keyboard.international8"), + (143, "key.keyboard.international9"), + (144, "key.keyboard.lang1"), + (145, "key.keyboard.lang2"), + (146, "key.keyboard.lang3"), + (147, "key.keyboard.lang4"), + (148, "key.keyboard.lang5"), + (149, "key.keyboard.lang6"), + (150, "key.keyboard.lang7"), + (151, "key.keyboard.lang8"), + (152, "key.keyboard.lang9"), + (153, "key.keyboard.alternate.erase"), + (154, "key.keyboard.sys.req"), + (155, "key.keyboard.cancel"), + (156, "key.keyboard.clear"), + (157, "key.keyboard.prior"), + (158, "key.keyboard.enter2"), + (159, "key.keyboard.separator"), + (160, "key.keyboard.out"), + (161, "key.keyboard.oper"), + (162, "key.keyboard.clear.again"), + (163, "key.keyboard.crsel"), + (164, "key.keyboard.exsel"), + (176, "key.keyboard.keypad.00"), + (177, "key.keyboard.keypad.000"), + (178, "key.keyboard.thousands.separator"), + (179, "key.keyboard.decimal.separator"), + (180, "key.keyboard.currency.unit"), + (181, "key.keyboard.currency.subunit"), + (182, "key.keyboard.keypad.left.parenthesis"), + (183, "key.keyboard.keypad.right.parenthesis"), + (184, "key.keyboard.keypad.left.brace"), + (185, "key.keyboard.keypad.right.brace"), + (186, "key.keyboard.keypad.tab"), + (187, "key.keyboard.keypad.backspace"), + (188, "key.keyboard.keypad.a"), + (189, "key.keyboard.keypad.b"), + (190, "key.keyboard.keypad.c"), + (191, "key.keyboard.keypad.d"), + (192, "key.keyboard.keypad.e"), + (193, "key.keyboard.keypad.f"), + (194, "key.keyboard.keypad.xor"), + (195, "key.keyboard.keypad.power"), + (196, "key.keyboard.keypad.percent"), + (197, "key.keyboard.keypad.less"), + (198, "key.keyboard.keypad.greater"), + (199, "key.keyboard.keypad.ampersand"), + (200, "key.keyboard.keypad.double.ampersand"), + (201, "key.keyboard.keypad.vertical.bar"), + (202, "key.keyboard.keypad.double.vertical.bar"), + (203, "key.keyboard.keypad.colon"), + (204, "key.keyboard.keypad.hash"), + (205, "key.keyboard.keypad.space"), + (206, "key.keyboard.keypad.at"), + (207, "key.keyboard.keypad.exclamation"), + (208, "key.keyboard.keypad.memory.store"), + (209, "key.keyboard.keypad.memory.recall"), + (210, "key.keyboard.keypad.memory.clear"), + (211, "key.keyboard.keypad.memory.add"), + (212, "key.keyboard.keypad.memory.subtract"), + (213, "key.keyboard.keypad.memory.multiply"), + (214, "key.keyboard.keypad.memory.divide"), + (215, "key.keyboard.keypad.plus.minus"), + (216, "key.keyboard.keypad.clear"), + (217, "key.keyboard.keypad.clear.entry"), + (218, "key.keyboard.keypad.binary"), + (219, "key.keyboard.keypad.octal"), + (220, "key.keyboard.keypad.decimal"), + (221, "key.keyboard.keypad.hexadecimal"), + (224, "key.keyboard.left.control"), + (225, "key.keyboard.left.shift"), + (226, "key.keyboard.left.alt"), + (227, "key.keyboard.left.win"), + (228, "key.keyboard.right.control"), + (229, "key.keyboard.right.shift"), + (230, "key.keyboard.right.alt"), + (231, "key.keyboard.right.win"), + (257, "key.keyboard.mode"), + (258, "key.keyboard.sleep"), + (259, "key.keyboard.wake"), + (260, "key.keyboard.channel.up"), + (261, "key.keyboard.channel.down"), + (262, "key.keyboard.media.play"), + (263, "key.keyboard.media.pause"), + (264, "key.keyboard.media.record"), + (265, "key.keyboard.media.fast.forward"), + (266, "key.keyboard.media.rewind"), + (267, "key.keyboard.media.next.track"), + (268, "key.keyboard.media.previous.track"), + (269, "key.keyboard.media.stop"), + (270, "key.keyboard.media.eject"), + (271, "key.keyboard.media.play.pause"), + (272, "key.keyboard.media.select"), + (273, "key.keyboard.ac.new"), + (274, "key.keyboard.ac.open"), + (275, "key.keyboard.ac.close"), + (276, "key.keyboard.ac.exit"), + (277, "key.keyboard.ac.save"), + (278, "key.keyboard.ac.print"), + (279, "key.keyboard.ac.properties"), + (280, "key.keyboard.ac.search"), + (281, "key.keyboard.ac.home"), + (282, "key.keyboard.ac.back"), + (283, "key.keyboard.ac.forward"), + (284, "key.keyboard.ac.stop"), + (285, "key.keyboard.ac.refresh"), + (286, "key.keyboard.ac.bookmarks"), + (287, "key.keyboard.soft.left"), + (288, "key.keyboard.soft.right"), + (289, "key.keyboard.call"), + (290, "key.keyboard.end.call"), +]; + +/// Mouse buttons: (button number, key name). +pub const MOUSE: &[(i32, &str)] = &[ + (1, "key.mouse.left"), + (2, "key.mouse.middle"), + (3, "key.mouse.right"), + (4, "key.mouse.4"), + (5, "key.mouse.5"), + (6, "key.mouse.6"), + (7, "key.mouse.7"), + (8, "key.mouse.8"), +]; diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index a62323409..155ffcc24 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -43,6 +43,7 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[ ("key.advancements", "key.keyboard.l", "misc"), ("key.quickActions", "key.keyboard.g", "misc"), ("key.debug.overlay", "key.keyboard.f3", "debug"), + ("key.debug.modifier", "key.keyboard.f3", "debug"), ("key.hotbar.1", "key.keyboard.1", "inventory"), ("key.hotbar.2", "key.keyboard.2", "inventory"), ("key.hotbar.3", "key.keyboard.3", "inventory"), @@ -52,7 +53,32 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[ ("key.hotbar.7", "key.keyboard.7", "inventory"), ("key.hotbar.8", "key.keyboard.8", "inventory"), ("key.hotbar.9", "key.keyboard.9", "inventory"), + ("key.debug.reloadChunk", "key.keyboard.a", "debug"), + ("key.debug.showHitboxes", "key.keyboard.b", "debug"), + ("key.debug.clearChat", "key.keyboard.d", "debug"), + ("key.debug.crash", "key.keyboard.c", "debug"), + ("key.debug.showChunkBorders", "key.keyboard.g", "debug"), + ("key.debug.showAdvancedTooltips", "key.keyboard.h", "debug"), + ("key.debug.copyRecreateCommand", "key.keyboard.i", "debug"), + ("key.debug.spectate", "key.keyboard.n", "debug"), + ("key.debug.switchGameMode", "key.keyboard.f4", "debug"), + ("key.debug.debugOptions", "key.keyboard.f6", "debug"), + ("key.debug.focusPause", "key.keyboard.p", "debug"), + ("key.debug.dumpDynamicTextures", "key.keyboard.s", "debug"), + ("key.debug.reloadResourcePacks", "key.keyboard.t", "debug"), + ("key.debug.profiling", "key.keyboard.l", "debug"), + ("key.debug.copyLocation", "key.keyboard.c", "debug"), + ("key.debug.dumpVersion", "key.keyboard.v", "debug"), + ("key.debug.profilingChart", "key.keyboard.1", "debug"), + ("key.debug.fpsCharts", "key.keyboard.2", "debug"), + ("key.debug.networkCharts", "key.keyboard.3", "debug"), + ("key.debug.lightmapTexture", "key.keyboard.4", "debug"), + ("key.debug.improvedTransparency", "key.keyboard.x", "debug"), ]; +/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option). +pub fn is_toggle(name: &str) -> bool { + matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack") +} /// KeyMapping.Category sort order. pub const CATEGORIES: [&str; 8] = [ "movement", diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client/src/keymapping.rs new file mode 100644 index 000000000..157e59cb8 --- /dev/null +++ b/crates/horizon-client/src/keymapping.rs @@ -0,0 +1,110 @@ +//! The down/click state of `KeyMapping` and `ToggleKeyMapping` (sneak, +//! sprint, attack and use can be toggled instead of held). + +/// One mapping's runtime state. `toggle` is `Some(restore)` for a +/// `ToggleKeyMapping` (with its `shouldRestore` flag), `None` for a plain one. +#[derive(Clone, Debug)] +pub struct KeyState { + pub is_down: bool, + click_count: i32, + released_by_screen_when_down: bool, + toggle: Option, + keyboard: bool, +} + +impl KeyState { + pub fn plain() -> Self { + Self { + is_down: false, + click_count: 0, + released_by_screen_when_down: false, + toggle: None, + keyboard: true, + } + } + /// A `ToggleKeyMapping`; `keyboard` is whether the bound key is a keyboard key. + pub fn toggle(should_restore: bool, keyboard: bool) -> Self { + Self { + toggle: Some(should_restore), + keyboard, + ..Self::plain() + } + } + /// `KeyMapping.click`: one more pending click. + pub fn click(&mut self) { + self.click_count += 1; + } + /// `consumeClick`. + pub fn consume_click(&mut self) -> bool { + if self.click_count == 0 { + false + } else { + self.click_count -= 1; + true + } + } + /// `setDown`; `needs_toggle` is the mapping's option value. + pub fn set_down(&mut self, down: bool, needs_toggle: bool) { + if self.toggle.is_some() && needs_toggle { + if down { + self.is_down = !self.is_down; + } + } else { + self.is_down = down; + } + } + /// `shouldSetOnIngameFocus` for a keyboard-bound, bound key. + pub fn should_set_on_ingame_focus(&self, needs_toggle: bool) -> bool { + self.keyboard && (self.toggle.is_none() || !needs_toggle) + } + /// `release` (a screen opened): drops pending clicks and the held state. + pub fn release(&mut self, needs_toggle: bool) { + if self.toggle.is_some() { + // ToggleKeyMapping.release does not clear pending clicks. + if needs_toggle && self.is_down || self.released_by_screen_when_down { + self.released_by_screen_when_down = true; + } + self.reset(); + } else { + self.click_count = 0; + self.set_down(false, needs_toggle); + } + } + /// `ToggleKeyMapping.reset`. + pub fn reset(&mut self) { + self.is_down = false; + } + /// `shouldRestoreStateOnScreenClosed` (clears the remembered release). + pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool { + let Some(restore) = self.toggle else { + return false; + }; + let result = restore && needs_toggle && self.keyboard && self.released_by_screen_when_down; + self.released_by_screen_when_down = false; + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn toggle_flips_on_press_and_ignores_release() { + let mut k = KeyState::toggle(true, true); + k.set_down(true, true); + assert!(k.is_down); + k.set_down(false, true); + assert!(k.is_down); + k.set_down(true, true); + assert!(!k.is_down); + } + #[test] + fn screen_release_restores_toggled_state() { + let mut k = KeyState::toggle(true, true); + k.set_down(true, true); + k.release(true); + assert!(!k.is_down); + assert!(k.should_restore_state_on_screen_closed(true)); + assert!(!k.should_restore_state_on_screen_closed(true)); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 089f6fb82..69532768b 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -37,7 +37,10 @@ pub mod hunger; pub mod input; pub mod item_data; pub mod items; +pub mod java_text; +pub mod key_names; pub mod keybinds; +pub mod keymapping; pub mod landing; pub mod lang; pub mod light; @@ -46,9 +49,12 @@ pub mod mesher; pub mod mobs; pub mod models; pub mod motion; +pub mod mouse; pub mod multiplayer; pub mod music; pub mod net; +pub mod options_file; +pub mod options_fixes; pub mod options_ui; pub mod packs; pub mod particles; @@ -70,6 +76,7 @@ pub mod text; pub mod title; pub mod ui; pub mod vanillagen; +pub mod window; pub mod world; pub mod zip; pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/mouse.rs b/crates/horizon-client/src/mouse.rs new file mode 100644 index 000000000..98efc7ed4 --- /dev/null +++ b/crates/horizon-client/src/mouse.rs @@ -0,0 +1,283 @@ +//! Mouse look and scrolling of 26.3: `MouseHandler` (accumulated movement, +//! sensitivity curve, cinematic smoothing, inversion), `SmoothDouble`, +//! `ScrollWheelHandler` and `Entity.turn`. + +/// `SmoothDouble`. +#[derive(Clone, Debug, Default)] +pub struct SmoothDouble { + target_value: f64, + remaining_value: f64, + last_amount: f64, +} + +impl SmoothDouble { + pub fn get_new_delta_value(&mut self, target_delta: f64, time: f64) -> f64 { + self.target_value += target_delta; + let mut delta = self.target_value - self.remaining_value; + let new_last_amount = self.last_amount + 0.5 * (delta - self.last_amount); + let delta_sign = java_signum(delta); + if delta_sign * delta > delta_sign * self.last_amount { + delta = new_last_amount; + } + self.last_amount = new_last_amount; + self.remaining_value += delta * time; + delta * time + } + pub fn reset(&mut self) { + *self = Self::default(); + } +} + +/// `Math.signum(double)`. +pub fn java_signum(v: f64) -> f64 { + if v == 0.0 || v.is_nan() { v } else { v.signum() } +} + +/// `ScrollWheelHandler`. +#[derive(Clone, Debug, Default)] +pub struct ScrollWheelHandler { + accumulated_x: f64, + accumulated_y: f64, +} + +impl ScrollWheelHandler { + /// `onMouseScroll`: whole wheel steps `(x, y)` once enough has accumulated. + pub fn on_mouse_scroll(&mut self, x: f64, y: f64) -> (i32, i32) { + if self.accumulated_x != 0.0 && java_signum(x) != java_signum(self.accumulated_x) { + self.accumulated_x = 0.0; + } + if self.accumulated_y != 0.0 && java_signum(y) != java_signum(self.accumulated_y) { + self.accumulated_y = 0.0; + } + self.accumulated_x += x; + self.accumulated_y += y; + // Java's double-to-int cast saturates and maps NaN to zero, like Rust's. + let wheel_x = self.accumulated_x as i32; + let wheel_y = self.accumulated_y as i32; + if wheel_x == 0 && wheel_y == 0 { + return (0, 0); + } + self.accumulated_x -= f64::from(wheel_x); + self.accumulated_y -= f64::from(wheel_y); + (wheel_x, wheel_y) + } + + /// `getNextScrollWheelSelection`. + pub fn next_selection(wheel: f64, current_selected: i32, limit: i32) -> i32 { + let step = java_signum(wheel) as i32; + let mut current = (current_selected - step).max(-1); + while current < 0 { + current += limit; + } + while current >= limit { + current -= limit; + } + current + } +} + +/// Entity rotation as `Entity.turn` keeps it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Rotation { + pub x_rot: f32, + pub y_rot: f32, + pub x_rot_o: f32, + pub y_rot_o: f32, +} + +impl Rotation { + fn set_x_rot(&mut self, x_rot: f32) { + if x_rot.is_finite() { + self.x_rot = (x_rot % 360.0).clamp(-90.0, 90.0); + } + } + fn set_y_rot(&mut self, y_rot: f32) { + if y_rot.is_finite() { + self.y_rot = y_rot; + } + } + /// `Entity.turn(xo, yo)`: mouse deltas in, 0.15 degrees per unit, pitch clamped. + pub fn turn(&mut self, xo: f64, yo: f64) { + let x_delta = (yo as f32) * 0.15; + let y_delta = (xo as f32) * 0.15; + self.set_x_rot(self.x_rot + x_delta); + self.set_y_rot(self.y_rot + y_delta); + self.set_x_rot(mth_clamp(self.x_rot, -90.0, 90.0)); + self.x_rot_o += x_delta; + self.y_rot_o += y_delta; + self.x_rot_o = mth_clamp(self.x_rot_o, -90.0, 90.0); + } +} + +/// `Mth.clamp(float, float, float)`. +pub fn mth_clamp(value: f32, min: f32, max: f32) -> f32 { + if value < min { + min + } else if value.is_nan() || max.is_nan() { + f32::NAN + } else { + value.min(max) + } +} + +/// The options `turnPlayer` reads. +#[derive(Clone, Copy, Debug)] +pub struct LookOptions { + pub sensitivity: f64, + pub smooth_camera: bool, + /// First-person camera and the player is scoping (spyglass). + pub scoping: bool, + pub invert_x: bool, + pub invert_y: bool, +} + +/// The input state of `MouseHandler` that drives the camera and the hotbar. +#[derive(Clone, Debug)] +pub struct MouseLook { + xpos: f64, + ypos: f64, + ignore_first_move: bool, + smooth_turn_x: SmoothDouble, + smooth_turn_y: SmoothDouble, + accumulated_dx: f64, + accumulated_dy: f64, + pub scroll: ScrollWheelHandler, + last_handle_movement_time: f64, +} + +impl Default for MouseLook { + fn default() -> Self { + Self { + xpos: 0.0, + ypos: 0.0, + ignore_first_move: true, + smooth_turn_x: SmoothDouble::default(), + smooth_turn_y: SmoothDouble::default(), + accumulated_dx: 0.0, + accumulated_dy: 0.0, + scroll: ScrollWheelHandler::default(), + // Double.MIN_VALUE + last_handle_movement_time: 4.9e-324, + } + } +} + +impl MouseLook { + /// `setIgnoreFirstMove`. + pub fn set_ignore_first_move(&mut self) { + self.ignore_first_move = true; + } + + /// `onMove`: relative motion counts while the pointer is grabbed, absolute + /// motion otherwise. + pub fn on_move(&mut self, xpos: f64, ypos: f64, xrel: f64, yrel: f64, window_active: bool, grabbed: bool) { + if self.ignore_first_move { + self.xpos = xpos; + self.ypos = ypos; + self.ignore_first_move = false; + } else { + if window_active { + if grabbed { + self.accumulated_dx += xrel; + self.accumulated_dy += yrel; + } else { + self.accumulated_dx += xpos - self.xpos; + self.accumulated_dy += ypos - self.ypos; + } + } + self.xpos = xpos; + self.ypos = ypos; + } + } + + /// Movement accumulated since the last frame (for screens' mouse-moved events). + pub fn accumulated(&self) -> (f64, f64) { + (self.accumulated_dx, self.accumulated_dy) + } + + /// `handleAccumulatedMovement` for a frame at `time` seconds: the + /// `(xo, yo)` passed to `Entity.turn` when the pointer is grabbed and the + /// window is active. The accumulators are cleared either way. + pub fn handle_accumulated_movement( + &mut self, + time: f64, + window_active: bool, + grabbed_with_player: bool, + look: LookOptions, + ) -> Option<(f64, f64)> { + let mousea = time - self.last_handle_movement_time; + self.last_handle_movement_time = time; + let turn = (window_active && grabbed_with_player).then(|| self.turn_player(mousea, look)); + self.accumulated_dx = 0.0; + self.accumulated_dy = 0.0; + turn + } + + fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) { + let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32); + let sensitivity_mod = ss * ss * ss; + let sens = sensitivity_mod * 8.0; + let (xo, yo) = if look.smooth_camera { + ( + self.smooth_turn_x.get_new_delta_value(self.accumulated_dx * sens, mousea * sens), + self.smooth_turn_y.get_new_delta_value(self.accumulated_dy * sens, mousea * sens), + ) + } else if look.scoping { + self.smooth_turn_x.reset(); + self.smooth_turn_y.reset(); + (self.accumulated_dx * sensitivity_mod, self.accumulated_dy * sensitivity_mod) + } else { + self.smooth_turn_x.reset(); + self.smooth_turn_y.reset(); + (self.accumulated_dx * sens, self.accumulated_dy * sens) + }; + (if look.invert_x { -xo } else { xo }, if look.invert_y { -yo } else { yo }) + } + + /// `onScroll` for the in-game case (no screen, player present): the wheel + /// value `wheel` the hotbar or spectator speed reacts to, and the raw + /// wheel steps. `None` when no whole step has accumulated. + pub fn on_scroll( + &mut self, + xoffset: f64, + yoffset: f64, + discrete: bool, + wheel_sensitivity: f64, + ) -> Option<(i32, (i32, i32))> { + let scale = |v: f64| (if discrete { java_signum(v) } else { v }) * wheel_sensitivity; + let (x, y) = self.scroll.on_mouse_scroll(scale(xoffset), scale(yoffset)); + if x == 0 && y == 0 { + return None; + } + let wheel = if y == 0 { -x } else { y }; + Some((wheel, (x, y))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() { + let mut look = MouseLook::default(); + look.on_move(0.0, 0.0, 0.0, 0.0, true, true); + look.on_move(1.0, 0.0, 1.0, 0.0, true, true); + let (xo, _) = look + .handle_accumulated_movement( + 1.0, + true, + true, + LookOptions { sensitivity: 0.5, smooth_camera: false, scoping: false, invert_x: false, invert_y: false }, + ) + .unwrap(); + let mut rot = Rotation { x_rot: 0.0, y_rot: 0.0, x_rot_o: 0.0, y_rot_o: 0.0 }; + rot.turn(xo, 0.0); + assert!((rot.y_rot - 0.15 * 1.0).abs() < 1e-6, "{}", rot.y_rot); + } + #[test] + fn scroll_accumulates_fractions() { + let mut look = MouseLook::default(); + assert_eq!(look.on_scroll(0.0, 0.4, false, 1.0), None); + assert_eq!(look.on_scroll(0.0, 0.7, false, 1.0), Some((1, (0, 1)))); + } +} diff --git a/crates/horizon-client/src/options_file.rs b/crates/horizon-client/src/options_file.rs new file mode 100644 index 000000000..50bfa80ab --- /dev/null +++ b/crates/horizon-client/src/options_file.rs @@ -0,0 +1,717 @@ +//! `options.txt` exactly as `Options.load`/`Options.save` handle it in 26.3: +//! the processing order, per-option codecs and validation (`OptionInstance`), +//! plain fields, key mappings, sound volumes and model parts. Typed access for +//! the game lives in `settings`. +use crate::{ + java_text::{self, Json}, + key_names, +}; +use std::sync::LazyLock; + +/// A stored option value. +#[derive(Clone, Debug, PartialEq)] +pub enum V { + Bool(bool), + Int(i32), + Double(f64), + Str(String), + List(Vec), +} + +/// How an `OptionInstance` decodes, validates and encodes its value. +#[derive(Clone, Copy, Debug)] +pub enum Spec { + /// `Codec.BOOL`. + Bool, + /// `IntRange(min, max)`: codec `intRange(min, max + 1)`, validated to `max`. + Int(i32, i32), + /// `ClampingLazyMaxIntRange(min, ..)` while the game is not running. + LazyInt(i32), + /// `IntRange(imin, imax).xmap(i / k, (int)(v * k))` with `doubleRange(lo, hi)`. + Scaled(i32, i32, f64, f64, f64), + /// The frame rate limit: `IntRange(1, 26).xmap(i * 10, v / 10)`, codec 10..=260. + FrameLimit, + /// Field of view degrees stored as `(fov - 70) / 40`. + Fov, + /// `IntRange(-200, 100).xmap(10^(i/100), floor(log10(v) * 100))`. + WheelSensitivity, + /// `UnitDouble`. + Unit, + /// `UnitDouble.xmap(square, sqrt)` with an explicit `doubleRange(0, 1)` codec. + UnitSquare, + /// `UnitDouble.xmap(square, sqrt)` using the value set's own codec. + UnitSquareImplicit, + /// String-represented enum. + Named(&'static [&'static str]), + /// Enum stored as its id, wrapping out-of-range ids. + Id(i32), + /// `CloudStatus` with the boolean alternative. + Clouds, + /// Any string (`LazyEnum` while the game is not running). + AnyStr, +} + +#[derive(Clone, Copy, Debug)] +enum Kind { + Option(Spec), + PlainBool, + PlainInt, + PlainStr, + List, + Tutorial, + Key, +} + +struct Def { + key: String, + kind: Kind, + default: V, +} + +const TUTORIAL_STEPS: [&str; 6] = [ + "movement", + "find_tree", + "punch_tree", + "open_inventory", + "craft_planks", + "none", +]; +const MODEL_PARTS: [&str; 7] = [ + "cape", + "jacket", + "left_sleeve", + "right_sleeve", + "left_pants_leg", + "right_pants_leg", + "hat", +]; +const GRAPHICS_BACKEND: &[&str] = &["default", "opengl", "vulkan"]; +const GRAPHICS_PRESET: &[&str] = &["fast", "fancy", "fabulous", "custom"]; +const INACTIVITY: &[&str] = &["minimized", "afk"]; +const CLOUDS: &[&str] = &["false", "fast", "true"]; +const MAIN_HAND: &[&str] = &["left", "right"]; +const PRESENCE: &[&str] = &["none", "limited", "all"]; +const MUSIC_TOAST: &[&str] = &["never", "pause", "pause_and_toast"]; +const MUSIC_FREQUENCY: &[&str] = &["DEFAULT", "FREQUENT", "CONSTANT"]; + +fn def(key: &str, kind: Kind, default: V) -> Def { + Def { + key: key.to_owned(), + kind, + default, + } +} + +/// The processing order of `Options.processOptions`. +static TABLE: LazyLock> = LazyLock::new(|| { + use Kind::{List, Option as O, PlainBool as PB, PlainInt as PI, PlainStr as PS, Tutorial}; + use Spec::{ + AnyStr, Bool, Clouds, Fov, FrameLimit, Id, Int, LazyInt, Named, Scaled, Unit, UnitSquare, + UnitSquareImplicit, WheelSensitivity, + }; + let b = |key: &str, d: bool| def(key, O(Bool), V::Bool(d)); + let i = |key: &str, lo, hi, d: i32| def(key, O(Int(lo, hi)), V::Int(d)); + let u = |key: &str, d: f64| def(key, O(Unit), V::Double(d)); + let n = + |key: &str, names: &'static [&'static str], d: i32| def(key, O(Named(names)), V::Int(d)); + let id = |key: &str, count: i32, d: i32| def(key, O(Id(count)), V::Int(d)); + let pb = |key: &str, d: bool| def(key, PB, V::Bool(d)); + let mut t = vec![ + b("ao", true), + i("biomeBlendRadius", 0, 7, 2), + def( + "chunkSectionFadeInTime", + O(Scaled(0, 40, 20.0, 0.0, 2.0)), + V::Double(0.75), + ), + b("cutoutLeaves", true), + b("enableVsync", true), + def( + "entityDistanceScaling", + O(Scaled(2, 20, 4.0, 0.5, 5.0)), + V::Double(1.0), + ), + b("entityShadows", true), + b("forceUnicodeFont", false), + b("japaneseGlyphVariants", false), + def("fov", O(Fov), V::Int(70)), + def("fovEffectScale", O(UnitSquare), V::Double(1.0)), + def("darknessEffectScale", O(UnitSquareImplicit), V::Double(1.0)), + u("glintSpeed", 0.5), + u("glintStrength", 0.75), + n("preferredGraphicsBackend", GRAPHICS_BACKEND, 0), + n("graphicsPreset", GRAPHICS_PRESET, 1), + id("prioritizeChunkUpdates", 3, 0), + b("fullscreen", false), + b("exclusiveFullscreen", false), + b("macFullscreenMenuVisibility", false), + u("gamma", 0.5), + def("guiScale", O(LazyInt(0)), V::Int(0)), + def("debugGuiScale", O(LazyInt(-1)), V::Int(0)), + i("maxAnisotropyBit", 1, 3, 2), + id("textureFiltering", 3, 0), + def("maxFps", O(FrameLimit), V::Int(120)), + b("improvedTransparency", false), + n("inactivityFpsLimit", INACTIVITY, 1), + i("mipmapLevels", 0, 4, 4), + id("narrator", 4, 0), + id("particles", 3, 0), + b("reducedDebugInfo", false), + def("renderClouds", O(Clouds), V::Int(2)), + i("cloudRange", 2, 128, 128), + i("renderDistance", 2, 32, 12), + i("simulationDistance", 5, 32, 12), + u("screenEffectScale", 1.0), + def("soundDevice", O(AnyStr), V::Str(String::new())), + b("vignette", true), + i("weatherRadius", 3, 10, 10), + b("autoJump", false), + b("rotateWithMinecart", false), + b("operatorItemsTab", false), + b("autoSuggestions", true), + b("chatColors", true), + b("chatLinks", true), + b("chatLinksPrompt", true), + b("discrete_mouse_scroll", false), + b("invertXMouse", false), + b("invertYMouse", false), + b("realmsNotifications", true), + b("showSubtitles", false), + b("directionalAudio", false), + b("bobView", true), + b("toggleCrouch", false), + b("toggleSprint", false), + b("toggleAttack", false), + b("toggleUse", false), + i("sprintWindow", 0, 10, 7), + b("darkMojangStudiosBackground", false), + b("hideLightningFlashes", false), + b("hideSplashTexts", false), + u("mouseSensitivity", 0.5), + u("damageTiltStrength", 1.0), + b("highContrast", false), + b("highContrastBlockOutline", false), + b("narratorHotkey", true), + def("resourcePacks", List, V::List(Vec::new())), + def("incompatibleResourcePacks", List, V::List(Vec::new())), + def("lastServer", PS, V::Str(String::new())), + def("lang", PS, V::Str("en_us".into())), + id("chatVisibility", 3, 0), + u("chatOpacity", 1.0), + u("chatLineSpacing", 0.0), + u("textBackgroundOpacity", 0.5), + b("backgroundForChatOnly", true), + pb("hideServerAddress", false), + pb("advancedItemTooltips", false), + pb("pauseOnLostFocus", true), + def("overrideWidth", PI, V::Int(0)), + def("overrideHeight", PI, V::Int(0)), + u("chatHeightFocused", 1.0), + def( + "chatDelay", + O(Scaled(0, 60, 10.0, 0.0, 6.0)), + V::Double(0.0), + ), + u("chatHeightUnfocused", 0.4375), + u("chatScale", 1.0), + u("chatWidth", 1.0), + def( + "notificationDisplayTime", + O(Scaled(5, 100, 10.0, 0.5, 10.0)), + V::Double(1.0), + ), + pb("useNativeTransport", true), + n("mainHand", MAIN_HAND, 1), + id("attackIndicator", 3, 1), + def("tutorialStep", Tutorial, V::Int(0)), + def("mouseWheelSensitivity", O(WheelSensitivity), V::Double(1.0)), + b("allowCursorChanges", true), + b("quitShortcuts", true), + b("ctrlClickEmulatesRightClick", false), + def("glDebugVerbosity", PI, V::Int(1)), + pb("skipMultiplayerWarning", false), + b("hideMatchedNames", true), + pb("joinedFirstServer", false), + pb("syncChunkWrites", false), + b("showAutosaveIndicator", true), + b("allowServerListing", true), + b("inGameNotification", false), + n("sharePresence", PRESENCE, 2), + b("onlyShowSecureChat", false), + b("saveChatDrafts", false), + u("panoramaScrollSpeed", 1.0), + b("telemetryOptInExtra", false), + pb("onboardAccessibility", true), + i("menuBackgroundBlurriness", 0, 10, 5), + pb("startedCleanly", true), + n("musicToast", MUSIC_TOAST, 0), + n("musicFrequency", MUSIC_FREQUENCY, 0), + ]; + for (name, key, _) in crate::keybinds::MAPPINGS { + t.push(def( + &format!("key_{name}"), + Kind::Key, + V::Str((*key).to_owned()), + )); + } + for source in crate::settings::SOUND_SOURCES { + t.push(u(&format!("soundCategory_{source}"), 1.0)); + } + for part in MODEL_PARTS { + t.push(pb(&format!("modelPart_{part}"), true)); + } + t +}); + +/// Mth.floor for doubles. +fn floor_int(v: f64) -> i32 { + let i = v as i32; + if v < f64::from(i) { i - 1 } else { i } +} + +fn number(json: &Json) -> Option<&str> { + match json { + Json::Number(n) => Some(n), + _ => None, + } +} +fn codec_int(json: &Json) -> Option { + number(json).map(Json::int_value) +} +fn codec_double(json: &Json) -> Option { + number(json).map(Json::double_value) +} +fn codec_bool(json: &Json) -> Option { + match json { + Json::Bool(b) => Some(*b), + _ => None, + } +} +fn codec_string(json: &Json) -> Option<&str> { + match json { + Json::String(s) => Some(s), + _ => None, + } +} +fn double_range(v: f64, lo: f64, hi: f64) -> Option { + // Double.compareTo: -0.0 sorts below 0.0 and NaN above everything. + (v.total_cmp(&lo).is_ge() && v.total_cmp(&hi).is_le() && !v.is_nan()).then_some(v) +} +fn log_mouse(value: i32) -> f64 { + 10f64.powf(f64::from(value) / 100.0) +} +fn unit_alt(json: &Json) -> Option { + codec_double(json) + .and_then(|v| double_range(v, 0.0, 1.0)) + .or_else(|| codec_bool(json).map(|b| if b { 1.0 } else { 0.0 })) +} + +impl Spec { + /// `codec.parse(JsonOps.INSTANCE, element)`. + fn decode(self, json: &Json) -> Option { + match self { + Spec::Bool => codec_bool(json).map(V::Bool), + Spec::Int(lo, hi) => { + let v = codec_int(json)?; + (v >= lo && i64::from(v) <= i64::from(hi) + 1).then_some(V::Int(v)) + } + Spec::LazyInt(lo) => { + let v = codec_int(json)?; + (v >= lo).then_some(V::Int(v)) + } + Spec::Scaled(.., lo, hi) => double_range(codec_double(json)?, lo, hi).map(V::Double), + Spec::FrameLimit => { + let v = codec_int(json)?; + (10..=260).contains(&v).then_some(V::Int(v)) + } + Spec::Fov => Some(V::Int((codec_double(json)? * 40.0 + 70.0) as i32)), + Spec::WheelSensitivity => { + double_range(codec_double(json)?, log_mouse(-200), log_mouse(100)).map(V::Double) + } + Spec::Unit => unit_alt(json).map(V::Double), + Spec::UnitSquare => double_range(codec_double(json)?, 0.0, 1.0).map(V::Double), + Spec::UnitSquareImplicit => unit_alt(json).map(|v| V::Double(v * v)), + Spec::Named(names) => { + let s = codec_string(json)?; + names.iter().position(|n| *n == s).map(|i| V::Int(i as i32)) + } + Spec::Id(count) => codec_int(json).map(|v| V::Int(v.rem_euclid(count))), + Spec::Clouds => { + if let Some(s) = codec_string(json) { + return CLOUDS + .iter() + .position(|n| *n == s) + .map(|i| V::Int(i as i32)); + } + codec_bool(json).map(|b| V::Int(if b { 2 } else { 0 })) + } + Spec::AnyStr => codec_string(json).map(|s| V::Str(s.to_owned())), + } + } + + /// `ValueSet.validateValue`; `None` makes `OptionInstance.set` fall back + /// to the option's initial value. + fn validate(self, v: &V) -> Option { + match (self, v) { + (Spec::Bool, V::Bool(_)) => Some(v.clone()), + (Spec::Int(lo, hi), V::Int(x)) => (*x >= lo && *x <= hi).then(|| v.clone()), + (Spec::LazyInt(lo), V::Int(x)) => Some(V::Int((*x).clamp(lo, 2_147_483_646))), + (Spec::Scaled(imin, imax, k, ..), V::Double(x)) => { + let i = (x * k) as i32; + (i >= imin && i <= imax).then(|| V::Double(f64::from(i) / k)) + } + (Spec::FrameLimit, V::Int(x)) => { + let i = x / 10; + (1..=26).contains(&i).then(|| V::Int(i * 10)) + } + (Spec::Fov, V::Int(x)) => (30..=110).contains(x).then(|| v.clone()), + (Spec::WheelSensitivity, V::Double(x)) => { + let i = floor_int(x.log10() * 100.0); + (-200..=100).contains(&i).then(|| V::Double(log_mouse(i))) + } + (Spec::Unit, V::Double(x)) => (*x >= 0.0 && *x <= 1.0).then(|| v.clone()), + (Spec::UnitSquare | Spec::UnitSquareImplicit, V::Double(x)) => { + let root = x.sqrt(); + (0.0..=1.0).contains(&root).then_some(V::Double(root * root)) + } + (Spec::Named(names), V::Int(x)) => { + (*x >= 0 && (*x as usize) < names.len()).then(|| v.clone()) + } + (Spec::Id(count), V::Int(x)) => (*x >= 0 && *x < count).then(|| v.clone()), + (Spec::Clouds, V::Int(x)) => (0..3).contains(x).then(|| v.clone()), + (Spec::AnyStr, V::Str(_)) => Some(v.clone()), + _ => None, + } + } + + /// `codec.encodeStart(JsonOps.INSTANCE, value)` rendered by Gson. + fn encode(self, v: &V) -> Option { + let double = |x: f64| java_text::double_to_string(x); + Some(match (self, v) { + (Spec::Bool, V::Bool(b)) => b.to_string(), + (Spec::Int(lo, hi), V::Int(x)) => { + if *x < lo || i64::from(*x) > i64::from(hi) + 1 { + return None; + } + x.to_string() + } + (Spec::LazyInt(lo), V::Int(x)) => { + if *x < lo { + return None; + } + x.to_string() + } + (Spec::Scaled(.., lo, hi), V::Double(x)) => { + double_range(*x, lo, hi)?; + double(*x) + } + (Spec::FrameLimit, V::Int(x)) => { + if !(10..=260).contains(x) { + return None; + } + x.to_string() + } + (Spec::Fov, V::Int(x)) => double((f64::from(*x) - 70.0) / 40.0), + (Spec::WheelSensitivity, V::Double(x)) => { + double_range(*x, log_mouse(-200), log_mouse(100))?; + double(*x) + } + (Spec::Unit, V::Double(x)) => { + double_range(*x, 0.0, 1.0)?; + double(*x) + } + (Spec::UnitSquare, V::Double(x)) => { + double_range(*x, 0.0, 1.0)?; + double(*x) + } + (Spec::UnitSquareImplicit, V::Double(x)) => { + let root = x.sqrt(); + double_range(root, 0.0, 1.0)?; + double(root) + } + (Spec::Named(names), V::Int(x)) => { + java_text::gson_string(names.get(usize::try_from(*x).ok()?)?) + } + (Spec::Id(_), V::Int(x)) => x.to_string(), + (Spec::Clouds, V::Int(x)) => { + java_text::gson_string(CLOUDS.get(usize::try_from(*x).ok()?)?) + } + (Spec::AnyStr, V::Str(s)) => java_text::gson_string(s), + _ => return None, + }) + } +} + +/// `InputConstants.getKey(name)`: the canonical name of a key, or the +/// unbound key when `name` is invalid. +pub fn canonical_key(name: &str) -> Result { + for (_, n) in key_names::KEYBOARD.iter().chain(key_names::MOUSE) { + if *n == name { + return Ok(name.to_owned()); + } + } + for (prefix, table) in [ + ("key.keyboard", key_names::KEYBOARD), + ("key.mouse", key_names::MOUSE), + ] { + if let Some(rest) = name.strip_prefix(prefix) { + // substring(prefix.length() + 1): the separator is skipped blindly. + let mut chars = rest.chars(); + if chars.next().is_none() { + // StringIndexOutOfBoundsException is not an IllegalArgumentException. + return Err(java_text::SyntaxError); + } + let Some(value) = crate::options_fixes::java_parse_int(chars.as_str()) else { + return Ok("key.keyboard.unknown".into()); + }; + return Ok(table + .iter() + .find(|(v, _)| *v == value) + .map_or_else(|| format!("{prefix}.{value}"), |(_, n)| (*n).to_owned())); + } + } + Ok("key.keyboard.unknown".into()) +} + +fn read_list(text: &str) -> Result, java_text::SyntaxError> { + // GsonHelper.fromNullableJson with a List type token. + Ok(java_text::parse_strict_string_list(text)?.unwrap_or_default()) +} + +/// All option values in `processOptions` order. +#[derive(Clone, Debug, PartialEq)] +pub struct OptionsFile { + values: Vec, + /// `fullscreenResolution`, kept verbatim. + pub fullscreen_resolution: Option, +} + +impl Default for OptionsFile { + fn default() -> Self { + Self { + values: TABLE.iter().map(|d| d.default.clone()).collect(), + fullscreen_resolution: None, + } + } +} + +impl OptionsFile { + fn index(key: &str) -> Option { + TABLE.iter().position(|d| d.key == key) + } + pub fn get(&self, key: &str) -> Option<&V> { + Self::index(key).map(|i| &self.values[i]) + } + pub fn bool(&self, key: &str) -> bool { + matches!(self.get(key), Some(V::Bool(true))) + } + pub fn int(&self, key: &str) -> i32 { + match self.get(key) { + Some(V::Int(i)) => *i, + _ => 0, + } + } + pub fn double(&self, key: &str) -> f64 { + match self.get(key) { + Some(V::Double(d)) => *d, + _ => 0.0, + } + } + pub fn string(&self, key: &str) -> String { + match self.get(key) { + Some(V::Str(s)) => s.clone(), + _ => String::new(), + } + } + pub fn list(&self, key: &str) -> Vec { + match self.get(key) { + Some(V::List(l)) => l.clone(), + _ => Vec::new(), + } + } + /// The serialized name of an enum-valued option. + pub fn name(&self, key: &str) -> String { + let Some(i) = Self::index(key) else { + return String::new(); + }; + match (TABLE[i].kind, &self.values[i]) { + (Kind::Option(Spec::Named(names)), V::Int(x)) => { + names.get(*x as usize).copied().unwrap_or("").to_owned() + } + (Kind::Option(Spec::Clouds), V::Int(x)) => { + CLOUDS.get(*x as usize).copied().unwrap_or("").to_owned() + } + _ => String::new(), + } + } + /// `OptionInstance.set` with a candidate value (invalid values revert to + /// the initial value). + pub fn set(&mut self, key: &str, value: V) { + let Some(i) = Self::index(key) else { return }; + let Kind::Option(spec) = TABLE[i].kind else { + self.values[i] = value; + return; + }; + self.values[i] = spec + .validate(&value) + .unwrap_or_else(|| TABLE[i].default.clone()); + } + /// Select an enum option by serialized name. + pub fn set_name(&mut self, key: &str, name: &str) { + let Some(i) = Self::index(key) else { return }; + let names: &[&str] = match TABLE[i].kind { + Kind::Option(Spec::Named(names)) => names, + Kind::Option(Spec::Clouds) => CLOUDS, + _ => return, + }; + if let Some(p) = names.iter().position(|n| *n == name) { + self.values[i] = V::Int(p as i32); + } + } + /// Key mapping value by mapping name. + pub fn key_binding(&self, name: &str) -> String { + self.string(&format!("key_{name}")) + } + + /// `Options.load` on the text of an options file. + pub fn parse(text: &str) -> Self { + let mut file = Self::default(); + let mut raw: std::collections::HashMap = std::collections::HashMap::new(); + for line in split_lines(text) { + if let Some((k, v)) = line.split_once(':') { + raw.insert(k.to_owned(), v.to_owned()); + } + } + let version = raw + .get("version") + .and_then(|v| crate::options_fixes::java_parse_int(v)) + .unwrap_or(0); + // A fixer failure abandons the whole file, leaving the defaults. + if crate::options_fixes::update(&mut raw, version).is_ok() { + file.apply(&raw); + } + file + } + + fn apply(&mut self, raw: &std::collections::HashMap) { + // A syntax error aborts the rest of the load, fullscreenResolution included. + if self.try_apply(raw).is_ok() + && let Some(r) = raw.get("fullscreenResolution") + { + self.fullscreen_resolution = Some(r.clone()); + } + } + + fn try_apply( + &mut self, + raw: &std::collections::HashMap, + ) -> Result<(), java_text::SyntaxError> { + for (i, d) in TABLE.iter().enumerate() { + let Some(text) = raw.get(&d.key) else { + continue; + }; + match d.kind { + Kind::Option(spec) => { + let json = + java_text::parse_lenient(if text.is_empty() { "\"\"" } else { text })?; + if let Some(decoded) = spec.decode(&json) { + self.values[i] = + spec.validate(&decoded).unwrap_or_else(|| d.default.clone()); + } + } + Kind::PlainBool => self.values[i] = V::Bool(text == "true"), + Kind::PlainInt => { + if let Some(v) = crate::options_fixes::java_parse_int(text) { + self.values[i] = V::Int(v); + } + } + Kind::PlainStr => self.values[i] = V::Str(text.clone()), + Kind::List => self.values[i] = V::List(read_list(text)?), + Kind::Tutorial => { + let step = TUTORIAL_STEPS.iter().position(|n| n == text).unwrap_or(5); + self.values[i] = V::Int(step as i32); + } + Kind::Key => { + let V::Str(current) = &self.values[i] else { + continue; + }; + if current != text { + self.values[i] = V::Str(canonical_key(text)?); + } + } + } + } + Ok(()) + } + + /// `Options.save`. + pub fn serialize(&self) -> String { + let mut out = format!("version:{}\n", horizon_world::DATA_VERSION); + for (d, v) in TABLE.iter().zip(&self.values) { + let rendered = match (d.kind, v) { + (Kind::Option(spec), v) => match spec.encode(v) { + Some(s) => s, + None => continue, + }, + (Kind::PlainBool, V::Bool(b)) => b.to_string(), + (Kind::PlainInt, V::Int(x)) => x.to_string(), + (Kind::PlainStr | Kind::Key, V::Str(s)) => s.clone(), + (Kind::List, V::List(items)) => { + let parts: Vec = + items.iter().map(|s| java_text::gson_string(s)).collect(); + format!("[{}]", parts.join(",")) + } + (Kind::Tutorial, V::Int(x)) => TUTORIAL_STEPS + .get(*x as usize) + .copied() + .unwrap_or("none") + .to_owned(), + _ => continue, + }; + out.push_str(&d.key); + out.push(':'); + out.push_str(&rendered); + out.push('\n'); + } + if let Some(r) = &self.fullscreen_resolution { + out.push_str("fullscreenResolution:"); + out.push_str(r); + out.push('\n'); + } + out + } +} + +/// `BufferedReader.lines()`: \n, \r\n and \r terminate lines. +fn split_lines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let bytes = text.as_bytes(); + let mut start = 0; + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'\n' => { + lines.push(&text[start..i]); + start = i + 1; + } + b'\r' => { + lines.push(&text[start..i]); + if bytes.get(i + 1) == Some(&b'\n') { + i += 1; + } + start = i + 1; + } + _ => {} + } + i += 1; + } + if start < bytes.len() { + lines.push(&text[start..]); + } + lines +} + +/// Option names in processing order (for tests and tooling). +pub fn keys() -> Vec<&'static str> { + TABLE.iter().map(|d| d.key.as_str()).collect() +} diff --git a/crates/horizon-client/src/options_fixes.rs b/crates/horizon-client/src/options_fixes.rs new file mode 100644 index 000000000..a11248925 --- /dev/null +++ b/crates/horizon-client/src/options_fixes.rs @@ -0,0 +1,319 @@ +//! The `OPTIONS` data fixers of 26.3 (`DataFixTypes.OPTIONS`), applied to the +//! raw key/value strings of an `options.txt` older than the current version. +use std::collections::HashMap; + +/// A fixer threw an exception; vanilla abandons loading the file. +#[derive(Debug)] +pub struct FixFailed; + +pub type Raw = HashMap; + +/// OptionsKeyLwjgl3Fix.MAP: GLFW 2 key codes to key names. +const LWJGL3: &[(i32, &str)] = &[ + (0, "key.unknown"), + (11, "key.0"), + (2, "key.1"), + (3, "key.2"), + (4, "key.3"), + (5, "key.4"), + (6, "key.5"), + (7, "key.6"), + (8, "key.7"), + (9, "key.8"), + (10, "key.9"), + (30, "key.a"), + (40, "key.apostrophe"), + (48, "key.b"), + (43, "key.backslash"), + (14, "key.backspace"), + (46, "key.c"), + (58, "key.caps.lock"), + (51, "key.comma"), + (32, "key.d"), + (211, "key.delete"), + (208, "key.down"), + (18, "key.e"), + (207, "key.end"), + (28, "key.enter"), + (13, "key.equal"), + (1, "key.escape"), + (33, "key.f"), + (59, "key.f1"), + (68, "key.f10"), + (87, "key.f11"), + (88, "key.f12"), + (100, "key.f13"), + (101, "key.f14"), + (102, "key.f15"), + (103, "key.f16"), + (104, "key.f17"), + (105, "key.f18"), + (113, "key.f19"), + (60, "key.f2"), + (61, "key.f3"), + (62, "key.f4"), + (63, "key.f5"), + (64, "key.f6"), + (65, "key.f7"), + (66, "key.f8"), + (67, "key.f9"), + (34, "key.g"), + (41, "key.grave.accent"), + (35, "key.h"), + (199, "key.home"), + (23, "key.i"), + (210, "key.insert"), + (36, "key.j"), + (37, "key.k"), + (82, "key.keypad.0"), + (79, "key.keypad.1"), + (80, "key.keypad.2"), + (81, "key.keypad.3"), + (75, "key.keypad.4"), + (76, "key.keypad.5"), + (77, "key.keypad.6"), + (71, "key.keypad.7"), + (72, "key.keypad.8"), + (73, "key.keypad.9"), + (78, "key.keypad.add"), + (83, "key.keypad.decimal"), + (181, "key.keypad.divide"), + (156, "key.keypad.enter"), + (141, "key.keypad.equal"), + (55, "key.keypad.multiply"), + (74, "key.keypad.subtract"), + (38, "key.l"), + (203, "key.left"), + (56, "key.left.alt"), + (26, "key.left.bracket"), + (29, "key.left.control"), + (42, "key.left.shift"), + (219, "key.left.win"), + (50, "key.m"), + (12, "key.minus"), + (49, "key.n"), + (69, "key.num.lock"), + (24, "key.o"), + (25, "key.p"), + (209, "key.page.down"), + (201, "key.page.up"), + (197, "key.pause"), + (52, "key.period"), + (183, "key.print.screen"), + (16, "key.q"), + (19, "key.r"), + (205, "key.right"), + (184, "key.right.alt"), + (27, "key.right.bracket"), + (157, "key.right.control"), + (54, "key.right.shift"), + (220, "key.right.win"), + (31, "key.s"), + (70, "key.scroll.lock"), + (39, "key.semicolon"), + (53, "key.slash"), + (57, "key.space"), + (20, "key.t"), + (15, "key.tab"), + (22, "key.u"), + (200, "key.up"), + (47, "key.v"), + (17, "key.w"), + (45, "key.x"), + (21, "key.y"), + (44, "key.z"), +]; + +/// `Integer.parseInt(String)`. +pub fn java_parse_int(text: &str) -> Option { + let digits = text.strip_prefix(['+', '-']).unwrap_or(text); + if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { + return None; + } + text.parse::().ok() +} + +enum Number<'a> { + Special(f64), + Decimal(bool, &'a str), +} + +fn java_number(text: &str) -> Option> { + let t = text.trim_matches(|c: char| c <= ' '); + let (negative, body) = match t.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, t.strip_prefix('+').unwrap_or(t)), + }; + match body { + "NaN" => return Some(Number::Special(f64::NAN)), + "Infinity" => { + return Some(Number::Special(if negative { + f64::NEG_INFINITY + } else { + f64::INFINITY + })); + } + _ => {} + } + let body = body.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(body); + if body.is_empty() + || !body + .chars() + .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-')) + || !body.chars().any(|c| c.is_ascii_digit()) + { + return None; + } + Some(Number::Decimal(negative, body)) +} + +/// `Double.parseDouble(String)` for decimal and special forms. +pub fn java_parse_double(text: &str) -> Option { + match java_number(text)? { + Number::Special(v) => Some(v), + Number::Decimal(negative, body) => body + .parse::() + .ok() + .map(|v| if negative { -v } else { v }), + } +} + +/// `Float.parseFloat(String)`. +pub fn java_parse_float(text: &str) -> Option { + match java_number(text)? { + Number::Special(v) => Some(v as f32), + Number::Decimal(negative, body) => body + .parse::() + .ok() + .map(|v| if negative { -v } else { v }), + } +} + +fn rename(raw: &mut Raw, from: &str, to: &str, fix: impl FnOnce(&str) -> String) { + if let Some(old) = raw.remove(from) { + let value = fix(&old); + raw.insert(to.to_owned(), value); + } +} + +/// `OPTIONS` fixers from `version` up to the current data version. +pub fn update(raw: &mut Raw, version: i32) -> Result<(), FixFailed> { + if version < 816 + && let Some(lang) = raw.get_mut("lang") { + *lang = lang.to_lowercase(); + } + if version < 1344 { + let keys: Vec = raw + .keys() + .filter(|k| k.starts_with("key_")) + .cloned() + .collect(); + for key in keys { + let old = java_parse_int(&raw[&key]).ok_or(FixFailed)?; + let name = if old < 0 { + match old + 100 { + 0 => "key.mouse.left".to_owned(), + 1 => "key.mouse.right".to_owned(), + 2 => "key.mouse.middle".to_owned(), + button => format!("key.mouse.{}", button + 1), + } + } else { + LWJGL3 + .iter() + .find(|(v, _)| *v == old) + .map_or("key.unknown", |(_, n)| n) + .to_owned() + }; + raw.insert(key, name); + } + } + if version < 1446 { + let keys: Vec = raw + .keys() + .filter(|k| k.starts_with("key_")) + .cloned() + .collect(); + for key in keys { + let old = raw[&key].clone(); + if !old.starts_with("key.mouse") && !old.starts_with("scancode.") { + // substring(4) on a shorter value throws. + let rest: String = old.chars().skip(4).collect(); + if old.chars().count() < 4 { + return Err(FixFailed); + } + raw.insert(key, format!("key.keyboard.{rest}")); + } + } + } + if version < 1936 + && let Some(opacity) = raw.get("chatOpacity") { + let background = java_parse_double(opacity).map_or(0.5, |v| (0.9 * v + 0.1) / 2.0); + raw.insert( + "textBackgroundOpacity".into(), + crate::java_text::double_to_string(background), + ); + } + if version < 2556 { + rename(raw, "fancyGraphics", "graphicsMode", |v| { + if v == "true" { "1" } else { "0" }.to_owned() + }); + } + if version < 2558 + && let Some(v) = raw.remove("key_key.swapHands") { + raw.insert("key_key.swapOffhand".into(), v); + } + if version < 3201 { + for key in ["resourcePacks", "incompatibleResourcePacks"] { + if let Some(v) = raw.get_mut(key) { + *v = v.replace("\"programer_art\"", "\"programmer_art\""); + } + } + } + if version < 3214 + && let Some(ao) = raw.get_mut("ao") { + match ao.as_str() { + "0" => *ao = "false".into(), + "1" | "2" => *ao = "true".into(), + _ => {} + } + } + if version < 3319 { + raw.insert("onboardAccessibility".into(), "false".into()); + } + if version < 3943 + && let Some(v) = raw.get_mut("menuBackgroundBlurriness") { + let value = java_parse_float(v).map_or(5, |d| ((d * 10.0) + 0.5).floor() as i32); + *v = value.to_string(); + } + if version < 4651 { + let mode = raw.get("graphicsMode").cloned(); + for (name, fast, fancy, fabulous) in [ + ("cutoutLeaves", "false", "true", "true"), + ("weatherRadius", "5", "10", "10"), + ("vignette", "false", "true", "true"), + ("improvedTransparency", "false", "false", "true"), + ] { + let value = match mode.as_deref() { + Some("2") => fabulous, + Some("0") => fast, + _ => fancy, + }; + raw.insert(name.into(), value.into()); + } + raw.insert("graphicsPreset".into(), "custom".into()); + } + if version < 4661 { + rename(raw, "showNowPlayingToast", "musicToast", |v| { + if v == "false" { + "never" + } else { + "pause_and_toast" + } + .to_owned() + }); + } + if version < 4892 { + raw.insert("preferredGraphicsBackend".into(), "default".into()); + } + Ok(()) +} diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 0ea0c7bdc..afd037249 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -2,7 +2,8 @@ //! encodings (Options.processOptions); lines Horizon does not know are kept. //! The option screens live in `options_ui`. use crate::keybinds::KeyBinds; -use std::{collections::BTreeMap, fs, path::Path}; +use crate::options_file::{OptionsFile, V}; +use std::{fs, path::Path}; /// SoundSource names in vanilla order. pub const SOUND_SOURCES: [&str; 11] = [ @@ -159,8 +160,13 @@ pub struct Settings { /// Enabled resource packs, bottom first (resourcePacks). pub resource_packs: Vec, pub keys: KeyBinds, - /// Lines Horizon does not interpret, kept verbatim. - pub extra: BTreeMap, + /// Every option in its stored form (the typed fields above mirror it). + pub file: OptionsFile, + pub invert_x: bool, + pub toggle_attack: bool, + pub toggle_use: bool, + /// Taps of the sprint key counted as double taps (sprintWindow). + pub sprint_window: i32, } impl Default for Settings { fn default() -> Self { @@ -220,258 +226,220 @@ impl Default for Settings { reduced_debug_info: false, high_contrast: false, main_hand_left: false, - resource_packs: vec!["vanilla".into()], + resource_packs: Vec::new(), keys: KeyBinds::default(), - extra: BTreeMap::new(), + file: OptionsFile::default(), + invert_x: false, + toggle_attack: false, + toggle_use: false, + sprint_window: 7, } } } -fn unquote(v: &str) -> &str { - v.strip_prefix('"') - .and_then(|v| v.strip_suffix('"')) - .unwrap_or(v) +fn put_f(f: &mut OptionsFile, key: &str, v: f32) { + if v != f.double(key) as f32 { + f.set(key, V::Double(f64::from(v))); + } } -fn parse_list(v: &str) -> Vec { - serde_json::from_str::>(v).unwrap_or_default() +fn put_i(f: &mut OptionsFile, key: &str, v: i32) { + if v != f.int(key) { + f.set(key, V::Int(v)); + } +} +fn put_b(f: &mut OptionsFile, key: &str, v: bool) { + if v != f.bool(key) { + f.set(key, V::Bool(v)); + } +} +fn put_name(f: &mut OptionsFile, key: &str, v: &str) { + if v != f.name(key) { + f.set_name(key, v); + } +} +fn put_s(f: &mut OptionsFile, key: &str, v: &str) { + if v != f.string(key) { + f.set(key, V::Str(v.to_owned())); + } } impl Settings { pub fn load(path: &Path) -> Self { - let Ok(text) = fs::read_to_string(path) else { + let Ok(bytes) = fs::read(path) else { return Self::default(); }; - Self::parse(&text) + Self::parse(&String::from_utf8_lossy(&bytes)) } pub fn parse(text: &str) -> Self { - let mut s = Self::default(); - for line in text.lines() { - let Some((k, v)) = line.split_once(':') else { - continue; - }; - let f = |d: f32| v.parse::().unwrap_or(d); - let b = |d: bool| match v { - "true" => true, - "false" => false, - _ => d, - }; - let i = |d: i32| v.parse::().unwrap_or(d); - match k { - "version" => {} - "fov" => { - s.fov = v - .parse::() - .map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0)) - } - "renderDistance" => s.render_distance = i(12).clamp(2, 32), - "simulationDistance" => s.simulation_distance = i(12).clamp(5, 32), - "mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0), - "guiScale" => s.gui_scale = v.parse().unwrap_or(0), - "bobView" => s.view_bobbing = b(true), - "gamma" => s.gamma = f(0.5).clamp(0.0, 1.0), - "maxFps" => s.max_fps = v.parse::().unwrap_or(260).clamp(10, 260), - "enableVsync" => s.vsync = b(true), - "fullscreen" => s.fullscreen = b(false), - "ao" => s.smooth_lighting = b(true), - "renderClouds" => s.clouds = unquote(v).to_owned(), - "cloudRange" => s.cloud_range = i(128).clamp(2, 128), - "particles" => s.particles = v.parse::().unwrap_or(0).min(2), - "entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0), - "entityShadows" => s.entity_shadows = b(true), - "biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7), - "graphicsPreset" => s.graphics_preset = unquote(v).to_owned(), - "mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4), - "weatherRadius" => s.weather_radius = i(10).clamp(3, 10), - "chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0), - "vignette" => s.vignette = b(true), - "showAutosaveIndicator" => s.autosave_indicator = b(true), - "cutoutLeaves" => s.cutout_leaves = b(true), - "improvedTransparency" => s.improved_transparency = b(false), - "attackIndicator" => s.attack_indicator = v.parse::().unwrap_or(1).min(2), - "inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(), - "prioritizeChunkUpdates" => { - s.prioritize_chunk_updates = v.parse::().unwrap_or(0).min(2) - } - "menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10), - "invertYMouse" => s.invert_y = b(false), - "mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0), - "discrete_mouse_scroll" => s.discrete_scroll = b(false), - "toggleCrouch" => s.toggle_crouch = b(false), - "toggleSprint" => s.toggle_sprint = b(false), - "autoJump" => s.auto_jump = b(false), - "lang" => s.language = v.to_owned(), - "forceUnicodeFont" => s.force_unicode = b(false), - "japaneseGlyphVariants" => s.japanese_glyphs = b(false), - "chatVisibility" => s.chat_visibility = v.parse::().unwrap_or(0).min(2), - "chatColors" => s.chat_colors = b(true), - "chatLinks" => s.chat_links = b(true), - "chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0), - "textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0), - "chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0), - "chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0), - "chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0), - "chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0), - "chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0), - "autoSuggestions" => s.auto_suggestions = b(true), - "reducedDebugInfo" => s.reduced_debug_info = b(false), - "highContrast" => s.high_contrast = b(false), - "mainHand" => s.main_hand_left = unquote(v) == "left", - "resourcePacks" => s.resource_packs = parse_list(v), - _ if k.starts_with("key_") => { - if !s.keys.set_saved(&k[4..], v) { - s.extra.insert(k.to_owned(), v.to_owned()); - } - } - _ if k.starts_with("soundCategory_") => { - let name = &k["soundCategory_".len()..]; - match SOUND_SOURCES.iter().position(|n| *n == name) { - Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0), - Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0), - None => { - s.extra.insert(k.to_owned(), v.to_owned()); - } - } - } - _ => { - s.extra.insert(k.to_owned(), v.to_owned()); - } - } - } - s + Self::from_file(OptionsFile::parse(text)) } - /// The `options.txt` text (Options.save: `version` first, then key:value). - pub fn serialize(&self) -> String { - let mut lines: Vec<(String, String)> = vec![ - ("ao".into(), self.smooth_lighting.to_string()), - ("biomeBlendRadius".into(), self.biome_blend.to_string()), - ("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()), - ("cutoutLeaves".into(), self.cutout_leaves.to_string()), - ("enableVsync".into(), self.vsync.to_string()), - ( - "entityDistanceScaling".into(), - self.entity_distance.to_string(), - ), - ("entityShadows".into(), self.entity_shadows.to_string()), - ("forceUnicodeFont".into(), self.force_unicode.to_string()), - ( - "japaneseGlyphVariants".into(), - self.japanese_glyphs.to_string(), - ), - ("fov".into(), ((self.fov - 70.0) / 40.0).to_string()), - ( - "graphicsPreset".into(), - format!("\"{}\"", self.graphics_preset), - ), - ( - "prioritizeChunkUpdates".into(), - self.prioritize_chunk_updates.to_string(), - ), - ("fullscreen".into(), self.fullscreen.to_string()), - ("gamma".into(), self.gamma.to_string()), - ("guiScale".into(), self.gui_scale.to_string()), - ("maxFps".into(), self.max_fps.to_string()), - ( - "improvedTransparency".into(), - self.improved_transparency.to_string(), - ), - ( - "inactivityFpsLimit".into(), - format!("\"{}\"", self.inactivity_fps_limit), - ), - ("mipmapLevels".into(), self.mipmap_levels.to_string()), - ("particles".into(), self.particles.to_string()), - ( - "reducedDebugInfo".into(), - self.reduced_debug_info.to_string(), - ), - ("renderClouds".into(), format!("\"{}\"", self.clouds)), - ("cloudRange".into(), self.cloud_range.to_string()), - ("renderDistance".into(), self.render_distance.to_string()), - ( - "simulationDistance".into(), - self.simulation_distance.to_string(), - ), - ("vignette".into(), self.vignette.to_string()), - ("weatherRadius".into(), self.weather_radius.to_string()), - ("autoJump".into(), self.auto_jump.to_string()), - ("autoSuggestions".into(), self.auto_suggestions.to_string()), - ("chatColors".into(), self.chat_colors.to_string()), - ("chatLinks".into(), self.chat_links.to_string()), - ( - "discrete_mouse_scroll".into(), - self.discrete_scroll.to_string(), - ), - ("invertYMouse".into(), self.invert_y.to_string()), - ("bobView".into(), self.view_bobbing.to_string()), - ("toggleCrouch".into(), self.toggle_crouch.to_string()), - ("toggleSprint".into(), self.toggle_sprint.to_string()), - ("mouseSensitivity".into(), self.sensitivity.to_string()), - ("highContrast".into(), self.high_contrast.to_string()), - ( - "resourcePacks".into(), - serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()), - ), - ("lang".into(), self.language.clone()), - ("chatVisibility".into(), self.chat_visibility.to_string()), - ("chatOpacity".into(), self.chat_opacity.to_string()), - ("chatLineSpacing".into(), self.chat_line_spacing.to_string()), - ( - "textBackgroundOpacity".into(), - self.text_background_opacity.to_string(), - ), - ( - "chatHeightFocused".into(), - self.chat_height_focused.to_string(), - ), - ( - "chatHeightUnfocused".into(), - self.chat_height_unfocused.to_string(), - ), - ("chatScale".into(), self.chat_scale.to_string()), - ("chatWidth".into(), self.chat_width.to_string()), - ( - "mainHand".into(), - if self.main_hand_left { - "\"left\"".into() - } else { - "\"right\"".into() - }, - ), - ("attackIndicator".into(), self.attack_indicator.to_string()), - ( - "mouseWheelSensitivity".into(), - self.mouse_wheel_sensitivity.to_string(), - ), - ( - "showAutosaveIndicator".into(), - self.autosave_indicator.to_string(), - ), - ( - "menuBackgroundBlurriness".into(), - self.menu_blur.to_string(), - ), - ]; - for (name, key) in self.keys.saved() { - lines.push((format!("key_{name}"), key)); + /// Typed view of an options file. + pub fn from_file(f: OptionsFile) -> Self { + let mut keys = KeyBinds::default(); + for (name, _, _) in crate::keybinds::MAPPINGS { + keys.set(name, &f.key_binding(name)); } + let mut volumes = [1.0; 11]; + for (i, source) in SOUND_SOURCES.iter().enumerate() { + volumes[i] = f.double(&format!("soundCategory_{source}")) as f32; + } + Self { + fov: f.int("fov") as f32, + render_distance: f.int("renderDistance"), + simulation_distance: f.int("simulationDistance"), + sensitivity: f.double("mouseSensitivity") as f32, + master_volume: volumes[0], + volumes, + gui_scale: f.int("guiScale").max(0) as u32, + view_bobbing: f.bool("bobView"), + gamma: f.double("gamma") as f32, + max_fps: f.int("maxFps") as u32, + vsync: f.bool("enableVsync"), + fullscreen: f.bool("fullscreen"), + smooth_lighting: f.bool("ao"), + clouds: f.name("renderClouds"), + cloud_range: f.int("cloudRange"), + particles: f.int("particles") as u8, + entity_distance: f.double("entityDistanceScaling") as f32, + entity_shadows: f.bool("entityShadows"), + biome_blend: f.int("biomeBlendRadius"), + graphics_preset: f.name("graphicsPreset"), + mipmap_levels: f.int("mipmapLevels"), + weather_radius: f.int("weatherRadius"), + chunk_fade: f.double("chunkSectionFadeInTime") as f32, + vignette: f.bool("vignette"), + autosave_indicator: f.bool("showAutosaveIndicator"), + cutout_leaves: f.bool("cutoutLeaves"), + improved_transparency: f.bool("improvedTransparency"), + attack_indicator: f.int("attackIndicator") as u8, + inactivity_fps_limit: f.name("inactivityFpsLimit"), + prioritize_chunk_updates: f.int("prioritizeChunkUpdates") as u8, + menu_blur: f.int("menuBackgroundBlurriness"), + invert_x: f.bool("invertXMouse"), + invert_y: f.bool("invertYMouse"), + mouse_wheel_sensitivity: f.double("mouseWheelSensitivity") as f32, + discrete_scroll: f.bool("discrete_mouse_scroll"), + toggle_crouch: f.bool("toggleCrouch"), + toggle_sprint: f.bool("toggleSprint"), + toggle_attack: f.bool("toggleAttack"), + toggle_use: f.bool("toggleUse"), + sprint_window: f.int("sprintWindow"), + auto_jump: f.bool("autoJump"), + language: f.string("lang"), + force_unicode: f.bool("forceUnicodeFont"), + japanese_glyphs: f.bool("japaneseGlyphVariants"), + chat_visibility: f.int("chatVisibility") as u8, + chat_colors: f.bool("chatColors"), + chat_links: f.bool("chatLinks"), + chat_opacity: f.double("chatOpacity") as f32, + text_background_opacity: f.double("textBackgroundOpacity") as f32, + chat_scale: f.double("chatScale") as f32, + chat_width: f.double("chatWidth") as f32, + chat_height_focused: f.double("chatHeightFocused") as f32, + chat_height_unfocused: f.double("chatHeightUnfocused") as f32, + chat_line_spacing: f.double("chatLineSpacing") as f32, + auto_suggestions: f.bool("autoSuggestions"), + reduced_debug_info: f.bool("reducedDebugInfo"), + high_contrast: f.bool("highContrast"), + main_hand_left: f.name("mainHand") == "left", + resource_packs: f.list("resourcePacks"), + keys, + file: f, + } + } + /// The options file reflecting the typed fields; values the game did not + /// change keep their stored form. + pub fn to_file(&self) -> OptionsFile { + let mut f = self.file.clone(); + put_i(&mut f, "fov", self.fov as i32); + put_i(&mut f, "renderDistance", self.render_distance); + put_i(&mut f, "simulationDistance", self.simulation_distance); + put_f(&mut f, "mouseSensitivity", self.sensitivity); for (i, source) in SOUND_SOURCES.iter().enumerate() { let v = if i == 0 { self.master_volume } else { self.volumes[i] }; - lines.push((format!("soundCategory_{source}"), v.to_string())); + put_f(&mut f, &format!("soundCategory_{source}"), v); } - let known: std::collections::BTreeSet = - lines.iter().map(|(k, _)| k.clone()).collect(); - for (k, v) in &self.extra { - if !known.contains(k) { - lines.push((k.clone(), v.clone())); - } + put_i(&mut f, "guiScale", self.gui_scale as i32); + put_b(&mut f, "bobView", self.view_bobbing); + put_f(&mut f, "gamma", self.gamma); + put_i(&mut f, "maxFps", self.max_fps as i32); + put_b(&mut f, "enableVsync", self.vsync); + put_b(&mut f, "fullscreen", self.fullscreen); + put_b(&mut f, "ao", self.smooth_lighting); + put_name(&mut f, "renderClouds", &self.clouds); + put_i(&mut f, "cloudRange", self.cloud_range); + put_i(&mut f, "particles", i32::from(self.particles)); + put_f(&mut f, "entityDistanceScaling", self.entity_distance); + put_b(&mut f, "entityShadows", self.entity_shadows); + put_i(&mut f, "biomeBlendRadius", self.biome_blend); + put_name(&mut f, "graphicsPreset", &self.graphics_preset); + put_i(&mut f, "mipmapLevels", self.mipmap_levels); + put_i(&mut f, "weatherRadius", self.weather_radius); + put_f(&mut f, "chunkSectionFadeInTime", self.chunk_fade); + put_b(&mut f, "vignette", self.vignette); + put_b(&mut f, "showAutosaveIndicator", self.autosave_indicator); + put_b(&mut f, "cutoutLeaves", self.cutout_leaves); + put_b(&mut f, "improvedTransparency", self.improved_transparency); + put_i(&mut f, "attackIndicator", i32::from(self.attack_indicator)); + put_name(&mut f, "inactivityFpsLimit", &self.inactivity_fps_limit); + put_i( + &mut f, + "prioritizeChunkUpdates", + i32::from(self.prioritize_chunk_updates), + ); + put_i(&mut f, "menuBackgroundBlurriness", self.menu_blur); + put_b(&mut f, "invertXMouse", self.invert_x); + put_b(&mut f, "invertYMouse", self.invert_y); + put_f( + &mut f, + "mouseWheelSensitivity", + self.mouse_wheel_sensitivity, + ); + put_b(&mut f, "discrete_mouse_scroll", self.discrete_scroll); + put_b(&mut f, "toggleCrouch", self.toggle_crouch); + put_b(&mut f, "toggleSprint", self.toggle_sprint); + put_b(&mut f, "toggleAttack", self.toggle_attack); + put_b(&mut f, "toggleUse", self.toggle_use); + put_i(&mut f, "sprintWindow", self.sprint_window); + put_b(&mut f, "autoJump", self.auto_jump); + put_s(&mut f, "lang", &self.language); + put_b(&mut f, "forceUnicodeFont", self.force_unicode); + put_b(&mut f, "japaneseGlyphVariants", self.japanese_glyphs); + put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility)); + put_b(&mut f, "chatColors", self.chat_colors); + put_b(&mut f, "chatLinks", self.chat_links); + put_f(&mut f, "chatOpacity", self.chat_opacity); + put_f( + &mut f, + "textBackgroundOpacity", + self.text_background_opacity, + ); + put_f(&mut f, "chatScale", self.chat_scale); + put_f(&mut f, "chatWidth", self.chat_width); + put_f(&mut f, "chatHeightFocused", self.chat_height_focused); + put_f(&mut f, "chatHeightUnfocused", self.chat_height_unfocused); + put_f(&mut f, "chatLineSpacing", self.chat_line_spacing); + put_b(&mut f, "autoSuggestions", self.auto_suggestions); + put_b(&mut f, "reducedDebugInfo", self.reduced_debug_info); + put_b(&mut f, "highContrast", self.high_contrast); + put_name( + &mut f, + "mainHand", + if self.main_hand_left { "left" } else { "right" }, + ); + if self.resource_packs != f.list("resourcePacks") { + f.set("resourcePacks", V::List(self.resource_packs.clone())); } - let mut out = format!("version:{}\n", horizon_world::DATA_VERSION); - for (k, v) in lines { - out.push_str(&format!("{k}:{v}\n")); + for (name, key) in self.keys.saved() { + put_s(&mut f, &format!("key_{name}"), &key); } - out + f + } + /// The `options.txt` text (Options.save). + pub fn serialize(&self) -> String { + self.to_file().serialize() } pub fn save(&self, path: &Path) { let _ = fs::write(path, self.serialize()); @@ -520,7 +488,8 @@ mod tests { let out = s.serialize(); assert!(out.starts_with("version:")); assert!(out.contains("\nkey_key.jump:key.keyboard.j\n")); - assert!(out.contains("\nsomeFutureOption:42\n")); + // Options.save writes only the options it knows. + assert!(!out.contains("someFutureOption")); assert!(out.contains("\nrenderClouds:\"fast\"\n")); let again = Settings::parse(&out); assert_eq!(again.fov, 90.0); diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs new file mode 100644 index 000000000..d5d0d0c2d --- /dev/null +++ b/crates/horizon-client/src/window.rs @@ -0,0 +1,226 @@ +//! Window sizing and frame pacing of 26.3: `Window.calculateScale` and +//! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`, +//! `FramerateLimiter` and the vsync present-mode choice. + +/// `Window.calculateScale`: the largest scale that leaves at least 320x240 +/// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped +/// to even when unicode is enforced. +pub fn calculate_scale(framebuffer: [i32; 2], max_scale: i32, enforce_unicode: bool) -> i32 { + let [width, height] = framebuffer; + let mut scale = 1; + while scale != max_scale + && scale < width + && scale < height + && width / (scale + 1) >= 320 + && height / (scale + 1) >= 240 + { + scale += 1; + } + if enforce_unicode && scale % 2 != 0 { + scale += 1; + } + scale +} + +/// `Window.setGuiScale`: the GUI-scaled size of a framebuffer. +pub fn gui_scaled_size(framebuffer: [i32; 2], gui_scale: i32) -> [i32; 2] { + let scaled = |v: i32| (f64::from(v) / f64::from(gui_scale)).ceil() as i32; + [scaled(framebuffer[0]), scaled(framebuffer[1])] +} + +/// `MouseHandler.getScaledXPos`/`getScaledYPos`. +pub fn scaled_pos(pos: f64, gui_scaled: i32, screen: i32) -> f64 { + pos * f64::from(gui_scaled) / f64::from(screen) +} + +/// `InactivityFpsLimit`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InactivityFpsLimit { + Minimized, + Afk, +} + +/// `FramerateLimitTracker.FramerateThrottleReason`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ThrottleReason { + None, + WindowIconified, + LongAfk, + ShortAfk, + OutOfLevelMenu, +} + +/// What `FramerateLimitTracker` looks at. +#[derive(Clone, Copy, Debug)] +pub struct FrameContext { + pub inactivity: InactivityFpsLimit, + pub iconified: bool, + pub focused: bool, + pub exclusive_fullscreen: bool, + pub now_ms: i64, + pub latest_input_ms: i64, + pub has_level: bool, + pub has_screen: bool, + pub has_overlay: bool, +} + +/// `getThrottleReason`. +pub fn throttle_reason(c: FrameContext) -> ThrottleReason { + if !c.iconified && (c.focused || !c.exclusive_fullscreen) { + if c.inactivity == InactivityFpsLimit::Afk { + let afk = c.now_ms - c.latest_input_ms; + if afk > 600_000 { + return ThrottleReason::LongAfk; + } + if afk > 60_000 { + return ThrottleReason::ShortAfk; + } + } + if c.has_level || (!c.has_screen && !c.has_overlay) { + ThrottleReason::None + } else { + ThrottleReason::OutOfLevelMenu + } + } else { + ThrottleReason::WindowIconified + } +} + +/// `getFramerateLimit`. +pub fn framerate_limit(option_limit: i32, c: FrameContext) -> i32 { + match throttle_reason(c) { + ThrottleReason::None => option_limit, + ThrottleReason::WindowIconified | ThrottleReason::LongAfk => 10, + ThrottleReason::ShortAfk => option_limit.min(30), + ThrottleReason::OutOfLevelMenu => 60, + } +} + +/// `isHeavilyThrottled`. +pub fn heavily_throttled(reason: ThrottleReason) -> bool { + matches!(reason, ThrottleReason::WindowIconified | ThrottleReason::LongAfk) +} + +/// Present modes the renderer can choose between. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PresentMode { + Fifo, + Mailbox, + Immediate, +} + +/// `GpuSurface.PresentMode.getSupportedVsyncMode`: vsync means Fifo only, +/// otherwise the first of Immediate, Mailbox, Fifo that is supported. +pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option { + let preferred: &[PresentMode] = if vsync { + &[PresentMode::Fifo] + } else { + &[PresentMode::Immediate, PresentMode::Mailbox, PresentMode::Fifo] + }; + preferred.iter().copied().find(|m| supported.contains(m)) +} + +/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep +/// and spin decisions are testable. +#[derive(Clone, Debug)] +pub struct FramerateLimiter { + last_frame_time: i64, + average_overshoot_ns: i64, + last_framerate_limit: i32, +} + +/// Time source of the limiter. +pub trait LimiterClock { + fn nanos(&mut self) -> i64; + /// `LockSupport.parkNanos`. + fn park(&mut self, nanos: i64); + /// `Thread.onSpinWait`. + fn spin(&mut self); +} + +impl FramerateLimiter { + pub fn new(now_ns: i64) -> Self { + Self { + last_frame_time: now_ns, + average_overshoot_ns: 0, + last_framerate_limit: 0, + } + } + pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) { + let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit); + let target_time_ns = self.last_frame_time + target_time_per_frame; + if framerate_limit != self.last_framerate_limit { + self.average_overshoot_ns = 0; + self.last_framerate_limit = framerate_limit; + } + loop { + let remaining = target_time_ns - clock.nanos(); + if remaining <= 0 { + break; + } + if remaining > self.average_overshoot_ns + 500_000 { + let sleep_start = clock.nanos(); + let expected = remaining - self.average_overshoot_ns - 500_000; + clock.park(expected); + let duration = clock.nanos() - sleep_start; + let overshoot = duration - expected; + if overshoot > 0 && overshoot < 25_000_000 { + self.average_overshoot_ns = + (0.1 * overshoot as f64 + 0.9 * self.average_overshoot_ns as f64) as i64; + self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000); + } + } else { + clock.spin(); + } + } + self.last_frame_time = clock.nanos(); + } + pub fn last_frame_time(&self) -> i64 { + self.last_frame_time + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Virtual { + now: i64, + oversleep: i64, + } + impl LimiterClock for Virtual { + fn nanos(&mut self) -> i64 { + self.now + } + fn park(&mut self, nanos: i64) { + self.now += nanos + self.oversleep; + } + fn spin(&mut self) { + self.now += 1000; + } + } + + #[test] + fn scale_matches_the_320_by_240_rule() { + assert_eq!(calculate_scale([854, 480], 0, false), 2); + assert_eq!(calculate_scale([1920, 1080], 0, false), 4); + assert_eq!(calculate_scale([1920, 1080], 3, false), 3); + assert_eq!(calculate_scale([1920, 1080], 3, true), 4); + assert_eq!(gui_scaled_size([1921, 1081], 4), [481, 271]); + } + #[test] + fn limiter_paces_frames_at_the_target() { + let mut limiter = FramerateLimiter::new(0); + let mut clock = Virtual { now: 1_000_000, oversleep: 200_000 }; + limiter.limit_display_fps(100, &mut clock); + assert!(clock.now >= 10_000_000); + assert!(clock.now < 10_000_000 + 1_000_000); + } + #[test] + fn vsync_only_uses_fifo() { + let all = [PresentMode::Mailbox, PresentMode::Fifo, PresentMode::Immediate]; + assert_eq!(vsync_present_mode(&all, true), Some(PresentMode::Fifo)); + assert_eq!(vsync_present_mode(&all, false), Some(PresentMode::Immediate)); + assert_eq!(vsync_present_mode(&[PresentMode::Fifo], false), Some(PresentMode::Fifo)); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java new file mode 100644 index 000000000..0be89888a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java @@ -0,0 +1,377 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.FramerateLimitTracker; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Window; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.*; +import net.minecraft.client.*; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.tutorial.Tutorial; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ServerTickRateManager; +import net.minecraft.server.players.PlayerList; +import net.minecraft.world.entity.player.Input; +import net.minecraft.world.entity.player.Inventory; + +/** + * Drives the real DeltaTracker.Timer, ServerTickRateManager, Window.calculateScale, + * FramerateLimitTracker, MouseHandler (move, scroll, turnPlayer), Entity.turn and + * ToggleKeyMapping with the input sequences in a JSON-lines file and prints + * every observable bit-exactly. Hosts are uninitialised shells (Unsafe) that + * carry only the fields the exercised code reads. + */ +public final class VanillaGameLoopOracle { + static Object unsafe; + static Method allocate; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class type, String name) throws Exception { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static float f(JsonElement v) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16)); + } + + static double d(JsonElement v) { + return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16)); + } + + static String fb(float v) { + return String.format("%08x", Float.floatToRawIntBits(v) == 0x7fc00000 || Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v)); + } + + static String db(double v) { + return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v)); + } + + // ---- stubs for the server tick manager ------------------------------------------------- + static final List reports = new ArrayList<>(); + + static final class StubStack extends CommandSourceStack { + StubStack() { + super(null, null, null, null, null, (Component) null, null); + } + + @Override + public void sendSuccess(Supplier message, boolean broadcast) { + var contents = (TranslatableContents) message.get().getContents(); + reports.add(contents.getArgs()[0] + " " + contents.getArgs()[1]); + } + } + + static final class StubPlayers extends PlayerList { + StubPlayers() { + super(null, null, null, (net.minecraft.server.notifications.NotificationService) null); + } + + @Override + public void broadcastAll(net.minecraft.network.protocol.Packet packet) { + } + } + + static StubStack stubStack; + static StubPlayers stubPlayers; + + static final class StubServer extends MinecraftServer { + StubServer() { + super(null, null, null, null, null, null, null, null, null, false, null); + } + + @Override public PlayerList getPlayerList() { return stubPlayers; } + @Override public CommandSourceStack createCommandSourceStack() { return stubStack; } + @Override public void onTickRateChanged() { } + @Override protected boolean initServer() { return false; } + @Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; } + @Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; } + @Override public boolean shouldRconBroadcast() { return false; } + @Override protected net.minecraft.util.debugchart.SampleLogger getTickTimeLogger() { return null; } + @Override public boolean isTickTimeLoggingEnabled() { return false; } + @Override public net.minecraft.SystemReport fillServerSystemReport(net.minecraft.SystemReport r) { return r; } + @Override public boolean isDedicatedServer() { return false; } + @Override public int getRateLimitPacketsPerSecond() { return 0; } + @Override public int getCommandSpamThresholdSeconds() { return 0; } + @Override public int getChatSpamThresholdSeconds() { return 0; } + @Override public boolean useNativeTransport() { return false; } + @Override public boolean isPublished() { return false; } + @Override public int getMaxPlayers() { return 0; } + @Override public boolean shouldInformAdmins() { return false; } + @Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; } + } + + static final class StubPlayer extends LocalPlayer { + boolean scoping; + + StubPlayer() { + super(null, null, null, null, null, Input.EMPTY, false, null, null); + } + + @Override public boolean isScoping() { return scoping; } + @Override public boolean isSpectator() { return false; } + } + + static Minecraft shell; + static Options options; + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + shell = make(Minecraft.class); + field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer()); + field(Minecraft.class, "instance").set(null, shell); + options = new Options(shell, Files.createTempDirectory("opts").toFile()); + stubStack = make(StubStack.class); + stubPlayers = make(StubPlayers.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + switch (c.get("t").getAsString()) { + case "timer" -> timer(c, out); + case "rate" -> rate(c, out); + case "scale" -> scale(c, out); + case "limit" -> limit(c, out); + case "mouse" -> mouse(c, out); + case "scroll" -> scroll(c, out); + case "key" -> key(c, out); + default -> throw new IllegalArgumentException(line); + } + } + } + System.exit(0); + } + + static void timer(JsonObject c, PrintWriter out) { + float[] mspt = {0}; + var timer = new DeltaTracker.Timer(f(c.get("tps")), c.get("start").getAsLong(), + d -> mspt[0] == 0 ? d : Math.max(d, mspt[0])); + out.println("timer"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + String name = op.get(0).getAsString(); + String result = ""; + switch (name) { + case "adv" -> { + mspt[0] = op.get(2).isJsonNull() ? 0 : f(op.get(2)); + result = " " + timer.advanceGameTime(op.get(1).getAsLong()); + } + case "real" -> timer.advanceRealTime(op.get(1).getAsLong()); + case "pause" -> timer.updatePauseState(op.get(1).getAsBoolean()); + case "frozen" -> timer.updateFrozenState(op.get(1).getAsBoolean()); + default -> throw new IllegalArgumentException(name); + } + out.println(name + result + " " + fb(timer.getGameTimeDeltaTicks()) + " " + fb(timer.getGameTimeDeltaPartialTick(false)) + + " " + fb(timer.getGameTimeDeltaPartialTick(true)) + " " + fb(timer.getRealtimeDeltaTicks())); + } + } + + static void rate(JsonObject c, PrintWriter out) throws Exception { + var m = make(ServerTickRateManager.class); + field(ServerTickRateManager.class, "server").set(m, make(StubServer.class)); + // Field initialisers do not run on a shell. + field(net.minecraft.world.TickRateManager.class, "tickrate").setFloat(m, 20.0F); + field(net.minecraft.world.TickRateManager.class, "nanosecondsPerTick").setLong(m, 50_000_000L); + field(net.minecraft.world.TickRateManager.class, "runGameElements").setBoolean(m, true); + var startTime = field(ServerTickRateManager.class, "sprintTickStartTime"); + var spend = field(ServerTickRateManager.class, "sprintTimeSpend"); + out.println("rate"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + String name = op.get(0).getAsString(); + reports.clear(); + String result = ""; + switch (name) { + case "rate" -> m.setTickRate(f(op.get(1))); + case "freeze" -> m.setFrozen(op.get(1).getAsBoolean()); + case "step" -> result = " " + m.stepGameIfPaused(op.get(1).getAsInt()); + case "stopstep" -> result = " " + m.stopStepping(); + case "sprint" -> result = " " + m.requestGameToSprint(op.get(1).getAsInt()); + case "check" -> { + result = " " + m.checkShouldSprintThisTick(); + if (m.runsNormally() && result.equals(" true")) { + startTime.setLong(m, op.get(1).getAsLong()); + } else if (m.runsNormally() && reports.isEmpty()) { + // unreachable: the else branch always reports + } + } + case "end" -> { + long before = spend.getLong(m); + m.endTickWork(); + spend.setLong(m, before + (op.get(1).getAsLong() - startTime.getLong(m))); + } + case "stopsprint" -> result = " " + m.stopSprinting(); + case "tick" -> m.tick(); + default -> throw new IllegalArgumentException(name); + } + out.println(name + result + " | " + fb(m.tickrate()) + " " + m.nanosecondsPerTick() + " " + fb(m.millisecondsPerTick()) + + " " + m.runsNormally() + " " + m.isSteppingForward() + " " + m.frozenTicksToRun() + " " + m.isFrozen() + + " " + m.isSprinting() + (reports.isEmpty() ? "" : " report " + reports.get(0))); + } + } + + static Window window(int w, int h, int sw, int sh) throws Exception { + Window window = make(Window.class); + field(Window.class, "framebufferWidth").setInt(window, w); + field(Window.class, "framebufferHeight").setInt(window, h); + field(Window.class, "width").setInt(window, sw); + field(Window.class, "height").setInt(window, sh); + return window; + } + + static void scale(JsonObject c, PrintWriter out) throws Exception { + Window window = window(c.get("w").getAsInt(), c.get("h").getAsInt(), c.get("sw").getAsInt(), c.get("sh").getAsInt()); + int scale = window.calculateScale(c.get("max").getAsInt(), c.get("uni").getAsBoolean()); + window.setGuiScale(scale); + out.println("scale " + scale + " " + window.getGuiScaledWidth() + " " + window.getGuiScaledHeight() + " " + + db(MouseHandler.getScaledXPos(window, d(c.get("x")))) + " " + db(MouseHandler.getScaledYPos(window, d(c.get("y"))))); + } + + static void limit(JsonObject c, PrintWriter out) throws Exception { + Window window = window(1, 1, 1, 1); + field(Window.class, "iconified").setBoolean(window, c.get("iconified").getAsBoolean()); + field(Window.class, "focused").setBoolean(window, c.get("focused").getAsBoolean()); + Minecraft mc = make(Minecraft.class); + field(Minecraft.class, "window").set(mc, window); + Gui gui = make(Gui.class); + field(Gui.class, "screen").set(gui, c.get("screen").getAsBoolean() ? make(net.minecraft.client.gui.screens.PauseScreen.class) : null); + field(Gui.class, "overlay").set(gui, c.get("overlay").getAsBoolean() ? make(net.minecraft.client.gui.screens.LoadingOverlay.class) : null); + field(Minecraft.class, "gui").set(mc, gui); + field(Minecraft.class, "level").set(mc, c.get("level").getAsBoolean() ? make(net.minecraft.client.multiplayer.ClientLevel.class) : null); + options.framerateLimit().set(c.get("opt").getAsInt()); + options.inactivityFpsLimit().set(c.get("afk").getAsBoolean() ? InactivityFpsLimit.AFK : InactivityFpsLimit.MINIMIZED); + var tracker = new FramerateLimitTracker(options, mc); + field(FramerateLimitTracker.class, "latestInputTime").setLong(tracker, net.minecraft.util.Util.getMillis() - c.get("ago").getAsLong()); + out.println("limit " + tracker.getThrottleReason() + " " + tracker.getFramerateLimit() + " " + tracker.isHeavilyThrottled()); + } + + static MouseHandler handler(Minecraft mc) throws Exception { + MouseHandler h = new MouseHandler(mc); + return h; + } + + static void mouse(JsonObject c, PrintWriter out) throws Exception { + Window window = window(1, 1, 1, 1); + field(Window.class, "handle").setLong(window, 1L); + field(Window.class, "focused").setBoolean(window, c.get("active").getAsBoolean()); + Minecraft mc = make(Minecraft.class); + field(Minecraft.class, "window").set(mc, window); + field(Minecraft.class, "options").set(mc, options); + field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class)); + field(Minecraft.class, "tutorial").set(mc, make(Tutorial.class)); + StubPlayer player = make(StubPlayer.class); + player.scoping = c.get("scoping").getAsBoolean(); + mc.player = player; + options.sensitivity().set(d(c.get("sens"))); + options.smoothCamera = c.get("smooth").getAsBoolean(); + options.invertMouseX().set(c.get("ix").getAsBoolean()); + options.invertMouseY().set(c.get("iy").getAsBoolean()); + MouseHandler h = handler(mc); + field(MouseHandler.class, "mouseGrabbed").setBoolean(h, c.get("grabbed").getAsBoolean()); + var turn = MouseHandler.class.getDeclaredMethod("turnPlayer", double.class); + turn.setAccessible(true); + var dx = field(MouseHandler.class, "accumulatedDX"); + var dy = field(MouseHandler.class, "accumulatedDY"); + double last = Double.MIN_VALUE; + out.println("mouse"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "move" -> h.onMove(1L, d(op.get(1)), d(op.get(2)), d(op.get(3)), d(op.get(4))); + case "ignore" -> h.setIgnoreFirstMove(); + case "frame" -> { + double time = d(op.get(1)); + double mousea = time - last; + last = time; + // MouseHandler.handleAccumulatedMovement without the SDL clock and screens. + if (mc.isWindowActive() && h.isMouseGrabbed() && mc.player != null) { + turn.invoke(h, mousea); + } + dx.setDouble(h, 0.0); + dy.setDouble(h, 0.0); + out.println("frame " + fb(player.getXRot()) + " " + fb(player.getYRot()) + " " + + fb(player.xRotO) + " " + fb(player.yRotO)); + } + default -> throw new IllegalArgumentException(op.toString()); + } + } + } + + static void scroll(JsonObject c, PrintWriter out) throws Exception { + Window window = window(1, 1, 1, 1); + field(Window.class, "handle").setLong(window, 1L); + Minecraft mc = make(Minecraft.class); + field(Minecraft.class, "window").set(mc, window); + field(Minecraft.class, "options").set(mc, options); + field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class)); + field(Minecraft.class, "gui").set(mc, make(Gui.class)); + StubPlayer player = make(StubPlayer.class); + Inventory inventory = make(Inventory.class); + inventory.setSelectedSlot(c.get("slot").getAsInt()); + field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory); + mc.player = player; + options.discreteMouseScroll().set(c.get("discrete").getAsBoolean()); + options.mouseWheelSensitivity().set(d(c.get("sens"))); + MouseHandler h = handler(mc); + out.println("scroll"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + h.onScroll(1L, d(op.get(0)), d(op.get(1))); + out.println(inventory.getSelectedSlot()); + } + } + + static int keys = 0; + + static void key(JsonObject c, PrintWriter out) throws Exception { + AtomicBoolean option = new AtomicBoolean(); + int value = 10000 + keys++; + KeyMapping mapping = c.get("toggle").getAsBoolean() + ? new ToggleKeyMapping("key.test" + value, c.get("keyboard").getAsBoolean() ? InputConstants.Type.KEYBOARD : InputConstants.Type.MOUSE, + value, KeyMapping.Category.MISC, option::get, c.get("restore").getAsBoolean()) + : new KeyMapping("key.test" + value, InputConstants.Type.KEYBOARD, value, KeyMapping.Category.MISC); + var release = KeyMapping.class.getDeclaredMethod("release"); + release.setAccessible(true); + var key = c.get("toggle").getAsBoolean() && !c.get("keyboard").getAsBoolean() + ? InputConstants.Type.MOUSE.getOrCreate(value) : InputConstants.Type.KEYBOARD.getOrCreate(value); + out.println("key"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + String result = ""; + switch (op.get(0).getAsString()) { + case "option" -> option.set(op.get(1).getAsBoolean()); + case "down" -> mapping.setDown(op.get(1).getAsBoolean()); + case "release" -> release.invoke(mapping); + case "restore" -> result = mapping instanceof ToggleKeyMapping t ? " " + t.shouldRestoreStateOnScreenClosed() : " false"; + case "click" -> KeyMapping.click(key); + case "consume" -> result = " " + mapping.consumeClick(); + case "ingame" -> { + var m = KeyMapping.class.getDeclaredMethod("shouldSetOnIngameFocus"); + m.setAccessible(true); + result = " " + m.invoke(mapping); + } + default -> throw new IllegalArgumentException(op.toString()); + } + out.println(op.get(0).getAsString() + result + " " + mapping.isDown()); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsOracle.java new file mode 100644 index 000000000..7e8215ffb --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsOracle.java @@ -0,0 +1,63 @@ +package dev.horizonlab.parity; + +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; +import net.minecraft.util.datafix.DataFixers; + +/** + * Loads each options.txt case through the real Options.load and writes it back + * with Options.save, then dumps the key mapping table (order, defaults, + * categories). The Minecraft instance is an uninitialised shell that only + * supplies the data fixer. + */ +public final class VanillaOptionsOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + var uf = u.getDeclaredField("theUnsafe"); + uf.setAccessible(true); + Object unsafe = uf.get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class); + Field fixer = Minecraft.class.getDeclaredField("fixerUpper"); + fixer.setAccessible(true); + fixer.set(shell, DataFixers.getDataFixer()); + Field instance = Minecraft.class.getDeclaredField("instance"); + instance.setAccessible(true); + instance.set(null, shell); + Path cases = Path.of(args[0]); + Path work = Files.createTempDirectory("opts"); + List files = new ArrayList<>(); + try (var s = Files.list(cases)) { + s.sorted().forEach(files::add); + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + boolean first = true; + for (Path file : files) { + Path target = work.resolve("options.txt"); + Files.deleteIfExists(target); + if (!file.getFileName().toString().equals("absent.txt")) { + Files.copy(file, target); + } + Options options = new Options(shell, work.toFile()); + options.save(); + out.print("== " + file.getFileName() + "\n"); + out.print(Files.readString(target, StandardCharsets.UTF_8)); + if (first) { + first = false; + out.print("== keys\n"); + for (KeyMapping k : options.keyMappings) { + out.print(k.getName() + " " + k.getDefaultKey().getName() + " " + k.getCategory().id().getPath() + " " + + (k instanceof ToggleKeyMapping) + "\n"); + } + } + } + } + System.exit(0); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsTableExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsTableExporter.java new file mode 100644 index 000000000..00b34b33c --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaOptionsTableExporter.java @@ -0,0 +1,119 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.*; +import net.minecraft.client.*; +import net.minecraft.util.datafix.DataFixers; + +/** + * Dumps Options.processOptions as a table: key, kind and default in processing + * order. Used to (re)generate the Rust options table; the differential harness + * then proves the Rust port agrees on loading and saving. + */ +public final class VanillaOptionsTableExporter { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + var uf = u.getDeclaredField("theUnsafe"); + uf.setAccessible(true); + Object unsafe = uf.get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class); + Field instance = Minecraft.class.getDeclaredField("instance"); + instance.setAccessible(true); + instance.set(null, shell); + Path work = Files.createTempDirectory("opts"); + Options options = new Options(shell, work.toFile()); + Method process = Options.class.getDeclaredMethod("processOptions", Class.forName("net.minecraft.client.Options$FieldAccess")); + process.setAccessible(true); + Field valuesField = OptionInstance.class.getDeclaredField("values"); + valuesField.setAccessible(true); + Gson gson = new Gson(); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) { + Class fa = Class.forName("net.minecraft.client.Options$FieldAccess"); + Object access = Proxy.newProxyInstance(fa.getClassLoader(), new Class[]{fa}, (proxy, method, a) -> { + String name = (String) a[0]; + Class rt = method.getReturnType(); + if (a.length == 2 && a[1] instanceof OptionInstance oi) { + Object vs = valuesField.get(oi); + var encoded = ((OptionInstance) oi).codec().encodeStart(JsonOps.INSTANCE, oi.get()).result().orElse(null); + if (vs instanceof OptionInstance.Enum en) { + StringBuilder sb = new StringBuilder(); + for (Object v : en.values()) { + sb.append(gson.toJson(((com.mojang.serialization.Codec) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(','); + } + out.println("enum " + name + " " + sb); + } + if (vs instanceof OptionInstance.SliderableEnum en) { + StringBuilder sb = new StringBuilder(); + for (Object v : en.values()) { + sb.append(gson.toJson(((com.mojang.serialization.Codec) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(','); + } + out.println("enum " + name + " " + sb); + } + out.println("option " + name + " " + vs.getClass().getSimpleName() + " " + describe(vs) + " => " + gson.toJson(encoded)); + return null; + } + if (a.length == 2) { + out.println("plain " + name + " " + rt.getSimpleName() + " => " + a[1]); + return a[1]; + } + if (a.length == 4) { + Object conv = ((Function) a[3]).apply(a[1]); + out.println("custom " + name + " => " + conv); + return a[1]; + } + return null; + }); + process.invoke(options, access); + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + Field map = com.mojang.blaze3d.platform.InputConstants.Type.class.getDeclaredField("map"); + map.setAccessible(true); + for (var type : com.mojang.blaze3d.platform.InputConstants.Type.values()) { + var m = (it.unimi.dsi.fastutil.ints.Int2ObjectMap) map.get(type); + var entries = new TreeMap(); + for (var e : m.int2ObjectEntrySet()) { + entries.put(e.getIntKey(), e.getValue().getName()); + } + for (var e : entries.entrySet()) { + out.println(type.name().toLowerCase() + " " + e.getKey() + " " + e.getValue()); + } + } + } + System.exit(0); + } + + static String describe(Object vs) throws Exception { + if (vs instanceof Record r) { + StringBuilder sb = new StringBuilder("{"); + for (var c : r.getClass().getRecordComponents()) { + Object v = c.getAccessor().invoke(r); + String s = String.valueOf(v); + if (v instanceof List l) { + s = l.toString(); + } else if (v != null && s.contains("$$Lambda")) { + s = ""; + } + if (c.getName().equals("codec") || c.getName().equals("valueSetter") || c.getName().equals("altCondition") + || c.getName().equals("validateValue") || c.getName().equals("maxSupplier") || c.getName().equals("values") && !(v instanceof List)) { + if (c.getName().equals("maxSupplier")) { + s = ""; + } else if (!c.getName().equals("values")) { + s = ""; + } + } + sb.append(c.getName()).append('=').append(s).append(' '); + } + return sb.append('}').toString(); + } + return vs.toString(); + } +} diff --git a/tools/oracle_harness.py b/tools/oracle_harness.py new file mode 100644 index 000000000..a19b5ba94 --- /dev/null +++ b/tools/oracle_harness.py @@ -0,0 +1,118 @@ +"""Shared plumbing for single-oracle differential harnesses. + +A harness supplies a Java oracle (compiled against the pinned client jar and its +libraries), a Rust example probe, and a text input; both programs write one +result line per input line and the outputs must be byte-identical.""" +import os +from pathlib import Path +import subprocess + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + + +def run_logged(command, build, name, timeout=900, **kwargs): + with (build / (name + '.log')).open('w') as log: + subprocess.run([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout, + stdout=log, stderr=subprocess.STDOUT, **kwargs) + + +def compile_oracle(build, oracle_name, jars, libraries, java_major): + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle_name + '.java') + classes = build / 'classes' + classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + run_logged(['javac', '--release', java_major, '-proc:none', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + build, 'compile-java-' + oracle_name) + return classes, dependencies, oracle + + +def build_probe(build, example): + run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], + build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3')) + import json + metadata = json.loads(subprocess.check_output( + ['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) + return Path(metadata['target_directory']) / 'debug/examples' / example + + +def java_run(build, classes, dependencies, main_class, args, name, jvm=()): + run_logged(['java', '-Xmx2g', '-Djava.awt.headless=true', *jvm, '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.' + main_class, *args], build, name) + + +def compare(client_out, rust_out, expected_lines): + matched = base.compare(client_out, rust_out) + if matched != expected_lines: + raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines') + return matched + + +def differential(name, oracle, probe, make_input, scope, sources=(), expected_lines=None): + """Compile the oracle and probe, run both on one input and require identical output.""" + import platform + lock, jars, libraries = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / name + build.mkdir(exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle_path = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle + '.java') + all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py', + lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs', + lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)] + tested = base.source_hashes(all_sources) + input_path, units = make_input(build) + input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None + classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) + binary = build_probe(build, probe) + run_logged([binary, input_path, build / 'rust.txt'], build, 'rust') + java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client') + try: + matched = base.compare(build / 'client.txt', build / 'rust.txt') + except AssertionError as error: + raise AssertionError(str(error) + explain(build, str(error))) from None + if expected_lines is not None and matched != expected_lines: + raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines') + base.ensure_sources_unchanged(all_sources, tested) + if input_hash is not None and input_hash != lab.digest(input_path, 'sha256'): + raise AssertionError('Input fixtures changed') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'], + platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], units=units, + sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'), + matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope)) + print(f'{units:,} {name} cases match the pinned client ({matched:,} output lines): {report}', flush=True) + return matched + + +def explain(build, message): + """Summarise differing sections ("== name" blocks) of multi-case outputs.""" + def sections(path): + out, name = {}, None + for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): + if line.startswith('== '): + name = line[3:] + out[name] = [] + elif name is not None: + out[name].append(line) + return out + left, right = sections(build / 'client.txt'), sections(build / 'rust.txt') + report, count = '', 0 + for name in left: + if left[name] != right.get(name): + count += 1 + if count <= 25: + case = build / 'cases' / name + text = case.read_text(encoding='utf-8', errors='replace') if case.is_file() else '' + a, b = left[name], right.get(name, []) + diffs = [(x, y) for x, y in zip(a, b) if x != y][:4] + if len(a) != len(b): + diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>')) + report += f"\n case {name}: {text[:300]!r}\n differences (vanilla, rust): {diffs}" + return f'\n{count} differing cases.' + report diff --git a/tools/test_options_parity.py b/tools/test_options_parity.py new file mode 100644 index 000000000..c1c17bf23 --- /dev/null +++ b/tools/test_options_parity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Compare options.txt loading and saving, and the key mapping table, with the +pinned client: every file is loaded through the real Options.load and written +back with Options.save, and the Rust port must produce identical text.""" +from pathlib import Path +import random +import shutil + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + +VERSION = 5023 + +# Raw JSON-ish value texts: valid, boundary, wrong-typed, lenient-parser and +# syntax-error forms. Syntax errors abort the rest of a load, as in vanilla. +TOKENS = [ + 'true', 'false', 'TRUE', 'False', '"true"', '0', '1', '2', '3', '4', '5', '-1', '-3', '7', '10', '11', '12', '13', + '16', '27', '29', '30', '31', '32', '33', '60', '65', '69', '70', '71', '100', '109', '110', '111', '120', '128', + '129', '130', '255', '256', '260', '261', '1000', '2147483646', '2147483647', '2147483648', '-2147483648', + '0.0', '0.1', '0.25', '0.3', '0.5', '0.75', '0.77', '0.99', '1.0', '1.5', '2.0', '2.5', '5.0', '5.5', '6.0', + '10.0', '10.5', '-0.5', '-0.0', '1e0', '1e1', '1E-2', '1e2', '2.5e-1', '0.0001', '1e30', '12.7', '4.99', + '"fast"', '"fancy"', '"fabulous"', '"custom"', '"afk"', '"minimized"', '"left"', '"right"', '"default"', + '"opengl"', '"all"', '"none"', '"limited"', '"never"', '"pause"', '"pause_and_toast"', '"DEFAULT"', '"FREQUENT"', + '"CONSTANT"', '"false"', '"movement"', '"Fast"', "'fast'", 'fast', 'afk', 'left', 'abc', '', ' ', '""', 'null', + '[]', '[1,2]', '["vanilla"]', '["vanilla","file/x.zip"]', '{}', '[vanilla,a]', '["a&=\'"]', '0.5f', '.5', + '007', '+1', 'NaN', 'Infinity', '-Infinity', '0x10', '1 2', '"unterminated', '{', ']', '1,2', '0.5 # note', + '0.5 // note', '/* c */ 0.5', '0.5;', ')]}\'\n0.5', 'tRuE', 'nul', 'true false', +] +KEY_TOKENS = [ + 'key.keyboard.w', 'key.keyboard.unknown', 'key.mouse.left', 'key.mouse.9', 'key.mouse.99', 'key.keyboard.200', + 'key.keyboard.007', 'key.keyboard.-5', 'key.keyboard.+4', 'key.keyboard.', 'key.keyboard', 'key.mouse', 'key.mousefoo', + 'key.keyboardX5', 'key.keyboard.abc', 'key.keyboard.f13', 'key.keyboard.keypad.0', 'key.keyboard.right.shift', + '', 'w', 'key.w', 'scancode.17', 'key.keyboard.4294967296', 'key.keyboard.2147483647', 'key.keyboard.2147483648', + 'KEY.KEYBOARD.W', 'key.keyboard.menu', 'key.keyboard.f24', +] +PLAIN_TOKENS = ['true', 'false', 'True', '1', '0', 'yes', '', ' true', 'abc', '5', '-1', '2147483648', '+3', '007', '1.0'] +STRING_TOKENS = ['en_us', 'FR_fr', '', ' a:b ', 'a:b:c', 'Ünïcode', '"quoted"', 'x' * 300] +TAIL = 'musicFrequency:"FREQUENT"\nmodelPart_hat:false\n' # shows whether a load was aborted + + +def option_keys(): + """Option-instance keys, read from the Rust table through the probe-independent + list below (generated from VanillaOptionsTableExporter output).""" + return ALL_KEYS + + +# Every key the 26.3 Options writes, in processing order (verified by the +# defaults case: a mismatch in either name or order fails the comparison). +ALL_KEYS = [ + 'ao', 'biomeBlendRadius', 'chunkSectionFadeInTime', 'cutoutLeaves', 'enableVsync', 'entityDistanceScaling', + 'entityShadows', 'forceUnicodeFont', 'japaneseGlyphVariants', 'fov', 'fovEffectScale', 'darknessEffectScale', + 'glintSpeed', 'glintStrength', 'preferredGraphicsBackend', 'graphicsPreset', 'prioritizeChunkUpdates', + 'fullscreen', 'exclusiveFullscreen', 'macFullscreenMenuVisibility', 'gamma', 'guiScale', 'debugGuiScale', + 'maxAnisotropyBit', 'textureFiltering', 'maxFps', 'improvedTransparency', 'inactivityFpsLimit', 'mipmapLevels', + 'narrator', 'particles', 'reducedDebugInfo', 'renderClouds', 'cloudRange', 'renderDistance', + 'simulationDistance', 'screenEffectScale', 'soundDevice', 'vignette', 'weatherRadius', 'autoJump', + 'rotateWithMinecart', 'operatorItemsTab', 'autoSuggestions', 'chatColors', 'chatLinks', 'chatLinksPrompt', + 'discrete_mouse_scroll', 'invertXMouse', 'invertYMouse', 'realmsNotifications', 'showSubtitles', + 'directionalAudio', 'bobView', 'toggleCrouch', 'toggleSprint', 'toggleAttack', 'toggleUse', 'sprintWindow', + 'darkMojangStudiosBackground', 'hideLightningFlashes', 'hideSplashTexts', 'mouseSensitivity', + 'damageTiltStrength', 'highContrast', 'highContrastBlockOutline', 'narratorHotkey', 'resourcePacks', + 'incompatibleResourcePacks', 'lastServer', 'lang', 'chatVisibility', 'chatOpacity', 'chatLineSpacing', + 'textBackgroundOpacity', 'backgroundForChatOnly', 'hideServerAddress', 'advancedItemTooltips', + 'pauseOnLostFocus', 'overrideWidth', 'overrideHeight', 'chatHeightFocused', 'chatDelay', 'chatHeightUnfocused', + 'chatScale', 'chatWidth', 'notificationDisplayTime', 'useNativeTransport', 'mainHand', 'attackIndicator', + 'tutorialStep', 'mouseWheelSensitivity', 'allowCursorChanges', 'quitShortcuts', 'ctrlClickEmulatesRightClick', + 'glDebugVerbosity', 'skipMultiplayerWarning', 'hideMatchedNames', 'joinedFirstServer', 'syncChunkWrites', + 'showAutosaveIndicator', 'allowServerListing', 'inGameNotification', 'sharePresence', 'onlyShowSecureChat', + 'saveChatDrafts', 'panoramaScrollSpeed', 'telemetryOptInExtra', 'onboardAccessibility', + 'menuBackgroundBlurriness', 'startedCleanly', 'musicToast', 'musicFrequency', +] +PLAIN = {'lastServer', 'lang', 'hideServerAddress', 'advancedItemTooltips', 'pauseOnLostFocus', 'overrideWidth', + 'overrideHeight', 'useNativeTransport', 'glDebugVerbosity', 'skipMultiplayerWarning', 'joinedFirstServer', + 'syncChunkWrites', 'onboardAccessibility', 'startedCleanly'} +PLAIN_STRINGS = {'lastServer', 'lang'} +MAPPINGS = None +SOUNDS = ['master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice', 'ui'] +PARTS = ['cape', 'jacket', 'left_sleeve', 'right_sleeve', 'left_pants_leg', 'right_pants_leg', 'hat'] + + +def write(directory, index, text, newline='\n'): + (directory / f'{index:05d}.txt').write_bytes(text.replace('\n', newline).encode('utf-8')) + + +def make_cases(build): + directory = build / 'cases' + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir() + rng = random.Random(0x4f5054) + n = 0 + # The no-file case is named absent.txt so the oracle skips the copy. + (directory / 'absent.txt').write_text('') + n += 1 + header = f'version:{VERSION}\n' + # One option per file with each token: isolates every codec path. + for key in ALL_KEYS: + tokens = PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else ( + STRING_TOKENS if key in PLAIN_STRINGS else TOKENS) + for token in tokens: + write(directory, n, f'{header}{key}:{token}\n{TAIL}') + n += 1 + # Round trips of values the game itself would save. + for key in ALL_KEYS: + write(directory, n, f'{header}{key}:{rng.choice(TOKENS)}\n{key}:{rng.choice(TOKENS)}\n') + n += 1 + # Key mappings, sound volumes and model parts. + keys = ['key.attack', 'key.use', 'key.forward', 'key.sneak', 'key.sprint', 'key.hotbar.1', 'key.swapOffhand', + 'key.debug.modifier', 'key.debug.profilingChart', 'key.spectatorHotbar', 'key.nonexistent'] + for key in keys: + for token in KEY_TOKENS: + write(directory, n, f'{header}key_{key}:{token}\n{TAIL}') + n += 1 + for source in SOUNDS + ['nonexistent']: + for token in TOKENS[:60]: + write(directory, n, f'{header}soundCategory_{source}:{token}\n{TAIL}') + n += 1 + for part in PARTS + ['nonexistent']: + for token in PLAIN_TOKENS: + write(directory, n, f'{header}modelPart_{part}:{token}\n') + n += 1 + # Random multi-option files, some with CRLF/CR line ends, noise and duplicates. + syntax_errors = {'1 2', '"unterminated', '{', ']', '1,2', 'true false', '0.5 // note'} + safe = [t for t in TOKENS if t not in syntax_errors] + for _ in range(1500): + lines = [] if rng.random() < 0.1 else [f'version:{VERSION}'] + for _ in range(rng.randrange(1, 40)): + key = rng.choice(ALL_KEYS) + pool = safe if rng.random() < 0.9 else TOKENS + lines.append(f'{key}:{rng.choice(PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else pool)}') + if rng.random() < 0.05: + lines.append(rng.choice(['', 'garbage', ':', 'novalue:', ':novalue', 'a:b:c', 'fullscreenResolution:1920x1080@60:24'])) + newline = rng.choice(['\n', '\n', '\r\n', '\r']) + write(directory, n, '\n'.join(lines) + rng.choice(['', '\n']), newline) + n += 1 + # Older files exercise the data fixers; each version boundary of the OPTIONS fixers. + legacy = [ + 'fancyGraphics:true\nao:2\nlang:EN_US\nchatOpacity:0.4\nmenuBackgroundBlurriness:0.5\nkey_key.forward:17\n' + 'key_key.attack:-100\nkey_key.use:-99\nkey_key.pickItem:-98\nkey_key.jump:-95\nresourcePacks:["programer_art"]\n' + 'showNowPlayingToast:true\n', + 'fancyGraphics:false\nao:0\nkey_key.forward:key.w\nkey_key.swapHands:key.f\nmouseSensitivity:0.5\n', + 'graphicsMode:2\nao:1\nmenuBackgroundBlurriness:abc\nchatOpacity:abc\nshowNowPlayingToast:false\n', + 'graphicsMode:0\nmenuBackgroundBlurriness:0.35\nchatOpacity:1e-3\n', + 'graphicsMode:1\nlang:Fr_Ca\nresourcePacks:["a","programer_art"]\nincompatibleResourcePacks:["programer_art"]\n', + 'key_key.forward:abc\n', 'key_key.forward:\n', 'key_key.attack:k\n', 'chatOpacity:Infinity\n', + 'chatOpacity: 0.5d\n', 'menuBackgroundBlurriness:0.25\n', 'menuBackgroundBlurriness:1.04999\n', + ] + versions = [-1, 0, 100, 504, 505, 815, 816, 1343, 1344, 1445, 1446, 1935, 1936, 2555, 2556, 2557, 2558, 3200, 3201, + 3213, 3214, 3318, 3319, 3942, 3943, 4650, 4651, 4660, 4661, 4891, 4892, 5022, 5023, 5024, 9999] + for version in versions: + for body in legacy: + write(directory, n, f'version:{version}\n{body}') + n += 1 + for body in legacy: + write(directory, n, body) + n += 1 + write(directory, n, f'version:abc\n{body}') + n += 1 + write(directory, n, f'version: 5023\n{body}') + n += 1 + for text in ['fullscreenResolution:1920x1080@60:24\n', 'fullscreenResolution:\n', 'fov:abc\nfullscreenResolution:x\n', + 'fov:1 2\nfullscreenResolution:x\n', 'version:5023\nfov:0.5\n', 'FOV:0.5\n', ' fov:0.5\n', 'fov :0.5\n']: + write(directory, n, f'version:{VERSION}\n{text}') + n += 1 + return directory, n + + +def main(): + scope = ('Real Options.load and Options.save (26.3) on generated options.txt files: the full option table in ' + 'processing order with defaults, every codec/validator path (int ranges, quantised doubles, unit doubles with ' + 'boolean alternative, string and id enums with wrapping, clouds, fov, frame limit, scroll sensitivity), plain ' + 'fields, lenient Gson parsing and syntax-error aborts, key mappings (names, scancode-number forms, unbinding), ' + 'sound volumes, model parts, line endings, the OPTIONS data fixers across version boundaries, and the ' + 'KeyMapping table (order, defaults, categories, toggle mappings). Does not cover option screens or ' + 'runtime side effects of setting an option.') + harness.differential( + 'rust-options-parity', 'VanillaOptionsOracle', 'options_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/options_file.rs', lab.ROOT / 'crates/horizon-client/src/options_fixes.rs', + lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client/src/key_names.rs', + lab.ROOT / 'crates/horizon-client/src/keybinds.rs']) + + +if __name__ == '__main__': + main() From 513004936d195237b470c174ac2fe9fd0829436f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:17:24 +0200 Subject: [PATCH 04/24] Keep container names and saddle components, order and search the recipe book like vanilla Containers now remember a custom name: it is read and saved as CustomName, taken from the item when placed (including by dispensers), shown as the screen title of chests, furnaces, the brewing stand, hoppers, dispensers and the crafter, and given back to the dropped item when the block is broken. Saddles on pigs, striders and horses are kept as full item stacks instead of a flag, so their components survive taming, the horse menu, dispensers, saving and death drops. The recipe book lists dye, transmute (shulker box, bundle, map cloning) and tipped arrow recipes, searches the tooltip lines and ids of a collection's results the way the vanilla search tree does, and squeezes new recipes' tabs and buttons once, saving the pending recipes as toBeDisplayed. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/chunk.rs | 3 + crates/horizon-client/src/crafting.rs | 59 ++++++++++ crates/horizon-client/src/entity_nbt.rs | 30 ++--- crates/horizon-client/src/game.rs | 16 +++ crates/horizon-client/src/game/creatures.rs | 4 +- crates/horizon-client/src/game/dispenser.rs | 3 +- crates/horizon-client/src/game/machines.rs | 1 + .../src/game/machines/crafter.rs | 2 +- crates/horizon-client/src/game/mount_menu.rs | 11 +- crates/horizon-client/src/game/mounts.rs | 6 +- crates/horizon-client/src/game/recipe_book.rs | 108 ++++++++++++++++-- crates/horizon-client/src/game/stations.rs | 8 +- crates/horizon-client/src/game/storage.rs | 42 ++++++- crates/horizon-client/src/hud.rs | 8 ++ crates/horizon-client/src/mobs.rs | 22 ++++ crates/horizon-client/src/recipe_book.rs | 94 +++++++++++---- crates/horizon-client/src/save.rs | 17 ++- crates/horizon-client/src/streaming.rs | 3 + crates/horizon-client/src/world.rs | 3 + 19 files changed, 376 insertions(+), 64 deletions(-) diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index d5e65655c..6e76783ba 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -100,6 +100,8 @@ pub struct Chunk { pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>, + /// `CustomName` of the container block entities (shown as the screen title). + pub block_names: Vec<((i32, i32, i32), String)>, /// Generation postprocessing marks (ProtoChunk.postProcessing) as world /// positions, applied once by LevelChunk.postProcessGeneration. pub postprocess: Vec<[i32; 3]>, @@ -125,6 +127,7 @@ impl Chunk { light_loaded: false, fresh: false, block_entities: Vec::new(), + block_names: Vec::new(), structure_refs: Vec::new(), postprocess: Vec::new(), saved: None, diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index cf2e43f03..754c701b3 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -253,6 +253,65 @@ pub enum Special { /// `RepairItemRecipe`: two damaged items of one kind. RepairItem, } +impl Special { + /// The recipe-book displays of a learnable (non-custom) crafting recipe: + /// its layout and result. + pub fn book_displays(&self) -> Vec<(crate::recipe_book::Display, ItemStack)> { + use crate::recipe_book::Display; + match self { + Self::Transmute { + input, + material, + min, + max, + add_count, + result, + } => (*min..=*max) + .map(|n| { + let mut ingredients = vec![input.clone()]; + ingredients.extend(std::iter::repeat_n(material.clone(), n)); + let mut made = result.create(); + if result.item.is_none() { + // The result keeps the input's item: show the first one. + if let Some(first) = input.0.iter().min() { + made.item = Arc::from(first.as_str()); + } + } + if *add_count { + made.count += n as u32; + } + (Display::Shapeless(ingredients), made) + }) + .collect(), + Self::Dye { + target, + dye, + result, + } => vec![( + Display::Shapeless(vec![target.clone(), dye.clone()]), + result.create(), + )], + Self::Imbue { + source, + material, + result, + } => { + let cells = (0..9) + .map(|i| Some(if i == 4 { source } else { material }.clone())) + .collect(); + vec![( + Display::Shaped { + width: 3, + height: 3, + cells, + }, + result.create(), + )] + } + _ => Vec::new(), + } + } +} /// `CraftingInput`: the occupied bounding box of the grid. pub struct Input<'a> { pub width: usize, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index ea44c09be..0cc6b4ec8 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -211,11 +211,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&"Items".into()); } let mut equipment = Vec::new(); - if m.extra.saddled { - equipment.push(( - "saddle", - Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]), - )); + if let Some(saddle) = m.saddle_item() { + equipment.push(("saddle", crate::save::item_to_nbt(&saddle))); } if let Some(armor) = &m.extra.head { equipment.push(( @@ -241,11 +238,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Some(Tag::Compound(c)) => c.clone(), _ => Compound::new(), }; - if m.extra.saddled { - equipment.insert( - "saddle".into(), - Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]), - ); + if let Some(saddle) = m.saddle_item() { + equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle)); } else { equipment.remove(&"saddle".into()); } @@ -499,8 +493,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.species(), crate::mobs::Species::Pig | crate::mobs::Species::Strider ) { - m.extra.saddled = - tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle"); + let saddle = tag + .get("equipment") + .and_then(|e| e.get("saddle")) + .and_then(crate::save::item_from_nbt); + if saddle.is_some() || flag(tag, "Saddle") { + m.set_saddle(Some(saddle.unwrap_or_else(|| { + crate::items::ItemStack::new("minecraft:saddle", 1) + }))); + } } if crate::mobs::equine::is_equine(m.species()) { m.extra.tame = flag(tag, "Tame"); @@ -514,7 +515,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.items = crate::save::decode_items(tag.get("Items"), 15); } let eq = tag.get("equipment"); - m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some(); + m.set_saddle( + eq.and_then(|e| e.get("saddle")) + .and_then(crate::save::item_from_nbt), + ); m.extra.head = eq .and_then(|e| e.get("body")) .and_then(|b| text(b.get("id"))) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e8d7eb2e4..afbe3345c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -630,6 +630,8 @@ struct Game<'a> { pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>, /// Layers of broken banners waiting for their dropped item. pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>, + /// Custom names of broken containers, for the dropped item (`copy_components`). + pending_names: HashMap<[i32; 3], (String, String)>, /// The recipe book of the open screen (game/recipe_book.rs). recipe_ui: recipe_book::RecipeUi, /// The horse inventory (game/mount_menu.rs). @@ -1005,6 +1007,7 @@ impl Game<'_> { /// Block.popResource fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) { self.attach_shulker_contents(pos, &mut stack); + self.attach_container_name(pos, &mut stack); self.attach_banner_layers(pos, &mut stack); let r = &mut self.world.random; let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25; @@ -1838,6 +1841,7 @@ impl Game<'_> { .block_entities .insert((target[0], target[1], target[2]), entity); self.fill_placed_box(target, &stack); + self.name_placed_container(target, &stack); self.fill_placed_banner(target, &stack); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); @@ -3249,6 +3253,7 @@ impl Game<'_> { } }; part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy); + let title = &self.container_title(title.to_owned()); let tw = HudBatch::text_width(atlas, title); batch.text(atlas, title, ox + (176.0 - tw) / 2.0, oy + 6.0, grey, false); batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); @@ -4416,6 +4421,13 @@ impl Game<'_> { .filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z) .map(|(p, e)| (*p, e.clone())) .collect(); + c.block_names = self + .world + .block_names + .iter() + .filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z) + .map(|(p, n)| (*p, n.clone())) + .collect(); self.attach_save_data(&mut c); Arc::new(c) } @@ -6999,6 +7011,9 @@ impl Game<'_> { self.world .block_entities .retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); + self.world + .block_names + .retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); } if !modified.is_empty() && let Err(e) = self @@ -7751,6 +7766,7 @@ pub fn run() -> Result<()> { ender_open: None, pending_shulker: HashMap::new(), pending_banner: HashMap::new(), + pending_names: HashMap::new(), recipe_ui: Default::default(), mount_menu: Default::default(), hook: None, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 81f17ed01..afba945ab 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -727,8 +727,8 @@ impl Game<'_> { } // Saddles, horse armour and chests always drop. let mut gear: Vec<&str> = Vec::new(); - if m.extra.saddled { - gear.push("minecraft:saddle"); + if let Some(saddle) = m.saddle_item() { + self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10); } // WitherBoss.dropCustomDeathLoot. if m.species() == Species::Wither { diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 75f39881d..9eb27a255 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -578,7 +578,7 @@ impl Game<'_> { (_, Some(1)) => m.extra.chest = Some(item.clone()), (_, Some(2)) => m.extra.legs = Some(item.clone()), (_, Some(3)) => m.extra.feet = Some(item.clone()), - ("saddle", _) => m.extra.saddled = true, + ("saddle", _) => m.set_saddle(Some(one.clone())), _ => m.extra.head = Some(item.clone()), } // setGuaranteedDrop / setPersistenceRequired. @@ -1155,6 +1155,7 @@ impl Game<'_> { if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { self.world.block_entities.insert(target, entity); self.fill_placed_box([target.0, target.1, target.2], &stack); + self.name_placed_container([target.0, target.1, target.2], &stack); } let sounds = self.res.facts.get(state).sounds.clone(); self.audio.play( diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 5f75bf86d..418d0eafc 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -746,6 +746,7 @@ impl Game<'_> { batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX); } let grey = horizon_client::hud::rgba(64, 64, 64, 255); + let title = &self.container_title(title.to_owned()); let title_x = if screen == Screen::Hopper { 8.0 } else { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 470424c44..1c8a558e6 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -270,7 +270,7 @@ impl Game<'_> { 256.0, ); let grey = rgba(64, 64, 64, 255); - let title = self.translate("container.crafter", "Crafter"); + let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 3e33872cb..8fe819a96 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -67,10 +67,7 @@ impl Game<'_> { mob: m.id, species, columns, - saddle: m - .extra - .saddled - .then(|| ItemStack::new("minecraft:saddle", 1)), + saddle: m.saddle_item(), armor: m .extra .head @@ -137,18 +134,18 @@ impl Game<'_> { let Some(index) = self.mount_mob_index(open.mob) else { return; }; - let (saddle, armor) = (open.saddle.is_some(), open.armor.clone()); + let (saddle, armor) = (open.saddle.clone(), open.armor.clone()); let items = open.items.clone(); let m = &mut self.mobs[index]; let at = m.center(); - let sound = if saddle && !m.extra.saddled { + let sound = if saddle.is_some() && !m.extra.saddled { Some("minecraft:entity.horse.saddle") } else if armor.is_some() && m.extra.head.is_none() { Some("minecraft:entity.horse.armor") } else { None }; - m.extra.saddled = saddle; + m.set_saddle(saddle); if open.show_armor { m.extra.head = armor.map(|a| a.item); } diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index bfe73d235..fdd6c5ece 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -38,13 +38,14 @@ impl Game<'_> { } /// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one. fn interact_steerable(&mut self, index: usize, item: &str) -> bool { + let held = self.inventory[self.selected].clone(); let m = &mut self.mobs[index]; if m.is_baby() || !m.alive() || Some(m.id) == self.riding { return false; } let at = m.center(); if item == "minecraft:saddle" && !m.extra.saddled { - m.extra.saddled = true; + m.set_saddle(held); let sound = if m.species() == Species::Strider { "minecraft:entity.strider.saddle" } else { @@ -91,6 +92,7 @@ impl Game<'_> { } /// `AbstractHorse.mobInteract`. Returns whether the click was used. pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool { + let held = self.inventory[self.selected].clone(); let m = &self.mobs[index]; let species = m.species(); if matches!(species, Species::Pig | Species::Strider) { @@ -118,7 +120,7 @@ impl Game<'_> { let at = m.center(); let tamed = m.extra.tame; let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled { - m.extra.saddled = true; + m.set_saddle(held); Some("minecraft:entity.horse.saddle") } else if item.ends_with("_horse_armor") && species == Species::Horse diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 658db4ada..60fc4ec50 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -68,6 +68,9 @@ pub(super) struct RecipeUi { overlay: Option, view: View, view_key: u64, + /// Squeeze animations of new recipes: ticks left per button index and tab. + button_anim: Vec<(usize, f32)>, + tab_anim: Vec<(Tab, f32)>, } impl RecipeUi { @@ -179,6 +182,11 @@ impl Game<'_> { return; } self.ensure_book(); + for id in recipes { + if !self.level.recipe_book.to_be_displayed.contains(id) { + self.level.recipe_book.to_be_displayed.push(id.clone()); + } + } let icon = self .recipe_ui .book @@ -291,6 +299,71 @@ impl Game<'_> { if self.recipe_ui.page >= pages.max(1) { self.recipe_ui.page = 0; } + self.start_new_recipe_animations(book_type); + } + /// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs + /// holding a recipe still to be displayed squeeze, and the buttons of the + /// shown page squeeze once and clear their recipes' highlight. + fn start_new_recipe_animations(&mut self, book_type: BookType) { + if self.level.recipe_book.to_be_displayed.is_empty() { + return; + } + let Some(book) = self.recipe_ui.book.take() else { + return; + }; + let unlocked = self.unlocked_recipes(); + let filtering = self.book_filtering(book_type); + let (gw, gh) = self.book_grid(); + let available = self.book_available(book_type); + let shown = |e: &Entry| { + (book_type != BookType::Crafting || e.fits(gw, gh)) + && (!filtering || available.can_craft(&e.requirements())) + }; + let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id); + let mut tabs = Vec::new(); + for tab in self.recipe_ui.view.tabs.clone() { + if tab == Tab::Search { + continue; + } + let hit = book + .collections(&unlocked, book_type, tab) + .iter() + .flat_map(|c| c.entries.iter()) + .any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i])); + if hit { + tabs.push((tab, 15.0)); + } + } + self.recipe_ui.tab_anim = tabs; + let first = self.recipe_ui.page * 20; + let mut buttons = Vec::new(); + let mut cleared = Vec::new(); + for (n, button) in self + .recipe_ui + .view + .buttons + .iter() + .skip(first) + .take(20) + .enumerate() + { + let ids: Vec<&String> = button + .entries + .iter() + .map(|e| &book.entries[e.0].id) + .filter(|id| self.level.recipe_book.to_be_displayed.contains(*id)) + .collect(); + if !ids.is_empty() { + buttons.push((first + n, 15.0)); + cleared.extend(ids.into_iter().cloned()); + } + } + self.level + .recipe_book + .to_be_displayed + .retain(|id| !cleared.contains(id)); + self.recipe_ui.button_anim = buttons; + self.recipe_ui.book = Some(book); } fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View { let Some(book) = ui.book.as_ref() else { @@ -329,9 +402,8 @@ impl Game<'_> { continue; } if !query.is_empty() - && !c.entries.iter().any(|&i| { - let e = &book.entries[i]; - book.matches_search(e, &query, &self.res.names.item(&e.result.item)) + && !book.collection_matches(&c.entries, &query, &|stack| { + self.stack_tooltip(stack).into_iter().map(|l| l.0).collect() }) { continue; @@ -972,26 +1044,30 @@ impl Game<'_> { .tab .filter(|t| tabs.contains(t)) .unwrap_or(Tab::Search); - let mut tab_icons = Vec::new(); + let frame = self.frame_ticks; for (n, tab) in tabs.iter().enumerate() { let (x, y) = self.tab_pos(xo, yo, n); let selected = *tab == current; let name = if selected { "tab_selected" } else { "tab" }; let sx = if selected { x - 2.0 } else { x }; + let start = batch.vertices.len(); batch.sprite(&self.res.atlas, &sprite(name), sx, y); let (a, b) = tab.icons(); let shift = if selected { -2.0 } else { 0.0 }; match b { Some(b) => { - tab_icons.push((a, x + 3.0 + shift, y + 5.0)); - tab_icons.push((b, x + 14.0 + shift, y + 5.0)); + self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0); + self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0); } - None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)), + None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0), + } + if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) { + let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); + batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze); + entry.1 -= frame; } } - for (item, x, y) in tab_icons { - self.draw_item(batch, &ItemStack::new(item, 1), x, y); - } + self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0); // Craftable filter. let filtering = self.book_filtering(book_type); let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0); @@ -1019,6 +1095,7 @@ impl Game<'_> { break; }; let (x, y) = Self::button_pos(xo, yo, n); + let anim_start = batch.vertices.len(); let many = button.entries.len() > 1; let name = match (button.craftable(), many) { (true, true) => "slot_many_craftable", @@ -1048,6 +1125,16 @@ impl Game<'_> { offset -= 1.0; } self.draw_item_plain(batch, &stack, x + offset, y + offset); + if let Some(entry) = self + .recipe_ui + .button_anim + .iter_mut() + .find(|e| e.0 == first + n) + { + let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin(); + batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze); + entry.1 -= self.frame_ticks; + } if inside(cursor, x, y, 25.0, 25.0) && !overlay_open { let mut lines = self.stack_tooltip(&stack); if many { @@ -1059,6 +1146,7 @@ impl Game<'_> { tooltip = Some(lines); } } + self.recipe_ui.button_anim.retain(|e| e.1 > 0.0); // Page arrows and number. if pages > 1 { let page_text = self diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 9d01ff059..90892be56 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1305,7 +1305,13 @@ impl Game<'_> { ); } } - let title = self.translate("container.brewing", "Brewing Stand"); + let default = self.translate("container.brewing", "Brewing Stand"); + let title = self + .station + .as_ref() + .and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2]))) + .cloned() + .unwrap_or(default); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 865852fc7..cf9a3a1ac 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -11,6 +11,14 @@ impl Game<'_> { /// Block-entity contents on removal: shulker boxes keep theirs for the /// dropped box (`copy_components`), other containers spill them. pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) { + if let Some(name) = self + .world + .block_names + .remove(&(pos[0], pos[1], pos[2])) + .filter(|_| !matches!(entity, BlockEntity::Banner(_))) + { + self.pending_names.insert(pos, (block.to_owned(), name)); + } if let BlockEntity::Banner(banner) = entity { self.pending_banner.insert(pos, banner); return; @@ -41,6 +49,38 @@ impl Game<'_> { stack.data_mut().container = contents; } } + /// The custom name a broken container drops with (`copy_components`). + pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) { + if self + .pending_names + .get(&pos) + .is_some_and(|(item, _)| **item == *stack.item) + && let Some((_, name)) = self.pending_names.remove(&pos) + { + stack.data_mut().custom_name = Some(name); + } + } + /// A placed container takes the item's custom name. + pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) { + let key = (pos[0], pos[1], pos[2]); + if let Some(name) = stack.custom_name() + && !matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Banner(_) | BlockEntity::Sign(_)) + ) + { + self.world.block_names.insert(key, name.to_owned()); + } + } + /// The custom name of the open container, or its default title + /// (a double chest is named by whichever half has a name). + pub(super) fn container_title(&self, default: String) -> String { + self.container_parts() + .iter() + .find_map(|(key, _)| self.world.block_names.get(key)) + .cloned() + .unwrap_or(default) + } /// A placed shulker box takes the item's contents. pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) { let Some(data) = stack.data() else { return }; @@ -234,7 +274,7 @@ impl Game<'_> { _ if rows > 3 => ("container.chestDouble", "Large Chest"), _ => ("container.chest", "Chest"), }; - self.translate(key, fallback) + self.container_title(self.translate(key, fallback)) } /// `ContainerScreen` / `ShulkerBoxScreen`: the background with its /// container rows, the title and the inventory label. diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 93e011d51..ed1a91c15 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -278,6 +278,14 @@ impl HudBatch { /// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the /// GUI scissor): axis-aligned quads are cut with their UVs, others are /// kept or dropped by their centre. + /// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose + /// matrix of translate, scale, translate back). + pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) { + for v in &mut self.vertices[start..] { + v.pos[0] = cx + (v.pos[0] - cx) * sx; + v.pos[1] = cy + (v.pos[1] - cy) * sy; + } + } pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) { let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec(); self.vertices.truncate(start); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 929f205ac..dea18eca2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -438,6 +438,9 @@ pub struct Extra { /// `Mob.canPickUpLoot` (also lets dispensers equip it). pub pick_up_loot: bool, pub saddled: bool, + /// The saddle's components (name, enchantments...) when it is not a bare + /// one; `saddled` stays the gameplay flag. + pub saddle_stack: Option, pub chested: bool, /// The chest contents of a donkey or mule (15 slots). pub items: Vec>, @@ -1136,3 +1139,22 @@ pub fn render_model( } } } + +impl Mob { + /// The saddle worn, with its components. + pub fn saddle_item(&self) -> Option { + self.extra.saddled.then(|| { + self.extra + .saddle_stack + .clone() + .unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1)) + }) + } + /// Wear (or take off) a saddle stack, keeping its components. + pub fn set_saddle(&mut self, saddle: Option) { + self.extra.saddled = saddle.is_some(); + self.extra.saddle_stack = saddle + .map(|s| crate::items::ItemStack { count: 1, ..s }) + .filter(|s| s.damage != 0 || s.extra.is_some()); + } +} diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 4aeb50f7c..674882b8b 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -280,7 +280,20 @@ impl Book { ingredients, result, } => (Display::Shapeless(ingredients.clone()), result), - Recipe::Special(_) => continue, + // Custom recipes are never learnable; the others show one + // display per material count (TransmuteRecipe.display). + Recipe::Special(special) => { + for (display, result) in special.book_displays() { + entries.push(Entry { + id: format!("minecraft:{name}"), + category: crafting_category(&category), + group: group(&grp), + display, + result, + }); + } + continue; + } }; entries.push(Entry { id: format!("minecraft:{name}"), @@ -376,24 +389,33 @@ impl Book { items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone())); items } - /// `RecipeCollection` search: the result's name or registry path, or - /// `@namespace`. - pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool { + /// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a + /// `FullTextSearchTree`): without a colon the text must occur in a + /// tooltip line of a result item of the collection; `namespace:path` + /// needs the namespace in a result id and the path in an id or a line. + pub fn collection_matches( + &self, + entries: &[usize], + query: &str, + tooltip: &dyn Fn(&ItemStack) -> Vec, + ) -> bool { let query = query.to_lowercase(); - if let Some(ns) = query.strip_prefix('@') { - return entry - .result - .item - .split(':') - .next() - .is_some_and(|n| n.starts_with(ns)); - } - name.to_lowercase().contains(&query) - || entry - .result - .item - .trim_start_matches("minecraft:") - .contains(&query) + let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect(); + let in_lines = |text: &str| { + results + .iter() + .any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text))) + }; + let Some((namespace, path)) = query.split_once(':') else { + return in_lines(&query); + }; + let (namespace, path) = (namespace.trim(), path.trim()); + let id = |r: &&ItemStack| { + let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item)); + (ns.to_lowercase(), p.to_lowercase()) + }; + results.iter().any(|r| id(r).0.contains(namespace)) + && (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path)) } } @@ -524,6 +546,8 @@ pub struct Settings { pub filtering: [bool; 4], /// Unlocked recipe ids (`recipes`). pub recipes: Vec, + /// Recipes not yet shown in the book (`toBeDisplayed`): they animate once. + pub to_be_displayed: Vec, } impl Settings { pub fn read(tag: Option<&Tag>) -> Self { @@ -535,18 +559,21 @@ impl Settings { s.open[b.index()] = flag(open); s.filtering[b.index()] = flag(filter); } - if let Some(Tag::List(list)) = tag.get("recipes") { - s.recipes = list + let ids = |key: &str| match tag.get(key) { + Some(Tag::List(list)) => list .iter() .filter_map(|t| match t { Tag::String(id) => Some(id.to_string_lossy()), _ => None, }) - .collect(); - } + .collect(), + _ => Vec::new(), + }; + s.recipes = ids("recipes"); + s.to_be_displayed = ids("toBeDisplayed"); s } - /// The compound written to the player file; `toBeDisplayed` stays empty. + /// The compound written to the player file. pub fn write(&self) -> Tag { let mut entries: Vec<(&str, Tag)> = Vec::new(); for b in BookType::ALL { @@ -558,7 +585,7 @@ impl Settings { Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect()) }; entries.push(("recipes", list(&self.recipes))); - entries.push(("toBeDisplayed", Tag::List(Vec::new()))); + entries.push(("toBeDisplayed", list(&self.to_be_displayed))); Tag::compound(entries) } } @@ -672,6 +699,25 @@ mod tests { assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1); } #[test] + fn search_reads_tooltip_lines_and_ids() { + let book = Book { + entries: vec![Entry { + id: "minecraft:stick".into(), + category: Category::CraftingMisc, + group: None, + display: Display::Shapeless(Vec::new()), + result: ItemStack::new("minecraft:stick", 4), + }], + order: HashMap::new(), + }; + let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()]; + assert!(book.collection_matches(&[0], "STI", &lines)); + // Plain text searches tooltips only, not the registry path. + assert!(!book.collection_matches(&[0], "stick:", &lines)); + assert!(book.collection_matches(&[0], "minecraft:stic", &lines)); + assert!(!book.collection_matches(&[0], "other:stick", &lines)); + } + #[test] fn settings_round_trip() { let mut s = Settings::default(); s.open[BookType::Furnace.index()] = true; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 7ab494bbf..f81a13cea 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -730,7 +730,15 @@ pub fn encode_with( let mut block_entities: Vec = chunk .block_entities .iter() - .map(|(p, e)| encode_block_entity(*p, e, &block_name(p))) + .map(|(p, e)| { + let mut tag = encode_block_entity(*p, e, &block_name(p)); + if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p) + && let Tag::Compound(map) = &mut tag + { + map.insert("CustomName".into(), string(name)); + } + tag + }) .collect(); if let Some(extras) = extras { for raw in &extras.block_entities { @@ -940,7 +948,12 @@ pub fn decode_with( if let Some(Tag::List(entities)) = tag.get("block_entities") { for e in entities { match decode_block_entity(e) { - Some(be) => chunk.block_entities.push(be), + Some(be) => { + if let Some(name) = text(e.get("CustomName")) { + chunk.block_names.push((be.0, name)); + } + chunk.block_entities.push(be); + } None => extras.block_entities.push(e.clone()), } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index c43e82e69..fdaf96332 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -320,6 +320,9 @@ impl Streaming { world .block_entities .extend(std::mem::take(&mut chunk.block_entities)); + world + .block_names + .extend(std::mem::take(&mut chunk.block_names)); let entities = std::mem::take(&mut chunk.entities); if !entities.is_empty() { world.loaded_entities.push(((chunk.x, chunk.z), entities)); diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 657f4635f..fe3d9cc40 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -26,6 +26,8 @@ pub struct World { /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// `BaseContainerBlockEntity.name`: custom names of container block entities. + pub block_names: HashMap<(i32, i32, i32), String>, /// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent /// within spawning range (local difficulty). pub inhabited: HashMap<(i32, i32), i64>, @@ -106,6 +108,7 @@ impl World { loaded_entities: Vec::new(), modified: HashSet::new(), block_entities: HashMap::new(), + block_names: HashMap::new(), inhabited: HashMap::new(), game_time: 0, day_time: 1000, From a0e96053906bba5ab4dc1c7b08b74bb05cde0aa9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:48:16 +0200 Subject: [PATCH 05/24] WIP: paletted containers and mesher changes Work in progress before merging main. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/examples/chunk_bench.rs | 196 +++++ .../examples/section_mesh_fixture.rs | 15 +- crates/horizon-client/src/chunk.rs | 91 ++- crates/horizon-client/src/game/end.rs | 9 +- crates/horizon-client/src/game/remote.rs | 71 +- crates/horizon-client/src/light.rs | 5 +- crates/horizon-client/src/mesher.rs | 16 +- crates/horizon-client/src/save.rs | 116 +-- crates/horizon-client/src/testgen.rs | 8 +- crates/horizon-client/src/vanillagen.rs | 47 +- .../horizon-core/examples/paletted_fixture.rs | 135 ++++ crates/horizon-core/src/lib.rs | 1 + crates/horizon-core/src/paletted.rs | 739 ++++++++++++++++++ .../VanillaPalettedContainerOracle.java | 103 +++ tools/test_paletted_container_parity.py | 99 +++ 15 files changed, 1473 insertions(+), 178 deletions(-) create mode 100644 crates/horizon-client/examples/chunk_bench.rs create mode 100644 crates/horizon-core/examples/paletted_fixture.rs create mode 100644 crates/horizon-core/src/paletted.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java create mode 100644 tools/test_paletted_container_parity.py diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs new file mode 100644 index 000000000..b99f49a2a --- /dev/null +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -0,0 +1,196 @@ +//! Resident chunk storage benchmark: generates a block of vanilla terrain, then +//! reports the resident block/biome memory, the cost of lookups, meshing and +//! lighting on it. +//! +//! chunk_bench [--seed S] [--size N] +#![forbid(unsafe_code)] +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + chunk::{Chunk, MIN_Y, SECTIONS}, + light::{LightTables, light_chunk}, + mesher::{MeshTables, Mesher}, + models, + streaming::{ChunkGenerator, Proto}, + vanillagen::VanillaTerrain, +}; +use horizon_core::biome::BiomeZoom; +use std::{path::PathBuf, sync::Arc, time::Instant}; +type Result = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?); + let flag = |name: &str, default: i64| -> i64 { + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(default) + }; + let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Biomes::load(&root)?; + let tables = MeshTables::new(&assets, &facts, models::load_visibility(&root, assets.registry)?)?; + let light = LightTables::load(&root, assets.registry, &facts)?; + let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?; + let mut worker = terrain.worker(); + + // Protos for size+4 columns, decorated for the inner size+2, finished as size+2. + let started = Instant::now(); + let outer = size + 4; + let mut protos: Vec> = (0..outer * outer) + .map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer))) + .collect(); + eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64()); + let started = Instant::now(); + let inner = size + 2; + for z in 1..=inner { + for x in 1..=inner { + let mut region: [Proto; 9] = std::array::from_fn(|k| { + let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); + protos[((z + dz) * outer + x + dx) as usize].take().expect("proto") + }); + terrain.decorate(&mut worker, &mut region); + for (k, p) in region.into_iter().enumerate() { + let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); + protos[((z + dz) * outer + x + dx) as usize] = Some(p); + } + } + } + eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64()); + let started = Instant::now(); + let mut chunks: Vec = Vec::new(); + for z in 1..=inner { + for x in 1..=inner { + let proto = protos[(z * outer + x) as usize].take().expect("proto"); + let mut chunk = terrain.finish(proto); + chunk.x = x; + chunk.z = z; + chunks.push(chunk); + } + } + let finish = started.elapsed().as_secs_f64(); + println!("finish (proto -> resident chunk): {:.1} ms per chunk", finish * 1e3 / chunks.len() as f64); + + let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); + let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); + + // Light all inner-inner columns. + let started = Instant::now(); + let mut lit = Vec::new(); + for z in 2..inner { + for x in 2..inner { + let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) + }); + let borrowed = horizon_client::mesher::borrow(®ion); + lit.push(((x, z), light_chunk(&borrowed, &light, true))); + } + } + println!("light: {:.2} ms per column", started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64); + let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); + for ((x, z), sections) in lit { + chunks[((z - 1) * inner + x - 1) as usize].sections = sections; + } + let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); + let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); + + // Memory. + let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize); + for chunk in &chunks { + bytes += chunk.heap_bytes(); + for s in &chunk.sections { + sections += 1; + uniform += usize::from(s.is_uniform(s.get(0))); + } + } + println!( + "resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)", + chunks.len(), + sections, + uniform, + bytes as f64 / 1024.0 / chunks.len() as f64, + bytes as f64 / 1048576.0 + ); + + // Meshing. + let mut mesher = Mesher { + nether_shading: false, + assets: &assets, + tables: &tables, + biomes: &biomes, + visibility: tables.visibility.clone(), + zoom: BiomeZoom::new(7), + blend_radius: 2, + smooth_lighting: true, + cutout_leaves: true, + }; + let mut best = f64::MAX; + let mut quads = 0usize; + for _ in 0..3 { + let started = Instant::now(); + let mut jobs = 0; + quads = 0; + for z in 2..inner { + for x in 2..inner { + let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) + }); + let borrowed = horizon_client::mesher::borrow(®ion); + for sy in 0..SECTIONS as i32 { + let mesh = mesher.mesh(&borrowed, sy); + quads += (mesh.solid.len() + mesh.translucent.len()) / 4; + jobs += 1; + } + } + } + best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs)); + } + println!("mesh: {:.1} us per section ({} quads total)", best * 1e6, quads); + + // Random lookups, as collision and entity queries do. + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let started = Instant::now(); + let mut sum = 0u64; + let lookups = 20_000_000u64; + for _ in 0..lookups { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32; + let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32; + let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize]; + let (x, y, z) = ( + (state >> 16) as i32 & 15, + MIN_Y + ((state >> 24) % 384) as i32, + (state >> 40) as i32 & 15, + ); + sum += u64::from(chunk.get(x, y, z)); + } + println!( + "random get: {:.2} ns per lookup (checksum {sum})", + started.elapsed().as_secs_f64() * 1e9 / lookups as f64 + ); + // Coherent scan, as a column or area query does. + let started = Instant::now(); + let mut sum = 0u64; + for _ in 0..4 { + for chunk in &chunks { + for y in MIN_Y..MIN_Y + 384 { + for z in 0..16 { + for x in 0..16 { + sum += u64::from(chunk.get(x, y, z)); + } + } + } + } + } + println!( + "scan get: {:.2} ns per lookup (checksum {sum})", + started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0) + ); + Ok(()) +} diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index d4c710fbc..d17c33466 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -104,14 +104,21 @@ fn scene( blend_radius = int(&field["radius"])?; let default = biomes.id(field["default"].as_str().ok_or("missing default biome")?); for chunk in &mut chunks { - Arc::make_mut(&mut chunk.biomes).fill(default); + for qy in 0..96 { + for cell in 0..16 { + chunk.set_biome_cell(cell & 3, qy, cell >> 2, default); + } + } } for cell in field["cells"].as_array().ok_or("missing biome cells")? { let (qx, qy, qz) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?); let i = chunk_index(qx * 4, qz * 4)?; - let slot = ((qy - MIN_Y / 4) * 16 + (qz & 3) * 4 + (qx & 3)) as usize; - Arc::make_mut(&mut chunks[i].biomes)[slot] = - biomes.id(cell[3].as_str().ok_or("biome name")?); + chunks[i].set_biome_cell( + qx, + qy - MIN_Y / 4, + qz, + biomes.id(cell[3].as_str().ok_or("biome name")?), + ); } } let region: [[Option<&Chunk>; 3]; 3] = diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index d5e65655c..207e8df52 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -2,17 +2,18 @@ //! threads can mesh and light immutable snapshots while the game thread edits //! (copy-on-write through `Arc::make_mut`). use horizon_world::registry::BlockStateId; +use horizon_core::paletted::{PalettedContainer, Strategy}; use std::sync::Arc; pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; pub const SECTIONS: usize = (HEIGHT / 16) as usize; -#[derive(Clone)] -pub enum Blocks { - Uniform(u16), - Full(Box<[u16; 4096]>), -} +/// Block states are `PalettedContainer`s over the pinned registry (35,723 +/// states: a 16-bit global palette); biomes are 4x4x4 containers over the +/// biome table (67 entries: a 7-bit global palette). +pub const BLOCK_STRATEGY: Strategy = Strategy::blocks(16); +pub const BIOME_STRATEGY: Strategy = Strategy::biomes(7); /// Packed light per block: sky light in the high nibble, block light in the low one. #[derive(Clone)] pub enum Light { @@ -25,13 +26,16 @@ pub fn index(x: i32, y: i32, z: i32) -> usize { } #[derive(Clone)] pub struct Section { - pub blocks: Blocks, + pub blocks: PalettedContainer, + /// Biome table index per 4x4x4 cell, `(y << 2 | z) << 2 | x`. + pub biomes: PalettedContainer, pub light: Light, } impl Default for Section { fn default() -> Self { Self { - blocks: Blocks::Uniform(0), + blocks: PalettedContainer::new(BLOCK_STRATEGY, 0), + biomes: PalettedContainer::new(BIOME_STRATEGY, 0), light: Light::Uniform(0xF0), } } @@ -39,23 +43,19 @@ impl Default for Section { impl Section { #[inline] pub fn get(&self, i: usize) -> u16 { - match &self.blocks { - Blocks::Uniform(v) => *v, - Blocks::Full(a) => a[i], - } + self.blocks.get(i) as u16 } pub fn set(&mut self, i: usize, v: u16) -> u16 { - match &mut self.blocks { - Blocks::Uniform(u) if *u == v => v, - Blocks::Uniform(u) => { - let old = *u; - let mut a = Box::new([old; 4096]); - a[i] = v; - self.blocks = Blocks::Full(a); - old - } - Blocks::Full(a) => std::mem::replace(&mut a[i], v), - } + self.blocks.set(i, u32::from(v)) as u16 + } + /// All 4,096 block states in index order. + pub fn unpack(&self, out: &mut [u16; 4096]) { + self.blocks.unpack_u16(out); + } + /// The block states of a whole section at once. + pub fn from_blocks(values: &[u16; 4096]) -> PalettedContainer { + let wide: Vec = values.iter().map(|&v| u32::from(v)).collect(); + PalettedContainer::from_values(BLOCK_STRATEGY, &wide) } #[inline] pub fn light(&self, i: usize) -> u8 { @@ -65,17 +65,26 @@ impl Section { } } pub fn is_uniform(&self, v: u16) -> bool { - match &self.blocks { - Blocks::Uniform(u) => *u == v, - Blocks::Full(a) => a.iter().all(|&b| b == v), - } + self.blocks.is_uniform(u32::from(v)) } - /// Collapse storage that became uniform. + /// Heap bytes held by the block, biome and light storage (benchmark accounting). + pub fn heap_bytes(&self) -> usize { + self.blocks.heap_bytes() + + self.biomes.heap_bytes() + + match &self.light { + Light::Uniform(_) => 0, + Light::Full(_) => 4096, + } + } + /// Collapse storage that became uniform, and drop palette entries no + /// block uses any more. pub fn compact(&mut self) { - if let Blocks::Full(a) = &self.blocks - && a.iter().all(|&b| b == a[0]) - { - self.blocks = Blocks::Uniform(a[0]); + for container in [&mut self.blocks, &mut self.biomes] { + if container.bits() != 0 { + if let Some(v) = container.uniform() { + *container = PalettedContainer::new(container.strategy(), v); + } + } } if let Light::Full(a) = &self.light && a.iter().all(|&b| b == a[0]) @@ -89,8 +98,6 @@ pub struct Chunk { pub x: i32, pub z: i32, pub sections: Vec>, - /// Biome index per 4x4x4 cell (x,z in 0..4, y in 0..96) into `Biomes`. - pub biomes: Arc>, /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. pub heights: Arc<[i16; 256]>, pub lit: bool, @@ -119,7 +126,6 @@ impl Chunk { sections: (0..SECTIONS) .map(|_| Arc::new(Section::default())) .collect(), - biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, light_loaded: false, @@ -161,9 +167,24 @@ impl Chunk { } self.sections[s as usize].light(index(x, y, z)) } + /// Heap bytes held by the sections (benchmark accounting). + pub fn heap_bytes(&self) -> usize { + self.sections.iter().map(|s| s.heap_bytes()).sum::() + } + /// Biome table index at a block position (`ChunkAccess.getNoiseBiome` with + /// the quart y clamped to the column). #[inline] pub fn biome(&self, x: i32, y: i32, z: i32) -> u16 { let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1); - self.biomes[(qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize] + self.sections[(qy >> 2) as usize] + .biomes + .get(((qy & 3) << 4 | ((z & 15) >> 2) << 2 | (x & 15) >> 2) as usize) as u16 + } + /// Sets the biome of one quart cell (`qy` counts from the column's bottom). + pub fn set_biome_cell(&mut self, qx: i32, qy: i32, qz: i32, biome: u16) { + let section = Arc::make_mut(&mut self.sections[(qy >> 2) as usize]); + section + .biomes + .set(((qy & 3) << 4 | (qz & 3) << 2 | (qx & 3)) as usize, u32::from(biome)); } } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 3f88a5ed9..080525a43 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -933,9 +933,14 @@ impl Game<'_> { }; let mut found = Vec::new(); for (s, section) in chunk.sections.iter().enumerate() { - let horizon_client::chunk::Blocks::Full(blocks) = §ion.blocks else { + if !section + .blocks + .maybe_has(|v| v == u32::from(portal) || v == u32::from(gateway)) + { continue; - }; + } + let mut blocks = Box::new([0u16; 4096]); + section.unpack(&mut blocks); for (i, &b) in blocks.iter().enumerate() { if b == portal || b == gateway { let y = horizon_client::chunk::MIN_Y + s as i32 * 16 + (i >> 8) as i32; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 1e9f59167..ab9585758 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -9,7 +9,7 @@ use super::{Dim, Game, Mining, Screen}; use horizon_client::{ Result, - chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section}, + chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section}, containers::{BlockEntity, Furnace, FurnaceKind}, entities::{Experience, ItemEntity}, hud::{HudBatch, rgba}, @@ -22,7 +22,7 @@ use horizon_client::{ streaming::{ChunkGenerator, Proto, Streaming}, world::World, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource}; use horizon_protocol::{ entity_data::{ITEM_ENTITY_ITEM, Value}, item::{Hashed, Stack}, @@ -434,54 +434,55 @@ impl Game<'_> { .sections(r.dimension.sections(), 16, r.biome_bits) .map_err(|e| e.to_string())?; let mut chunk = Chunk::empty(p.x, p.z); - let mut biomes = vec![0u16; chunk.biomes.len()]; let offset = (r.dimension.min_y - MIN_Y).div_euclid(16); + // Biome table index per quart cell of the dimension's own sections. + let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len()); for (i, s) in sections.iter().enumerate() { let target = offset + i as i32; + let mut cells = [0u32; 64]; + for (j, cell) in cells.iter_mut().enumerate() { + *cell = u32::from( + r.biome_map + .get(s.biomes.get(j) as usize) + .copied() + .unwrap_or(0), + ); + } + biome_cells.push(cells); if !(0..SECTIONS as i32).contains(&target) { continue; } - let blocks = if s.states.bits == 0 { - Blocks::Uniform(s.states.get(0) as u16) - } else { - let mut a = Box::new([0u16; 4096]); - for (j, v) in a.iter_mut().enumerate() { - *v = s.states.get(j) as u16; - } - Blocks::Full(a) - }; + let strategy = BLOCK_STRATEGY; + let palette = s.states.palette.iter().map(|&p| p as u32).collect(); + let words = s.states.data.iter().map(|&w| w as u64).collect(); + let blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) + .map_err(|e| e.to_string())?; let mut section = Section { blocks, + biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells), light: Light::Uniform(0xF0), }; section.compact(); chunk.sections[target as usize] = Arc::new(section); - for j in 0..64 { - let biome = r - .biome_map - .get(s.biomes.get(j) as usize) - .copied() - .unwrap_or(0); - if let Some(cell) = biomes.get_mut(target as usize * 64 + j) { - *cell = biome; + } + // Sections outside the dimension's range take its nearest biomes + // (the column's top or bottom cell layer repeated). + if !biome_cells.is_empty() { + let last = biome_cells.len() - 1; + for si in 0..SECTIONS as i32 { + let i = si - offset; + if (0..sections.len() as i32).contains(&i) { + continue; } + let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) }; + let mut cells = [0u32; 64]; + for (j, cell) in cells.iter_mut().enumerate() { + *cell = biome_cells[edge][layer * 16 + j % 16]; + } + Arc::make_mut(&mut chunk.sections[si as usize]).biomes = + PalettedContainer::from_values(BIOME_STRATEGY, &cells); } } - // Columns outside the dimension's range take its nearest biome. - let (lo, hi) = ( - offset.max(0) as usize * 64, - ((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64, - ); - if lo < hi { - for j in 0..biomes.len() { - if j < lo { - biomes[j] = biomes[lo + j % 16]; - } else if j >= hi { - biomes[j] = biomes[hi - 16 + j % 16]; - } - } - } - chunk.biomes = Arc::new(biomes); Ok(chunk) } /// Keep the renderable block entities (chests, furnaces) in step with blocks. diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 930a26610..93ce0f653 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -216,6 +216,7 @@ pub fn light_chunk( let mut block = vec![0u8; W * W * h]; let mut queue = VecDeque::new(); let mut sky_queue = VecDeque::new(); + let mut ids = Box::new([0u16; 4096]); for (dz, row) in region.iter().enumerate() { for (dx, chunk) in row.iter().enumerate() { let Some(chunk) = chunk else { continue }; @@ -223,8 +224,8 @@ pub fn light_chunk( if section.is_uniform(0) { continue; } - for i in 0..4096 { - let id = section.get(i); + section.unpack(&mut ids); + for (i, &id) in ids.iter().enumerate() { let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8); let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz); states[p] = id; diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 63a929074..52c8f22ff 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -383,6 +383,13 @@ impl Padded { let mut blocks = vec![0u16; P * P * P]; let mut light = vec![0u8; P * P * P]; let base_y = MIN_Y + sy * 16; + // The section itself is unpacked in one pass; the border cells of the + // neighbouring sections are read one by one. + let mut own = Box::new([0u16; 4096]); + let center = region[1][1].map(|c| &c.sections[sy as usize]); + if let Some(section) = center { + section.unpack(&mut own); + } for y in -B..16 + B { let wy = base_y + y; for z in -B..16 + B { @@ -390,7 +397,14 @@ impl Padded { let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]; let i = pi(x, y, z); if let Some(c) = chunk { - blocks[i] = c.get(x & 15, wy, z & 15); + blocks[i] = if (0..16).contains(&x) + && (0..16).contains(&y) + && (0..16).contains(&z) + { + own[(y << 8 | z << 4 | x) as usize] + } else { + c.get(x & 15, wy, z & 15) + }; light[i] = c.light(x & 15, wy, z & 15); } else { light[i] = 0xF0; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 1b532c59b..29a1b1dc5 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -16,10 +16,11 @@ use crate::{ Result, biome::Biomes, - chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS}, + chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS}, streaming::ChunkGenerator, }; use horizon_core::{ + paletted::PalettedContainer, position::{BlockPos, ChunkPos}, ticks::{SavedTick, TickPriority, TickTypeId}, }; @@ -42,29 +43,6 @@ use std::{ pub const VERSION_NAME: &str = "26.3"; -fn pack(indices: &[u16], bits: u32) -> Vec { - let per_long = (64 / bits) as usize; - let mut longs = vec![0i64; indices.len().div_ceil(per_long)]; - for (i, &v) in indices.iter().enumerate() { - longs[i / per_long] |= - (i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits); - } - longs -} -fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec { - let per_long = (64 / bits) as usize; - let mask = (1u64 << bits) - 1; - (0..count) - .map(|i| { - longs.get(i / per_long).map_or(0, |&l| { - ((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16 - }) - }) - .collect() -} -fn bits_for(len: usize, min: u32) -> u32 { - (usize::BITS - (len.max(1) - 1).leading_zeros()).max(min) -} fn string(s: &str) -> Tag { Tag::String(s.into()) } @@ -584,33 +562,22 @@ pub fn encode_with( }); for (si, section) in chunk.sections.iter().enumerate() { let y = (MIN_Y >> 4) + si as i32; - let ids: Vec = match §ion.blocks { - Blocks::Uniform(v) => vec![*v], - Blocks::Full(a) => a.to_vec(), - }; - let mut palette: Vec = Vec::new(); - let mut lookup: HashMap = HashMap::new(); - let indices: Vec = ids - .iter() - .map(|id| { - *lookup.entry(*id).or_insert_with(|| { - palette.push(*id); - (palette.len() - 1) as u16 - }) - }) - .collect(); + // PalettedContainer.pack: distinct states in index order, indices at + // the saved width. + let packed = section.blocks.pack(); let mut states = vec![( "palette", Tag::List( - palette + packed + .palette .iter() - .map(|id| { - let state = registry.state(BlockStateId(u32::from(*id))); + .map(|&id| { + let state = registry.state(BlockStateId(id)); match state { // BlockState.CODEC: the block name for default states. Some(s) if tables.is_some_and(|t| { - t.default_state.get(*id as usize) == Some(&true) + t.default_state.get(id as usize) == Some(&true) }) => { string(&s.name) @@ -622,37 +589,27 @@ pub fn encode_with( .collect(), ), )]; - if palette.len() > 1 { + if let Some(data) = &packed.data { states.push(( "data", - Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))), + Tag::LongArray(data.iter().map(|&w| w as i64).collect()), )); } - let quart: Vec = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect(); - let mut biome_palette: Vec = Vec::new(); - let biome_indices: Vec = quart - .iter() - .map(|b| match biome_palette.iter().position(|p| p == b) { - Some(i) => i as u16, - None => { - biome_palette.push(*b); - (biome_palette.len() - 1) as u16 - } - }) - .collect(); + let biome_packed = section.biomes.pack(); let mut biome_tag = vec![( "palette", Tag::List( - biome_palette + biome_packed + .palette .iter() - .map(|b| string(&biomes.get(*b).name)) + .map(|&b| string(&biomes.get(b as u16).name)) .collect(), ), )]; - if biome_palette.len() > 1 { + if let Some(data) = &biome_packed.data { biome_tag.push(( "data", - Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))), + Tag::LongArray(data.iter().map(|&w| w as i64).collect()), )); } let mut entries = vec![ @@ -811,7 +768,6 @@ pub fn decode_with( } let air = registry.default_state("minecraft:air")?.0 as u16; let mut cache: HashMap = HashMap::new(); - let mut biome_data = (*chunk.biomes).clone(); let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk); }; @@ -854,15 +810,14 @@ pub fn decode_with( }) .collect(); let target = Arc::make_mut(&mut chunk.sections[si as usize]); - if ids.len() <= 1 { - target.blocks = Blocks::Uniform(ids.first().copied().unwrap_or(air)); - } else if let Some(Tag::LongArray(data)) = states.get("data") { - let indices = unpack(data, bits_for(ids.len(), 4), 4096); - let mut full = Box::new([air; 4096]); - for (i, idx) in indices.iter().enumerate() { - full[i] = ids.get(*idx as usize).copied().unwrap_or(air); - } - target.blocks = Blocks::Full(full); + let data = match states.get("data") { + Some(Tag::LongArray(data)) => Some(data.iter().map(|&w| w as u64).collect::>()), + _ => None, + }; + let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); + if let Ok(blocks) = PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref()) + { + target.blocks = blocks; } } if let Some(b) = section.get("biomes") @@ -875,18 +830,21 @@ pub fn decode_with( _ => 0, }) .collect(); - let indices = match b.get("data") { - Some(Tag::LongArray(data)) if ids.len() > 1 => { - unpack(data, bits_for(ids.len(), 0), 64) - } - _ => vec![0; 64], + let data = match b.get("data") { + Some(Tag::LongArray(data)) => Some(data.iter().map(|&w| w as u64).collect::>()), + _ => None, }; - for (i, idx) in indices.iter().enumerate() { - biome_data[si as usize * 64 + i] = ids.get(*idx as usize).copied().unwrap_or(0); + let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); + let target = Arc::make_mut(&mut chunk.sections[si as usize]); + if let Ok(container) = + PalettedContainer::from_packed(BIOME_STRATEGY, palette.clone(), data.as_deref()) + { + target.biomes = container; + } else if let Some(&first) = palette.first() { + target.biomes = PalettedContainer::new(BIOME_STRATEGY, first); } } } - chunk.biomes = Arc::new(biome_data); let mut extras = ChunkExtras { last_update: number(tag.get("LastUpdate")).unwrap_or(0), ..ChunkExtras::default() diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs index 3ca7fff7d..2581d9229 100644 --- a/crates/horizon-client/src/testgen.rs +++ b/crates/horizon-client/src/testgen.rs @@ -76,7 +76,13 @@ impl ChunkGenerator for TestTerrain { impl TestTerrain { fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk { let mut chunk = Chunk::empty(cx, cz); - chunk.biomes = std::sync::Arc::new(vec![self.plains; chunk.biomes.len()]); + for s in &mut chunk.sections { + std::sync::Arc::make_mut(s).biomes = + horizon_core::paletted::PalettedContainer::new( + crate::chunk::BIOME_STRATEGY, + u32::from(self.plains), + ); + } for z in 0..16 { for x in 0..16 { let (wx, wz) = (cx * 16 + x, cz * 16 + z); diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 19dc4ec2b..b0d56a66e 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -2,10 +2,10 @@ //! aquifers, surface rules, carvers and placed features) to chunk streaming. use crate::{ biome::Biomes, - chunk::{Chunk, HEIGHT, MIN_Y}, + chunk::{BIOME_STRATEGY, Chunk, HEIGHT, MIN_Y, SECTIONS, Section}, streaming::{ChunkGenerator, Proto}, }; -use horizon_core::position::ChunkPos; +use horizon_core::{paletted::PalettedContainer, position::ChunkPos}; use horizon_world::{ registry::BlockRegistry, worldgen::generator::{GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk}, @@ -177,15 +177,26 @@ impl ChunkGenerator for VanillaTerrain { chunk.terrain.min_y().max(MIN_Y), (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT), ); - for y in lo..hi { - for z in 0..16 { - for x in 0..16 { - let id = chunk.block(bx + x, y, bz + z).0 as u16; - if id != 0 { - out.set(x, y, z, id); + let mut values = Box::new([0u16; 4096]); + for si in 0..SECTIONS as i32 { + let base = MIN_Y + si * 16; + if base + 16 <= lo || base >= hi { + continue; + } + values.fill(0); + let mut any = false; + for y in base.max(lo)..(base + 16).min(hi) { + for z in 0..16 { + for x in 0..16 { + let id = chunk.block(bx + x, y, bz + z).0 as u16; + values[((y & 15) << 8 | z << 4 | x) as usize] = id; + any |= id != 0; } } } + if any { + Arc::make_mut(&mut out.sections[si as usize]).blocks = Section::from_blocks(&values); + } } let base_section = chunk.terrain.min_y() >> 4; for (i, marks) in chunk.terrain.postprocessing().iter().enumerate() { @@ -199,19 +210,17 @@ impl ChunkGenerator for VanillaTerrain { } } } - let mut biomes = vec![0u16; 16 * (HEIGHT as usize / 4)]; - for qy in 0..HEIGHT / 4 { - for qz in 0..4 { - for qx in 0..4 { - let y = (MIN_Y + qy * 4).clamp(lo, hi - 1); - let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4); - let index = id.0 as usize; - biomes[(qy * 16 + qz * 4 + qx) as usize] = - self.biome_map.get(index).copied().unwrap_or(0); - } + for si in 0..SECTIONS as i32 { + let mut cells = [0u32; 64]; + for (j, cell) in cells.iter_mut().enumerate() { + let (qx, qz, qy) = (j as i32 & 3, (j as i32 >> 2) & 3, si * 4 + (j as i32 >> 4)); + let y = (MIN_Y + qy * 4).clamp(lo, hi - 1); + let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4); + *cell = u32::from(self.biome_map.get(id.0 as usize).copied().unwrap_or(0)); } + Arc::make_mut(&mut out.sections[si as usize]).biomes = + PalettedContainer::from_values(BIOME_STRATEGY, &cells); } - out.biomes = Arc::new(biomes); out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); out.structure_refs = chunk .structures() diff --git a/crates/horizon-core/examples/paletted_fixture.rs b/crates/horizon-core/examples/paletted_fixture.rs new file mode 100644 index 000000000..4008e573f --- /dev/null +++ b/crates/horizon-core/examples/paletted_fixture.rs @@ -0,0 +1,135 @@ +//! Text transport for the PalettedContainer comparison: replays scripted edits +//! and prints the same hashes as `VanillaPalettedContainerOracle`. +use horizon_core::paletted::{PalettedContainer, Strategy}; +use std::{ + fs, + io::{self, Write}, +}; +const BASIS: u64 = 0xcbf2_9ce4_8422_2325; +fn fnv(h: u64, b: u8) -> u64 { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) +} +fn hash_bytes(bytes: &[u8]) -> u64 { + bytes.iter().fold(BASIS, |h, &b| fnv(h, b)) +} +fn varint(out: &mut Vec, mut v: u32) { + while v >= 0x80 { + out.push((v & 0x7F) as u8 | 0x80); + v >>= 7; + } + out.push(v as u8); +} +/// `PalettedContainer.write`. +fn write(c: &PalettedContainer) -> Vec { + let (bits, palette, words) = c.to_wire(); + let mut out = vec![bits]; + if bits == 0 { + varint(&mut out, palette[0]); + } else if !palette.is_empty() { + varint(&mut out, palette.len() as u32); + for p in palette { + varint(&mut out, p); + } + } + for w in words { + out.extend(w.to_be_bytes()); + } + out +} +/// `PalettedContainer.read` for the leading byte, palette and longs. +fn read(strategy: Strategy, bytes: &[u8]) -> PalettedContainer { + let mut at = 1; + let mut varint = || { + let (mut v, mut shift) = (0u32, 0); + loop { + let b = bytes[at]; + at += 1; + v |= u32::from(b & 0x7F) << shift; + if b & 0x80 == 0 { + return v; + } + shift += 7; + } + }; + let bits = bytes[0]; + let palette = if bits == 0 { + vec![varint()] + } else if strategy.wire_has_palette(bits) { + let n = varint(); + (0..n).map(|_| varint()).collect() + } else { + Vec::new() + }; + let words = bytes[at..] + .chunks_exact(8) + .map(|c| u64::from_be_bytes(c.try_into().unwrap())) + .collect(); + PalettedContainer::from_wire(strategy, bits, palette, words).unwrap() +} +fn wire(c: &PalettedContainer) -> String { + let bytes = write(c); + format!("{}:{}", bytes.len(), hash_bytes(&bytes) as i64) +} +fn values(c: &PalettedContainer) -> i64 { + let mut h = BASIS; + for i in 0..c.strategy().entries() { + for b in c.get(i).to_le_bytes() { + h = fnv(h, b); + } + } + h as i64 +} +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let mut out = io::BufWriter::new(fs::File::create(&args[2])?); + for line in fs::read_to_string(&args[1])?.lines() { + let t: Vec<&str> = line.split_whitespace().collect(); + let strategy = if t[1] == "blocks" { + Strategy::blocks(16) + } else { + Strategy::biomes(7) + }; + let mut c = PalettedContainer::new(strategy, t[2].parse()?); + let every: usize = t[3].parse()?; + let (mut olds, mut n) = (BASIS, 0usize); + let mut checkpoints = Vec::new(); + for pair in t[4..].chunks(2) { + let old = c.set(pair[0].parse()?, pair[1].parse()?); + for b in old.to_le_bytes() { + olds = fnv(olds, b); + } + n += 1; + if n % every == 0 { + checkpoints.push(wire(&c)); + } + } + let reread = read(strategy, &write(&c)); + let packed = c.pack(); + let storage = packed.data.as_ref().map_or(BASIS, |data| { + data.iter() + .flat_map(|w| w.to_le_bytes()) + .fold(BASIS, |h, b| fnv(h, b)) + }); + let palette: Vec = packed.palette.iter().map(u32::to_string).collect(); + let loaded = + PalettedContainer::from_packed(strategy, packed.palette.clone(), packed.data.as_deref())?; + writeln!( + out, + "{} {} cp={} bits={} final={} values={} read={}/{} packed={}/{}/{} loaded={}/{}", + t[0], + olds as i64, + checkpoints.join(","), + c.bits(), + wire(&c), + values(&c), + values(&reread), + wire(&reread), + packed.bits, + storage as i64, + palette.join(","), + values(&loaded), + wire(&loaded), + )?; + } + Ok(()) +} diff --git a/crates/horizon-core/src/lib.rs b/crates/horizon-core/src/lib.rs index 01af3f932..79045910a 100644 --- a/crates/horizon-core/src/lib.rs +++ b/crates/horizon-core/src/lib.rs @@ -9,6 +9,7 @@ pub mod carving; pub mod density; pub mod geometry; pub mod noise; +pub mod paletted; pub mod position; pub mod random; pub mod storage; diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs new file mode 100644 index 000000000..8f39cebb7 --- /dev/null +++ b/crates/horizon-core/src/paletted.rs @@ -0,0 +1,739 @@ +//! Resident `PalettedContainer` of Java Edition 26.3: single-value, linear and +//! hash-map palettes with vanilla's bit-width thresholds, and the global +//! palette beyond them, over `SimpleBitStorage` words (values never span +//! longs). One container type serves blocks (16^3 entries) and biomes (4^3). +//! +//! Growth follows `PalettedContainer.onResize`: a full palette asks for one +//! more bit, the new configuration is built by re-adding the distinct values +//! in index order, and the value that did not fit is added last. Palettes +//! never shrink while resident; `pack` writes the canonical saved form. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `Strategy.createForBlockStates`: 4096 entries, linear palettes up to 4 + /// bits and hash-map palettes from 5 to 8. + Blocks, + /// `Strategy.createForBiomes`: 64 entries, linear palettes up to 3 bits. + Biomes, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Strategy { + pub kind: Kind, + /// `ceillog2` of the registry size: the width of the global palette. + pub global_bits: u8, +} +/// `getConfigurationForBitCount`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Config { + Single, + /// Palette of up to `1 << bits` entries, stored in `bits` bits. + List(u8), + Global, +} +impl Strategy { + pub const fn blocks(global_bits: u8) -> Self { + Self { + kind: Kind::Blocks, + global_bits, + } + } + pub const fn biomes(global_bits: u8) -> Self { + Self { + kind: Kind::Biomes, + global_bits, + } + } + pub const fn entries(self) -> usize { + match self.kind { + Kind::Blocks => 4096, + Kind::Biomes => 64, + } + } + fn config(self, bits: u8) -> Config { + match (self.kind, bits) { + (_, 0) => Config::Single, + (Kind::Blocks, 1..=4) => Config::List(4), + (Kind::Blocks, 5..=8) => Config::List(bits), + (Kind::Biomes, 1..=3) => Config::List(bits), + _ => Config::Global, + } + } + /// Whether a container written with leading byte `bits` lists its palette + /// (all but the global one). + pub fn wire_has_palette(self, bits: u8) -> bool { + self.config(bits) != Config::Global + } + /// Bits of the storage a configuration keeps in memory. + fn storage_bits(self, config: Config) -> u8 { + match config { + Config::Single => 0, + Config::List(bits) => bits, + Config::Global => self.global_bits, + } + } +} +/// `Mth.ceillog2`. +pub fn ceil_log2(n: usize) -> u8 { + if n <= 1 { + 0 + } else { + (usize::BITS - (n - 1).leading_zeros()) as u8 + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PaletteError { + /// A palette bigger than its configuration allows, or empty. + BadPalette { len: usize }, + /// Storage with the wrong number of longs. + BadStorage { expected: usize, actual: usize }, + /// A stored index past the palette. + BadIndex { index: u32, palette: usize }, + /// The declared bit count does not match the palette. + BadBits { declared: u8, expected: u8 }, +} +impl std::fmt::Display for PaletteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{self:?}") + } +} +impl std::error::Error for PaletteError {} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Palette { + Single(u32), + /// Linear and hash-map palettes alike: ids in insertion order. + List(Vec), + Global, +} +/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits] = ceil(2^20 / +/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`. +const MAGIC: [u32; 33] = { + let mut table = [0; 33]; + let mut bits = 1; + while bits <= 32 { + let per = 64 / bits as u32; + table[bits] = (1u32 << 20).div_ceil(per); + bits += 1; + } + table +}; +/// Words of `bits`-wide values: `entries.div_ceil(64 / bits)`. +pub fn storage_len(bits: u8, entries: usize) -> usize { + if bits == 0 { + 0 + } else { + entries.div_ceil(64 / usize::from(bits)) + } +} +#[inline] +fn locate(bits: u8, i: usize) -> (usize, u32) { + if bits.is_power_of_two() { + // 64 / bits is a power of two: shifts instead of the multiplication. + let log = bits.trailing_zeros(); + let word = i >> (6 - log); + (word, ((i & ((64 >> log) - 1)) as u32) << log) + } else { + let per = 64 / u32::from(bits); + let word = (i as u32 * MAGIC[usize::from(bits)]) >> 20; + (word as usize, (i as u32 - word * per) * u32::from(bits)) + } +} +#[inline] +fn mask(bits: u8) -> u64 { + (1u64 << bits) - 1 +} +fn read(words: &[u64], bits: u8, i: usize) -> u32 { + let (word, shift) = locate(bits, i); + ((words[word] >> shift) & mask(bits)) as u32 +} +fn write(words: &mut [u64], bits: u8, i: usize, value: u32) { + let (word, shift) = locate(bits, i); + words[word] = (words[word] & !(mask(bits) << shift)) | (u64::from(value) << shift); +} +/// Words holding `ids` in `bits`-wide slots. +fn pack_words(bits: u8, entries: usize, ids: impl Iterator) -> Vec { + let mut words = vec![0u64; storage_len(bits, entries)]; + for (i, id) in ids.enumerate() { + write(&mut words, bits, i, id); + } + words +} +/// The saved form: distinct values in index order, and the packed indices +/// when there is more than one value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Packed { + pub palette: Vec, + /// Bits per index in `data` (0 when `data` is absent). + pub bits: u8, + pub data: Option>, +} + +#[derive(Clone, Debug)] +pub struct PalettedContainer { + strategy: Strategy, + bits: u8, + palette: Palette, + words: Vec, +} +impl PalettedContainer { + /// `new PalettedContainer(initialValue, strategy)`. + pub fn new(strategy: Strategy, value: u32) -> Self { + Self { + strategy, + bits: 0, + palette: Palette::Single(value), + words: Vec::new(), + } + } + pub fn strategy(&self) -> Strategy { + self.strategy + } + /// Bits per stored index (`BitStorage.getBits`). + pub fn bits(&self) -> u8 { + self.bits + } + /// Entries in the palette (the global palette reports its bit capacity). + pub fn palette_len(&self) -> usize { + match &self.palette { + Palette::Single(_) => 1, + Palette::List(list) => list.len(), + Palette::Global => 1 << self.bits.min(31), + } + } + pub fn is_global(&self) -> bool { + matches!(self.palette, Palette::Global) + } + #[inline] + fn raw(&self, i: usize) -> usize { + let (word, shift) = locate(self.bits, i); + ((self.words[word] >> shift) & mask(self.bits)) as usize + } + #[inline] + pub fn get(&self, i: usize) -> u32 { + match &self.palette { + Palette::Single(value) => *value, + Palette::List(list) => list[self.raw(i)], + Palette::Global => self.raw(i) as u32, + } + } + /// The value when every entry is equal, without the palette having to be + /// minimal. + pub fn uniform(&self) -> Option { + match &self.palette { + Palette::Single(value) => Some(*value), + Palette::List(list) if list.len() == 1 => Some(list[0]), + Palette::Global => self.all_equal(self.get(0)).then(|| self.get(0)), + Palette::List(list) => { + let first = list[self.raw(0)]; + self.all_equal(first).then_some(first) + } + } + } + /// Whether all entries equal `value`. + pub fn is_uniform(&self, value: u32) -> bool { + match &self.palette { + Palette::Single(v) => *v == value, + Palette::List(list) => match list.iter().position(|&v| v == value) { + None => false, + Some(_) if list.len() == 1 => true, + Some(_) => self.all_equal(value), + }, + Palette::Global => self.all_equal(value), + } + } + fn all_equal(&self, value: u32) -> bool { + let id = match &self.palette { + Palette::Single(v) => return *v == value, + Palette::List(list) => match list.iter().position(|&v| v == value) { + Some(id) => id as u64, + None => return false, + }, + Palette::Global => u64::from(value), + }; + let bits = usize::from(self.bits); + let per = 64 / bits; + let pattern = (0..per).fold(0u64, |word, slot| word | id << (slot * bits)); + let entries = self.strategy.entries(); + let full = entries / per; + if self.words[..full].iter().any(|&w| w != pattern) { + return false; + } + let tail = entries - full * per; + tail == 0 || { + let used = (1u64 << (tail * bits)) - 1; + self.words[full] & used == pattern & used + } + } + /// `getAndSet`: stores `value` and returns the previous one. + pub fn set(&mut self, i: usize, value: u32) -> u32 { + let id = self.id_for(value); + match &self.palette { + Palette::Single(old) => *old, + Palette::List(list) => { + let old = read(&self.words, self.bits, i) as usize; + write(&mut self.words, self.bits, i, id as u32); + list[old] + } + Palette::Global => { + let old = read(&self.words, self.bits, i); + write(&mut self.words, self.bits, i, id as u32); + old + } + } + } + /// `Palette.idFor`, growing the container when the palette is full. + fn id_for(&mut self, value: u32) -> usize { + match &mut self.palette { + Palette::Single(v) if *v == value => 0, + Palette::Single(_) => self.resize(1, value), + Palette::List(list) => { + if let Some(id) = list.iter().position(|&v| v == value) { + id + } else if list.len() < 1 << self.bits { + list.push(value); + list.len() - 1 + } else { + self.resize(self.bits + 1, value) + } + } + Palette::Global => value as usize, + } + } + /// `PalettedContainer.onResize`: rebuild with the configuration for + /// `bits`, then add `last` and return its id. + fn resize(&mut self, bits: u8, last: u32) -> usize { + let strategy = self.strategy; + let config = strategy.config(bits); + let storage_bits = strategy.storage_bits(config); + let entries = strategy.entries(); + let mut palette = match config { + Config::Single => Palette::Single(last), + Config::List(_) => Palette::List(Vec::new()), + Config::Global => Palette::Global, + }; + let mut words = vec![0u64; storage_len(storage_bits, entries)]; + let id_in = |palette: &mut Palette, value: u32| -> u32 { + match palette { + Palette::Single(_) => 0, + Palette::List(list) => match list.iter().position(|&v| v == value) { + Some(id) => id as u32, + None => { + list.push(value); + list.len() as u32 - 1 + } + }, + Palette::Global => value, + } + }; + if let Palette::Single(only) = self.palette { + let id = id_in(&mut palette, only); + if storage_bits > 0 && id != 0 { + for i in 0..entries { + write(&mut words, storage_bits, i, id); + } + } + } else { + let (mut last_old, mut new_id) = (u32::MAX, 0); + for i in 0..entries { + let old = read(&self.words, self.bits, i); + if old != last_old { + last_old = old; + let value = match &self.palette { + Palette::List(list) => list[old as usize], + _ => old, + }; + new_id = id_in(&mut palette, value); + } + if storage_bits > 0 { + write(&mut words, storage_bits, i, new_id); + } + } + } + let id = id_in(&mut palette, last); + self.palette = palette; + self.bits = storage_bits; + self.words = words; + id as usize + } + /// All values in index order. + pub fn unpack(&self, out: &mut [u32]) { + assert_eq!(out.len(), self.strategy.entries()); + match &self.palette { + Palette::Single(value) => out.fill(*value), + palette => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + let id = ((word >> (slot * bits)) & m) as u32; + *cell = match palette { + Palette::List(list) => list[id as usize], + _ => id, + }; + } + } + } + } + } + /// Block ids as 16-bit values (callers whose registry fits in 16 bits). + pub fn unpack_u16(&self, out: &mut [u16; 4096]) { + debug_assert_eq!(self.strategy.entries(), 4096); + match &self.palette { + Palette::Single(value) => out.fill(*value as u16), + palette => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + let id = ((word >> (slot * bits)) & m) as usize; + *cell = match palette { + Palette::List(list) => list[id] as u16, + _ => id as u16, + }; + } + } + } + } + } + /// A container holding `values` in the smallest configuration for their + /// distinct count, with palette ids in first-occurrence order, like a + /// container unpacked from disk. + pub fn from_values(strategy: Strategy, values: &[u32]) -> Self { + assert_eq!(values.len(), strategy.entries()); + let mut palette: Vec = Vec::new(); + let mut small = true; + let mut lookup: std::collections::HashMap = std::collections::HashMap::new(); + let mut ids = Vec::with_capacity(values.len()); + for &value in values { + let id = if small { + match palette.iter().position(|&v| v == value) { + Some(id) => id as u32, + None => { + palette.push(value); + if palette.len() > 16 { + small = false; + lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32))); + } + palette.len() as u32 - 1 + } + } + } else { + *lookup.entry(value).or_insert_with(|| { + palette.push(value); + palette.len() as u32 - 1 + }) + }; + ids.push(id); + } + Self::build(strategy, palette, &ids) + } + /// A container over a distinct-value `palette` and an id per entry. + fn build(strategy: Strategy, palette: Vec, ids: &[u32]) -> Self { + let config = strategy.config(ceil_log2(palette.len())); + match config { + Config::Single => Self::new(strategy, palette[0]), + Config::List(bits) => Self { + strategy, + bits, + words: pack_words(bits, ids.len(), ids.iter().copied()), + palette: Palette::List(palette), + }, + Config::Global => { + let bits = strategy.global_bits; + Self { + strategy, + bits, + words: pack_words(bits, ids.len(), ids.iter().map(|&id| palette[id as usize])), + palette: Palette::Global, + } + } + } + } + /// `PalettedContainer.read`: the container as sent on the wire. `bits` is + /// the leading byte, `palette` the VarInt entries (a single one for + /// `bits == 0`, none for the global palette) and `words` the longs. + pub fn from_wire( + strategy: Strategy, + bits: u8, + palette: Vec, + words: Vec, + ) -> Result { + let config = strategy.config(bits); + let storage_bits = strategy.storage_bits(config); + let expected = storage_len(storage_bits, strategy.entries()); + if words.len() != expected { + return Err(PaletteError::BadStorage { + expected, + actual: words.len(), + }); + } + match config { + Config::Single => { + if palette.len() != 1 { + return Err(PaletteError::BadPalette { len: palette.len() }); + } + Ok(Self::new(strategy, palette[0])) + } + Config::List(bits) => { + if palette.is_empty() || palette.len() > 1 << bits { + return Err(PaletteError::BadPalette { len: palette.len() }); + } + let container = Self { + strategy, + bits, + palette: Palette::List(palette), + words, + }; + container.check_indices()?; + Ok(container) + } + Config::Global => Ok(Self { + strategy, + bits: storage_bits, + palette: Palette::Global, + words, + }), + } + } + fn check_indices(&self) -> Result<(), PaletteError> { + let Palette::List(list) = &self.palette else { + return Ok(()); + }; + if list.len() == 1 << self.bits { + return Ok(()); + } + for i in 0..self.strategy.entries() { + let index = read(&self.words, self.bits, i); + if index as usize >= list.len() { + return Err(PaletteError::BadIndex { + index, + palette: list.len(), + }); + } + } + Ok(()) + } + /// `PalettedContainer.write`: the leading bits byte, the palette entries + /// (none for the global palette) and the raw longs, exactly as resident. + pub fn to_wire(&self) -> (u8, Vec, &[u64]) { + let palette = match &self.palette { + Palette::Single(value) => vec![*value], + Palette::List(list) => list.clone(), + Palette::Global => Vec::new(), + }; + (self.bits, palette, &self.words) + } + /// `PalettedContainer.pack`: distinct values in index order, indices + /// re-encoded for the saved bit width. + pub fn pack(&self) -> Packed { + let entries = self.strategy.entries(); + let mut palette: Vec = Vec::new(); + let mut ids = Vec::with_capacity(entries); + let mut values = vec![0u32; entries]; + self.unpack(&mut values); + let mut lookup: std::collections::HashMap = std::collections::HashMap::new(); + for &value in &values { + let id = *lookup.entry(value).or_insert_with(|| { + palette.push(value); + palette.len() as u32 - 1 + }); + ids.push(id); + } + let bits = match self.strategy.config(ceil_log2(palette.len())) { + Config::Single => 0, + Config::List(bits) => bits, + Config::Global => ceil_log2(palette.len()), + }; + let data = (bits != 0).then(|| pack_words(bits, entries, ids.iter().copied())); + Packed { + palette, + bits, + data, + } + } + /// `PalettedContainer.unpack`: a container from the saved form. + pub fn from_packed( + strategy: Strategy, + palette: Vec, + data: Option<&[u64]>, + ) -> Result { + if palette.is_empty() { + return Err(PaletteError::BadPalette { len: 0 }); + } + let config = strategy.config(ceil_log2(palette.len())); + let entries = strategy.entries(); + let disc_bits = match config { + Config::Single => return Ok(Self::new(strategy, palette[0])), + Config::List(bits) => bits, + Config::Global => ceil_log2(palette.len()), + }; + let data = data.ok_or(PaletteError::BadStorage { + expected: storage_len(disc_bits, entries), + actual: 0, + })?; + let expected = storage_len(disc_bits, entries); + if data.len() != expected { + return Err(PaletteError::BadStorage { + expected, + actual: data.len(), + }); + } + let mut ids = Vec::with_capacity(entries); + for i in 0..entries { + let index = read(data, disc_bits, i); + if index as usize >= palette.len() { + return Err(PaletteError::BadIndex { + index, + palette: palette.len(), + }); + } + ids.push(index); + } + Ok(match config { + Config::List(bits) => Self { + strategy, + bits, + words: data.to_vec(), + palette: Palette::List(palette), + }, + _ => Self::build(strategy, palette, &ids), + }) + } + /// Whether any palette entry satisfies `predicate` (`maybeHas`): entries + /// no longer used by any position still count. + pub fn maybe_has(&self, mut predicate: impl FnMut(u32) -> bool) -> bool { + match &self.palette { + Palette::Single(value) => predicate(*value), + Palette::List(list) => list.iter().any(|&v| predicate(v)), + Palette::Global => (0..1u32 << self.bits.min(31)).any(predicate), + } + } + /// Heap bytes held by the palette and the storage. + pub fn heap_bytes(&self) -> usize { + self.words.capacity() * 8 + + match &self.palette { + Palette::List(list) => list.capacity() * 4, + _ => 0, + } + } +} +impl PartialEq for PalettedContainer { + /// Equal when every entry is. + fn eq(&self, other: &Self) -> bool { + let entries = self.strategy.entries(); + entries == other.strategy.entries() && (0..entries).all(|i| self.get(i) == other.get(i)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + const BLOCKS: Strategy = Strategy::blocks(16); + const BIOMES: Strategy = Strategy::biomes(7); + fn rng(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + #[test] + fn grows_through_vanilla_widths() { + let mut c = PalettedContainer::new(BLOCKS, 0); + assert_eq!((c.bits(), c.palette_len()), (0, 1)); + let mut expected = Vec::new(); + for n in 1..=300u32 { + c.set(n as usize, n); + expected.push(match n + 1 { + 2..=16 => 4, + 17..=32 => 5, + 33..=64 => 6, + 65..=128 => 7, + 129..=256 => 8, + _ => 16, + }); + assert_eq!(c.bits(), *expected.last().unwrap(), "after {n} values"); + } + assert!(c.is_global()); + for n in 1..=300u32 { + assert_eq!(c.get(n as usize), n); + } + let mut b = PalettedContainer::new(BIOMES, 3); + for n in 1..=9u32 { + b.set(n as usize, n + 3); + let want = match n + 1 { + 2 => 1, + 3..=4 => 2, + 5..=8 => 3, + _ => 7, + }; + assert_eq!(b.bits(), want, "after {n} biomes"); + } + } + #[test] + fn matches_a_plain_array_under_random_edits() { + for (strategy, distinct) in [(BLOCKS, 700u64), (BLOCKS, 12), (BIOMES, 9), (BIOMES, 3)] { + let entries = strategy.entries(); + let mut state = 0x1234_5678_9ABC_DEF1u64; + let mut c = PalettedContainer::new(strategy, 5); + let mut plain = vec![5u32; entries]; + for _ in 0..20_000 { + let r = rng(&mut state); + let i = (r % entries as u64) as usize; + let v = ((r >> 20) % distinct) as u32 * 7; + assert_eq!(c.set(i, v), plain[i]); + plain[i] = v; + } + let mut out = vec![0; entries]; + c.unpack(&mut out); + assert_eq!(out, plain); + for (i, &v) in plain.iter().enumerate() { + assert_eq!(c.get(i), v); + } + let packed = c.pack(); + let loaded = PalettedContainer::from_packed(strategy, packed.palette.clone(), packed.data.as_deref()) + .unwrap(); + assert_eq!(loaded, c); + assert_eq!(loaded.pack(), packed); + let again = PalettedContainer::from_values(strategy, &plain); + assert_eq!(again, c); + assert_eq!(again.pack(), packed); + let (bits, palette, words) = c.to_wire(); + let wire = PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap(); + assert_eq!(wire, c); + } + } + #[test] + fn uniform_detection_ignores_stale_palette_entries() { + let mut c = PalettedContainer::new(BLOCKS, 0); + c.set(10, 3); + assert!(!c.is_uniform(0)); + c.set(10, 0); + assert!(c.palette_len() == 2 && c.is_uniform(0) && c.uniform() == Some(0)); + assert!(!c.is_uniform(3)); + for i in 0..4096 { + c.set(i, 3); + } + assert_eq!(c.uniform(), Some(3)); + } + #[test] + fn rejects_malformed_wire_data() { + assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0; 255]).is_err()); + assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0x3333; 256]).is_err()); + assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![], vec![0; 256]).is_err()); + assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![1, 2], vec![]).is_err()); + assert!(PalettedContainer::from_wire(BIOMES, 2, vec![1, 2, 3, 4, 5], vec![0; 4]).is_err()); + assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![9], vec![]).is_ok()); + } + #[test] + fn division_magic_is_exact() { + for bits in 1..=32u8 { + let per = 64 / usize::from(bits); + for i in 0..4096usize { + assert_eq!(locate(bits, i).0, i / per, "bits {bits} index {i}"); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java new file mode 100644 index 000000000..a03b0eadc --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java @@ -0,0 +1,103 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.nio.file.*; +import java.util.*; +import java.util.stream.LongStream; +import net.minecraft.core.IdMap; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.level.chunk.PalettedContainer; +import net.minecraft.world.level.chunk.PalettedContainerRO; +import net.minecraft.world.level.chunk.Strategy; + +/** Runs the real PalettedContainer (single-value, linear, hash-map and global palettes, resize, + * network write/read, pack/unpack) over scripted edits and records hashes of everything + * observable: set results, the serialized container after every few edits, the saved form and + * the containers read back from both. */ +public final class VanillaPalettedContainerOracle { + private static final Gson JSON = new GsonBuilder().serializeNulls().create(); + /** The palettes compare entries by identity, as registry objects allow: intern the boxes. */ + private static final Map INTERNED = new HashMap<>(); + private static Integer intern(int value) { return INTERNED.computeIfAbsent(value, v -> new Integer(v)); } + private static final class Ids implements IdMap { + final int size; + Ids(int size) { this.size = size; } + public int getId(Integer value) { return value < size ? value : -1; } + public Integer byId(int id) { return id >= 0 && id < size ? intern(id) : null; } + public int size() { return size; } + public Iterator iterator() { return java.util.stream.IntStream.range(0, size).boxed().iterator(); } + } + private static long fnv(long h, int b) { return (h ^ (b & 0xFF)) * 0x100000001b3L; } + private static final long BASIS = 0xcbf29ce484222325L; + private static long hashBytes(byte[] bytes) { + long h = BASIS; + for (byte b : bytes) h = fnv(h, b); + return h; + } + private static long hashValues(PalettedContainer c, int bits) { + long h = BASIS; + int n = 1 << (3 * bits); + for (int i = 0; i < n; i++) { + int v = c.get(i & (n - 1) & ((1 << bits) - 1), i >> (2 * bits), (i >> bits) & ((1 << bits) - 1)); + for (int k = 0; k < 4; k++) h = fnv(h, v >> (8 * k)); + } + return h; + } + private static byte[] write(PalettedContainer c) { + var buffer = new FriendlyByteBuf(Unpooled.buffer()); + c.write(buffer); + byte[] bytes = new byte[buffer.readableBytes()]; + buffer.readBytes(bytes); + return bytes; + } + private static String wire(PalettedContainer c) { + byte[] bytes = write(c); + return bytes.length + ":" + hashBytes(bytes); + } + /** Input line: name kind initial every i v i v ...; output: one line of fields. */ + private static String scenario(String line) { + var t = line.trim().split(" "); + boolean blocks = t[1].equals("blocks"); + int bits = blocks ? 4 : 2; + Strategy strategy = blocks ? Strategy.createForBlockStates(new Ids(35723)) : Strategy.createForBiomes(new Ids(67)); + var c = new PalettedContainer<>(intern(Integer.parseInt(t[2])), strategy); + int every = Integer.parseInt(t[3]); + var checkpoints = new StringJoiner(","); + long oldsHash = BASIS; + int n = 0, mask = (1 << bits) - 1; + for (int k = 4; k + 1 < t.length; k += 2) { + int i = Integer.parseInt(t[k]); + int old = c.getAndSetUnchecked(i & mask, i >> (2 * bits), (i >> bits) & mask, intern(Integer.parseInt(t[k + 1]))); + for (int j = 0; j < 4; j++) oldsHash = fnv(oldsHash, old >> (8 * j)); + if (++n % every == 0) checkpoints.add(wire(c)); + } + var out = new StringJoiner(" "); + out.add(t[0]).add(Long.toString(oldsHash)).add("cp=" + checkpoints).add("bits=" + c.bitsPerEntry()); + out.add("final=" + wire(c)).add("values=" + hashValues(c, bits)); + var read = new PalettedContainer<>(intern(0), strategy); + read.read(new FriendlyByteBuf(Unpooled.wrappedBuffer(write(c)))); + out.add("read=" + hashValues(read, bits) + "/" + wire(read)); + var packed = c.pack(strategy); + long[] storage = packed.storage().map(LongStream::toArray).orElse(null); + long storageHash = BASIS; + if (storage != null) for (long word : storage) for (int j = 0; j < 8; j++) storageHash = fnv(storageHash, (int) (word >> (8 * j))); + var palette = new StringJoiner(","); + for (int v : packed.paletteEntries()) palette.add(Integer.toString(v)); + out.add("packed=" + packed.bitsPerEntry() + "/" + storageHash + "/" + palette); + var loaded = PalettedContainer.unpack(strategy, new PalettedContainerRO.PackedData<>(packed.paletteEntries(), + Optional.ofNullable(storage).map(LongStream::of), -1)).getOrThrow(); + out.add("loaded=" + hashValues(loaded, bits) + "/" + wire(loaded)); + return out.toString(); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + try (var input = Files.newBufferedReader(Path.of(args[0])); var output = Files.newBufferedWriter(Path.of(args[1]))) { + for (String line; (line = input.readLine()) != null; ) { + output.write(scenario(line)); + output.newLine(); + } + } + } +} diff --git a/tools/test_paletted_container_parity.py b/tools/test_paletted_container_parity.py new file mode 100644 index 000000000..f3b2e28bc --- /dev/null +++ b/tools/test_paletted_container_parity.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Compare Horizon's resident PalettedContainer with the client's own. + +Scripted edits run through vanilla's PalettedContainer (block-state and biome +strategies: single-value, linear, hash-map and global palettes, resizing, network +write and read, pack and unpack) and through horizon_core::paletted. Both sides +print the set results, the serialized container after every few edits, the +container read back from the wire, the saved form (palette, bit width, storage) +and the container loaded from it, as hashes. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +BUILD = lab.ROOT / 'target/paletted-container-parity' +LIMITS = {'blocks': (4096, 35723), 'biomes': (64, 67)} + + +def corpus(): + rng = random.Random(0x50414C45545445) + counts = [1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 31, 32, 33, 64, 100, 128, 129, 200, 256, 257, 300, 700, 2000] + for kind, (entries, ids) in LIMITS.items(): + for count in counts: + if kind == 'biomes' and count > 70: + continue + for trial in range(6): + pool = rng.sample(range(ids), min(count, ids)) + initial = rng.choice(pool) if trial % 2 else rng.randrange(ids) + ops = [] + for _ in range(rng.choice([entries // 4, entries, entries * 3])): + ops.append((rng.randrange(entries), rng.choice(pool))) + if trial == 5: + # Every position written once, in order, then half of them reset. + ops = [(i, pool[i % len(pool)]) for i in range(entries)] + [(i, initial) for i in range(0, entries, 2)] + yield f'{kind}_{count}_{trial}', kind, initial, rng.choice([1, 7, 37, 211]), ops + # A few edits at a time: the palette grows one value at a time from a single value. + for trial in range(20): + ops = [(rng.randrange(entries), rng.randrange(ids)) for _ in range(rng.randrange(1, 40))] + yield f'{kind}_sparse_{trial}', kind, rng.randrange(ids), 1, ops + # Overwriting with the value already there, and filling a section with one value. + yield f'{kind}_fill', kind, 3, 500, [(i, 9) for i in range(entries)] + [(i, 3) for i in range(entries)] + yield f'{kind}_same', kind, 3, 1, [(i, 3) for i in range(0, entries, 5)] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.parse_args() + lock, jars, libraries = base.verify_artifacts() + BUILD.mkdir(parents=True, exist_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java' + sources = [Path(__file__), oracle, lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-core/examples/paletted_fixture.rs', + *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs'))] + tested = base.source_hashes(sources) + scenarios = list(corpus()) + inputs = BUILD / 'inputs.txt' + inputs.write_text(''.join(f'{name} {kind} {initial} {every} ' + ' '.join(f'{i} {v}' for i, v in ops) + '\n' + for name, kind, initial, every, ops in scenarios)) + + def run(command, name): + with (BUILD / (name + '.log')).open('w') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + classes = BUILD / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', os.environ.get('CARGO_BUILD_JOBS', '3'), '-p', 'horizon-core', '--example', 'paletted_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) + binary = Path(metadata['target_directory']) / 'fast/examples/paletted_fixture' + run([binary, inputs, BUILD / 'rust.txt'], 'rust') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPalettedContainerOracle', inputs, BUILD / 'client.txt'], 'client') + client = (BUILD / 'client.txt').read_text().splitlines() + rust = (BUILD / 'rust.txt').read_text().splitlines() + assert len(client) == len(rust) == len(scenarios), (len(client), len(rust), len(scenarios)) + bad = [(a, b) for a, b in zip(client, rust) if a != b] + base.ensure_sources_unchanged(sources, tested) + for a, b in bad[:5]: + print('client', a[:600]) + print('rust ', b[:600]) + if bad: + raise SystemExit(f'{len(bad)} of {len(scenarios)} scenarios differ') + edits = sum(len(s[4]) for s in scenarios) + report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenarios': len(scenarios), 'edits': edits, + 'sources_sha256': tested} + lab.write_json(BUILD / 'report.json', report) + print(f'PalettedContainer parity: {len(scenarios)} scenarios, {edits:,} edits, all hashes identical') + + +if __name__ == '__main__': + main() From c9ad9869d9c9387fa7e562e433a06f0b1013282f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:49:56 +0200 Subject: [PATCH 06/24] Start the menu click oracle and tweak the interaction lab Work in progress on the vanilla menu oracle adapter used by the upcoming menu click parity harness. Co-Authored-By: Claude Sonnet 5.5 --- .../horizonlab/parity/VanillaMenuOracle.java | 201 ++++++++++++++++++ tools/interaction_lab.py | 9 +- 2 files changed, 207 insertions(+), 3 deletions(-) create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java new file mode 100644 index 000000000..674ffa00e --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -0,0 +1,201 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeManager; + +/** + * Original oracle: AbstractContainerMenu.clicked over vanilla's real menu + * classes. A stand-in player (inventory, drops recorded) and a stand-in server + * level (real RecipeManager, no networking) run each case's clicks; after + * every click the slots, carried stack, data slots, drops and player state + * are printed as canonical NBT. + */ +public final class VanillaMenuOracle { + static Object unsafe; + static java.lang.reflect.Method allocate; + static RecipeManager recipes; + static final List drops = new ArrayList<>(); + + @SuppressWarnings("unchecked") + static T make(Class type) { + try { + return (T) allocate.invoke(unsafe, type); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + static void set(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + f.set(target, value); + } + + static final class Server extends net.minecraft.server.dedicated.DedicatedServer { + Server() { + super(null, null, null, null, null, null, null, null, null, null); + } + @Override public RecipeManager getRecipeManager() { return recipes; } + } + + static final class Connection extends ServerGamePacketListenerImpl { + Connection() { + super(null, null, null, null); + } + @Override public void send(net.minecraft.network.protocol.Packet packet) { } + } + + static final class World extends ServerLevel { + Server server; + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public net.minecraft.server.MinecraftServer getServer() { return server; } + @Override public RecipeManager recipeAccess() { return recipes; } + @Override public boolean isClientSide() { return false; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; } + @Override public net.minecraft.world.level.gamerules.GameRules getGameRules() { return new net.minecraft.world.level.gamerules.GameRules(FeatureFlags.DEFAULT_FLAGS); } + @Override public void levelEvent(net.minecraft.world.entity.Entity p, int type, BlockPos pos, int data) { } + @Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { } + @Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; } + @Override public void gameEvent(net.minecraft.core.Holder e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + } + + static final class FakePlayer extends ServerPlayer { + World world; + boolean creative; + Inventory inv; + FakePlayer() { + super(null, null, null, null); + } + @Override public Inventory getInventory() { return inv; } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public boolean isSpectator() { return false; } + @Override public EntityType getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public boolean canUseSlot(EquipmentSlot slot) { return true; } + @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { } + @Override public boolean hasDisconnected() { return false; } + @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { + if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); + return null; + } + @Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); } + @Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); } + } + + static AbstractContainerMenu menu(String kind, FakePlayer player, Inventory inv) { + var access = ContainerLevelAccess.create(player.world, BlockPos.ZERO); + if (kind.startsWith("chest")) { + int rows = Integer.parseInt(kind.substring(5)); + MenuType type = new MenuType[]{MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6}[rows - 1]; + return new ChestMenu(type, 0, inv, new SimpleContainer(9 * rows), rows); + } + return switch (kind) { + case "inventory" -> new InventoryMenu(inv, true, player); + case "crafting" -> new CraftingMenu(0, inv, access); + case "hopper" -> new HopperMenu(0, inv); + case "dispenser" -> new DispenserMenu(0, inv); + case "shulker" -> new ShulkerBoxMenu(0, inv); + case "furnace" -> new FurnaceMenu(0, inv); + case "blast_furnace" -> new BlastFurnaceMenu(0, inv); + case "smoker" -> new SmokerMenu(0, inv); + case "brewing" -> new BrewingStandMenu(0, inv); + case "crafter" -> new CrafterMenu(0, inv); + default -> throw new IllegalArgumentException(kind); + }; + } + + static String state(AbstractContainerMenu menu, Inventory inv) throws Exception { + StringBuilder out = new StringBuilder(); + for (int i = 0; i < menu.slots.size(); i++) { + out.append(i > 0 ? " " : "").append(ParityData.canon(menu.getSlot(i).getItem())); + } + out.append(" | ").append(ParityData.canon(menu.getCarried())); + Field dataSlots = AbstractContainerMenu.class.getDeclaredField("dataSlots"); + dataSlots.setAccessible(true); + List data = (List) dataSlots.get(menu); + out.append(" |"); + for (DataSlot d : data) out.append(' ').append(d.get()); + out.append(" | ").append(String.join(";", drops)); + return out.toString(); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + drops.clear(); + var world = make(World.class); + world.server = make(Server.class); + var player = make(FakePlayer.class); + player.world = world; + player.creative = f.get("creative").getAsBoolean(); + set(player, ServerPlayer.class, "connection", make(Connection.class)); + var inv = new Inventory(player, new EntityEquipment()); + player.inv = inv; + AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); + set(player, Player.class, "inventoryMenu", menu); + var slotsJson = f.getAsJsonArray("slots"); + for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString())); + menu.setCarried(ParityData.stack(f.get("carried").getAsString())); + var dataJson = f.getAsJsonArray("data"); + for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); + drops.clear(); + out.println("init " + state(menu, inv)); + for (var opJson : f.getAsJsonArray("ops")) { + var op = opJson.getAsJsonArray(); + int slot = op.get(0).getAsInt(); + int button = op.get(1).getAsInt(); + var input = ContainerInput.valueOf(op.get(2).getAsString()); + try { + menu.clicked(slot, button, input, player); + } catch (RuntimeException e) { + Throwable cause = e.getCause() != null ? e.getCause() : e; + out.println("error " + cause.getClass().getSimpleName()); + if (System.getenv("MENU_TRACE") != null) cause.printStackTrace(); + continue; + } + out.println(state(menu, inv)); + } + out.println("end"); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index 19cbd44bd..2c8944f02 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -34,9 +34,12 @@ class Vanilla: def compile(self, *oracles): sources = [PARITY / (name + '.java') for name in oracles] - subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', - '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', - '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], check=True) + done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30', + '-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True) + if done.returncode: + print(done.stderr.replace(str(lab.ROOT) + '/', '')) + raise SystemExit('javac failed') def run(self, oracle, *args, heap='2G'): subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps, From 2209950220fa883295b0d5fc7633a532cfcfcf19 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:01:10 +0200 Subject: [PATCH 07/24] WIP: paletted containers and mesher changes Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/examples/chunk_bench.rs | 26 +++++++++++--- crates/horizon-client/src/chunk.rs | 17 +++++----- .../src/game/commands/terrain_cmds.rs | 3 +- crates/horizon-client/src/game/sculk.rs | 34 +++++++++---------- crates/horizon-client/src/mesher.rs | 15 ++++---- crates/horizon-client/src/save.rs | 11 ++++-- crates/horizon-client/src/testgen.rs | 9 +++-- crates/horizon-client/src/vanillagen.rs | 3 +- .../horizon-core/examples/paletted_fixture.rs | 11 +++--- crates/horizon-core/src/paletted.rs | 11 ++++-- 10 files changed, 82 insertions(+), 58 deletions(-) diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index b99f49a2a..be60496f0 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -33,7 +33,11 @@ fn main() -> Result<()> { let assets = Assets::load(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; let biomes = Biomes::load(&root)?; - let tables = MeshTables::new(&assets, &facts, models::load_visibility(&root, assets.registry)?)?; + let tables = MeshTables::new( + &assets, + &facts, + models::load_visibility(&root, assets.registry)?, + )?; let light = LightTables::load(&root, assets.registry, &facts)?; let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?; let mut worker = terrain.worker(); @@ -51,7 +55,9 @@ fn main() -> Result<()> { for x in 1..=inner { let mut region: [Proto; 9] = std::array::from_fn(|k| { let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize].take().expect("proto") + protos[((z + dz) * outer + x + dx) as usize] + .take() + .expect("proto") }); terrain.decorate(&mut worker, &mut region); for (k, p) in region.into_iter().enumerate() { @@ -73,7 +79,10 @@ fn main() -> Result<()> { } } let finish = started.elapsed().as_secs_f64(); - println!("finish (proto -> resident chunk): {:.1} ms per chunk", finish * 1e3 / chunks.len() as f64); + println!( + "finish (proto -> resident chunk): {:.1} ms per chunk", + finish * 1e3 / chunks.len() as f64 + ); let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); @@ -90,7 +99,10 @@ fn main() -> Result<()> { lit.push(((x, z), light_chunk(&borrowed, &light, true))); } } - println!("light: {:.2} ms per column", started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64); + println!( + "light: {:.2} ms per column", + started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64 + ); let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); for ((x, z), sections) in lit { chunks[((z - 1) * inner + x - 1) as usize].sections = sections; @@ -149,7 +161,11 @@ fn main() -> Result<()> { } best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs)); } - println!("mesh: {:.1} us per section ({} quads total)", best * 1e6, quads); + println!( + "mesh: {:.1} us per section ({} quads total)", + best * 1e6, + quads + ); // Random lookups, as collision and entity queries do. let mut state = 0x9E37_79B9_7F4A_7C15u64; diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 207e8df52..caf489f1a 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -1,8 +1,8 @@ //! Resident client chunk storage. Sections are reference-counted so worker //! threads can mesh and light immutable snapshots while the game thread edits //! (copy-on-write through `Arc::make_mut`). -use horizon_world::registry::BlockStateId; use horizon_core::paletted::{PalettedContainer, Strategy}; +use horizon_world::registry::BlockStateId; use std::sync::Arc; pub const MIN_Y: i32 = -64; @@ -80,10 +80,10 @@ impl Section { /// block uses any more. pub fn compact(&mut self) { for container in [&mut self.blocks, &mut self.biomes] { - if container.bits() != 0 { - if let Some(v) = container.uniform() { - *container = PalettedContainer::new(container.strategy(), v); - } + if container.bits() != 0 + && let Some(v) = container.uniform() + { + *container = PalettedContainer::new(container.strategy(), v); } } if let Light::Full(a) = &self.light @@ -183,8 +183,9 @@ impl Chunk { /// Sets the biome of one quart cell (`qy` counts from the column's bottom). pub fn set_biome_cell(&mut self, qx: i32, qy: i32, qz: i32, biome: u16) { let section = Arc::make_mut(&mut self.sections[(qy >> 2) as usize]); - section - .biomes - .set(((qy & 3) << 4 | (qz & 3) << 2 | (qx & 3)) as usize, u32::from(biome)); + section.biomes.set( + ((qy & 3) << 4 | (qz & 3) << 2 | (qx & 3)) as usize, + u32::from(biome), + ); } } diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 5804e8013..678f4e2ab 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -214,10 +214,9 @@ impl Game<'_> { continue; } let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1); - let index = (qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize; if let Some(chunk) = self.world.chunks.get_mut(&key) { let chunk = std::sync::Arc::make_mut(chunk); - std::sync::Arc::make_mut(&mut chunk.biomes)[index] = target as u16; + chunk.set_biome_cell((x & 15) >> 2, qy, (z & 15) >> 2, target as u16); } touched.insert(key); changed += 1; diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index e2d985417..15d10a355 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -336,30 +336,28 @@ impl Game<'_> { } } fn sculk_scan_chunk(&mut self, key: (i32, i32)) { - use horizon_client::chunk::{Blocks, MIN_Y}; + use horizon_client::chunk::MIN_Y; let Some(chunk) = self.world.chunks.get(&key).cloned() else { return; }; let mut found = Vec::new(); for (s, section) in chunk.sections.iter().enumerate() { let y0 = MIN_Y + s as i32 * 16; - match §ion.blocks { - Blocks::Uniform(v) => { - // A uniform section of sculk blocks does not exist. - let _ = v; - } - Blocks::Full(a) => { - for (i, v) in a.iter().enumerate() { - if self.kind_of_state(*v) != 0 { - let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8); - found.push(( - key.0 * 16 + x as i32, - y0 + y as i32, - key.1 * 16 + z as i32, - *v, - )); - } - } + if section.blocks.uniform().is_some() { + // A uniform section of sculk blocks does not exist. + continue; + } + let mut a = [0u16; 4096]; + section.unpack(&mut a); + for (i, v) in a.iter().enumerate() { + if self.kind_of_state(*v) != 0 { + let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8); + found.push(( + key.0 * 16 + x as i32, + y0 + y as i32, + key.1 * 16 + z as i32, + *v, + )); } } } diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 52c8f22ff..ee296269b 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -397,14 +397,13 @@ impl Padded { let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]; let i = pi(x, y, z); if let Some(c) = chunk { - blocks[i] = if (0..16).contains(&x) - && (0..16).contains(&y) - && (0..16).contains(&z) - { - own[(y << 8 | z << 4 | x) as usize] - } else { - c.get(x & 15, wy, z & 15) - }; + blocks[i] = + if (0..16).contains(&x) && (0..16).contains(&y) && (0..16).contains(&z) + { + own[(y << 8 | z << 4 | x) as usize] + } else { + c.get(x & 15, wy, z & 15) + }; light[i] = c.light(x & 15, wy, z & 15); } else { light[i] = 0xF0; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 95aa1f1b7..8fa168ef1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -863,11 +863,14 @@ pub fn decode_with( .collect(); let target = Arc::make_mut(&mut chunk.sections[si as usize]); let data = match states.get("data") { - Some(Tag::LongArray(data)) => Some(data.iter().map(|&w| w as u64).collect::>()), + Some(Tag::LongArray(data)) => { + Some(data.iter().map(|&w| w as u64).collect::>()) + } _ => None, }; let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); - if let Ok(blocks) = PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref()) + if let Ok(blocks) = + PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref()) { target.blocks = blocks; } @@ -883,7 +886,9 @@ pub fn decode_with( }) .collect(); let data = match b.get("data") { - Some(Tag::LongArray(data)) => Some(data.iter().map(|&w| w as u64).collect::>()), + Some(Tag::LongArray(data)) => { + Some(data.iter().map(|&w| w as u64).collect::>()) + } _ => None, }; let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs index 2581d9229..e0a5d49b3 100644 --- a/crates/horizon-client/src/testgen.rs +++ b/crates/horizon-client/src/testgen.rs @@ -77,11 +77,10 @@ impl TestTerrain { fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk { let mut chunk = Chunk::empty(cx, cz); for s in &mut chunk.sections { - std::sync::Arc::make_mut(s).biomes = - horizon_core::paletted::PalettedContainer::new( - crate::chunk::BIOME_STRATEGY, - u32::from(self.plains), - ); + std::sync::Arc::make_mut(s).biomes = horizon_core::paletted::PalettedContainer::new( + crate::chunk::BIOME_STRATEGY, + u32::from(self.plains), + ); } for z in 0..16 { for x in 0..16 { diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index b0d56a66e..c889c5169 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -195,7 +195,8 @@ impl ChunkGenerator for VanillaTerrain { } } if any { - Arc::make_mut(&mut out.sections[si as usize]).blocks = Section::from_blocks(&values); + Arc::make_mut(&mut out.sections[si as usize]).blocks = + Section::from_blocks(&values); } } let base_section = chunk.terrain.min_y() >> 4; diff --git a/crates/horizon-core/examples/paletted_fixture.rs b/crates/horizon-core/examples/paletted_fixture.rs index 4008e573f..feff4db89 100644 --- a/crates/horizon-core/examples/paletted_fixture.rs +++ b/crates/horizon-core/examples/paletted_fixture.rs @@ -106,13 +106,14 @@ fn main() -> Result<(), Box> { let reread = read(strategy, &write(&c)); let packed = c.pack(); let storage = packed.data.as_ref().map_or(BASIS, |data| { - data.iter() - .flat_map(|w| w.to_le_bytes()) - .fold(BASIS, |h, b| fnv(h, b)) + data.iter().flat_map(|w| w.to_le_bytes()).fold(BASIS, fnv) }); let palette: Vec = packed.palette.iter().map(u32::to_string).collect(); - let loaded = - PalettedContainer::from_packed(strategy, packed.palette.clone(), packed.data.as_deref())?; + let loaded = PalettedContainer::from_packed( + strategy, + packed.palette.clone(), + packed.data.as_deref(), + )?; writeln!( out, "{} {} cp={} bits={} final={} values={} read={}/{} packed={}/{}/{} loaded={}/{}", diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index 8f39cebb7..9344d9392 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -693,15 +693,20 @@ mod tests { assert_eq!(c.get(i), v); } let packed = c.pack(); - let loaded = PalettedContainer::from_packed(strategy, packed.palette.clone(), packed.data.as_deref()) - .unwrap(); + let loaded = PalettedContainer::from_packed( + strategy, + packed.palette.clone(), + packed.data.as_deref(), + ) + .unwrap(); assert_eq!(loaded, c); assert_eq!(loaded.pack(), packed); let again = PalettedContainer::from_values(strategy, &plain); assert_eq!(again, c); assert_eq!(again.pack(), packed); let (bits, palette, words) = c.to_wire(); - let wire = PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap(); + let wire = + PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap(); assert_eq!(wire, c); } } From 89630c80fe537829757d447662cee4d3c4ba78a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:01:09 +0200 Subject: [PATCH 08/24] Port AbstractContainerMenu clicks and test them against vanilla menus A pure menu engine now implements every click type (pickup, quick move, swap, clone, throw, the three quick craft drags, pickup all) for the player inventory, crafting table, chests, hopper, dispenser, shulker box and the furnaces, with armour, fuel, output and crafting result slot rules, the crafting result recompute and remainders, and Inventory.add. The new menu click harness runs thousands of randomized click sequences through vanilla's real menu classes and this engine and compares every slot, the carried stack, data slots and drops. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/examples/menu_fixture.rs | 69 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 1186 +++++++++++++++++ .../horizonlab/parity/VanillaMenuOracle.java | 6 +- tools/logs/latest.log | 0 tools/test_menu_click_parity.py | 164 +++ 6 files changed, 1425 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/examples/menu_fixture.rs create mode 100644 crates/horizon-client/src/menu.rs create mode 100644 tools/logs/latest.log create mode 100644 tools/test_menu_click_parity.py diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs new file mode 100644 index 000000000..ded828ef3 --- /dev/null +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -0,0 +1,69 @@ +//! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per +//! line (menu, creative, slots, carried, data, ops) and prints the oracle's +//! state lines after every click. +//! +//! usage: menu_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::Items, + menu::{Env, Input, Kind, Menu}, +}; +use serde_json::Value; +use std::{fs, path::Path}; + +fn state(menu: &Menu) -> String { + let slots: Vec = (0..menu.slot_count()) + .map(|i| canon_stack(menu.slot(i))) + .collect(); + let data: String = menu.data.iter().map(|d| format!(" {d}")).collect(); + format!( + "{} | {} |{data} | {}", + slots.join(" "), + canon_stack(menu.carried.as_ref()), + menu.drops.join(";") + ) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let env = Env { + items: &items, + recipes: &recipes, + }; + let mut out = String::new(); + for line in input.lines() { + let case: Value = serde_json::from_str(line)?; + let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?; + let mut menu = Menu::new(kind); + menu.creative = case["creative"].as_bool().unwrap_or(false); + for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { + menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); + } + menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { + menu.data[i] = v.as_i64().unwrap_or(0) as i32; + } + menu.drops.clear(); + out += &format!("init {}\n", state(&menu)); + for op in case["ops"].as_array().ok_or("ops")? { + let slot = op[0].as_i64().unwrap_or(0) as i32; + let button = op[1].as_i64().unwrap_or(0) as i32; + let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; + match menu.click(&env, slot, button, kind) { + Ok(()) => out += &format!("{}\n", state(&menu)), + Err(name) => out += &format!("error {name}\n"), + } + } + out += "end\n"; + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 09c1ecbb0..bb2dd3763 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -46,6 +46,7 @@ pub mod keybinds; pub mod landing; pub mod lang; pub mod light; +pub mod menu; pub mod merchant; pub mod mesher; pub mod mobs; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs new file mode 100644 index 000000000..5190cf16f --- /dev/null +++ b/crates/horizon-client/src/menu.rs @@ -0,0 +1,1186 @@ +//! `AbstractContainerMenu.clicked` over vanilla's slot layouts: every +//! `ContainerInput` (pickup, quick move, swap, clone, throw, the three quick +//! craft drags, pickup all) for the player inventory, the crafting table, the +//! chest family, hoppers, dispensers, shulker boxes and the furnaces. +//! `tools/test_menu_click_parity.py` compares every click with vanilla's menu +//! classes. +use crate::{ + crafting::Recipes, + items::{ItemStack, Items}, +}; + +/// What a menu needs to know about items and recipes. +pub struct Env<'a> { + pub items: &'a Items, + pub recipes: &'a Recipes, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Input { + Pickup, + QuickMove, + Swap, + Clone, + Throw, + QuickCraft, + PickupAll, +} + +impl Input { + pub fn parse(name: &str) -> Option { + Some(match name { + "PICKUP" => Self::Pickup, + "QUICK_MOVE" => Self::QuickMove, + "SWAP" => Self::Swap, + "CLONE" => Self::Clone, + "THROW" => Self::Throw, + "QUICK_CRAFT" => Self::QuickCraft, + "PICKUP_ALL" => Self::PickupAll, + _ => return None, + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Inventory, + Crafting, + Chest(usize), + Hopper, + Dispenser, + Shulker, + /// The cooking recipe type: smelting, blasting or smoking. + Furnace(&'static str), +} + +impl Kind { + pub fn parse(name: &str) -> Option { + if let Some(rows) = name.strip_prefix("chest") { + return rows.parse().ok().map(Self::Chest); + } + Some(match name { + "inventory" => Self::Inventory, + "crafting" => Self::Crafting, + "hopper" => Self::Hopper, + "dispenser" => Self::Dispenser, + "shulker" => Self::Shulker, + "furnace" => Self::Furnace("smelting"), + "blast_furnace" => Self::Furnace("blasting"), + "smoker" => Self::Furnace("smoking"), + _ => return None, + }) + } +} + +/// `Slot` subclasses that change the rules. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Role { + Plain, + /// `ArmorSlot` for the equipment slot with this `EquipmentSlot.getIndex`. + Armor(usize), + Shulker, + Fuel, + /// `FurnaceResultSlot`. + Output, + /// `ResultSlot` of a crafting grid. + CraftResult, +} + +#[derive(Clone, Copy)] +struct Slot { + container: usize, + index: usize, + role: Role, +} + +/// The containers a menu spans. +const PLAYER: usize = 0; +const MAIN: usize = 1; +const GRID: usize = 2; +const RESULT: usize = 3; +/// `Container.getMaxStackSize`. +const CONTAINER_MAX: u32 = 99; +const OFFHAND: usize = 40; + +pub struct Menu { + kind: Kind, + slots: Vec, + containers: [Vec>; 4], + grid_size: usize, + pub carried: Option, + pub data: Vec, + pub creative: bool, + /// Dropped stacks (canonical text), `xp+N` and the like, in order. + pub drops: Vec, + quick_status: i32, + quick_type: i32, + quick_slots: Vec, +} + +fn same_item(a: &ItemStack, b: &ItemStack) -> bool { + a.item == b.item +} + +fn split(stack: &mut ItemStack, amount: u32) -> ItemStack { + let real = amount.min(stack.count); + let mut out = stack.clone(); + out.count = real; + stack.count -= real; + out +} + +fn tidy(slot: &mut Option) { + if slot.as_ref().is_some_and(|s| s.count == 0) { + *slot = None; + } +} + +/// An index outside the slot list: vanilla's `IndexOutOfBoundsException`. +pub const OUT_OF_BOUNDS: &str = "IndexOutOfBoundsException"; + +impl Menu { + pub fn new(kind: Kind) -> Self { + let mut containers: [Vec>; 4] = Default::default(); + containers[PLAYER] = vec![None; 41]; + let mut slots = Vec::new(); + let mut grid_size = 0; + let main = |n: usize, role: Role| -> Vec { + (0..n) + .map(|index| Slot { + container: MAIN, + index, + role, + }) + .collect() + }; + let player = |slots: &mut Vec| { + for i in (9..36).chain(0..9) { + slots.push(Slot { + container: PLAYER, + index: i, + role: Role::Plain, + }); + } + }; + let grid = |slots: &mut Vec, n: usize| { + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CraftResult, + }); + for index in 0..n * n { + slots.push(Slot { + container: GRID, + index, + role: Role::Plain, + }); + } + }; + let mut data = 0; + match kind { + Kind::Inventory => { + grid_size = 2; + grid(&mut slots, 2); + for (i, eq) in [3usize, 2, 1, 0].into_iter().enumerate() { + slots.push(Slot { + container: PLAYER, + index: 39 - i, + role: Role::Armor(eq), + }); + } + player(&mut slots); + slots.push(Slot { + container: PLAYER, + index: OFFHAND, + role: Role::Plain, + }); + } + Kind::Crafting => { + grid_size = 3; + grid(&mut slots, 3); + player(&mut slots); + } + Kind::Chest(rows) => { + containers[MAIN] = vec![None; rows * 9]; + slots.extend(main(rows * 9, Role::Plain)); + player(&mut slots); + } + Kind::Hopper => { + containers[MAIN] = vec![None; 5]; + slots.extend(main(5, Role::Plain)); + player(&mut slots); + } + Kind::Dispenser => { + containers[MAIN] = vec![None; 9]; + slots.extend(main(9, Role::Plain)); + player(&mut slots); + } + Kind::Shulker => { + containers[MAIN] = vec![None; 27]; + slots.extend(main(27, Role::Shulker)); + player(&mut slots); + } + Kind::Furnace(_) => { + containers[MAIN] = vec![None; 3]; + slots.extend([ + Slot { + container: MAIN, + index: 0, + role: Role::Plain, + }, + Slot { + container: MAIN, + index: 1, + role: Role::Fuel, + }, + Slot { + container: MAIN, + index: 2, + role: Role::Output, + }, + ]); + player(&mut slots); + data = 4; + } + } + containers[GRID] = vec![None; grid_size * grid_size]; + containers[RESULT] = vec![None; 1]; + Self { + kind, + slots, + containers, + grid_size, + carried: None, + data: vec![0; data], + creative: false, + drops: Vec::new(), + quick_status: 0, + quick_type: 0, + quick_slots: Vec::new(), + } + } + + pub fn slot_count(&self) -> usize { + self.slots.len() + } + + pub fn slot(&self, i: usize) -> Option<&ItemStack> { + let s = self.slots[i]; + self.containers[s.container][s.index].as_ref() + } + + /// Sets a slot as a test fixture does (`Slot.set`). + pub fn set_slot(&mut self, env: &Env, i: usize, stack: Option) { + self.put(env, i, stack); + } + + pub fn player_item(&self, i: usize) -> Option<&ItemStack> { + self.containers[PLAYER][i].as_ref() + } + + // ---- item helpers ---- + + fn max_stack(env: &Env, stack: &ItemStack) -> u32 { + env.items.get(&stack.item).map_or(64, |i| i.max_stack) + } + + fn damageable(env: &Env, stack: &ItemStack) -> bool { + env.items.get(&stack.item).is_some_and(|i| i.max_damage > 0) + } + + /// `ItemStack.isStackable`. + fn stackable(env: &Env, stack: &ItemStack) -> bool { + Self::max_stack(env, stack) > 1 && !(Self::damageable(env, stack) && stack.damage > 0) + } + + fn is_bucket(stack: &ItemStack) -> bool { + &*stack.item == "minecraft:bucket" + } + + fn is_fuel(env: &Env, stack: &ItemStack) -> bool { + env.items.get(&stack.item).is_some_and(|i| i.fuel.is_some()) + } + + /// `Item.canFitInsideContainerItems`: shulker boxes cannot nest. + fn fits_inside(stack: &ItemStack) -> bool { + !(stack.item.ends_with("shulker_box")) + } + + // ---- Slot ---- + + fn may_place(&self, env: &Env, s: usize, stack: &ItemStack) -> bool { + match self.slots[s].role { + Role::Plain => true, + Role::Armor(eq) => env + .items + .get(&stack.item) + .and_then(|i| { + let slot = match i.equip_slot.as_deref()? { + "feet" => 0, + "legs" => 1, + "chest" => 2, + "head" => 3, + _ => return None, + }; + let allowed = i + .equip_allowed + .as_ref() + .is_none_or(|a| a.contains("minecraft:player")); + Some(slot == eq && allowed) + }) + .unwrap_or(false), + Role::Shulker => Self::fits_inside(stack), + Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), + Role::Output | Role::CraftResult => false, + } + } + + fn may_pickup(&self, s: usize) -> bool { + match self.slots[s].role { + Role::Armor(_) => match self.slot(s) { + Some(stack) => { + self.creative || stack.enchantment_level("minecraft:binding_curse") == 0 + } + None => true, + }, + _ => true, + } + } + + /// `Slot.getMaxStackSize(stack)`. + fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { + let own = match self.slots[s].role { + Role::Armor(_) => 1, + Role::Fuel if Self::is_bucket(stack) => return 1, + _ => CONTAINER_MAX, + }; + own.min(Self::max_stack(env, stack)) + } + + /// `Container.setItem` (a grid change recomputes the result). + fn put(&mut self, env: &Env, s: usize, mut stack: Option) { + tidy(&mut stack); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = stack; + if slot.container == GRID { + self.recompute(env); + } + } + + /// `Slot.remove`: the container's `removeItem`. + fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option { + let slot = self.slots[s]; + if slot.container == RESULT { + return self.containers[RESULT][0].take(); + } + let cell = &mut self.containers[slot.container][slot.index]; + let out = cell + .as_mut() + .filter(|c| c.count > 0) + .map(|c| split(c, amount)); + tidy(cell); + if out.is_some() && slot.container == GRID { + self.recompute(env); + } + out + } + + /// `CraftingMenu.slotChangedCraftingGrid`. + fn recompute(&mut self, env: &Env) { + if self.grid_size == 0 { + return; + } + let result = env + .recipes + .find(&self.containers[GRID], self.grid_size) + .map(|(_, stack)| stack); + self.containers[RESULT][0] = result; + } + + /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. + fn on_take(&mut self, env: &Env, s: usize) { + if self.slots[s].role != Role::CraftResult { + return; + } + let n = self.grid_size; + let grid = self.containers[GRID].clone(); + let remaining = env + .recipes + .find(&grid, n) + .map(|(id, _)| env.recipes.remainders(id, &grid, n)) + .unwrap_or_else(|| { + // CraftingRecipe.defaultCraftingReminder + grid.iter() + .map(|cell| { + cell.as_ref().and_then(|stack| { + env.items + .get(&stack.item) + .and_then(|i| i.crafting_remainder.as_deref()) + .map(|r| ItemStack::new(r, 1)) + }) + }) + .collect() + }); + for cell in 0..n * n { + let mut here = self.containers[GRID][cell].take(); + if let Some(stack) = here.as_mut() { + stack.count -= 1; + } + tidy(&mut here); + self.containers[GRID][cell] = here; + if let Some(replacement) = remaining.get(cell).cloned().flatten() { + match self.containers[GRID][cell].as_mut() { + None => self.containers[GRID][cell] = Some(replacement), + Some(have) if have.same_item_same_components(&replacement) => { + let mut merged = replacement; + merged.count += have.count; + self.containers[GRID][cell] = Some(merged); + } + Some(_) => { + let mut left = replacement; + if !self.inventory_add(env, &mut left) { + self.drop_stack(&left); + } + } + } + } + } + self.recompute(env); + } + + fn drop_stack(&mut self, stack: &ItemStack) { + if stack.count > 0 { + self.drops.push(crate::item_data::canon_stack(Some(stack))); + } + } + + /// `Slot.tryRemove`. + fn try_remove( + &mut self, + env: &Env, + s: usize, + amount: u32, + max_amount: u32, + ) -> Option { + if !self.may_pickup(s) { + return None; + } + if !self.allow_modification(env, s) && max_amount < self.slot(s).map_or(0, |c| c.count) { + return None; + } + let result = self.remove(env, s, amount.min(max_amount))?; + if self.slot(s).is_none() { + self.put(env, s, None); + } + Some(result) + } + + fn allow_modification(&self, env: &Env, s: usize) -> bool { + self.may_pickup(s) + && match self.slot(s) { + Some(stack) => self.may_place(env, s, stack), + None => true, + } + } + + fn safe_take( + &mut self, + env: &Env, + s: usize, + amount: u32, + max_amount: u32, + ) -> Option { + let result = self.try_remove(env, s, amount, max_amount)?; + self.on_take(env, s); + Some(result) + } + + /// `Slot.safeInsert`: puts up to `amount` of `input` into the slot. + fn safe_insert(&mut self, env: &Env, s: usize, input: &mut Option, amount: u32) { + let Some(stack) = input.as_mut() else { return }; + if !self.may_place(env, s, stack) { + return; + } + let have = self.slot(s).map_or(0, |c| c.count); + let max = self.slot_max(env, s, stack); + let transferable = amount.min(stack.count).min(max.saturating_sub(have)); + if transferable == 0 { + return; + } + match self.slot(s).cloned() { + None => { + let part = split(stack, transferable); + self.put(env, s, Some(part)); + } + Some(mut current) if current.same_item_same_components(stack) => { + stack.count -= transferable; + current.count += transferable; + self.put(env, s, Some(current)); + } + Some(_) => {} + } + tidy(input); + } + + // ---- Inventory ---- + + /// `Inventory.getSlotWithRemainingSpace` (selected slot 0, offhand, rest). + fn slot_with_space(&self, env: &Env, stack: &ItemStack) -> Option { + let inv = &self.containers[PLAYER]; + [0, OFFHAND].into_iter().chain(0..36).find(|&i| { + inv[i].as_ref().is_some_and(|have| { + have.same_item_same_components(stack) + && Self::stackable(env, have) + && have.count < CONTAINER_MAX.min(Self::max_stack(env, have)) + }) + }) + } + + /// `Inventory.addResource`: returns what did not fit. + fn add_resource(&mut self, env: &Env, stack: &ItemStack) -> u32 { + let slot = self.slot_with_space(env, stack).or_else(|| { + self.containers[PLAYER][..36] + .iter() + .position(Option::is_none) + }); + let Some(slot) = slot else { return stack.count }; + let cell = self.containers[PLAYER][slot].get_or_insert_with(|| { + let mut empty = stack.clone(); + empty.count = 0; + empty + }); + let room = CONTAINER_MAX.min(Self::max_stack(env, cell)) - cell.count; + let add = stack.count.min(room); + cell.count += add; + tidy(&mut self.containers[PLAYER][slot]); + stack.count - add + } + + /// `Inventory.add(stack)`: the leftover stays in `stack`. + fn inventory_add(&mut self, env: &Env, stack: &mut ItemStack) -> bool { + if stack.count == 0 { + return false; + } + if Self::damageable(env, stack) && stack.damage > 0 { + if let Some(slot) = self.containers[PLAYER][..36] + .iter() + .position(Option::is_none) + { + self.containers[PLAYER][slot] = Some(stack.clone()); + stack.count = 0; + return true; + } + if self.creative { + stack.count = 0; + return true; + } + return false; + } + loop { + let last = stack.count; + stack.count = self.add_resource(env, stack); + if stack.count == 0 || stack.count >= last { + if stack.count == last && self.creative { + stack.count = 0; + return true; + } + return stack.count < last; + } + } + } +} + +/// `EquipmentSlot` of an item as the inventory menu's quick move sees it. +enum Equip { + Armor(usize), + Offhand, + Other, +} + +impl Menu { + fn equip(env: &Env, stack: &ItemStack) -> Equip { + match env + .items + .get(&stack.item) + .and_then(|i| i.equip_slot.as_deref()) + { + Some("feet") => Equip::Armor(0), + Some("legs") => Equip::Armor(1), + Some("chest") => Equip::Armor(2), + Some("head") => Equip::Armor(3), + Some("offhand") => Equip::Offhand, + _ => Equip::Other, + } + } + + fn has_item(&self, s: usize) -> bool { + self.slot(s).is_some() + } + + /// `AbstractContainerMenu.moveItemStackTo`. + fn move_to( + &mut self, + env: &Env, + stack: &mut ItemStack, + start: usize, + end: usize, + backwards: bool, + ) -> bool { + let mut changed = false; + let order = |_: ()| -> Vec { + if backwards { + (start..end).rev().collect() + } else { + (start..end).collect() + } + }; + if Self::stackable(env, stack) { + for dest in order(()) { + if stack.count == 0 { + break; + } + let max = match self.slot(dest) { + Some(target) if target.same_item_same_components(stack) => { + self.slot_max(env, dest, target) + } + _ => continue, + }; + let slot = self.slots[dest]; + let target = self.containers[slot.container][slot.index] + .as_mut() + .expect("checked"); + let total = target.count + stack.count; + if total <= max { + stack.count = 0; + target.count = total; + changed = true; + } else if target.count < max { + stack.count -= max - target.count; + target.count = max; + changed = true; + } + } + } + if stack.count > 0 { + for dest in order(()) { + if !self.has_item(dest) && self.may_place(env, dest, stack) { + let max = self.slot_max(env, dest, stack); + let part = split(stack, stack.count.min(max)); + self.put(env, dest, Some(part)); + changed = true; + break; + } + } + } + changed + } + + /// `quickMoveStack` of the menu's kind; the moved stack's original copy + /// (None when nothing moved). + fn quick_move(&mut self, env: &Env, index: usize) -> Option { + let mut stack = self.slot(index)?.clone(); + let clicked = stack.clone(); + let total = self.slots.len(); + let mut check_count = true; + let mut after_take = false; + match self.kind { + Kind::Chest(rows) => { + check_count = false; + let n = rows * 9; + if index < n { + if !self.move_to(env, &mut stack, n, total, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, n, false) { + return None; + } + } + Kind::Hopper => { + check_count = false; + if index < 5 { + if !self.move_to(env, &mut stack, 5, 41, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 5, false) { + return None; + } + } + Kind::Shulker => { + check_count = false; + if index < 27 { + if !self.move_to(env, &mut stack, 27, total, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 27, false) { + return None; + } + } + Kind::Dispenser => { + after_take = true; + if index < 9 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 9, false) { + return None; + } + } + Kind::Furnace(recipe) => { + after_take = true; + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index != 1 && index != 0 { + let smelts = env + .recipes + .cook(&format!("minecraft:{recipe}"), &stack) + .is_some(); + if smelts { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if Self::is_fuel(env, &stack) { + if !self.move_to(env, &mut stack, 1, 2, false) { + return None; + } + } else if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } + Kind::Crafting => { + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 10, 46, true) { + return None; + } + } else if (10..46).contains(&index) { + if !self.move_to(env, &mut stack, 1, 10, false) { + if index < 37 { + if !self.move_to(env, &mut stack, 37, 46, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 10, 37, false) { + return None; + } + } + } else if !self.move_to(env, &mut stack, 10, 46, false) { + return None; + } + } + Kind::Inventory => { + after_take = true; + let equip = Self::equip(env, &clicked); + let armor_free = |m: &Self, eq: usize| !m.has_item(8 - eq); + if index == 0 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if (1..9).contains(&index) { + if !self.move_to(env, &mut stack, 9, 45, false) { + return None; + } + } else if matches!(equip, Equip::Armor(eq) if armor_free(self, eq)) { + let Equip::Armor(eq) = equip else { + unreachable!() + }; + let pos = 8 - eq; + if !self.move_to(env, &mut stack, pos, pos + 1, false) { + return None; + } + } else if matches!(equip, Equip::Offhand) && !self.has_item(45) { + if !self.move_to(env, &mut stack, 45, 46, false) { + return None; + } + } else if (9..36).contains(&index) { + if !self.move_to(env, &mut stack, 36, 45, false) { + return None; + } + } else if (36..45).contains(&index) { + if !self.move_to(env, &mut stack, 9, 36, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 9, 45, false) { + return None; + } + } + } + // The stack was edited in place in its slot. + let slot = self.slots[index]; + if stack.count == 0 { + self.put(env, index, None); + } else { + self.containers[slot.container][slot.index] = Some(stack.clone()); + } + if check_count && stack.count == clicked.count { + return None; + } + if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) { + self.on_take(env, index); + } + if index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting) { + self.drop_stack(&stack); + } + Some(clicked) + } + + fn quick_replace(&self, s: usize, stack: &ItemStack, env: &Env) -> bool { + match self.slot(s) { + None => true, + Some(have) if have.same_item_same_components(stack) => { + have.count <= Self::max_stack(env, stack) + } + Some(_) => false, + } + } + + fn reset_quick_craft(&mut self) { + self.quick_status = 0; + self.quick_slots.clear(); + } + + /// `AbstractContainerMenu.clicked`: Err carries a vanilla exception name. + pub fn click( + &mut self, + env: &Env, + slot_index: i32, + button: i32, + input: Input, + ) -> Result<(), &'static str> { + let size = self.slots.len() as i32; + let in_range = |i: i32| (0..size).contains(&i); + if input == Input::QuickCraft { + let expected = self.quick_status; + self.quick_status = button & 3; + if (expected != 1 || self.quick_status != 2) && expected != self.quick_status { + self.reset_quick_craft(); + } else if self.carried.is_none() { + self.reset_quick_craft(); + } else if self.quick_status == 0 { + self.quick_type = (button >> 2) & 3; + if self.quick_type == 0 + || self.quick_type == 1 + || (self.quick_type == 2 && self.creative) + { + self.quick_status = 1; + self.quick_slots.clear(); + } else { + self.reset_quick_craft(); + } + } else if self.quick_status == 1 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + let carried = self.carried.clone().expect("checked"); + if self.quick_replace(s, &carried, env) + && self.may_place(env, s, &carried) + && (self.quick_type == 2 || carried.count as usize > self.quick_slots.len()) + && !self.quick_slots.contains(&s) + { + self.quick_slots.push(s); + } + } else if self.quick_status == 2 { + if !self.quick_slots.is_empty() { + if self.quick_slots.len() == 1 { + let s = self.quick_slots[0] as i32; + let ty = self.quick_type; + self.reset_quick_craft(); + return self.click(env, s, ty, Input::Pickup); + } + let mut source = self.carried.clone().expect("checked"); + let mut remaining = source.count as i64; + let carried = self.carried.clone().expect("checked"); + for s in self.quick_slots.clone() { + if self.quick_replace(s, &carried, env) + && self.may_place(env, s, &carried) + && (self.quick_type == 2 + || carried.count as usize >= self.quick_slots.len()) + { + let have = self.slot(s).map_or(0, |c| c.count); + let max = + Self::max_stack(env, &source).min(self.slot_max(env, s, &source)); + let each = match self.quick_type { + 0 => (source.count as f32 / self.quick_slots.len() as f32).floor() + as u32, + 1 => 1, + 2 => Self::max_stack(env, &source), + _ => source.count, + }; + let new_count = (each + have).min(max); + remaining -= i64::from(new_count) - i64::from(have); + let mut placed = source.clone(); + placed.count = new_count; + self.put(env, s, Some(placed)); + } + } + source.count = remaining.max(0) as u32; + self.carried = Some(source); + tidy(&mut self.carried); + } + self.reset_quick_craft(); + } else { + self.reset_quick_craft(); + } + return Ok(()); + } + if self.quick_status != 0 { + self.reset_quick_craft(); + return Ok(()); + } + if matches!(input, Input::Pickup | Input::QuickMove) && (button == 0 || button == 1) { + let primary = button == 0; + if slot_index == -999 { + if let Some(carried) = self.carried.as_mut() { + if primary { + let dropped = self.carried.take().expect("some"); + self.drop_stack(&dropped); + } else { + let one = split(carried, 1); + self.drop_stack(&one); + tidy(&mut self.carried); + } + } + } else if input == Input::QuickMove { + if slot_index < 0 { + return Ok(()); + } + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + if !self.may_pickup(s) { + return Ok(()); + } + let mut clicked = self.quick_move(env, s); + while let Some(c) = &clicked { + if !self.slot(s).is_some_and(|now| same_item(now, c)) { + break; + } + clicked = self.quick_move(env, s); + } + } else { + if slot_index < 0 { + return Ok(()); + } + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.pickup(env, slot_index as usize, primary); + } + } else if input == Input::Swap && ((0..9).contains(&button) || button == 40) { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.swap(env, slot_index as usize, button as usize); + } else if input == Input::Clone + && self.creative + && self.carried.is_none() + && slot_index >= 0 + { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + if let Some(stack) = self.slot(slot_index as usize) { + let mut copy = stack.clone(); + copy.count = Self::max_stack(env, stack); + self.carried = Some(copy); + } + } else if input == Input::Throw && self.carried.is_none() && slot_index >= 0 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + let s = slot_index as usize; + let amount = if button == 0 { + 1 + } else { + self.slot(s).map_or(0, |c| c.count) + }; + let mut taken = self.safe_take(env, s, amount, u32::MAX); + if let Some(t) = &taken { + self.drop_stack(t); + } + if button == 1 { + while let Some(t) = &taken { + if !self.slot(s).is_some_and(|now| same_item(now, t)) { + break; + } + taken = self.safe_take(env, s, amount, u32::MAX); + if let Some(t) = &taken { + self.drop_stack(t); + } + } + } + } else if input == Input::PickupAll && slot_index >= 0 { + if !in_range(slot_index) { + return Err(OUT_OF_BOUNDS); + } + self.pickup_all(env, slot_index as usize, button); + } + Ok(()) + } + + /// The PICKUP branch of `doClick` (without the bundle overrides). + fn pickup(&mut self, env: &Env, s: usize, primary: bool) { + let clicked = self.slot(s).cloned(); + match clicked { + None => { + if let Some(mut carried) = self.carried.take() { + let amount = if primary { carried.count } else { 1 }; + let mut input = Some(carried.clone()); + self.safe_insert(env, s, &mut input, amount); + carried = input.unwrap_or_else(|| { + let mut e = carried.clone(); + e.count = 0; + e + }); + self.carried = Some(carried); + tidy(&mut self.carried); + } + } + Some(clicked) if self.may_pickup(s) => match self.carried.take() { + None => { + let amount = if primary { + clicked.count + } else { + (clicked.count + 1) / 2 + }; + if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { + self.carried = Some(taken); + self.on_take(env, s); + } + } + Some(mut carried) => { + if self.may_place(env, s, &carried) { + if clicked.same_item_same_components(&carried) { + let amount = if primary { carried.count } else { 1 }; + let mut input = Some(carried.clone()); + self.safe_insert(env, s, &mut input, amount); + carried = input.unwrap_or_else(|| { + let mut e = carried.clone(); + e.count = 0; + e + }); + self.carried = Some(carried); + tidy(&mut self.carried); + } else if carried.count <= self.slot_max(env, s, &carried) { + self.carried = Some(clicked); + self.put(env, s, Some(carried)); + } else { + self.carried = Some(carried); + } + } else if clicked.same_item_same_components(&carried) { + let room = Self::max_stack(env, &carried).saturating_sub(carried.count); + self.carried = Some(carried.clone()); + if let Some(taken) = self.try_remove(env, s, clicked.count, room) { + if let Some(c) = self.carried.as_mut() { + c.count += taken.count; + } + self.on_take(env, s); + } + } else { + self.carried = Some(carried); + } + } + }, + Some(_) => {} + } + } + + /// The SWAP branch of `doClick`. + fn swap(&mut self, env: &Env, target: usize, button: usize) { + let inv_slot = button; + let source = self.containers[PLAYER][inv_slot].clone(); + let target_stack = self.slot(target).cloned(); + if source.is_none() && target_stack.is_none() { + return; + } + match (source, target_stack) { + (None, Some(taken)) => { + if self.may_pickup(target) { + self.containers[PLAYER][inv_slot] = Some(taken.clone()); + self.put(env, target, None); + self.on_take(env, target); + } + } + (Some(mut source), None) => { + if self.may_place(env, target, &source) { + let max = self.slot_max(env, target, &source); + if source.count > max { + let part = split(&mut source, max); + self.containers[PLAYER][inv_slot] = Some(source); + self.put(env, target, Some(part)); + } else { + self.containers[PLAYER][inv_slot] = None; + self.put(env, target, Some(source)); + } + } + } + (Some(mut source), Some(mut taken)) => { + if self.may_pickup(target) && self.may_place(env, target, &source) { + let max = self.slot_max(env, target, &source); + if source.count > max { + let part = split(&mut source, max); + self.containers[PLAYER][inv_slot] = Some(source); + self.put(env, target, Some(part)); + self.on_take(env, target); + if !self.inventory_add(env, &mut taken) { + self.drop_stack(&taken); + } + } else { + self.containers[PLAYER][inv_slot] = Some(taken); + self.put(env, target, Some(source)); + self.on_take(env, target); + } + } + } + (None, None) => {} + } + } + + /// The PICKUP_ALL branch (double click). + fn pickup_all(&mut self, env: &Env, s: usize, button: i32) { + let Some(carried) = self.carried.clone() else { + return; + }; + if self.has_item(s) && self.may_pickup(s) { + return; + } + let total = self.slots.len() as i32; + let (start, step) = if button == 0 { (0, 1) } else { (total - 1, -1) }; + let carried_max = Self::max_stack(env, &carried); + for pass in 0..2 { + let mut i = start; + while i >= 0 && i < total && self.carried.as_ref().map_or(0, |c| c.count) < carried_max + { + let t = i as usize; + i += step; + let have = self.carried.clone().expect("some"); + if self.has_item(t) + && self.quick_replace(t, &have, env) + && self.may_pickup(t) + && self.slots[t].container != RESULT + { + let item = self.slot(t).expect("has item").clone(); + if pass != 0 || item.count != Self::max_stack(env, &item) { + let room = carried_max - have.count; + if let Some(removed) = self.safe_take(env, t, item.count, room) { + if let Some(c) = self.carried.as_mut() { + c.count += removed.count; + } + } + } + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 674ffa00e..a505cb0bc 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -103,6 +103,9 @@ public final class VanillaMenuOracle { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); return null; } + @Override public void triggerRecipeCrafted(net.minecraft.world.item.crafting.RecipeHolder recipe, java.util.List items) { } + @Override public int awardRecipes(java.util.Collection> recipes) { return 0; } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { } @Override public void giveExperiencePoints(int amount) { drops.add("xp+" + amount); } @Override public void giveExperienceLevels(int amount) { drops.add("levels" + (amount >= 0 ? "+" : "") + amount); } } @@ -167,7 +170,8 @@ public final class VanillaMenuOracle { var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); - set(player, Player.class, "inventoryMenu", menu); + set(player, Player.class, "containerMenu", menu); + if (menu instanceof InventoryMenu im) set(player, Player.class, "inventoryMenu", im); var slotsJson = f.getAsJsonArray("slots"); for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString())); menu.setCarried(ParityData.stack(f.get("carried").getAsString())); diff --git a/tools/logs/latest.log b/tools/logs/latest.log new file mode 100644 index 000000000..e69de29bb diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py new file mode 100644 index 000000000..cd015e703 --- /dev/null +++ b/tools/test_menu_click_parity.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Compare AbstractContainerMenu.clicked with vanilla's menu classes. + +The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu +class with a stand-in player and level; the Rust example (menu_fixture) runs +horizon_client::menu. Cases are randomized slot contents with random click +sequences covering every ContainerInput (pickup, quick move, swap, clone, +throw, the three quick craft drags, pickup all) over the player inventory, +crafting table, chests, hopper, dispenser, shulker box and the furnaces. After +every click the slots, carried stack, data slots and drops are compared. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4} +COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', + 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', + 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', + 'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box', + 'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling', + 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest'] + + +def quote(text): + return '"' + text + '"' + + +def snbt(item, count, damage=0, curse=False): + comps = [] + if damage: + comps.append('"minecraft:damage":%d' % damage) + if curse: + comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}') + body = ',components:{%s}' % ','.join(comps) if comps else '' + return '{id:%s,count:%d%s}' % (quote(item), count, body) + + +class Gen: + def __init__(self, rng, items): + self.rng = rng + self.items = items + self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items] + self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k + and not k.endswith('_spawn_egg')] + + def stack(self): + rng = self.rng + item = rng.choice(self.pool if rng.random() < 0.85 else self.all) + info = self.items[item] + top = info.get('minecraft:max_stack_size', 64) + damage = 0 + if info.get('minecraft:max_damage') and rng.random() < 0.3: + damage = rng.randrange(1, info['minecraft:max_damage']) + count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) + return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info)) + + def slots(self, size, density): + return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] + + def recipe(self, slots, width): + """Fills the crafting grid (slots 1..) with a small known recipe.""" + rng = self.rng + amount = lambda: rng.choice([1, 1, 2, 5, 64]) + choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')], + [('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3], + [('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]] + pattern = rng.choice(choices) + if len(pattern) > width or any(len(row) > width for row in pattern): + pattern = [('oak_planks',), ('oak_planks',)] + for y, row in enumerate(pattern): + for x, name in enumerate(row): + slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1) + + def ops(self, size): + rng = self.rng + out = [] + for _ in range(rng.randrange(1, 9)): + kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'], + [30, 20, 8, 3, 6, 14, 6, 2])[0] + slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size) + if kind == 'PICKUP': + out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind]) + elif kind == 'QUICK_MOVE': + out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind]) + elif kind == 'SWAP': + out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind]) + elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'): + out.append([slot, rng.randrange(0, 2), kind]) + elif kind == 'DRAG': + ty = rng.randrange(0, 4) + out.append([-999, 0 | ty << 2, 'QUICK_CRAFT']) + for _ in range(rng.randrange(0, 6)): + out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT']) + out.append([-999, 2 | ty << 2, 'QUICK_CRAFT']) + else: + out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice( + ['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])]) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--cases', type=int, default=6000) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('menu-click-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaMenuOracle') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + rng = random.Random(args.seed) + g = Gen(rng, items) + cases = [] + for n in range(args.cases): + menu = list(MENUS)[n % len(MENUS)] + size = MENUS[menu] + slots = g.slots(size, rng.choice([0.1, 0.4, 0.8])) + if menu in ('inventory', 'crafting'): + slots[0] = '-' + if menu in ('inventory', 'crafting') and rng.random() < 0.6: + g.recipe(slots, 2 if menu == 'inventory' else 3) + cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, + 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [0] * DATA.get(menu, 0), + 'ops': g.ops(size)}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt') + lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + native = (work / 'native.txt').read_text().split('\n') + rust = (work / 'rust.txt').read_text().split('\n') + + def by_case(lines): + out, cur = [], [] + for line in lines: + cur.append(line) + if line == 'end' or line.startswith('error-case'): + out.append(cur) + cur = [] + return out + native, rust = by_case(native), by_case(rust) + bad = {} + for case, a, b in zip(cases, native, rust): + if a != b: + step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0 + op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None + bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b)) + total = sum(len(v) for v in bad.values()) + for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])): + print(f'{key}: {len(entries)} differing') + for case, step, a, b in entries[:args.limit]: + print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}') + print(f'{len(cases) - total}/{len(cases)} cases match') + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From d900b2a8e6bca73e018f62730ed45309dda1b265 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:08:27 +0200 Subject: [PATCH 09/24] Read the axe, hoe and shovel block transformers from the data pack A new block transformer module evaluates the data pack's rule based state providers the way BlockTransformer.transformBlock does (matching blocks and tags, all-of, copy properties) and derives the waxed twin of a copper block from the wax-off transforms. A harness compares every transformer, block state, face and block above with vanilla's own providers and with HoneycombItem.getWaxed. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/block_transform_fixture.rs | 94 +++++++ crates/horizon-client/src/block_transform.rs | 259 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaBlockTransformerOracle.java | 118 ++++++++ tools/test_block_transformer_parity.py | 60 ++++ 5 files changed, 532 insertions(+) create mode 100644 crates/horizon-client/examples/block_transform_fixture.rs create mode 100644 crates/horizon-client/src/block_transform.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java create mode 100644 tools/test_block_transformer_parity.py diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/block_transform_fixture.rs new file mode 100644 index 000000000..686ad8c42 --- /dev/null +++ b/crates/horizon-client/examples/block_transform_fixture.rs @@ -0,0 +1,94 @@ +//! Block transformer lookups for tools/test_block_transformer_parity.py: reads +//! "transformer TAB face TAB clicked TAB above" lines (states as +//! "name|prop=value,...") and prints the oracle's result lines. +//! +//! usage: block_transform_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + assets::Assets, + block_transform::{Around, Transformers}, + items::Items, +}; +use horizon_world::chunk::BlockState; +use std::{fs, path::Path}; + +fn parse(text: &str) -> BlockState { + let (name, props) = text.split_once('|').unwrap_or((text, "")); + BlockState { + name: name.to_owned(), + properties: props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(), + } +} + +fn describe(state: &BlockState) -> String { + let props: Vec = state + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}|{}", state.name, props.join(",")) +} + +struct Column { + clicked: BlockState, + above: BlockState, +} + +impl Around for Column { + fn state(&self, offset: [i32; 3]) -> BlockState { + match offset { + [0, 0, 0] => self.clicked.clone(), + [0, 1, 0] => self.above.clone(), + _ => BlockState { + name: "minecraft:stone".into(), + properties: Default::default(), + }, + } + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(args.get(1).ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let assets = Assets::load(root)?; + let transformers = Transformers::load(root, assets.registry)?; + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split('\t').collect(); + let around = Column { + clicked: parse(f[2]), + above: parse(f[3]), + }; + if f[0] == "honeycomb" { + let waxed = transformers.waxed(assets.registry, &around.clicked); + out += &format!("{}\n", waxed.map_or("none".to_owned(), |s| describe(&s))); + continue; + } + let id = format!("minecraft:{}", f[0]); + match transformers.apply(&items, assets.registry, &id, f[1], &around) { + None => out += "none\n", + Some((index, t, state)) => { + out += &format!( + "{index}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + describe(&state), + t.sound, + t.particle, + t.loot.as_deref().unwrap_or("-"), + t.drop_strategy, + t.update_from_neighbors, + t.transform_type, + t.consume_on_use, + t.damage + ); + } + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs new file mode 100644 index 000000000..fb94c2532 --- /dev/null +++ b/crates/horizon-client/src/block_transform.rs @@ -0,0 +1,259 @@ +//! The `minecraft:block_transformer` registry (axe, hoe, shovel) that +//! `BlockTransformer.transformBlock` reads: each transform's rule based state +//! provider is evaluated against the clicked block and the block above. +//! `tools/test_block_transformer_parity.py` compares every block state with +//! vanilla. +use crate::{Result, items::Items}; +use horizon_world::{chunk::BlockState, registry::BlockRegistry}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +enum Predicate { + Blocks(Vec), + Tag { tag: String, offset: [i32; 3] }, + AllOf(Vec), + AnyOf(Vec), +} + +enum Provider { + Rules(Vec<(Predicate, Provider)>), + State(BlockState), + /// `CopyPropertiesProvider`: the source with the clicked block's properties. + Copy(Box), +} + +/// One `BlockTransformData`. +pub struct Transform { + provider: Provider, + pub disallowed_faces: Vec, + pub sound: String, + pub particle: String, + pub loot: Option, + pub drop_strategy: String, + pub update_from_neighbors: bool, + pub transform_type: String, + pub consume_on_use: bool, + pub damage: u32, +} + +pub struct Transformers { + transformers: HashMap>, +} + +/// What the transformer reads of the world: the block state at an offset from +/// the clicked position. +pub trait Around { + fn state(&self, offset: [i32; 3]) -> BlockState; +} + +fn state_of(value: &Value, registry: &BlockRegistry) -> Option { + let name = value["id"].as_str().or_else(|| value["Name"].as_str())?; + let default = registry.default_state(name)?; + let mut state = registry.state(default)?.clone(); + for (k, v) in value["properties"].as_object().into_iter().flatten() { + state.properties.insert(k.clone(), v.as_str()?.to_owned()); + } + Some(state) +} + +fn predicate(value: &Value) -> Option { + Some(match value["type"].as_str()? { + "minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|b| b.as_str().map(str::to_owned)).collect(), + _ => return None, + }), + "minecraft:matching_block_tag" => { + let o = value["offset"].as_array(); + let at = |i: usize| o.and_then(|o| o.get(i)).and_then(Value::as_i64).unwrap_or(0) as i32; + Predicate::Tag { + tag: value["tag"].as_str()?.to_owned(), + offset: [at(0), at(1), at(2)], + } + } + "minecraft:all_of" => Predicate::AllOf( + value["predicates"] + .as_array()? + .iter() + .map(predicate) + .collect::>()?, + ), + "minecraft:any_of" => Predicate::AnyOf( + value["predicates"] + .as_array()? + .iter() + .map(predicate) + .collect::>()?, + ), + _ => return None, + }) +} + +fn provider(value: &Value, registry: &BlockRegistry) -> Option { + match value["type"].as_str() { + Some("minecraft:rule_based") => { + let mut rules = Vec::new(); + for rule in value["rules"].as_array()? { + rules.push((predicate(&rule["if_true"])?, provider(&rule["then"], registry)?)); + } + Some(Provider::Rules(rules)) + } + Some("minecraft:copy_properties") => Some(Provider::Copy(Box::new(provider( + &value["source"], + registry, + )?))), + _ => state_of(value, registry).map(Provider::State), + } +} + +/// `BlockState.withPropertiesOf`: the properties both blocks have. +fn with_properties_of( + registry: &BlockRegistry, + mut state: BlockState, + old: &BlockState, +) -> Option { + let defaults = registry + .default_state(&state.name) + .and_then(|id| registry.state(id))?; + for (k, v) in &old.properties { + if defaults.properties.contains_key(k) { + let mut candidate = state.clone(); + candidate.properties.insert(k.clone(), v.clone()); + if registry.resolve(&candidate).is_ok() { + state = candidate; + } + } + } + Some(state) +} + +impl Predicate { + fn test(&self, items: &Items, around: &dyn Around) -> bool { + match self { + Self::Blocks(names) => { + let state = around.state([0, 0, 0]); + names.iter().any(|n| *n == state.name) + } + Self::Tag { tag, offset } => { + let state = around.state(*offset); + items + .block_tags + .get(tag) + .is_some_and(|members| members.contains(&state.name)) + } + Self::AllOf(all) => all.iter().all(|p| p.test(items, around)), + Self::AnyOf(any) => any.iter().any(|p| p.test(items, around)), + } + } +} + +impl Provider { + fn state( + &self, + items: &Items, + registry: &BlockRegistry, + around: &dyn Around, + ) -> Option { + match self { + Self::Rules(rules) => rules + .iter() + .find(|(p, _)| p.test(items, around)) + .and_then(|(_, then)| then.state(items, registry, around)), + Self::State(state) => Some(state.clone()), + Self::Copy(source) => { + let state = source.state(items, registry, around)?; + with_properties_of(registry, state, &around.state([0, 0, 0])) + } + } + } +} + +impl Transformers { + /// Reads `data/minecraft/block_transformer/*.json`. + pub fn load(root: &Path, registry: &BlockRegistry) -> Result { + let mut transformers = HashMap::new(); + let dir = root.join("data/minecraft/block_transformer"); + if dir.exists() { + for entry in fs::read_dir(&dir)?.flatten() { + let path = entry.path(); + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let list: Value = serde_json::from_slice(&fs::read(&path)?)?; + let mut transforms = Vec::new(); + for t in list.as_array().into_iter().flatten() { + let text = |k: &str, d: &str| t[k].as_str().unwrap_or(d).to_owned(); + let Some(provider) = provider(&t["block_state_provider"], registry) else { + continue; + }; + transforms.push(Transform { + provider, + disallowed_faces: t["disallowed_faces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f.as_str().map(str::to_owned)) + .collect(), + sound: text("sound", "minecraft:empty"), + particle: text("particle", "none"), + loot: t["loot"].as_str().map(str::to_owned), + drop_strategy: text("drop_strategy", "from_middle"), + update_from_neighbors: t["update_from_neighbors"].as_bool().unwrap_or(true), + transform_type: text("transform_type", "single_block"), + consume_on_use: t["consume_on_use"].as_bool().unwrap_or(true), + damage: t["item_damage_per_use"].as_u64().unwrap_or(0) as u32, + }); + } + transformers.insert(format!("minecraft:{stem}"), transforms); + } + } + Ok(Self { transformers }) + } + + /// `BlockTransformer.transformBlock` without the world writes: the first + /// transform that allows the clicked face and provides a state, with its + /// index. + pub fn apply<'a>( + &'a self, + items: &Items, + registry: &BlockRegistry, + id: &str, + face: &str, + around: &dyn Around, + ) -> Option<(usize, &'a Transform, BlockState)> { + self.transformers + .get(id)? + .iter() + .enumerate() + .filter(|(_, t)| !t.disallowed_faces.iter().any(|f| f == face)) + .find_map(|(i, t)| Some((i, t, t.provider.state(items, registry, around)?))) + } + + /// `HoneycombItem.getWaxed`: the waxed twin of a copper block, found from + /// the axe's wax-off transforms (`WAX_OFF_BY_BLOCK` is the inverse of + /// `WAXABLES`). + pub fn waxed(&self, registry: &BlockRegistry, old: &BlockState) -> Option { + for transform in self.transformers.get("minecraft:axe")? { + if transform.particle != "wax_off" { + continue; + } + let Provider::Rules(rules) = &transform.provider else { + continue; + }; + for (predicate, then) in rules { + if let (Predicate::Blocks(names), Provider::Copy(source)) = (predicate, then) + && let Provider::State(unwaxed) = &**source + && unwaxed.name == old.name + && let Some(waxed) = names.first() + { + let target = registry + .default_state(waxed) + .and_then(|id| registry.state(id))? + .clone(); + return with_properties_of(registry, target, old); + } + } + } + None + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index bb2dd3763..ca2783d1d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -10,6 +10,7 @@ pub mod audio; pub mod banner; pub mod biome; pub mod block_entity_render; +pub mod block_transform; pub mod blocks; pub mod bossbar; pub mod brewing; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java new file mode 100644 index 000000000..bc8551c4d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockTransformerOracle.java @@ -0,0 +1,118 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.core.component.BlockTransformer; + +/** + * Original oracle: the data-driven axe/hoe/shovel BlockTransformer entries. + * "dump" lists every block state; a case line "transformer TAB face TAB + * clicked TAB above" (states as "name|prop=value,...") prints the first + * transform that yields a state and its settings, as BlockTransformer.transformBlock + * would pick it. + */ +public final class VanillaBlockTransformerOracle { + static String describe(BlockState state) { + StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|'); + List> props = new ArrayList<>(state.getProperties()); + props.sort(Comparator.comparing(Property::getName)); + boolean first = true; + for (Property p : props) { + out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p)); + first = false; + } + return out.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static String name(BlockState state, Property p) { + return p.getName(state.getValue(p)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static BlockState parse(String text) { + String[] parts = text.split("\\|", -1); + Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0])); + BlockState state = block.defaultBlockState(); + if (!parts[1].isEmpty()) { + for (String kv : parts[1].split(",")) { + String[] pair = kv.split("="); + Property p = block.getStateDefinition().getProperty(pair[0]); + state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow()); + } + } + return state; + } + + static LevelAccessor level(BlockState clicked, BlockState above) { + return (LevelAccessor) Proxy.newProxyInstance(LevelAccessor.class.getClassLoader(), new Class[]{LevelAccessor.class}, (proxy, method, args) -> { + if (method.getName().equals("getBlockState")) { + BlockPos pos = (BlockPos) args[0]; + return pos.getY() == 0 ? clicked : pos.getY() == 1 && pos.getX() == 0 && pos.getZ() == 0 ? above : net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(); + } + throw new UnsupportedOperationException(method.getName()); + }); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + if (args[0].equals("dump")) { + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (Block block : BuiltInRegistries.BLOCK) { + for (BlockState state : block.getStateDefinition().getPossibleStates()) out.println(describe(state)); + } + } + return; + } + var registry = ParityData.access.lookupOrThrow(Registries.BLOCK_TRANSFORMER); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + String[] f = line.split("\t", -1); + try { + if (f[0].equals("honeycomb")) { + out.println(net.minecraft.world.item.HoneycombItem.getWaxed(parse(f[2])).map(VanillaBlockTransformerOracle::describe).orElse("none")); + continue; + } + var transformer = registry.getOrThrow(ResourceKey.create(Registries.BLOCK_TRANSFORMER, Identifier.parse(f[0]))).value(); + Direction face = Direction.byName(f[1]); + BlockState clicked = parse(f[2]); + LevelAccessor level = level(clicked, parse(f[3])); + String result = "none"; + int index = 0; + for (var data : transformer.transforms()) { + if (!data.disallowedFaces().contains(face)) { + BlockState state = data.blockStateProvider().value().getOptionalState(level, RandomSource.create(0L), BlockPos.ZERO); + if (state != null) { + result = index + "\t" + describe(state) + "\t" + BuiltInRegistries.SOUND_EVENT.getKey(data.sound().value()) + + "\t" + data.particle().name().toLowerCase() + "\t" + + data.loot().map(k -> k.identifier().toString()).orElse("-") + "\t" + data.dropStrategy().name().toLowerCase() + + "\t" + data.updateFromNeighbors() + "\t" + data.transformType().name().toLowerCase() + "\t" + data.consumeOnUse() + + "\t" + data.itemDamagePerUse(); + break; + } + } + index++; + } + out.println(result); + } catch (Throwable e) { + out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage()); + } + } + } + } +} diff --git a/tools/test_block_transformer_parity.py b/tools/test_block_transformer_parity.py new file mode 100644 index 000000000..daad0c731 --- /dev/null +++ b/tools/test_block_transformer_parity.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Compare the data-driven axe/hoe/shovel block transformers with vanilla. + +The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's +BlockStateProviders on a stand-in level; the Rust example +(block_transform_fixture) evaluates horizon_client::block_transform. Cases are +every block state any transformer mentions (plus a random sample of all states) +under each transformer, with a few blocks above and three clicked faces. +""" +import argparse +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false'] +FACES = ['up', 'down', 'north'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--sample', type=int, default=3000) + parser.add_argument('--limit', type=int, default=4) + args = parser.parse_args() + work = lib.work_dir('block-transformer-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaBlockTransformerOracle') + vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt') + states = (work / 'states.txt').read_text().splitlines() + mentioned = set() + for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'): + text = path.read_text() + for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)): + mentioned.add('minecraft:' + name) + tags = set() + for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']: + for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']: + if not name.startswith('#'): + tags.add(name) + rng = random.Random(args.seed) + chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s] + chosen += rng.sample(states, args.sample) + cases = [] + for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']: + for state in chosen: + for face in FACES: + cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)])) + (work / 'cases.txt').write_text(''.join(c + '\n' for c in cases)) + vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt') + lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt') + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From 5ec93bf9e79f0e46e34467e49a65319d57a65575 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:48 +0200 Subject: [PATCH 10/24] Use the block transformers for axes, hoes, shovels and honeycomb in play Stripping, scraping, wax removal, tilling and path making now come from the data pack's transformers instead of hard coded block lists, so every copper variant, rooted dirt loot and the face restrictions behave like vanilla, and honeycomb waxes copper blocks. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 162 ++++++++++++++++++----------- crates/horizon-client/src/items.rs | 5 + 2 files changed, 105 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2af1021f2..e48da11f1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -446,6 +446,7 @@ pub struct Resources { facts: BlockFacts, items: Items, recipes: Recipes, + transformers: horizon_client::block_transform::Transformers, biomes: Arc, environment: Environment, atlas: HudAtlas, @@ -5419,6 +5420,90 @@ impl Game<'_> { } None } + /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. + fn use_block_transformer( + &mut self, + stack: &ItemStack, + pos: [i32; 3], + face: [i32; 3], + ) -> Result { + use horizon_client::block_transform::Around; + struct Column<'w> { + world: &'w World, + registry: &'w horizon_world::registry::BlockRegistry, + pos: [i32; 3], + } + impl Around for Column<'_> { + fn state(&self, o: [i32; 3]) -> horizon_world::chunk::BlockState { + let id = self + .world + .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); + self.registry + .state(id) + .cloned() + .unwrap_or_else(|| horizon_world::chunk::BlockState { + name: "minecraft:air".into(), + properties: Default::default(), + }) + } + } + let Some(id) = self + .res + .items + .get(&stack.item) + .and_then(|i| i.block_transformer.clone()) + else { + return Ok(false); + }; + let face_name = match face { + [0, -1, 0] => "down", + [0, 1, 0] => "up", + [0, 0, -1] => "north", + [0, 0, 1] => "south", + [-1, 0, 0] => "west", + _ => "east", + }; + let registry = self.res.assets.registry; + let (state, sound, loot, damage) = { + let around = Column { + world: &self.world, + registry, + pos, + }; + let Some((_, t, state)) = self.res.transformers.apply( + &self.res.items, + registry, + &id, + face_name, + &around, + ) else { + return Ok(false); + }; + (state, t.sound.clone(), t.loot.clone(), t.damage) + }; + let Ok(new) = registry.resolve(&state) else { + return Ok(false); + }; + self.level_set(pos, new)?; + if loot.as_deref() == Some("minecraft:till/rooted_dirt") { + self.pop_resource( + [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], + ItemStack::new("minecraft:hanging_roots", 1), + ); + } + self.audio.play( + &sound, + Some([ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]), + 1.0, + 1.0, + ); + self.damage_held(damage); + Ok(true) + } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { let registry = &self.res.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); @@ -5514,17 +5599,6 @@ impl Game<'_> { return Ok(false); }; let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let name = self - .res - .facts - .get(clicked) - .name - .trim_start_matches("minecraft:") - .to_owned(); - let above_air = - self.res - .facts - .is_air(self.world.block(hit.pos[0], hit.pos[1] + 1, hit.pos[2])); if item == "water_bucket" || item == "lava_bucket" { let target = if self.res.facts.get(clicked).replaceable { hit.pos @@ -5561,60 +5635,21 @@ impl Game<'_> { } return Ok(true); } - if item.ends_with("_hoe") && hit.face != [0, -1, 0] && above_air { - // HoeItem.TILLABLES - let result = match name.as_str() { - "grass_block" | "dirt_path" | "dirt" => Some("minecraft:farmland"), - "coarse_dirt" | "rooted_dirt" => Some("minecraft:dirt"), - _ => None, - }; - if let Some(result) = result { - self.set_state_named(hit.pos, result, &[])?; - if name == "rooted_dirt" { - self.pop_resource( - [hit.pos[0], hit.pos[1] - 1, hit.pos[2]], - ItemStack { - item: Arc::from("minecraft:hanging_roots"), - count: 1, - damage: 0, - extra: None, - }, - ); - } - self.audio - .play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); - return Ok(true); - } - } - if item.ends_with("_shovel") - && hit.face != [0, -1, 0] - && above_air - && matches!( - name.as_str(), - "grass_block" | "dirt" | "podzol" | "coarse_dirt" | "mycelium" | "rooted_dirt" - ) - { - // ShovelItem.FLATTENABLES - self.set_state_named(hit.pos, "minecraft:dirt_path", &[])?; - self.audio - .play("minecraft:item.shovel.flatten", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); + if self.use_block_transformer(&stack, hit.pos, hit.face)? { return Ok(true); } - if item.ends_with("_axe") && !name.starts_with("stripped_") { - // AxeItem.STRIPPABLES - let strippable = name.ends_with("_log") - || name.ends_with("_wood") - || name.ends_with("_stem") - || name.ends_with("_hyphae") - || name == "bamboo_block"; - let stripped = format!("minecraft:stripped_{name}"); - if strippable && self.res.assets.registry.default_state(&stripped).is_some() { - self.set_state_named(hit.pos, &stripped, &["axis"])?; + if item == "honeycomb" { + let registry = self.res.assets.registry; + let old = registry.state(clicked).cloned(); + if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) + && let Ok(state) = registry.resolve(&waxed) + { + self.level_set(hit.pos, state)?; self.audio - .play("minecraft:item.axe.strip", Some(at(hit.pos)), 1.0, 1.0); - self.damage_held(1); + .play("minecraft:item.honeycomb.wax_on", Some(at(hit.pos)), 1.0, 1.0); + if !self.creative { + self.consume_held(); + } return Ok(true); } } @@ -7606,6 +7641,8 @@ pub fn run() -> Result<()> { let items = Items::load(&root, assets.registry, &facts)?; eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); let recipes = Recipes::load(&root, &items)?; + let transformers = + horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); @@ -7677,6 +7714,7 @@ pub fn run() -> Result<()> { facts, items, recipes, + transformers, biomes, environment, atlas, diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 6e3ebe114..d7b75440e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -64,6 +64,8 @@ pub struct ItemInfo { pub crafting_remainder: Option, /// `dye`: the dye colour name (dyes, and anything else with the component). pub dye: Option, + /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. + pub block_transformer: Option, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -374,6 +376,9 @@ impl Items { .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), + block_transformer: c["minecraft:block_transformer"] + .as_str() + .map(str::to_owned), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) From 7bd28cc6f117732376e30853885facc84e65e337 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:13:50 +0200 Subject: [PATCH 11/24] Port the cauldron item interactions and test them against vanilla Using a bucket, bottle, water potion, dyed armour, patterned banner or dyed shulker box on an empty, water, lava or powder snow cauldron follows CauldronInteractions, including the creative-mode stack rules of ItemUtils.createFilledResult and the underwater refusal for lava and powder snow. A harness runs every item against every cauldron state in vanilla's own useItemOn and compares the result, block writes, sounds, drops and inventory. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 132 +++++++++ crates/horizon-client/src/cauldron.rs | 271 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu.rs | 17 ++ .../parity/VanillaCauldronOracle.java | 168 +++++++++++ tools/test_cauldron_parity.py | 81 ++++++ 6 files changed, 670 insertions(+) create mode 100644 crates/horizon-client/examples/cauldron_fixture.rs create mode 100644 crates/horizon-client/src/cauldron.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java create mode 100644 tools/test_cauldron_parity.py diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs new file mode 100644 index 000000000..3b8014410 --- /dev/null +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -0,0 +1,132 @@ +//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON +//! case per line and prints "result TAB events TAB inventory". +//! +//! usage: cauldron_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + cauldron::{Outcome, Player, interact}, + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::{ItemStack, Items}, + menu::{Env, Kind, Menu}, +}; +use horizon_world::chunk::BlockState; +use serde_json::Value; +use std::{fs, path::Path}; + +struct Stand<'a> { + menu: Menu, + env: &'a Env<'a>, + events: Vec, + hand: Option, +} + +impl Player for Stand<'_> { + fn creative(&self) -> bool { + self.menu.creative + } + fn hand(&mut self) -> &mut Option { + &mut self.hand + } + fn add(&mut self, stack: &mut ItemStack) -> bool { + // The held stack lives in inventory slot 0 for Inventory.add. + self.menu.set_player_item(0, self.hand.take()); + let added = self.menu.give(self.env, stack); + self.hand = self.menu.player_item(0).cloned(); + self.menu.set_player_item(0, None); + added + } + fn contains(&self, stack: &ItemStack) -> bool { + self.menu.player_contains(stack) + || self + .hand + .as_ref() + .is_some_and(|h| h.same_item_same_components(stack)) + } + fn drop_stack(&mut self, stack: ItemStack) { + self.events + .push(format!("drop {}", canon_stack(Some(&stack)))); + } +} + +fn parse(text: &str) -> BlockState { + let (name, props) = text.split_once('|').unwrap_or((text, "")); + BlockState { + name: name.to_owned(), + properties: props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(), + } +} + +fn describe(state: &BlockState) -> String { + let props: Vec = state + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}|{}", state.name, props.join(",")) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(args.get(1).ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let env = Env { + items: &items, + recipes: &recipes, + }; + let mut out = String::new(); + for line in input.lines() { + let case: Value = serde_json::from_str(line)?; + let mut menu = Menu::new(Kind::Inventory); + menu.creative = case["creative"].as_bool().unwrap_or(false); + for pair in case["inventory"].as_array().ok_or("inventory")? { + menu.set_player_item( + pair[0].as_u64().unwrap_or(0) as usize, + parse_stack(pair[1].as_str().unwrap_or("-"))?, + ); + } + let held = parse_stack(case["held"].as_str().unwrap_or("-"))?; + let mut stand = Stand { + menu, + env: &env, + events: Vec::new(), + hand: held, + }; + let cauldron = parse(case["state"].as_str().unwrap_or_default()); + let result = interact( + &items, + &cauldron, + case["under_water"].as_bool().unwrap_or(false), + &mut stand, + ); + if let Some(block) = &result.block { + stand.events.push(format!("set {}", describe(block))); + } + if let Some(sound) = result.sound { + stand.events.push(format!("sound {sound}")); + } + let kind = match result.outcome { + Outcome::Success => "success", + Outcome::Consume => "consume", + Outcome::Pass => "pass", + }; + stand.menu.set_player_item(0, stand.hand.take()); + let inventory: Vec = (0..41) + .filter_map(|i| { + stand + .menu + .player_item(i) + .map(|s| format!("{i}={}", canon_stack(Some(s)))) + }) + .collect(); + out += &format!("{kind}\t{}\t{}\n", stand.events.join(";"), inventory.join(" ")); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs new file mode 100644 index 000000000..6ab4fb5c3 --- /dev/null +++ b/crates/horizon-client/src/cauldron.rs @@ -0,0 +1,271 @@ +//! `CauldronInteractions`: what an item does to an empty, water, lava or +//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item +//! with vanilla's `useItemOn`. +use crate::items::{ItemStack, Items}; +use horizon_world::chunk::BlockState; + +/// The player side of an interaction. +pub trait Player { + fn creative(&self) -> bool; + /// The stack in the interacting hand. + fn hand(&mut self) -> &mut Option; + /// `Inventory.add`; the leftover stays in `stack`. + fn add(&mut self, stack: &mut ItemStack) -> bool; + /// `Inventory.contains`. + fn contains(&self, stack: &ItemStack) -> bool; + fn drop_stack(&mut self, stack: ItemStack); +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Outcome { + /// `InteractionResult.SUCCESS` + Success, + /// `InteractionResult.CONSUME` + Consume, + /// `TRY_WITH_EMPTY_HAND` + Pass, +} + +#[derive(Debug)] +pub struct Interaction { + pub outcome: Outcome, + /// The cauldron's new state. + pub block: Option, + pub sound: Option<&'static str>, +} + +fn state(name: &str, level: Option) -> BlockState { + BlockState { + name: name.to_owned(), + properties: level + .map(|l| ("level".to_owned(), l.to_string())) + .into_iter() + .collect(), + } +} + +fn pass() -> Interaction { + Interaction { + outcome: Outcome::Pass, + block: None, + sound: None, + } +} + +/// `ItemUtils.createFilledResult`. +fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) { + let creative = player.creative(); + if limit_creative && creative { + if !player.contains(&new) { + let mut new = new; + player.add(&mut new); + } + return; + } + let hand = player.hand(); + if !creative && let Some(held) = hand.as_mut() { + held.count -= 1; + if held.count == 0 { + *hand = None; + } + } + if hand.is_none() { + *hand = Some(new); + return; + } + let mut new = new; + if !player.add(&mut new) { + player.drop_stack(new); + } +} + +/// `LayeredCauldronBlock.lowerFillLevel`. +fn lowered(cauldron: &BlockState) -> BlockState { + let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(1); + if level <= 1 { + state("minecraft:cauldron", None) + } else { + let mut next = cauldron.clone(); + next.properties.insert("level".into(), (level - 1).to_string()); + next + } +} + +fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { + Interaction { + outcome: Outcome::Success, + block: Some(block), + sound, + } +} + +const COLORS: [&str; 16] = [ + "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", + "purple", "blue", "brown", "green", "red", "black", +]; + +/// The cauldron interaction of the held item (`useItemOn`); the hand stack is +/// changed through `player`. +pub fn interact( + items: &Items, + cauldron: &BlockState, + under_water: bool, + player: &mut dyn Player, +) -> Interaction { + let Some(held) = player.hand().clone() else { + return pass(); + }; + let kind = match cauldron.name.as_str() { + "minecraft:cauldron" => "empty", + "minecraft:water_cauldron" => "water", + "minecraft:lava_cauldron" => "lava", + "minecraft:powder_snow_cauldron" => "powder_snow", + _ => return pass(), + }; + let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(0); + let item = &*held.item; + let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); + // Dispatcher.get: tags first, then the item map. + if kind == "water" + && items + .item_tags + .get("minecraft:cauldron_can_remove_dye") + .is_some_and(|members| members.contains(item)) + { + if held.data().and_then(|d| d.dyed_color).is_none() { + return pass(); + } + if let Some(stack) = player.hand().as_mut() { + stack.data_mut().dyed_color = None; + stack.tidy(); + } + return changed(lowered(cauldron), None); + } + let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| { + if !can_fill { + return pass(); + } + filled(player, ItemStack::new(new, 1), true); + changed(state("minecraft:cauldron", None), Some(sound)) + }; + let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| { + filled(player, ItemStack::new("minecraft:bucket", 1), true); + changed(block, Some(sound)) + }; + match item { + "minecraft:lava_bucket" => { + return if under_water { + Interaction { + outcome: Outcome::Consume, + block: None, + sound: None, + } + } else { + empty_bucket( + player, + state("minecraft:lava_cauldron", None), + "minecraft:item.bucket.empty_lava", + ) + }; + } + "minecraft:water_bucket" => { + return empty_bucket( + player, + state("minecraft:water_cauldron", Some(3)), + "minecraft:item.bucket.empty", + ); + } + "minecraft:powder_snow_bucket" => { + return if under_water { + Interaction { + outcome: Outcome::Consume, + block: None, + sound: None, + } + } else { + empty_bucket( + player, + state("minecraft:powder_snow_cauldron", Some(3)), + "minecraft:item.bucket.empty_powder_snow", + ) + }; + } + _ => {} + } + match (kind, item) { + ("empty", "minecraft:potion") => { + if !water_potion { + return pass(); + } + filled(player, ItemStack::new("minecraft:glass_bottle", 1), true); + changed( + state("minecraft:water_cauldron", Some(1)), + Some("minecraft:item.bottle.empty"), + ) + } + ("water", "minecraft:bucket") => fill_bucket( + player, + "minecraft:water_bucket", + level == 3, + "minecraft:item.bucket.fill", + ), + ("water", "minecraft:glass_bottle") => { + filled( + player, + ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"), + true, + ); + changed(lowered(cauldron), Some("minecraft:item.bottle.fill")) + } + ("water", "minecraft:potion") => { + if level == 3 || !water_potion { + return pass(); + } + filled(player, ItemStack::new("minecraft:glass_bottle", 1), true); + let mut next = cauldron.clone(); + // BlockState.cycle on a 1..=3 property + next.properties + .insert("level".into(), (level % 3 + 1).to_string()); + changed(next, Some("minecraft:item.bottle.empty")) + } + ("water", name) + if name + .strip_prefix("minecraft:") + .and_then(|n| n.strip_suffix("_banner")) + .is_some_and(|c| COLORS.contains(&c)) => + { + let layers = held.data().map_or(0, |d| d.banner_patterns.len()); + if layers == 0 { + return pass(); + } + let mut cleaned = held.clone(); + cleaned.count = 1; + cleaned.data_mut().banner_patterns.pop(); + cleaned.tidy(); + filled(player, cleaned, false); + changed(lowered(cauldron), None) + } + ("water", name) + if name + .strip_prefix("minecraft:") + .and_then(|n| n.strip_suffix("_shulker_box")) + .is_some_and(|c| COLORS.contains(&c)) => + { + filled(player, held.transmute("minecraft:shulker_box", 1), false); + changed(lowered(cauldron), None) + } + ("lava", "minecraft:bucket") => fill_bucket( + player, + "minecraft:lava_bucket", + true, + "minecraft:item.bucket.fill_lava", + ), + ("powder_snow", "minecraft:bucket") => fill_bucket( + player, + "minecraft:powder_snow_bucket", + level == 3, + "minecraft:item.bucket.fill_powder_snow", + ), + _ => pass(), + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ca2783d1d..594064c90 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -14,6 +14,7 @@ pub mod block_transform; pub mod blocks; pub mod bossbar; pub mod brewing; +pub mod cauldron; pub mod chat; pub mod chunk; pub mod clock; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 5190cf16f..071d13be4 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -278,6 +278,23 @@ impl Menu { self.containers[PLAYER][i].as_ref() } + pub fn set_player_item(&mut self, i: usize, stack: Option) { + self.containers[PLAYER][i] = stack; + } + + /// `Inventory.add`: the leftover stays in `stack`. + pub fn give(&mut self, env: &Env, stack: &mut ItemStack) -> bool { + self.inventory_add(env, stack) + } + + /// `Inventory.contains(stack)`. + pub fn player_contains(&self, stack: &ItemStack) -> bool { + self.containers[PLAYER] + .iter() + .flatten() + .any(|have| have.same_item_same_components(stack)) + } + // ---- item helpers ---- fn max_stack(env: &Env, stack: &ItemStack) -> u32 { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java new file mode 100644 index 000000000..3c1b5dc04 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCauldronOracle.java @@ -0,0 +1,168 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluids; + +/** + * Original oracle: a cauldron's useItemOn (CauldronInteractions) with a + * recording stand-in level and player. Each case line is JSON: cauldron state + * ("name|prop=value"), the held stack, creative, whether water is above. The + * output line lists the result, block writes, sounds, the final inventory and + * drops. + */ +public final class VanillaCauldronOracle { + static Object unsafe; + static java.lang.reflect.Method allocate; + static final List events = new ArrayList<>(); + static boolean underWater; + + @SuppressWarnings("unchecked") + static T make(Class type) { + try { + return (T) allocate.invoke(unsafe, type); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + static void set(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + f.set(target, value); + } + + static String describe(BlockState state) { + StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|'); + List> props = new ArrayList<>(state.getProperties()); + props.sort(Comparator.comparing(Property::getName)); + boolean first = true; + for (Property p : props) { + out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p)); + first = false; + } + return out.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static String name(BlockState state, Property p) { + return p.getName(state.getValue(p)); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static BlockState parse(String text) { + String[] parts = text.split("\\|", -1); + Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0])); + BlockState state = block.defaultBlockState(); + if (!parts[1].isEmpty()) { + for (String kv : parts[1].split(",")) { + String[] pair = kv.split("="); + Property p = block.getStateDefinition().getProperty(pair[0]); + state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow()); + } + } + return state; + } + + static final class World extends ServerLevel { + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public boolean isClientSide() { return false; } + @Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; } + @Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); } + @Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { + events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s)); + } + @Override public void gameEvent(net.minecraft.core.Holder e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } + } + + static final class FakePlayer extends ServerPlayer { + boolean creative; + Inventory inv; + FakePlayer() { + super(null, null, null, null); + } + @Override public Inventory getInventory() { return inv; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); } + @Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { } + @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { + if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack)); + return null; + } + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + events.clear(); + underWater = f.get("under_water").getAsBoolean(); + var world = make(World.class); + var player = make(FakePlayer.class); + player.creative = f.get("creative").getAsBoolean(); + player.inv = new Inventory(player, new EntityEquipment()); + for (var other : f.getAsJsonArray("inventory")) { + var pair = other.getAsJsonArray(); + player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString())); + } + ItemStack held = ParityData.stack(f.get("held").getAsString()); + player.inv.setItem(0, held); + BlockState state = parse(f.get("state").getAsString()); + var cauldron = (AbstractCauldronBlock) state.getBlock(); + var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class, + net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class); + use.setAccessible(true); + InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null); + String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume" + : result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString(); + StringBuilder inventory = new StringBuilder(); + for (int i = 0; i < 41; i++) { + ItemStack s = player.inv.getItem(i); + if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' '); + } + out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim()); + } catch (Throwable e) { + out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_cauldron_parity.py b/tools/test_cauldron_parity.py new file mode 100644 index 000000000..f815d0cac --- /dev/null +++ b/tools/test_cauldron_parity.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Compare cauldron item interactions with vanilla's CauldronInteractions. + +The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn +with a recording level and player; the Rust example (cauldron_fixture) runs +horizon_client::cauldron. Every item is used on every cauldron state (empty, +water, lava and powder snow at each level), with water potions, dyed armour, +patterned banners and shulker boxes, in survival and creative, under water or +not, and with a crowded inventory. The result, block writes, sounds, drops and +the final inventory are compared. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib, lab +except ImportError: + import interaction_lab as lib + import lab + +STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2', + 'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1', + 'minecraft:powder_snow_cauldron|level=3'] +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def snbt(item, count=1, **components): + body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items())) + return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=7) + parser.add_argument('--limit', type=int, default=4) + args = parser.parse_args() + work = lib.work_dir('cauldron-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaCauldronOracle') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + rng = random.Random(args.seed) + held = [] + for name, info in items.items(): + if name == 'minecraft:air': + continue + top = info.get('minecraft:max_stack_size', 64) + held.append(snbt(name, 1)) + held.append(snbt(name, rng.randrange(1, top + 1))) + for color in DYES: + for layers in range(0, 4): + body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers)) + held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body)) + held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2]))) + for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']: + held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24))) + for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']: + for item in ['potion', 'splash_potion', 'lingering_potion']: + held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion)) + cases = [] + filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']] + for state in STATES: + for stack in held: + crowded = rng.random() < 0.25 + inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else [] + if not crowded and rng.random() < 0.3: + inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]] + cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3, + 'inventory': inventory}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt') + lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0], + lambda case: json.dumps(case)[:700], args.limit) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main() From f49faf685c3a4a36ad2cc743a77dd67519b54592 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:14:26 +0200 Subject: [PATCH 12/24] Use cauldron interactions in play Right clicking a cauldron with a bucket, bottle, water potion, dyed armour, banner or dyed shulker box now applies the verified cauldron rules to the held stack, inventory and block. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 8 +- crates/horizon-client/src/cauldron.rs | 20 +++-- crates/horizon-client/src/game.rs | 78 +++++++++++++++++++ 3 files changed, 96 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 3b8014410..e111782fb 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -3,7 +3,7 @@ //! //! usage: cauldron_fixture RESOURCES INPUT OUTPUT use horizon_client::{ - cauldron::{Outcome, Player, interact}, + cauldron::{Outcome, Player, interact, removes_dye}, crafting::Recipes, item_data::{canon_stack, parse_stack}, items::{ItemStack, Items}, @@ -99,10 +99,14 @@ fn main() -> horizon_client::Result<()> { hand: held, }; let cauldron = parse(case["state"].as_str().unwrap_or_default()); + let dye = stand + .hand + .as_ref() + .is_some_and(|h| removes_dye(&items, &h.item)); let result = interact( - &items, &cauldron, case["under_water"].as_bool().unwrap_or(false), + dye, &mut stand, ); if let Some(block) = &result.block { diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index 6ab4fb5c3..a2b48168a 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -2,6 +2,14 @@ //! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item //! with vanilla's `useItemOn`. use crate::items::{ItemStack, Items}; + +/// `ItemTags.CAULDRON_CAN_REMOVE_DYE` membership. +pub fn removes_dye(items: &Items, item: &str) -> bool { + items + .item_tags + .get("minecraft:cauldron_can_remove_dye") + .is_some_and(|members| members.contains(item)) +} use horizon_world::chunk::BlockState; /// The player side of an interaction. @@ -105,11 +113,12 @@ const COLORS: [&str; 16] = [ ]; /// The cauldron interaction of the held item (`useItemOn`); the hand stack is -/// changed through `player`. +/// changed through `player`. `removes_dye` is whether the held item is in the +/// `cauldron_can_remove_dye` tag. pub fn interact( - items: &Items, cauldron: &BlockState, under_water: bool, + removes_dye: bool, player: &mut dyn Player, ) -> Interaction { let Some(held) = player.hand().clone() else { @@ -126,12 +135,7 @@ pub fn interact( let item = &*held.item; let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); // Dispatcher.get: tags first, then the item map. - if kind == "water" - && items - .item_tags - .get("minecraft:cauldron_can_remove_dye") - .is_some_and(|members| members.contains(item)) - { + if kind == "water" && removes_dye { if held.data().and_then(|d| d.dyed_color).is_none() { return pass(); } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e48da11f1..52b0eb3a2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5420,6 +5420,79 @@ impl Game<'_> { } None } + /// `CauldronInteractions` for the held item aimed at a cauldron. + fn use_on_cauldron(&mut self, pos: [i32; 3]) -> Result { + use horizon_client::cauldron::{self, Outcome}; + struct Hand<'g, 'a>(&'g mut Game<'a>); + impl cauldron::Player for Hand<'_, '_> { + fn creative(&self) -> bool { + self.0.creative + } + fn hand(&mut self) -> &mut Option { + let selected = self.0.selected; + &mut self.0.inventory[selected] + } + fn add(&mut self, stack: &mut ItemStack) -> bool { + let before = stack.count; + match self.0.give(stack.clone()) { + None => stack.count = 0, + Some(rest) => stack.count = rest.count, + } + stack.count < before + } + fn contains(&self, stack: &ItemStack) -> bool { + self.0 + .inventory + .iter() + .flatten() + .any(|have| have.same_item_same_components(stack)) + } + fn drop_stack(&mut self, stack: ItemStack) { + if let Some(eye) = self.0.eye_position() { + self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40); + } + } + } + let registry = self.res.assets.registry; + let id = self.world.block(pos[0], pos[1], pos[2]); + let Some(state) = registry + .state(id) + .filter(|s| s.name.ends_with("cauldron")) + .cloned() + else { + return Ok(false); + }; + let Some(held) = self.inventory[self.selected].as_ref() else { + return Ok(false); + }; + let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); + let above = self.world.block(pos[0], pos[1] + 1, pos[2]); + let under_water = registry + .state(above) + .is_some_and(|s| s.name == "minecraft:water"); + let result = cauldron::interact(&state, under_water, removes_dye, &mut Hand(self)); + if result.outcome == Outcome::Pass { + return Ok(false); + } + if let Some(block) = result.block + && let Ok(new) = registry.resolve(&block) + { + self.level_set(pos, new)?; + } + if let Some(sound) = result.sound { + self.audio.play( + sound, + Some([ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]), + 1.0, + 1.0, + ); + } + Ok(true) + } /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. fn use_block_transformer( &mut self, @@ -5560,6 +5633,11 @@ impl Game<'_> { f64::from(p[2]) + 0.5, ] }; + if let Some(hit) = self.pick() + && self.use_on_cauldron(hit.pos)? + { + return Ok(true); + } if item == "bucket" { let Some(hit) = self.pick_fluid() else { return Ok(false); From f6e519097d906e1dc5f14ddade569ed0f331da9b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:14:42 +0200 Subject: [PATCH 13/24] Format the interaction work Co-Authored-By: Claude Sonnet 5.5 --- .../examples/block_transform_fixture.rs | 5 ++- .../examples/cauldron_fixture.rs | 11 +++++- crates/horizon-client/src/block_transform.rs | 16 ++++++-- crates/horizon-client/src/cauldron.rs | 33 +++++++++++++--- crates/horizon-client/src/game.rs | 38 +++++++++---------- crates/horizon-client/src/items.rs | 4 +- 6 files changed, 74 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/block_transform_fixture.rs index 686ad8c42..01d92a047 100644 --- a/crates/horizon-client/examples/block_transform_fixture.rs +++ b/crates/horizon-client/examples/block_transform_fixture.rs @@ -53,7 +53,10 @@ impl Around for Column { fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); - let root = Path::new(args.get(1).ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?); + let root = Path::new( + args.get(1) + .ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?, + ); let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let assets = Assets::load(root)?; diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index e111782fb..9f238396d 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -72,7 +72,10 @@ fn describe(state: &BlockState) -> String { fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); - let root = Path::new(args.get(1).ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?); + let root = Path::new( + args.get(1) + .ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?, + ); let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; @@ -129,7 +132,11 @@ fn main() -> horizon_client::Result<()> { .map(|s| format!("{i}={}", canon_stack(Some(s)))) }) .collect(); - out += &format!("{kind}\t{}\t{}\n", stand.events.join(";"), inventory.join(" ")); + out += &format!( + "{kind}\t{}\t{}\n", + stand.events.join(";"), + inventory.join(" ") + ); } fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; Ok(()) diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs index fb94c2532..92f1455e9 100644 --- a/crates/horizon-client/src/block_transform.rs +++ b/crates/horizon-client/src/block_transform.rs @@ -60,12 +60,19 @@ fn predicate(value: &Value) -> Option { Some(match value["type"].as_str()? { "minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] { Value::String(s) => vec![s.clone()], - Value::Array(a) => a.iter().filter_map(|b| b.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|b| b.as_str().map(str::to_owned)) + .collect(), _ => return None, }), "minecraft:matching_block_tag" => { let o = value["offset"].as_array(); - let at = |i: usize| o.and_then(|o| o.get(i)).and_then(Value::as_i64).unwrap_or(0) as i32; + let at = |i: usize| { + o.and_then(|o| o.get(i)) + .and_then(Value::as_i64) + .unwrap_or(0) as i32 + }; Predicate::Tag { tag: value["tag"].as_str()?.to_owned(), offset: [at(0), at(1), at(2)], @@ -94,7 +101,10 @@ fn provider(value: &Value, registry: &BlockRegistry) -> Option { Some("minecraft:rule_based") => { let mut rules = Vec::new(); for rule in value["rules"].as_array()? { - rules.push((predicate(&rule["if_true"])?, provider(&rule["then"], registry)?)); + rules.push(( + predicate(&rule["if_true"])?, + provider(&rule["then"], registry)?, + )); } Some(Provider::Rules(rules)) } diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index a2b48168a..9fbe1179f 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -89,12 +89,17 @@ fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) { /// `LayeredCauldronBlock.lowerFillLevel`. fn lowered(cauldron: &BlockState) -> BlockState { - let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(1); + let level: u8 = cauldron + .properties + .get("level") + .and_then(|l| l.parse().ok()) + .unwrap_or(1); if level <= 1 { state("minecraft:cauldron", None) } else { let mut next = cauldron.clone(); - next.properties.insert("level".into(), (level - 1).to_string()); + next.properties + .insert("level".into(), (level - 1).to_string()); next } } @@ -108,8 +113,22 @@ fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { } const COLORS: [&str; 16] = [ - "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", - "purple", "blue", "brown", "green", "red", "black", + "white", + "orange", + "magenta", + "light_blue", + "yellow", + "lime", + "pink", + "gray", + "light_gray", + "cyan", + "purple", + "blue", + "brown", + "green", + "red", + "black", ]; /// The cauldron interaction of the held item (`useItemOn`); the hand stack is @@ -131,7 +150,11 @@ pub fn interact( "minecraft:powder_snow_cauldron" => "powder_snow", _ => return pass(), }; - let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(0); + let level: u8 = cauldron + .properties + .get("level") + .and_then(|l| l.parse().ok()) + .unwrap_or(0); let item = &*held.item; let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water"); // Dispatcher.get: tags first, then the item map. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 52b0eb3a2..2fc27c703 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5508,16 +5508,15 @@ impl Game<'_> { } impl Around for Column<'_> { fn state(&self, o: [i32; 3]) -> horizon_world::chunk::BlockState { - let id = self - .world - .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); - self.registry - .state(id) - .cloned() - .unwrap_or_else(|| horizon_world::chunk::BlockState { + let id = + self.world + .block(self.pos[0] + o[0], self.pos[1] + o[1], self.pos[2] + o[2]); + self.registry.state(id).cloned().unwrap_or_else(|| { + horizon_world::chunk::BlockState { name: "minecraft:air".into(), properties: Default::default(), - }) + } + }) } } let Some(id) = self @@ -5543,13 +5542,11 @@ impl Game<'_> { registry, pos, }; - let Some((_, t, state)) = self.res.transformers.apply( - &self.res.items, - registry, - &id, - face_name, - &around, - ) else { + let Some((_, t, state)) = + self.res + .transformers + .apply(&self.res.items, registry, &id, face_name, &around) + else { return Ok(false); }; (state, t.sound.clone(), t.loot.clone(), t.damage) @@ -5723,8 +5720,12 @@ impl Game<'_> { && let Ok(state) = registry.resolve(&waxed) { self.level_set(hit.pos, state)?; - self.audio - .play("minecraft:item.honeycomb.wax_on", Some(at(hit.pos)), 1.0, 1.0); + self.audio.play( + "minecraft:item.honeycomb.wax_on", + Some(at(hit.pos)), + 1.0, + 1.0, + ); if !self.creative { self.consume_held(); } @@ -7719,8 +7720,7 @@ pub fn run() -> Result<()> { let items = Items::load(&root, assets.registry, &facts)?; eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); let recipes = Recipes::load(&root, &items)?; - let transformers = - horizon_client::block_transform::Transformers::load(&root, assets.registry)?; + let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index d7b75440e..c34c296d0 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -376,9 +376,7 @@ impl Items { .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), - block_transformer: c["minecraft:block_transformer"] - .as_str() - .map(str::to_owned), + block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) From 4a0d9ea01d1ca60c98da70eb2b04941ec52c3f56 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:16:12 +0200 Subject: [PATCH 14/24] Fix clippy findings in the menu, transformer and wiring code Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/block_transform.rs | 2 +- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/menu.rs | 16 ++++++++-------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/block_transform.rs b/crates/horizon-client/src/block_transform.rs index 92f1455e9..4cd1d6f94 100644 --- a/crates/horizon-client/src/block_transform.rs +++ b/crates/horizon-client/src/block_transform.rs @@ -142,7 +142,7 @@ impl Predicate { match self { Self::Blocks(names) => { let state = around.state([0, 0, 0]); - names.iter().any(|n| *n == state.name) + names.contains(&state.name) } Self::Tag { tag, offset } => { let state = around.state(*offset); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2852e9633..5725c9fe8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5746,7 +5746,7 @@ impl Game<'_> { } return Ok(true); } - if self.use_block_transformer(&stack, hit.pos, hit.face)? { + if self.use_block_transformer(stack, hit.pos, hit.face)? { return Ok(true); } if item == "honeycomb" { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 071d13be4..4d7cec897 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -878,9 +878,9 @@ impl Menu { if input == Input::QuickCraft { let expected = self.quick_status; self.quick_status = button & 3; - if (expected != 1 || self.quick_status != 2) && expected != self.quick_status { - self.reset_quick_craft(); - } else if self.carried.is_none() { + if ((expected != 1 || self.quick_status != 2) && expected != self.quick_status) + || self.carried.is_none() + { self.reset_quick_craft(); } else if self.quick_status == 0 { self.quick_type = (button >> 2) & 3; @@ -1069,7 +1069,7 @@ impl Menu { let amount = if primary { clicked.count } else { - (clicked.count + 1) / 2 + clicked.count.div_ceil(2) }; if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { self.carried = Some(taken); @@ -1190,10 +1190,10 @@ impl Menu { let item = self.slot(t).expect("has item").clone(); if pass != 0 || item.count != Self::max_stack(env, &item) { let room = carried_max - have.count; - if let Some(removed) = self.safe_take(env, t, item.count, room) { - if let Some(c) = self.carried.as_mut() { - c.count += removed.count; - } + if let Some(removed) = self.safe_take(env, t, item.count, room) + && let Some(c) = self.carried.as_mut() + { + c.count += removed.count; } } } From 5041496f0824048abf8a0f29bf437eb0433a5020 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:29:00 +0200 Subject: [PATCH 15/24] Add the brewing stand to the menu engine and click harness The brewing stand menu follows BrewingStandMenu: single-item potion slots, the ingredient and fuel slots with their quick move rules, checked against vanilla with potion bottles, ingredients and fuels in the random contents. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 2 + crates/horizon-client/src/menu.rs | 96 ++++++++++++++++++- tools/test_menu_click_parity.py | 14 ++- 4 files changed, 108 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 9f238396d..f2cd257cd 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -79,9 +79,11 @@ fn main() -> horizon_client::Result<()> { let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); let env = Env { items: &items, recipes: &recipes, + brewing: &brewing, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index ded828ef3..0909d3de4 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -34,9 +34,11 @@ fn main() -> horizon_client::Result<()> { let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; + let brewing = horizon_client::brewing::Brewing::load(root, &items); let env = Env { items: &items, recipes: &recipes, + brewing: &brewing, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 4d7cec897..b0bafd2bf 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -5,6 +5,7 @@ //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. use crate::{ + brewing::Brewing, crafting::Recipes, items::{ItemStack, Items}, }; @@ -13,6 +14,7 @@ use crate::{ pub struct Env<'a> { pub items: &'a Items, pub recipes: &'a Recipes, + pub brewing: &'a Brewing, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -51,6 +53,7 @@ pub enum Kind { Shulker, /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), + Brewing, } impl Kind { @@ -67,6 +70,7 @@ impl Kind { "furnace" => Self::Furnace("smelting"), "blast_furnace" => Self::Furnace("blasting"), "smoker" => Self::Furnace("smoking"), + "brewing" => Self::Brewing, _ => return None, }) } @@ -84,6 +88,12 @@ enum Role { Output, /// `ResultSlot` of a crafting grid. CraftResult, + /// `BrewingStandMenu.PotionSlot`. + Potion, + /// `BrewingStandMenu.IngredientsSlot`. + Ingredient, + /// `BrewingStandMenu.FuelSlot`. + BrewFuel, } #[derive(Clone, Copy)] @@ -220,6 +230,27 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } + Kind::Brewing => { + containers[MAIN] = vec![None; 5]; + for (index, role) in [ + Role::Potion, + Role::Potion, + Role::Potion, + Role::Ingredient, + Role::BrewFuel, + ] + .into_iter() + .enumerate() + { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + player(&mut slots); + data = 4; + } Kind::Furnace(_) => { containers[MAIN] = vec![None; 3]; slots.extend([ @@ -349,6 +380,19 @@ impl Menu { Role::Shulker => Self::fits_inside(stack), Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), Role::Output | Role::CraftResult => false, + Role::Potion => { + env.brewing.is_bottle(stack) + || env + .items + .item_tags + .get("minecraft:brewing_potion_inputs") + .is_some_and(|m| m.contains(&*stack.item)) + } + Role::Ingredient => env.brewing.is_reagent(stack), + Role::BrewFuel => env + .items + .get(&stack.item) + .is_some_and(|i| i.brewing_fuel.is_some()), } } @@ -367,7 +411,7 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) => 1, + Role::Armor(_) | Role::Potion => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -742,6 +786,56 @@ impl Menu { return None; } } + Kind::Brewing => { + after_take = true; + let slot = self.slots[index]; + let commit = |m: &mut Self, stack: &ItemStack| { + m.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + }; + if index <= 4 { + if !self.move_to(env, &mut stack, 5, 41, true) { + return None; + } + } else if env + .items + .get(&clicked.item) + .is_some_and(|i| i.brewing_fuel.is_some()) + { + let moved = self.move_to(env, &mut stack, 4, 5, false); + if moved + || (env.brewing.is_reagent(&stack) + && !self.move_to(env, &mut stack, 3, 4, false)) + { + commit(self, &stack); + return None; + } + } else if env.brewing.is_reagent(&stack) { + if !self.move_to(env, &mut stack, 3, 4, false) { + return None; + } + } else if env.brewing.is_bottle(&stack) + || env + .items + .item_tags + .get("minecraft:brewing_potion_inputs") + .is_some_and(|m| m.contains(&*stack.item)) + { + if !self.move_to(env, &mut stack, 0, 3, false) { + return None; + } + } else if (5..32).contains(&index) { + if !self.move_to(env, &mut stack, 32, 41, false) { + return None; + } + } else if (32..41).contains(&index) { + if !self.move_to(env, &mut stack, 5, 32, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 5, 41, false) { + return None; + } + } Kind::Furnace(recipe) => { after_take = true; if index == 2 { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index cd015e703..6f71e49ef 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -19,22 +19,25 @@ except ImportError: import lab MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, - 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4} COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', 'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box', 'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling', - 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest'] + 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder', + 'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath'] def quote(text): return '"' + text + '"' -def snbt(item, count, damage=0, curse=False): +def snbt(item, count, damage=0, curse=False, potion=None): comps = [] + if potion: + comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion) if damage: comps.append('"minecraft:damage":%d' % damage) if curse: @@ -60,7 +63,8 @@ class Gen: if info.get('minecraft:max_damage') and rng.random() < 0.3: damage = rng.randrange(1, info['minecraft:max_damage']) count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) - return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info)) + potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None + return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] From 3318a0481909f13f4de0d4f85eff730e86a55dea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:30:07 +0200 Subject: [PATCH 16/24] Add the crafter to the menu engine and click harness The crafter menu follows CrafterMenu: slots refuse items while their disabled flag is set, and the result slot is non-interactive. Random disabled flags are part of the harness cases. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/menu.rs | 31 ++++++++++++++++++++++++++++++- tools/test_menu_click_parity.py | 6 +++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index b0bafd2bf..c23db47ec 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -54,6 +54,7 @@ pub enum Kind { /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), Brewing, + Crafter, } impl Kind { @@ -71,6 +72,7 @@ impl Kind { "blast_furnace" => Self::Furnace("blasting"), "smoker" => Self::Furnace("smoking"), "brewing" => Self::Brewing, + "crafter" => Self::Crafter, _ => return None, }) } @@ -88,6 +90,10 @@ enum Role { Output, /// `ResultSlot` of a crafting grid. CraftResult, + /// `CrafterSlot`: refuses items while its disabled flag (data slot) is set. + CrafterIn, + /// `NonInteractiveResultSlot`. + Inert, /// `BrewingStandMenu.PotionSlot`. Potion, /// `BrewingStandMenu.IngredientsSlot`. @@ -230,6 +236,17 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } + Kind::Crafter => { + containers[MAIN] = vec![None; 9]; + slots.extend(main(9, Role::CrafterIn)); + player(&mut slots); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::Inert, + }); + data = 10; + } Kind::Brewing => { containers[MAIN] = vec![None; 5]; for (index, role) in [ @@ -379,7 +396,8 @@ impl Menu { .unwrap_or(false), Role::Shulker => Self::fits_inside(stack), Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), - Role::Output | Role::CraftResult => false, + Role::Output | Role::CraftResult | Role::Inert => false, + Role::CrafterIn => self.data.get(self.slots[s].index) != Some(&1), Role::Potion => { env.brewing.is_bottle(stack) || env @@ -398,6 +416,7 @@ impl Menu { fn may_pickup(&self, s: usize) -> bool { match self.slots[s].role { + Role::Inert => false, Role::Armor(_) => match self.slot(s) { Some(stack) => { self.creative || stack.enchantment_level("minecraft:binding_curse") == 0 @@ -836,6 +855,16 @@ impl Menu { return None; } } + Kind::Crafter => { + after_take = true; + if index < 9 { + if !self.move_to(env, &mut stack, 9, 45, true) { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 9, false) { + return None; + } + } Kind::Furnace(recipe) => { after_take = true; if index == 2 { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 6f71e49ef..5137537b2 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -19,8 +19,8 @@ except ImportError: import lab MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, - 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10} COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', @@ -132,7 +132,7 @@ def main(): if menu in ('inventory', 'crafting') and rng.random() < 0.6: g.recipe(slots, 2 if menu == 'inventory' else 3) cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, - 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [0] * DATA.get(menu, 0), + 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))], 'ops': g.ops(size)}) (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt') From 0351c4d6c4a126cb10ef413171d62ab4e75f6d85 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:30:49 +0200 Subject: [PATCH 17/24] Run container shift-clicks through the verified menu engine Shift-clicking in chests, barrels, shulker boxes, hoppers, droppers, dispensers and furnaces now builds the vanilla menu from the open container and the player inventory, applies quickMoveStack with the repeat-until-unchanged loop of doClick, and writes the slots back. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/storage.rs | 120 ++++++++++++---------- 1 file changed, 65 insertions(+), 55 deletions(-) diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index cf9a3a1ac..348983352 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -342,70 +342,80 @@ impl Game<'_> { impl Game<'_> { /// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace - /// menu for a shift-click on `slot`; false when the menu has none. + /// menu for a shift-click on `slot`, run by the verified menu engine + /// (`horizon_client::menu`); false when the menu has none. pub(super) fn container_quick_move(&mut self, slot: usize) -> bool { + use horizon_client::menu::{Env, Input, Kind, Menu}; let size = self.container_size(); - let furnace = match self.container_kind() { - Some(BlockEntity::Chest(_)) => None, - Some(BlockEntity::Furnace(f)) => Some(f.kind), + let (kind, count) = match self.container_kind() { + Some(BlockEntity::Chest(_)) => { + let shulker = self.container.is_some_and(|k| { + let id = self.world.block(k.0, k.1, k.2); + is_shulker_box(&self.res.facts.get(id).name) + }); + let kind = match size { + 5 => Kind::Hopper, + 9 => Kind::Dispenser, + 27 if shulker => Kind::Shulker, + n => Kind::Chest((n / 9).clamp(1, 6)), + }; + (kind, size) + } + Some(BlockEntity::Furnace(f)) => ( + Kind::Furnace( + match f.kind.recipe_type().trim_start_matches("minecraft:") { + "blasting" => "blasting", + "smoking" => "smoking", + _ => "smelting", + }, + ), + 3, + ), _ => return false, }; - if slot >= 300 + size.max(3) { + // Menu index <-> game slot: container 300.., main inventory 9..36, hotbar 0..9. + let to_menu = |g: usize| match g { + 300.. if g < 300 + count => Some(g - 300), + 9..36 => Some(count + g - 9), + 0..9 => Some(count + 27 + g), + _ => None, + }; + let from_menu = |i: usize| match i { + _ if i < count => 300 + i, + _ if i < count + 27 => 9 + i - count, + _ => i - count - 27, + }; + let Some(index) = to_menu(slot) else { return false; - } - let Some(mut stack) = self.slot_mut(slot).take() else { - return true; }; - let player: Vec = (9..36).chain(0..9).collect(); - let hotbar_or_main = |slot: usize| -> Vec { - if slot < 9 { - (9..36).collect() - } else { - (0..9).collect() + let mut menu = Menu::new(kind); + let total = menu.slot_count(); + let before: Vec> = (0..total) + .map(|i| self.slot_mut(from_menu(i)).clone()) + .collect(); + let after: Vec> = { + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + }; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); } + if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + return true; + } + (0..total).map(|i| menu.slot(i).cloned()).collect() }; - match furnace { - None => { - if slot >= 300 { - self.move_to(&mut stack, &player, true); - } else { - let targets: Vec = (300..300 + size).collect(); - self.move_to(&mut stack, &targets, false); - } - } - Some(kind) => { - // AbstractFurnaceMenu.quickMoveStack. - if slot >= 300 { - self.move_to(&mut stack, &player, slot == 302); - } else { - let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some(); - let fuel = self - .res - .items - .get(&stack.item) - .is_some_and(|i| i.fuel.is_some()); - let moved = if smeltable { - self.move_to(&mut stack, &[300], false) - } else if fuel { - self.move_to(&mut stack, &[301], false) - } else { - false - }; - if !moved && !smeltable && !fuel { - let other = hotbar_or_main(slot); - self.move_to(&mut stack, &other, false); - } - if let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - f.cooking_timer = 0; - } - } - } + for (i, stack) in after.into_iter().enumerate() { + *self.slot_mut(from_menu(i)) = stack; } - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + if matches!(kind, Kind::Furnace(_)) + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.cooking_timer = 0; } true } From b3b6e9583554c0e0032f2d2f1d58ecf14f881770 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:31:26 +0200 Subject: [PATCH 18/24] Run inventory and crafting table shift-clicks through the menu engine Shift-clicking an inventory, hotbar, armour or crafting grid slot now follows InventoryMenu and CraftingMenu quickMoveStack, including moving into the crafting grid, armour and off-hand slots and the repeat-until-unchanged loop. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 129 ++++++++++++++++-------------- 1 file changed, 67 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5725c9fe8..9c648216c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3527,6 +3527,69 @@ impl Game<'_> { self.close_ender_chest(); self.close_cart_container(); } + /// `quickMoveStack` of the player inventory or crafting table menu for a + /// shift-click, run by the verified menu engine (`horizon_client::menu`). + fn inventory_quick_move(&mut self, slot: usize) -> bool { + use horizon_client::menu::{Env, Input, Kind, Menu}; + let table = self.craft_size == 3; + let cells = self.craft_size * self.craft_size; + // Game slot <-> menu index. + let main = if table { 10 } else { 9 }; + let to_menu = |g: usize| match g { + 100..109 if g - 100 < cells => Some(1 + g - 100), + 500..504 if !table => Some(5 + g - 500), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + }; + let Some(index) = to_menu(slot) else { + return false; + }; + let total = main + 36 + usize::from(!table); + let mut game_slots: Vec> = vec![None; total]; + for g in (100..109).chain(500..504).chain(0..36) { + if let Some(i) = to_menu(g) { + game_slots[i] = Some(g); + } + } + let mut menu = Menu::new(if table { + Kind::Crafting + } else { + Kind::Inventory + }); + let before: Vec> = game_slots + .iter() + .map(|g| g.and_then(|g| self.slot_mut(g).clone())) + .collect(); + let offhand = self.offhand.clone(); + let after: Vec> = { + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + }; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); + } + if !table { + menu.set_slot(&env, 45, offhand); + } + if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + return true; + } + (0..total).map(|i| menu.slot(i).cloned()).collect() + }; + for (i, g) in game_slots.iter().enumerate() { + if let Some(g) = g { + *self.slot_mut(*g) = after[i].clone(); + } + } + if !table { + self.offhand = after[45].clone(); + } + self.apply_equipment(); + true + } fn click_inventory(&mut self, right: bool) { if self.mount_click(right) { return; @@ -3653,68 +3716,10 @@ impl Game<'_> { } return; } - if shift && (500..504).contains(&slot) { - // InventoryMenu.quickMoveStack: armour back to the main - // inventory, then the hotbar. - if let Some(stack) = self.armor[slot - 500].take() { - if let Some(i) = (9..36).chain(0..9).find(|&i| self.inventory[i].is_none()) { - self.inventory[i] = Some(stack); - } else { - self.armor[slot - 500] = Some(stack); - } - self.apply_equipment(); - } - return; - } - if shift && slot < 36 { - // InventoryMenu.quickMoveStack: armour into its empty slot, an - // off-hand item into an empty off hand. - let equip = self.inventory[slot] - .as_ref() - .and_then(|s| self.res.items.get(&s.item)) - .and_then(|i| i.equip_slot.clone()); - let armor = ["head", "chest", "legs", "feet"] - .iter() - .position(|s| equip.as_deref() == Some(*s)); - if let Some(a) = armor - && self.armor[a].is_none() - { - self.armor[a] = self.inventory[slot].take(); - self.apply_equipment(); - return; - } - if equip.as_deref() == Some("offhand") && self.offhand.is_none() { - self.offhand = self.inventory[slot].take(); - return; - } - // Quick move between hotbar and main inventory. - if let Some(stack) = self.inventory[slot].take() { - let range = if slot < 9 { 9..36 } else { 0..9 }; - let mut stack = stack; - for i in range.clone() { - if let Some(s) = &mut self.inventory[i] - && s.same_item_same_components(&stack) - { - let moved = max(&self.res.items, s) - .saturating_sub(s.count) - .min(stack.count); - s.count += moved; - stack.count -= moved; - } - } - if stack.count > 0 - && let Some(i) = range.clone().find(|&i| self.inventory[i].is_none()) - { - self.inventory[i] = Some(stack); - stack = ItemStack { - count: 0, - ..self.inventory[i].clone().unwrap() - }; - } - if stack.count > 0 { - self.inventory[slot] = Some(stack); - } - } + if shift + && (slot < 36 || (500..504).contains(&slot) || (100..109).contains(&slot)) + && self.inventory_quick_move(slot) + { return; } if (500..504).contains(&slot) { From 762ad298e64a3364f152952e8eb33c7390002cb2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:33:13 +0200 Subject: [PATCH 19/24] Finish the pending menu and storage work Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 359 +++++++++++++++++++--- crates/horizon-client/src/game/storage.rs | 74 +---- crates/horizon-client/src/menu.rs | 4 + 3 files changed, 316 insertions(+), 121 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9c648216c..721cf907b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -505,6 +505,10 @@ struct Game<'a> { carried: Option, craft_grid: Vec>, craft_size: usize, + /// A quick craft drag over inventory slots: (button, game slots so far). + inv_drag: Option<(i32, Vec)>, + /// The last inventory click, for the double click that gathers a stack. + last_inv_click: Option<(std::time::Instant, usize, bool)>, /// Open container block entity, if any. container: Option<(i32, i32, i32)>, /// Open workstation menu (enchanting table, anvil, ...). @@ -1072,9 +1076,9 @@ impl Game<'_> { } /// Player.drop: thrown from the eyes along the view direction. fn drop_held(&mut self, all: bool) { - let Some(eye) = self.eye_position() else { + if self.eye_position().is_none() { return; - }; + } let Some(stack) = self.inventory[self.selected].as_mut() else { return; }; @@ -1083,13 +1087,20 @@ impl Game<'_> { count, ..stack.clone() }; - // Player.drop: the drop statistics. - self.stats.add("dropped", &thrown.item, count as i32); - self.stats.custom("drop", 1); stack.count -= count; if stack.count == 0 { self.inventory[self.selected] = None; } + self.player_drop(thrown); + } + /// `Player.drop`: the statistics and a thrown item entity in front of the player. + fn player_drop(&mut self, thrown: ItemStack) { + let Some(eye) = self.eye_position() else { + return; + }; + // Player.drop: the drop statistics. + self.stats.add("dropped", &thrown.item, thrown.count as i32); + self.stats.custom("drop", 1); let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -3527,69 +3538,303 @@ impl Game<'_> { self.close_ender_chest(); self.close_cart_container(); } - /// `quickMoveStack` of the player inventory or crafting table menu for a - /// shift-click, run by the verified menu engine (`horizon_client::menu`). + /// `quickMoveStack` of the open plain menu for a shift-click. fn inventory_quick_move(&mut self, slot: usize) -> bool { - use horizon_client::menu::{Env, Input, Kind, Menu}; - let table = self.craft_size == 3; - let cells = self.craft_size * self.craft_size; - // Game slot <-> menu index. - let main = if table { 10 } else { 9 }; - let to_menu = |g: usize| match g { - 100..109 if g - 100 < cells => Some(1 + g - 100), - 500..504 if !table => Some(5 + g - 500), - 9..36 => Some(main + g - 9), - 0..9 => Some(main + 27 + g), - _ => None, - }; - let Some(index) = to_menu(slot) else { - return false; - }; - let total = main + 36 + usize::from(!table); - let mut game_slots: Vec> = vec![None; total]; - for g in (100..109).chain(500..504).chain(0..36) { - if let Some(i) = to_menu(g) { - game_slots[i] = Some(g); + self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove) + } + /// `AbstractContainerMenu.clicked` on the open inventory, crafting table, + /// chest, hopper, dispenser or furnace menu, run by the verified menu + /// engine (`horizon_client::menu`). `slot` None is outside the window. + /// False when the open screen is not one the engine models. + fn menu_click( + &mut self, + slot: Option, + button: i32, + input: horizon_client::menu::Input, + ) -> bool { + use horizon_client::menu::{Env, Kind, Menu}; + #[derive(Clone, Copy)] + struct Map { + container: usize, + table: bool, + cells: usize, + plain: bool, + } + impl Map { + fn main(&self) -> usize { + match (self.plain, self.table) { + (false, _) => self.container, + (true, true) => 10, + (true, false) => 9, + } + } + fn to_menu(&self, g: usize) -> Option { + let main = self.main(); + if self.plain { + match g { + 200 => Some(0), + 100..109 if g - 100 < self.cells => Some(1 + g - 100), + 500..504 if !self.table => Some(5 + g - 500), + 504 if !self.table => Some(45), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + } + } else { + match g { + 300.. if g < 300 + self.container => Some(g - 300), + 9..36 => Some(main + g - 9), + 0..9 => Some(main + 27 + g), + _ => None, + } + } + } + fn to_game(&self, i: usize) -> Option { + let main = self.main(); + if self.plain { + match i { + 0 => None, + 1..=9 if i - 1 < self.cells => Some(100 + i - 1), + 5..9 if !self.table => Some(500 + i - 5), + 45 if !self.table => Some(504), + _ if i >= main && i < main + 27 => Some(9 + i - main), + _ if i >= main + 27 && i < main + 36 => Some(i - main - 27), + _ => None, + } + } else if i < self.container { + Some(300 + i) + } else if i < self.container + 27 { + Some(9 + i - self.container) + } else { + Some(i - self.container - 27) + } } } - let mut menu = Menu::new(if table { - Kind::Crafting + let (kind, map) = if self.container.is_some() { + let size = self.container_size(); + let (kind, count) = match self.container_kind() { + Some(BlockEntity::Chest(_)) => { + let shulker = self.container.is_some_and(|k| { + let id = self.world.block(k.0, k.1, k.2); + storage::is_shulker_box(&self.res.facts.get(id).name) + }); + let kind = match size { + 5 => Kind::Hopper, + 9 => Kind::Dispenser, + 27 if shulker => Kind::Shulker, + n => Kind::Chest((n / 9).clamp(1, 6)), + }; + (kind, size) + } + Some(BlockEntity::Furnace(f)) => ( + Kind::Furnace( + match f.kind.recipe_type().trim_start_matches("minecraft:") { + "blasting" => "blasting", + "smoking" => "smoking", + _ => "smelting", + }, + ), + 3, + ), + _ => return false, + }; + let map = Map { + container: count, + table: false, + cells: 0, + plain: false, + }; + (kind, map) + } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + let table = self.craft_size == 3; + let map = Map { + container: 0, + table, + cells: self.craft_size * self.craft_size, + plain: true, + }; + ( + if table { + Kind::Crafting + } else { + Kind::Inventory + }, + map, + ) } else { - Kind::Inventory - }); - let before: Vec> = game_slots - .iter() - .map(|g| g.and_then(|g| self.slot_mut(g).clone())) + return false; + }; + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != horizon_client::menu::Input::QuickMove { + return false; + } + match map.to_menu(g) { + Some(i) => i as i32, + None => return false, + } + } + None => -999, + }; + let mut menu = Menu::new(kind); + let total = menu.slot_count(); + let before: Vec> = (0..total) + .map(|i| map.to_game(i).and_then(|g| self.slot_mut(g).clone())) .collect(); - let offhand = self.offhand.clone(); - let after: Vec> = { + let carried = self.carried.clone(); + let creative = self.creative; + let (after, carried, dropped): (Vec>, Option, Vec) = { let env = Env { items: &self.res.items, recipes: &self.res.recipes, brewing: &self.res.stations.brewing, }; + menu.creative = creative; for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } - if !table { - menu.set_slot(&env, 45, offhand); - } - if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { + menu.carried = carried; + if menu.click(&env, menu_slot, button, input).is_err() { return true; } - (0..total).map(|i| menu.slot(i).cloned()).collect() + ( + (0..total).map(|i| menu.slot(i).cloned()).collect(), + menu.carried.take(), + std::mem::take(&mut menu.dropped), + ) }; - for (i, g) in game_slots.iter().enumerate() { - if let Some(g) = g { - *self.slot_mut(*g) = after[i].clone(); + for (i, stack) in after.into_iter().enumerate() { + if let Some(g) = map.to_game(i) { + *self.slot_mut(g) = stack; } } - if !table { - self.offhand = after[45].clone(); + self.carried = carried; + for stack in dropped { + self.player_drop(stack); + } + if matches!(kind, Kind::Furnace(_)) + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.cooking_timer = 0; } self.apply_equipment(); true } + /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar + /// slot or the off hand, THROW one or the whole stack. + fn inventory_hotkey(&mut self, key: KeyCode) -> bool { + use horizon_client::menu::Input; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return false; + }; + let batch = HudBatch::new(size); + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { + return false; + }; + let digit = [ + KeyCode::Digit1, + KeyCode::Digit2, + KeyCode::Digit3, + KeyCode::Digit4, + KeyCode::Digit5, + KeyCode::Digit6, + KeyCode::Digit7, + KeyCode::Digit8, + KeyCode::Digit9, + ] + .iter() + .position(|k| *k == key); + let done = match (digit, key) { + (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap), + (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap), + (None, KeyCode::KeyQ) => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.menu_click(Some(slot), i32::from(all), Input::Throw) + } + _ => false, + }; + if done && let Some(key) = self.container { + self.container_changed(key); + } + done + } + /// The plain inventory mouse press: starts a quick craft drag when a + /// stack is held, gathers on a double click, else the normal click. + fn inventory_press(&mut self, right: bool) { + use horizon_client::menu::Input; + let slot = self.renderer.as_ref().and_then(|r| { + let batch = HudBatch::new([r.config.width, r.config.height]); + self.slot_at(&batch, self.cursor.0, self.cursor.1) + }); + let shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + if let Some(slot) = slot + && !shift + && slot != 200 + { + let now = std::time::Instant::now(); + let double = !right + && self.carried.is_some() + && self.last_inv_click.is_some_and(|(at, last, was_right)| { + last == slot && !was_right && now.duration_since(at).as_millis() < 250 + }); + self.last_inv_click = Some((now, slot, right)); + if double && self.menu_click(Some(slot), 0, Input::PickupAll) { + self.last_inv_click = None; + return; + } + if self.carried.is_some() { + self.inv_drag = Some((i32::from(right), vec![slot])); + return; + } + } + self.click_inventory(right); + } + /// Mouse movement while a quick craft drag is running. + fn inventory_drag_move(&mut self) { + let Some((_, slots)) = self.inv_drag.as_ref() else { + return; + }; + let Some(r) = self.renderer.as_ref() else { + return; + }; + let batch = HudBatch::new([r.config.width, r.config.height]); + if let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) + && slot != 200 + && !slots.contains(&slot) + && let Some((_, slots)) = self.inv_drag.as_mut() + { + slots.push(slot); + } + } + /// Mouse release: finishes a quick craft drag (one slot is a plain click). + fn inventory_release(&mut self) { + use horizon_client::menu::Input; + let Some((ty, slots)) = self.inv_drag.take() else { + return; + }; + if slots.len() == 1 { + if !self.menu_click(Some(slots[0]), ty, Input::Pickup) { + self.click_inventory(ty == 1); + } + } else { + let mask = |header: i32| header | (ty << 2); + self.menu_click(None, mask(0), Input::QuickCraft); + for slot in slots { + self.menu_click(Some(slot), mask(1), Input::QuickCraft); + } + self.menu_click(None, mask(2), Input::QuickCraft); + } + if let Some(key) = self.container { + self.container_changed(key); + } + } fn click_inventory(&mut self, right: bool) { if self.mount_click(right) { return; @@ -7129,6 +7374,18 @@ impl Game<'_> { Screen::WorldOptions => self.close_world_options(), Screen::Chat => self.close_chat(), }, + KeyCode::Digit1 + | KeyCode::Digit2 + | KeyCode::Digit3 + | KeyCode::Digit4 + | KeyCode::Digit5 + | KeyCode::Digit6 + | KeyCode::Digit7 + | KeyCode::Digit8 + | KeyCode::Digit9 + | KeyCode::KeyF + | KeyCode::KeyQ + if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {} KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. @@ -7376,6 +7633,7 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory { self.loom_drag(); + self.inventory_drag_move(); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -7503,12 +7761,15 @@ impl ApplicationHandler for Game<'_> { } } Screen::Inventory if pressed => { - self.click_inventory(button == MouseButton::Right); + self.inventory_press(button == MouseButton::Right); if let Some(key) = self.container { self.container_changed(key); } } - Screen::Inventory => self.loom_release(), + Screen::Inventory => { + self.inventory_release(); + self.loom_release(); + } Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); @@ -7913,6 +8174,8 @@ pub fn run() -> Result<()> { carried: None, craft_grid: vec![None; 9], craft_size: 2, + inv_drag: None, + last_inv_click: None, container: None, station: None, potions: Default::default(), diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 348983352..2cb6d40a0 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -345,79 +345,7 @@ impl Game<'_> { /// menu for a shift-click on `slot`, run by the verified menu engine /// (`horizon_client::menu`); false when the menu has none. pub(super) fn container_quick_move(&mut self, slot: usize) -> bool { - use horizon_client::menu::{Env, Input, Kind, Menu}; - let size = self.container_size(); - let (kind, count) = match self.container_kind() { - Some(BlockEntity::Chest(_)) => { - let shulker = self.container.is_some_and(|k| { - let id = self.world.block(k.0, k.1, k.2); - is_shulker_box(&self.res.facts.get(id).name) - }); - let kind = match size { - 5 => Kind::Hopper, - 9 => Kind::Dispenser, - 27 if shulker => Kind::Shulker, - n => Kind::Chest((n / 9).clamp(1, 6)), - }; - (kind, size) - } - Some(BlockEntity::Furnace(f)) => ( - Kind::Furnace( - match f.kind.recipe_type().trim_start_matches("minecraft:") { - "blasting" => "blasting", - "smoking" => "smoking", - _ => "smelting", - }, - ), - 3, - ), - _ => return false, - }; - // Menu index <-> game slot: container 300.., main inventory 9..36, hotbar 0..9. - let to_menu = |g: usize| match g { - 300.. if g < 300 + count => Some(g - 300), - 9..36 => Some(count + g - 9), - 0..9 => Some(count + 27 + g), - _ => None, - }; - let from_menu = |i: usize| match i { - _ if i < count => 300 + i, - _ if i < count + 27 => 9 + i - count, - _ => i - count - 27, - }; - let Some(index) = to_menu(slot) else { - return false; - }; - let mut menu = Menu::new(kind); - let total = menu.slot_count(); - let before: Vec> = (0..total) - .map(|i| self.slot_mut(from_menu(i)).clone()) - .collect(); - let after: Vec> = { - let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - }; - for (i, stack) in before.iter().enumerate() { - menu.set_slot(&env, i, stack.clone()); - } - if menu.click(&env, index as i32, 0, Input::QuickMove).is_err() { - return true; - } - (0..total).map(|i| menu.slot(i).cloned()).collect() - }; - for (i, stack) in after.into_iter().enumerate() { - *self.slot_mut(from_menu(i)) = stack; - } - if matches!(kind, Kind::Furnace(_)) - && let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - f.cooking_timer = 0; - } - true + self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove) } } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index c23db47ec..4ced9e6d0 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -128,6 +128,8 @@ pub struct Menu { pub creative: bool, /// Dropped stacks (canonical text), `xp+N` and the like, in order. pub drops: Vec, + /// The dropped stacks themselves, for the caller to throw. + pub dropped: Vec, quick_status: i32, quick_type: i32, quick_slots: Vec, @@ -302,6 +304,7 @@ impl Menu { data: vec![0; data], creative: false, drops: Vec::new(), + dropped: Vec::new(), quick_status: 0, quick_type: 0, quick_slots: Vec::new(), @@ -531,6 +534,7 @@ impl Menu { fn drop_stack(&mut self, stack: &ItemStack) { if stack.count > 0 { self.drops.push(crate::item_data::canon_stack(Some(stack))); + self.dropped.push(stack.clone()); } } From 145d54c542e7952a42aafa5b6df0d2b890052b49 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:33:13 +0200 Subject: [PATCH 20/24] Use Section::unpack and per-section biomes in the LAN chunk encoder Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/lan/chunks.rs | 29 ++++++++----------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 5660aaf94..70538468b 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -2,7 +2,7 @@ //! (sections with their paletted containers, block entities and the sky and //! block DataLayers) and the section block-change batches. use crate::{ - chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section}, + chunk::{Chunk, Light, MIN_Y, SECTIONS, Section}, containers::BlockEntity, }; use horizon_protocol::{ @@ -154,12 +154,7 @@ impl ChunkEncoder { .is_none_or(|f| f & NON_AIR == 0) } - fn section( - &self, - section: &Section, - chunk: &Chunk, - index: usize, - ) -> (horizon_protocol::chunk::Section, bool) { + fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) { let mut values = Vec::with_capacity(BLOCKS); let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false); let mut count = |state: u16, n: i16| { @@ -172,21 +167,15 @@ impl ChunkEncoder { } f & ENTITY != 0 }; - match §ion.blocks { - Blocks::Uniform(v) => { - entities |= count(*v, BLOCKS as i16); - values.resize(BLOCKS, i32::from(*v)); - } - Blocks::Full(a) => { - for &v in a.iter() { - entities |= count(v, 1); - values.push(i32::from(v)); - } - } + let mut unpacked = [0u16; BLOCKS]; + section.unpack(&mut unpacked); + for &v in &unpacked { + entities |= count(v, 1); + values.push(i32::from(v)); } let biome_values: Vec = (0..BIOMES) .map(|j| { - let internal = chunk.biomes.get(index * BIOMES + j).copied().unwrap_or(0); + let internal = section.biomes.get(j) as u16; self.biome_ids .get(usize::from(internal)) .copied() @@ -213,7 +202,7 @@ impl ChunkEncoder { let mut sections = Vec::with_capacity(SECTIONS); let mut entity_infos = Vec::new(); for (i, s) in chunk.sections.iter().enumerate() { - let (encoded, has_entities) = self.section(s, chunk, i); + let (encoded, has_entities) = self.section(s); if has_entities { for y in 0..16 { for z in 0..16 { From 0e0e94111f1b46cf70a87513c2bccbe16e53b4a4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:33:35 +0200 Subject: [PATCH 21/24] Add LAN discovery listing The multiplayer screen listens on the vanilla multicast group 224.0.2.60:4445 and lists LAN worlds announced with the [MOTD]/[AD] format, letting the player join them directly. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/lan/discovery.rs | 169 +++++++++++++++++++++ crates/horizon-client/src/lan/mod.rs | 6 + crates/horizon-client/src/multiplayer.rs | 81 ++++++++-- 3 files changed, 244 insertions(+), 12 deletions(-) create mode 100644 crates/horizon-client/src/lan/discovery.rs diff --git a/crates/horizon-client/src/lan/discovery.rs b/crates/horizon-client/src/lan/discovery.rs new file mode 100644 index 000000000..07eca3481 --- /dev/null +++ b/crates/horizon-client/src/lan/discovery.rs @@ -0,0 +1,169 @@ +//! LAN game discovery: LanServerPinger announces a hosted world on the +//! multicast group 224.0.2.60:4445 every 1.5 seconds as +//! `[MOTD]text[/MOTD][AD]port[/AD]`, and LanServerDetection collects those +//! announcements for the multiplayer screen. +use std::{ + io, + net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::{Duration, Instant}, +}; + +pub const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 2, 60); +pub const PORT: u16 = 4445; +/// LanServerPinger sleeps 1500 ms between announcements. +const INTERVAL: Duration = Duration::from_millis(1500); +/// LanServerDetection.LanServerList drops entries not refreshed for 5 s. +const EXPIRY: Duration = Duration::from_secs(5); + +/// LanServerPinger.createPingString. +pub fn ping_string(motd: &str, port: u16) -> String { + format!("[MOTD]{motd}[/MOTD][AD]{port}[/AD]") +} +fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> { + let start = s.find(open)? + open.len(); + let end = s[start..].find(close)? + start; + Some(&s[start..end]) +} +/// LanServerPinger.parseMotd; vanilla shows "missing no" when absent. +pub fn parse_motd(s: &str) -> String { + between(s, "[MOTD]", "[/MOTD]") + .unwrap_or("missing no") + .to_owned() +} +/// LanServerPinger.parseAddress: the announced port, if present and valid. +pub fn parse_port(s: &str) -> Option { + between(s, "[AD]", "[/AD]")?.parse().ok().filter(|p| *p > 0) +} + +/// Announces one hosted world until dropped. +pub struct Pinger { + stop: Arc, + thread: Option>, +} +impl Pinger { + pub fn start(motd: String, port: u16) -> io::Result { + let socket = UdpSocket::bind(("0.0.0.0", 0))?; + let _ = socket.set_multicast_ttl_v4(4); + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let message = ping_string(&motd, port); + let thread = std::thread::Builder::new() + .name("horizon-lan-ping".into()) + .spawn(move || { + let target = SocketAddr::V4(SocketAddrV4::new(GROUP, PORT)); + while !flag.load(Ordering::Relaxed) { + let _ = socket.send_to(message.as_bytes(), target); + let mut slept = Duration::ZERO; + while slept < INTERVAL && !flag.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + slept += Duration::from_millis(50); + } + } + })?; + Ok(Self { + stop, + thread: Some(thread), + }) + } +} +impl Drop for Pinger { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +/// A world announced on the local network. +#[derive(Clone, Debug, PartialEq)] +pub struct LanGame { + pub motd: String, + pub address: String, +} +type Games = Arc>>; + +/// Listens for announcements until the last clone is dropped. +#[derive(Clone, Debug)] +pub struct Scanner { + inner: Arc, +} +#[derive(Debug)] +struct ScanInner { + games: Games, + stop: Arc, +} +impl Drop for ScanInner { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} +impl Scanner { + /// Bind the discovery port; without it the list simply stays empty. + pub fn start() -> Self { + let games: Games = Arc::default(); + let stop = Arc::new(AtomicBool::new(false)); + if let Ok(socket) = bind_listener() { + let (games, stop) = (games.clone(), stop.clone()); + let _ = std::thread::Builder::new() + .name("horizon-lan-scan".into()) + .spawn(move || listen(socket, games, stop)); + } + Self { + inner: Arc::new(ScanInner { games, stop }), + } + } + /// The live announcements, oldest first. + pub fn games(&self) -> Vec { + let mut games = self.inner.games.lock().unwrap(); + games.retain(|(_, seen)| seen.elapsed() < EXPIRY); + games.iter().map(|(g, _)| g.clone()).collect() + } +} +fn bind_listener() -> io::Result { + let socket = UdpSocket::bind(("0.0.0.0", PORT))?; + socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?; + socket.set_read_timeout(Some(Duration::from_millis(250)))?; + Ok(socket) +} +fn listen(socket: UdpSocket, games: Games, stop: Arc) { + let mut buf = [0u8; 1024]; + while !stop.load(Ordering::Relaxed) { + let Ok((n, from)) = socket.recv_from(&mut buf) else { + continue; + }; + let text = String::from_utf8_lossy(&buf[..n]); + let Some(port) = parse_port(&text) else { + continue; + }; + let game = LanGame { + motd: parse_motd(&text), + address: format!("{}:{port}", from.ip()), + }; + let mut games = games.lock().unwrap(); + match games.iter_mut().find(|(g, _)| g.address == game.address) { + Some(entry) => *entry = (game, Instant::now()), + None => games.push((game, Instant::now())), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ping_string_round_trips() { + let s = ping_string("Steve - World", 25565); + assert_eq!(s, "[MOTD]Steve - World[/MOTD][AD]25565[/AD]"); + assert_eq!(parse_motd(&s), "Steve - World"); + assert_eq!(parse_port(&s), Some(25565)); + assert_eq!(parse_port("[AD]0[/AD]"), None); + assert_eq!(parse_motd("junk"), "missing no"); + } +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 6367295ae..b6af18530 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -8,6 +8,7 @@ pub mod chunks; pub mod conn; pub mod containers; pub mod data; +pub mod discovery; pub mod entity; pub mod guest; pub mod hub; @@ -111,6 +112,8 @@ pub struct Lan { events: Receiver, pub port: u16, listener: Option>, + /// The multicast announcement (LanServerPinger); absent when the socket failed. + _pinger: Option, } impl Lan { /// Listen on `port` (0 picks a free one). @@ -123,6 +126,7 @@ impl Lan { let listener = TcpListener::bind(("0.0.0.0", port))?; listener.set_nonblocking(true)?; let port = listener.local_addr()?.port(); + let _pinger = discovery::Pinger::start(motd.clone(), port).ok(); let (tx, events) = channel(); let shared = Arc::new(Shared { sync, @@ -142,6 +146,7 @@ impl Lan { events, port, listener: Some(listener), + _pinger, }) } /// Everything the connection threads reported since the last call. @@ -160,6 +165,7 @@ impl Lan { if let Some(t) = self.listener.take() { let _ = t.join(); } + self._pinger = None; } } impl Drop for Lan { diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 8e2ef5c64..ef067ce06 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -3,6 +3,7 @@ //! Disconnected screen. Entries are pinged in the background like //! ServerStatusPinger to show the MOTD, player count and latency. use crate::hud::{HudAtlas, HudBatch, rgba}; +use crate::lan::discovery::Scanner; use horizon_protocol::servers::{self, ServerEntry}; use std::{ collections::HashMap, @@ -31,6 +32,8 @@ pub enum Screen { servers: Vec, selected: Option, pings: Pings, + /// Worlds announced on the local network, listed after the servers. + lan: Scanner, }, /// Add (index None) or edit a server entry. Edit { @@ -92,6 +95,18 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) { } } +/// The address of list row `index`: the saved servers, then the LAN games. +fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option { + match servers.get(index) { + Some(s) => Some(s.ip.clone()), + None => lan + .games() + .into_iter() + .nth(index - servers.len()) + .map(|g| g.address), + } +} + impl Screen { pub fn list(saves: &Path) -> Self { let servers = servers::load(&servers_file(saves)); @@ -101,6 +116,7 @@ impl Screen { servers, selected: None, pings, + lan: Scanner::start(), } } pub fn buttons(&self, w: f32, h: f32) -> Vec { @@ -256,6 +272,7 @@ impl Screen { servers, selected, pings, + lan, } => { centered(batch, "Play Multiplayer", 8.0, u32::MAX); batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); @@ -319,6 +336,42 @@ impl Screen { ); } } + for (k, game) in lan.games().iter().enumerate() { + let i = servers.len() + k; + let y = 36.0 + i as f32 * 36.0; + if y + 36.0 > h - 64.0 { + break; + } + let x = w / 2.0 - 152.0; + if *selected == Some(i) { + batch.fill( + atlas, + x - 2.0, + y - 2.0, + 306.0, + 36.0, + rgba(128, 128, 128, 255), + ); + batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); + } + batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false); + batch.text( + atlas, + &game.motd, + x + 35.0, + y + 12.0, + rgba(128, 128, 128, 255), + false, + ); + batch.text( + atlas, + &game.address, + x + 35.0, + y + 22.0, + rgba(96, 96, 96, 255), + false, + ); + } if servers.is_empty() { centered( batch, @@ -392,12 +445,15 @@ impl Screen { match (&mut *self, id) { ( Self::List { - servers, selected, .. + servers, + selected, + lan, + .. }, Some(40), ) => { - if let Some(s) = selected.and_then(|i| servers.get(i)) { - return Outcome::Connect(s.ip.clone()); + if let Some(address) = selected.and_then(|i| entry_address(servers, lan, i)) { + return Outcome::Connect(address); } } (Self::List { .. }, Some(41)) => { @@ -446,21 +502,22 @@ impl Screen { (Self::List { .. }, Some(46)) => return Outcome::Back, ( Self::List { - servers, selected, .. + servers, + selected, + lan, + .. }, None, ) => { let index = ((y - 36.0) / 36.0).floor(); - if y >= 36.0 - && y < h - 64.0 - && (x - w / 2.0).abs() < 154.0 - && (index as usize) < servers.len() - { + if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 { let index = index as usize; - if *selected == Some(index) { - return Outcome::Connect(servers[index].ip.clone()); + if let Some(address) = entry_address(servers, lan, index) { + if *selected == Some(index) { + return Outcome::Connect(address); + } + *selected = Some(index); } - *selected = Some(index); } } ( From cedae6609d333b9194487d4a67a826b98c6c85b4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:02:24 +0200 Subject: [PATCH 22/24] Route inventory clicks, drags, double clicks, hotkeys and drops through the menu engine On the player inventory, crafting table, chest family, hopper, dispenser and furnace screens, holding a stack and dragging across slots now splits it (left even, right one each), a quick second click gathers matching stacks, number keys and F swap with the hotbar or off hand, and Q or Ctrl+Q throws one or the whole stack, all through the same engine the click harness checks against vanilla. Other screens keep their own click handling. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 54 ++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 721cf907b..847629c83 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3552,6 +3552,10 @@ impl Game<'_> { button: i32, input: horizon_client::menu::Input, ) -> bool { + self.menu_ops(&[(slot, button, input)]) + } + /// Several clicks on one menu instance (a quick craft drag is three). + fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::{Env, Kind, Menu}; #[derive(Clone, Copy)] struct Map { @@ -3568,7 +3572,7 @@ impl Game<'_> { (true, false) => 9, } } - fn to_menu(&self, g: usize) -> Option { + fn to_menu(self, g: usize) -> Option { let main = self.main(); if self.plain { match g { @@ -3589,7 +3593,7 @@ impl Game<'_> { } } } - fn to_game(&self, i: usize) -> Option { + fn to_game(self, i: usize) -> Option { let main = self.main(); if self.plain { match i { @@ -3664,18 +3668,22 @@ impl Game<'_> { } else { return false; }; - let menu_slot = match slot { - Some(g) => { - if g == 200 && input != horizon_client::menu::Input::QuickMove { - return false; + let mut clicks = Vec::new(); + for &(slot, button, input) in ops { + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != horizon_client::menu::Input::QuickMove { + return false; + } + match map.to_menu(g) { + Some(i) => i as i32, + None => return false, + } } - match map.to_menu(g) { - Some(i) => i as i32, - None => return false, - } - } - None => -999, - }; + None => -999, + }; + clicks.push((menu_slot, button, input)); + } let mut menu = Menu::new(kind); let total = menu.slot_count(); let before: Vec> = (0..total) @@ -3694,8 +3702,10 @@ impl Game<'_> { menu.set_slot(&env, i, stack.clone()); } menu.carried = carried; - if menu.click(&env, menu_slot, button, input).is_err() { - return true; + for (menu_slot, button, input) in clicks { + if menu.click(&env, menu_slot, button, input).is_err() { + return true; + } } ( (0..total).map(|i| menu.slot(i).cloned()).collect(), @@ -3825,11 +3835,17 @@ impl Game<'_> { } } else { let mask = |header: i32| header | (ty << 2); - self.menu_click(None, mask(0), Input::QuickCraft); - for slot in slots { - self.menu_click(Some(slot), mask(1), Input::QuickCraft); + let mut ops = vec![(None, mask(0), Input::QuickCraft)]; + ops.extend( + slots + .into_iter() + .map(|slot| (Some(slot), mask(1), Input::QuickCraft)), + ); + ops.push((None, mask(2), Input::QuickCraft)); + if !self.menu_ops(&ops) { + // Not a menu the engine models: the drag is a plain click. + self.click_inventory(ty == 1); } - self.menu_click(None, mask(2), Input::QuickCraft); } if let Some(key) = self.container { self.container_changed(key); From 528cb26f3324b78b35535da024042e200572a69b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:51:41 +0200 Subject: [PATCH 23/24] Add illusioners The illusioner is an illager spellcaster with a bow. It casts a mirror spell that makes it invisible for a minute while four mirror images wobble around it and reshuffle when it is hurt, and, on Hard-ish local difficulty, a blindness spell on a new target. It shoots arrows like a skeleton, flees from creakings, joins raids and illager target rules, scares villagers and traders, and shows its hat and bow arm pose as in vanilla. Other illagers no longer draw the hidden hat layer. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/creatures.rs | 5 + crates/horizon-client/src/game/fangs.rs | 1 + crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/ai.rs | 6 +- crates/horizon-client/src/mobs/illager.rs | 25 +- crates/horizon-client/src/mobs/illusioner.rs | 235 +++++++++++++++++++ crates/horizon-client/src/mobs/llama.rs | 2 +- crates/horizon-client/src/mobs/raider.rs | 1 + crates/horizon-client/src/mobs/ravager.rs | 3 +- crates/horizon-client/src/mobs/render.rs | 25 +- crates/horizon-client/src/mobs/riders.rs | 2 +- crates/horizon-client/src/mobs/spawning.rs | 1 + crates/horizon-client/src/mobs/species.rs | 16 ++ crates/horizon-client/src/mobs/trader.rs | 1 + crates/horizon-client/src/mobs/vex.rs | 1 + crates/horizon-client/src/mobs/villager.rs | 3 +- crates/horizon-client/src/settings.rs | 3 +- 17 files changed, 326 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/mobs/illusioner.rs diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index de37858b0..12d7a6006 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -466,6 +466,11 @@ impl Game<'_> { block_tags: &self.res.items.block_tags, biomes: &self.res.biomes, mob_griefing: self.ui.rules.bool("mob_griefing"), + difficulty: self.local_difficulty( + self.player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]), + ), } } /// `ServerLevel.getCurrentDifficultyAt`. diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index aa05dcc63..2f09bc538 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -79,6 +79,7 @@ impl Game<'_> { let ally = matches!( m.species(), Species::Evoker + | Species::Illusioner | Species::Vex | Species::Pillager | Species::Vindicator diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index d946ae183..a602c8be0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -27,6 +27,7 @@ pub mod guardian; pub mod happy_ghast; pub mod hostile; pub mod illager; +pub mod illusioner; pub mod keyframes; pub mod leash; pub mod living; @@ -488,6 +489,8 @@ pub struct Extra { pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, + /// An invisible illusioner's mirror images. + pub illusions: Option, /// A villager's claimed bed head and meeting bell. pub bed: Option<[i32; 3]>, pub meeting: Option<[i32; 3]>, @@ -887,6 +890,8 @@ pub struct MobWorld<'a> { pub biomes: &'a crate::biome::Biomes, /// The `mob_griefing` game rule. pub mob_griefing: bool, + /// `getCurrentDifficultyAt` near the player. + pub difficulty: spawning::LocalDifficulty, } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 3500769ed..464182970 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -122,7 +122,7 @@ pub fn family(s: Species) -> Family { S::Wolf | S::Cat => Family::Tame, S::Blaze | S::Ghast => Family::Nether, S::IronGolem | S::SnowGolem => Family::Golem, - S::Pillager | S::Vindicator | S::Evoker => Family::Illager, + S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => Family::Illager, S::Vex => Family::Vex, S::Ravager => Family::Ravager, S::Wither => Family::Wither, @@ -168,6 +168,7 @@ pub fn register(m: &mut Mob) { Family::Golem => super::golem::register_snow(m), Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m), Family::Illager if m.species() == Species::Evoker => super::illager::register_evoker(m), + Family::Illager if m.species() == Species::Illusioner => super::illusioner::register(m), Family::Illager => super::illager::register_vindicator(m), Family::Equine => super::equine::register(m), Family::Phantom => super::phantom::register(m), @@ -383,6 +384,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } tick_effects(m); + if m.species() == Species::Illusioner { + super::illusioner::tick(m, events); + } if m.hurt_time > 0 { m.hurt_time -= 1; } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index b3bd8a3da..2a07fc99a 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -20,6 +20,7 @@ fn raider(s: Species) -> bool { | Species::Vindicator | Species::Witch | Species::Evoker + | Species::Illusioner | Species::Ravager ) } @@ -30,6 +31,7 @@ fn targets(m: &mut Mob, villagers_seen: bool) { Species::Vindicator, Species::Witch, Species::Evoker, + Species::Illusioner, Species::Vex, Species::Ravager, ]; @@ -95,7 +97,7 @@ enum Spell { /// `SpellcasterCastingSpellGoal`: stand still facing the target while a /// spell is cast. #[derive(Clone, Debug)] -struct CastingSpell; +pub(super) struct CastingSpell; impl Goal for CastingSpell { goal_clone!(); fn flags(&self) -> u8 { @@ -542,6 +544,7 @@ enum ArmPose { Attacking, CrossbowHold, CrossbowCharge, + Bow, } /// `Pillager` / `Vindicator.getArmPose`. fn arm_pose(m: &Mob) -> ArmPose { @@ -557,6 +560,9 @@ fn arm_pose(m: &Mob) -> ArmPose { ArmPose::Neutral } } + Species::Illusioner if m.extra.variant2 != 0 => ArmPose::Spellcasting, + Species::Illusioner if m.ai.aggressive => ArmPose::Bow, + Species::Illusioner => ArmPose::Crossed, Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting, Species::Evoker if celebrating(m) => ArmPose::Celebrating, Species::Evoker => ArmPose::Crossed, @@ -576,7 +582,11 @@ fn celebrating(m: &Mob) -> bool { } /// Whether the held item shows (vindicators only draw their axe when angry). pub fn shows_item(m: &Mob) -> bool { - m.species() != Species::Vindicator || m.ai.aggressive + match m.species() { + Species::Vindicator => m.ai.aggressive, + Species::Illusioner => m.extra.variant2 != 0 || m.ai.aggressive, + _ => true, + } } fn hide(p: &mut Poses, part: &str) { if p.has(part) { @@ -600,6 +610,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.zrot("left_arm", 0.0); p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp * 0.5); p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp * 0.5); + // IllagerModel hides the hat; the illusioner's renderer shows it. + if m.species() != Species::Illusioner { + hide(p, "hat"); + } let pose = arm_pose(m); match pose { ArmPose::Attacking => { @@ -638,6 +652,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { bob(p, "right_arm", 1.0); bob(p, "left_arm", -1.0); } + ArmPose::Bow => { + p.yrot("right_arm", -0.1 + hy); + p.xrot("right_arm", -PI / 2.0 + hx); + p.xrot("left_arm", -0.942_477_9 + hx); + p.yrot("left_arm", hy - 0.4); + p.zrot("left_arm", PI / 2.0); + } ArmPose::CrossbowHold => { p.yrot("right_arm", -0.3 + hy); p.yrot("left_arm", 0.6 + hy); diff --git a/crates/horizon-client/src/mobs/illusioner.rs b/crates/horizon-client/src/mobs/illusioner.rs new file mode 100644 index 000000000..f37c4d01f --- /dev/null +++ b/crates/horizon-client/src/mobs/illusioner.rs @@ -0,0 +1,235 @@ +//! The illusioner (`Illusioner`): a bow-wielding spellcaster that turns +//! invisible behind four mirror images and blinds its target. +use super::{ + Mob, MobEvent, Species, Who, + goals::{ + Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Stroll, + goal_clone, reduced, + }, + illager::CastingSpell, + undead::BowAttack, +}; +use horizon_core::random::RandomSource; + +const INVISIBILITY: &str = "minecraft:invisibility"; +const BLINDNESS: &str = "minecraft:blindness"; +/// `Illusioner.NUM_ILLUSIONS`. +pub const COPIES: usize = 4; + +/// `Illusioner.clientSideIllusionTicks` and the two offset sets. +#[derive(Clone, Debug, Default)] +pub struct Illusions { + pub ticks: i32, + pub offsets: [[[f64; 3]; COPIES]; 2], +} + +pub const MIRROR: u8 = 5; +pub const BLINDNESS_SPELL: u8 = 4; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, CastingSpell); + g.add( + 3, + AvoidEntity::new(Avoid::Species(vec![Species::Creaking]), 8.0, 1.0, 1.2), + ); + g.add(4, Spell::new(MIRROR)); + g.add(5, Spell::new(BLINDNESS_SPELL)); + g.add(6, BowAttack::new(0.5, 20, 15.0)); + g.add(8, Stroll::new(0.6)); + g.add(9, LookAtPlayer::new(3.0).probability(1.0)); + g.add(10, LookAtPlayer::new(8.0)); + let mut hurt = HurtByTarget::new().alert(); + hurt.ignore = vec![ + Species::Pillager, + Species::Vindicator, + Species::Witch, + Species::Evoker, + Species::Illusioner, + Species::Vex, + Species::Ravager, + ]; + m.ai.targets.add(1, hurt); + m.ai.targets.add(2, NearestTarget::player(true)); + m.ai.targets.add( + 3, + NearestTarget::species(&[Species::Villager, Species::WanderingTrader], false), + ); + m.ai.targets + .add(3, NearestTarget::species(&[Species::IronGolem], false)); +} + +/// `Illusioner.finalizeSpawn`: a bow in the main hand. +pub fn finalize(m: &mut Mob) { + m.extra.main_hand = Some("minecraft:bow".into()); +} + +/// `IllusionerMirrorSpellGoal` and `IllusionerBlindnessSpellGoal`. +#[derive(Clone, Debug)] +struct Spell { + spell: u8, + warmup: i32, + next: i64, + last_target: Option, +} +impl Spell { + fn new(spell: u8) -> Self { + Self { + spell, + warmup: 0, + next: 0, + last_target: None, + } + } + /// (casting time, interval, prepare sound). + fn timing(&self) -> (i32, i64, &'static str) { + if self.spell == MIRROR { + (20, 340, "entity.illusioner.prepare_mirror") + } else { + (20, 180, "entity.illusioner.prepare_blindness") + } + } +} +impl Goal for Spell { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.target_info(cx.w).is_some_and(|t| t.alive) + || m.extra.counter > 0 + || i64::from(m.age) < self.next + { + return false; + } + if self.spell == MIRROR { + !m.has_effect(INVISIBILITY) + } else { + m.ai.target != self.last_target && cx.w.difficulty.effective > 2.0 + } + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.target_info(cx.w).is_some_and(|t| t.alive) && self.warmup > 0 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let (casting, interval, sound) = self.timing(); + self.warmup = reduced(20); + m.extra.counter = casting; + self.next = i64::from(m.age) + interval; + cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0)); + m.extra.variant2 = self.spell; + if self.spell == BLINDNESS_SPELL { + self.last_target = m.ai.target; + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.warmup -= 1; + if self.warmup != 0 { + return; + } + if self.spell == MIRROR { + m.add_effect(INVISIBILITY, 1200, 0); + } else if m.ai.target == Some(Who::Player) { + cx.events.push(MobEvent::EffectPlayer { + effect: BLINDNESS, + ticks: 400, + amplifier: 0, + }); + } + cx.events.push(MobEvent::Sound( + "entity.illusioner.cast_spell", + m.center(), + 1.0, + 1.0, + )); + } +} + +/// The client-side half of `Illusioner.aiStep`: new image offsets when +/// hurt and once a minute, with a puff of cloud and a sound. +pub fn tick(m: &mut Mob, events: &mut Vec) { + if !m.has_effect(INVISIBILITY) { + return; + } + let hurt = m.hurt_time; + let age = m.age; + let mut il = m.extra.illusions.take().unwrap_or_default(); + il.ticks = (il.ticks - 1).max(0); + if hurt == 1 || age % 1200 == 0 { + il.ticks = 3; + for i in 0..COPIES { + il.offsets[0][i] = il.offsets[1][i]; + let r = &mut m.random; + let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; + let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64; + let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; + il.offsets[1][i] = [x, y, z]; + } + events.push(MobEvent::Particles { + kind: "minecraft:cloud", + at: [m.position.x, m.position.y + 0.9, m.position.z], + count: 16, + }); + events.push(MobEvent::Sound( + "entity.illusioner.mirror_move", + m.center(), + 1.0, + 1.0, + )); + } else if hurt == 9 { + il.ticks = 3; + for i in 0..COPIES { + il.offsets[0][i] = il.offsets[1][i]; + il.offsets[1][i] = [0.0; 3]; + } + } + m.extra.illusions = Some(il); +} + +/// `Illusioner.getIllusionOffsets`. +pub fn offsets(m: &Mob, partial: f32) -> [[f64; 3]; COPIES] { + let Some(il) = &m.extra.illusions else { + return [[0.0; 3]; COPIES]; + }; + if il.ticks <= 0 { + return il.offsets[1]; + } + let scale = (f64::from(il.ticks as f32 - partial) / 3.0).powf(0.25); + let mut out = [[0.0; 3]; COPIES]; + for (i, o) in out.iter_mut().enumerate() { + for k in 0..3 { + o[k] = il.offsets[1][i][k] * (1.0 - scale) + il.offsets[0][i][k] * scale; + } + } + out +} + +/// The wobble `IllusionerRenderer.submit` adds to each image. +pub fn wobble(i: usize, age: f32) -> [f64; 3] { + let i = i as f32; + [ + f64::from((i + age * 0.5).cos()) * 0.025, + f64::from((i + age * 0.75).cos()) * 0.0125, + f64::from((i + age * 0.7).cos()) * 0.025, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn settled_offsets_are_the_new_set() { + let il = Illusions { + ticks: 0, + offsets: [[[1.0; 3]; COPIES], [[2.0; 3]; COPIES]], + }; + let mut v = [[0.0; 3]; COPIES]; + v.copy_from_slice(&il.offsets[1]); + assert_eq!(v[0], [2.0; 3]); + } + #[test] + fn wobble_is_small() { + assert!(wobble(1, 10.0).iter().all(|c| c.abs() <= 0.025)); + } +} diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index 4dd746407..fbae29b02 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -48,7 +48,7 @@ fn is_zombie(s: &Seen) -> bool { pub fn is_illager(s: &Seen) -> bool { matches!( s.species, - Species::Pillager | Species::Vindicator | Species::Evoker + Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner ) } pub fn register(m: &mut Mob) { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index a2ac618c3..e75464fc4 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -57,6 +57,7 @@ pub fn is_raider(s: Species) -> bool { Species::Pillager | Species::Vindicator | Species::Evoker + | Species::Illusioner | Species::Witch | Species::Ravager ) diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 0166a21c3..833182df5 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -25,6 +25,7 @@ pub fn register(m: &mut Mob) { Species::Pillager, Species::Vindicator, Species::Evoker, + Species::Illusioner, Species::Witch, Species::Ravager, ]; @@ -180,7 +181,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } let illager = matches!( s.species, - Species::Pillager | Species::Vindicator | Species::Evoker + Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner ); if !illager { events.push(MobEvent::AttackMob { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index aaee62988..a95f3eeb5 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -822,10 +822,33 @@ pub fn render_with( extra: &[(&Part, [f32; 4], u32)], out: &mut Vec, ) { - // The invisibility effect hides the model (a drinking wandering trader). + // The invisibility effect hides the model (a drinking wandering trader); + // an illusioner shows its four mirror images instead. if super::trader::is_invisible(m) { + if m.species() == Species::Illusioner { + let age = m.age as f32 + alpha; + for (i, off) in super::illusioner::offsets(m, alpha).iter().enumerate() { + let w = super::illusioner::wobble(i, age); + let shifted = + camera - glam::DVec3::new(off[0] + w[0], off[1] + w[1], off[2] + w[2]); + render_visible(m, alpha, shifted, atlas, light, data, extra, out); + } + } return; } + render_visible(m, alpha, camera, atlas, light, data, extra, out); +} +#[allow(clippy::too_many_arguments)] +fn render_visible( + m: &Mob, + alpha: f32, + camera: glam::DVec3, + atlas: Atlas, + light: u32, + data: &MobData, + extra: &[(&Part, [f32; 4], u32)], + out: &mut Vec, +) { let base = base_transform(m, alpha, camera); let overlay = u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); diff --git a/crates/horizon-client/src/mobs/riders.rs b/crates/horizon-client/src/mobs/riders.rs index 904743cef..94803534d 100644 --- a/crates/horizon-client/src/mobs/riders.rs +++ b/crates/horizon-client/src/mobs/riders.rs @@ -48,7 +48,7 @@ pub fn vehicle_attachment(r: &Mob) -> f64 { | S::Bogged | S::Parched | S::WitherSkeleton => 0.7, - S::Pillager | S::Vindicator | S::Evoker => 0.6, + S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => 0.6, _ => 0.0, } } diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 4644f079e..868658caa 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -397,6 +397,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { m.extra.main_hand = Some("minecraft:golden_axe".into()); m.extra.pick_up_loot = true; } + S::Illusioner => super::illusioner::finalize(m), S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()), S::Villager => { m.extra.variant = villager_type(biome); diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 23ef0fd23..c9c0554d3 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -78,6 +78,7 @@ pub enum Species { ElderGuardian, Shulker, Evoker, + Illusioner, Vex, Ravager, Wither, @@ -905,6 +906,20 @@ pub const ALL: &[Def] = &[ None, Baby::None ), + def!( + Illusioner, + "illusioner", + "illusioner#main", + "entity/illager/illusioner", + A::Illager, + [ + "entity.illusioner.ambient", + "entity.illusioner.hurt", + "entity.illusioner.death" + ], + None, + Baby::None + ), def!( Allay, "allay", @@ -1435,6 +1450,7 @@ impl Def { | S::ElderGuardian | S::Shulker | S::Evoker + | S::Illusioner | S::Vex | S::Ravager | S::Wither diff --git a/crates/horizon-client/src/mobs/trader.rs b/crates/horizon-client/src/mobs/trader.rs index 6df29b246..d72760e21 100644 --- a/crates/horizon-client/src/mobs/trader.rs +++ b/crates/horizon-client/src/mobs/trader.rs @@ -44,6 +44,7 @@ pub fn register(m: &mut Mob) { for (species, distance) in [ (Species::Zombie, 8.0), (Species::Evoker, 12.0), + (Species::Illusioner, 12.0), (Species::Vindicator, 8.0), (Species::Vex, 8.0), (Species::Pillager, 15.0), diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index 2ee444d84..6c7515ae9 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -32,6 +32,7 @@ pub fn register(m: &mut Mob) { Species::Pillager, Species::Vindicator, Species::Evoker, + Species::Illusioner, Species::Witch, Species::Vex, ]; diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 994f31fbd..ae1fb2d27 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -63,6 +63,7 @@ pub fn register(m: &mut Mob) { Species::Pillager, Species::Vindicator, Species::Evoker, + Species::Illusioner, Species::Ravager, Species::Zoglin, ]; @@ -1217,7 +1218,7 @@ fn hostile_range(s: Species) -> f64 { | Species::Vex | Species::Zombie | Species::ZombieVillager => 8.0, - Species::Evoker | Species::Ravager => 12.0, + Species::Evoker | Species::Illusioner | Species::Ravager => 12.0, Species::Pillager => 15.0, Species::Vindicator | Species::Zoglin => 10.0, _ => 0.0, diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 4b0a27838..b6ed40301 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -20,7 +20,7 @@ pub fn set_source_volumes(volumes: [f32; 11]) { pub fn sound_source(event: &str) -> usize { let e = event.trim_start_matches("minecraft:"); let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0); - const HOSTILE: [&str; 24] = [ + const HOSTILE: [&str; 25] = [ "zombie", "skeleton", "creeper", @@ -39,6 +39,7 @@ pub fn sound_source(event: &str) -> usize { "pillager", "vindicator", "evoker", + "illusioner", "ravager", "guardian", "elder_guardian", From 5dbf3b62a873900daa69143466e11cc54e804a24 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:15:53 +0200 Subject: [PATCH 24/24] Fix integration of the overnight branches After merging the overnight feature branches, the only remaining problem was a clippy lint in the illusioner mob code, where a manual modulo check had to become is_multiple_of. With that change, formatting, clippy with warnings denied and the full workspace test suite all pass. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/mobs/illusioner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/illusioner.rs b/crates/horizon-client/src/mobs/illusioner.rs index f37c4d01f..ee36acf40 100644 --- a/crates/horizon-client/src/mobs/illusioner.rs +++ b/crates/horizon-client/src/mobs/illusioner.rs @@ -156,7 +156,7 @@ pub fn tick(m: &mut Mob, events: &mut Vec) { let age = m.age; let mut il = m.extra.illusions.take().unwrap_or_default(); il.ticks = (il.ticks - 1).max(0); - if hurt == 1 || age % 1200 == 0 { + if hurt == 1 || age.is_multiple_of(1200) { il.ticks = 3; for i in 0..COPIES { il.offsets[0][i] = il.offsets[1][i];