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/42] 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 90023be7c24730000aca28391e2b9bb76ca4ff74 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:02:16 +0200 Subject: [PATCH 02/42] Add a whole-chunk differential harness against vanilla generation The new oracle drives vanilla's own chunk stages (structure starts and references, biomes, terrain with surface and carvers, then biome decoration with every placed feature and structure piece) through real WorldGenRegion instances, and the chunk_dump example runs the same stages in the same order in Horizon. The Python runner compares every block state, quart biome and block entity over terrain sites and structure sites found by scanning each seed, in the overworld, Nether and End, with phases that stop before features or run structure pieces only. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-world/examples/chunk_dump.rs | 222 ++++++++++ .../parity/VanillaChunkGenerationOracle.java | 404 ++++++++++++++++++ tools/test_chunk_generation_parity.py | 318 ++++++++++++++ 3 files changed, 944 insertions(+) create mode 100644 crates/horizon-world/examples/chunk_dump.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java create mode 100644 tools/test_chunk_generation_parity.py diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/chunk_dump.rs new file mode 100644 index 000000000..e7e440252 --- /dev/null +++ b/crates/horizon-world/examples/chunk_dump.rs @@ -0,0 +1,222 @@ +//! Whole-chunk dump in the format of the vanilla chunk-generation oracle. +//! +//! chunk_dump ... +//! With HORIZON_SCAN set, one rectangle lists the structure starts in it. +//! +//! Chunks are generated through biomes, terrain and carvers, then decorated in +//! row-major order over the target rectangle grown by one chunk, each with its +//! eight neighbours so feature spill persists, exactly as the oracle does. +//! For every target chunk this prints `chunk X Z`, one `q QY NAME...` line per +//! quart layer (16 columns, z-major), one `y Y ID...` line per block row and +//! one `be X Y Z CANONICAL_NBT` line per block entity. +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::BlockRegistry, + worldgen::generator::{GeneratorData, OverworldGenerator, ProtoChunk}, +}; +use serde_json::Value; +use std::{collections::HashMap, fmt::Write as _, fs, io::Write as _, path::Path}; + +type Error = Box; + +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { + let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; + let states = facts["states"].as_array().ok_or("facts states")?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(states.iter().map(|v| tag(&v[4])).collect()), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + Ok(Box::leak(Box::new(registry))) +} + +/// Type-prefixed scalars with sorted compound keys, as the oracle prints them. +fn canonical(tag: &Tag, out: &mut String) { + match tag { + Tag::End => {} + Tag::Byte(v) => write!(out, "b{v}").unwrap(), + Tag::Short(v) => write!(out, "s{v}").unwrap(), + Tag::Int(v) => write!(out, "i{v}").unwrap(), + Tag::Long(v) => write!(out, "l{v}").unwrap(), + Tag::Float(v) => write!(out, "f{}", *v as i32).unwrap(), + Tag::Double(v) => write!(out, "d{}", *v as i64).unwrap(), + Tag::String(s) => { + let text = s + .to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\""); + write!(out, "\"{text}\"").unwrap(); + } + Tag::ByteArray(v) => { + out.push_str("B["); + for b in v { + write!(out, "{},", *b as i8).unwrap(); + } + out.push(']'); + } + Tag::IntArray(v) => { + out.push_str("I["); + for b in v { + write!(out, "{b},").unwrap(); + } + out.push(']'); + } + Tag::LongArray(v) => { + out.push_str("L["); + for b in v { + write!(out, "{b},").unwrap(); + } + out.push(']'); + } + Tag::List(v) => { + out.push('['); + for item in v { + canonical(item, out); + out.push(','); + } + out.push(']'); + } + Tag::Compound(c) => { + out.push('{'); + for (k, v) in c { + write!(out, "{}=", k.to_string_lossy()).unwrap(); + canonical(v, out); + out.push(','); + } + out.push('}'); + } + } +} + +fn main() -> Result<(), Error> { + let mut args = std::env::args().skip(1); + let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); + let seed: i64 = args.next().ok_or("seed")?.parse()?; + let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); + let rects = args + .map(|rect| { + let v: Vec = rect.split(',').map(str::parse).collect::>()?; + let v: [i32; 4] = v.try_into().map_err(|_| "rectangle x0,z0,x1,z1")?; + Ok(v) + }) + .collect::, Error>>()?; + let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?; + let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; + let mut worker = generator.worker(); + // HORIZON_PHASE: terrain (no decoration), structures (pieces only) or full. + let phase = std::env::var("HORIZON_PHASE").unwrap_or_else(|_| "full".into()); + worker.set_structures_only(phase == "structures"); + if std::env::var_os("HORIZON_SCAN").is_some() { + let [x0, z0, x1, z1] = rects[0]; + for x in x0..=x1 { + for z in z0..=z1 { + for s in worker.structure_starts(ChunkPos::new(x, z)) { + if s.chunk == ChunkPos::new(x, z) { + println!( + "start {} {x} {z} {} {} {} {} {} {}", + s.name, + s.bounding_box.min[0], + s.bounding_box.min[1], + s.bounding_box.min[2], + s.bounding_box.max[0], + s.bounding_box.max[1], + s.bounding_box.max[2] + ); + } + } + } + } + return Ok(()); + } + for [x0, z0, x1, z1] in rects { + let mut chunks: HashMap<(i32, i32), ProtoChunk> = HashMap::new(); + for z in z0 - 2..=z1 + 2 { + for x in x0 - 2..=x1 + 2 { + chunks.insert((x, z), worker.generate_proto(ChunkPos::new(x, z))?); + } + } + let mut failed = 0; + let margin = i32::from(std::env::var_os("HORIZON_ISOLATED").is_none()); + for z in z0 - margin..=z1 + margin { + for x in x0 - margin..=x1 + margin { + let mut region = Vec::with_capacity(9); + for dz in -1..=1 { + for dx in -1..=1 { + region.push(chunks.remove(&(x + dx, z + dz)).ok_or("missing chunk")?); + } + } + let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region size")?; + let stats = if phase == "terrain" { + Default::default() + } else { + worker.decorate(&mut region)? + }; + if stats.failed > 0 || stats.unsupported > 0 { + failed += 1; + eprintln!( + "chunk {x} {z}: {} failed, {} unsupported {:?}", + stats.failed, stats.unsupported, stats.skipped + ); + } + for (i, chunk) in region.into_iter().enumerate() { + chunks.insert((x + i as i32 % 3 - 1, z + i as i32 / 3 - 1), chunk); + } + } + } + if failed > 0 { + eprintln!("{failed} chunks had failed or unsupported features"); + } + let stdout = std::io::stdout(); + let mut w = std::io::BufWriter::new(stdout.lock()); + for z in z0..=z1 { + for x in x0..=x1 { + let chunk = &chunks[&(x, z)]; + writeln!(w, "chunk {x} {z}")?; + let (min, height) = (chunk.terrain.min_y(), chunk.terrain.height()); + for qy in min >> 2..=(min + height - 1) >> 2 { + let mut line = format!("q {qy}"); + for qz in 0..4 { + for qx in 0..4 { + line.push(' '); + line.push_str(chunk.biome_at(x * 16 + qx * 4, qy * 4, z * 16 + qz * 4)); + } + } + writeln!(w, "{line}")?; + } + for y in min..min + height { + let mut line = format!("y {y}"); + for zz in 0..16 { + for xx in 0..16 { + write!(line, " {}", chunk.block(x * 16 + xx, y, z * 16 + zz).0)?; + } + } + writeln!(w, "{line}")?; + } + let mut entities: Vec<_> = chunk.block_entities.iter().collect(); + entities.sort_by_key(|(p, _)| *p); + for ([bx, by, bz], nbt) in entities { + let mut text = String::new(); + canonical(&Tag::Compound(nbt.clone()), &mut text); + writeln!(w, "be {bx} {by} {bz}\t{text}")?; + } + } + } + } + Ok(()) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java new file mode 100644 index 000000000..b381298ae --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -0,0 +1,404 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.GenerationChunkHolder; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.WorldGenRegion; +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.util.StaticCache2D; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.chunk.status.ChunkPyramid; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.blending.Blender; +import net.minecraft.world.level.levelgen.structure.*; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; +import net.minecraft.world.level.storage.LevelStorageSource; + +/** + * Original oracle: whole-chunk generation through vanilla's own pipeline. + * + * Chunks run through STRUCTURE_STARTS, STRUCTURE_REFERENCES, BIOMES, TERRAIN + * (noise, surface, carvers) and FEATURES exactly as the ChunkStatusTasks do, + * with actual WorldGenRegion instances over an allocation-only ServerLevel. + * FEATURES run in row-major order over the target rectangle grown by one chunk, + * so every target chunk has all eight neighbours decorated. Spill from + * neighbouring features therefore matches a canonical vanilla order. + * + * usage: dump OUT SEED DIMENSION X0,Z0,X1,Z1... (target chunks, inclusive) + * scan OUT SEED DIMENSION X0 Z0 X1 Z1 (structure starts per chunk) + * dump takes any number of X0,Z0,X1,Z1 rectangles, each generated from scratch. + */ +public final class VanillaChunkGenerationOracle { + private static final class OracleCache extends ServerChunkCache { + private OracleCache() { + super(null, null, null, null, null, null, 0, 0, false, null); + } + static ChunkGeneratorStructureState state; + static RandomState random; + static ChunkGenerator generator; + @Override + public ChunkGeneratorStructureState getGeneratorState() { + return state; + } + @Override + public RandomState randomState() { + return random; + } + @Override + public ChunkGenerator getGenerator() { + return generator; + } + } + + private static final class OracleLevel extends ServerLevel { + private OracleLevel() { + super(null, null, null, null, null, null, false, 0L, null, false); + } + static long seed; + static RegistryAccess access; + static net.minecraft.world.level.dimension.DimensionType type; + static StructureManager structures; + static BiomeResolver resolver; + static ServerChunkCache cache; + static ResourceKey key; + static int minY, height; + static Map chunks; + static net.minecraft.world.level.lighting.LevelLightEngine light; + @Override + public net.minecraft.world.level.lighting.LevelLightEngine getLightEngine() { + return light; + } + @Override + public long getSeed() { + return seed; + } + @Override + public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { + return net.minecraft.world.flag.FeatureFlagSet.of(); + } + @Override + public RegistryAccess registryAccess() { + return access; + } + @Override + public net.minecraft.world.level.dimension.DimensionType dimensionType() { + return type; + } + @Override + public StructureManager structureManager() { + return structures; + } + @Override + public BiomeResolver uncachedBiomeResolver() { + return resolver; + } + @Override + public ServerChunkCache getChunkSource() { + return cache; + } + @Override + public ResourceKey dimension() { + return key; + } + @Override + public net.minecraft.world.level.storage.ServerLevelData getLevelData() { + return DATA; + } + static final net.minecraft.world.level.storage.ServerLevelData DATA = (net.minecraft.world.level.storage.ServerLevelData) java.lang.reflect.Proxy.newProxyInstance( + OracleLevel.class.getClassLoader(), new Class[] {net.minecraft.world.level.storage.ServerLevelData.class}, (proxy, method, values) -> { + Class type = method.getReturnType(); + if (type == long.class) return 0L; + if (type == int.class) return 0; + if (type == boolean.class) return false; + if (type == float.class) return 0f; + if (type == double.class) return 0d; + return null; + }); + @Override + public int getMinY() { + return minY; + } + @Override + public int getHeight() { + return height; + } + @Override + public int getSeaLevel() { + return OracleCache.generator.getSeaLevel(); + } + @Override + public void updatePOIOnBlockStateChange(net.minecraft.core.BlockPos pos, net.minecraft.world.level.block.state.BlockState a, net.minecraft.world.level.block.state.BlockState b) {} + @Override + public ChunkAccess getChunk(int x, int z, ChunkStatus status, boolean load) { + return chunks.get(ChunkPos.pack(x, z)); + } + } + + private static final class ChunkHolder extends GenerationChunkHolder { + final ProtoChunk chunk; + ChunkHolder(ProtoChunk chunk) { + super(chunk.getPos()); + this.chunk = chunk; + } + @Override + public ChunkAccess getChunkIfPresentUnchecked(ChunkStatus status) { + return status.isOrBefore(chunk.getPersistedStatus()) ? chunk : null; + } + @Override + protected void addSaveDependency(CompletableFuture sync) {} + @Override + public int getTicketLevel() { + return 0; + } + @Override + public int getQueueLevel() { + return 0; + } + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + String mode = args[0]; + Path out = Path.of(args[1]); + long seed = Long.parseLong(args[2]); + String dimension = args[3]; + 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 loaded = net.minecraft.server.ReloadableServerRegistries.reload(layers.replaceFrom(RegistryLayer.WORLD, world), staticTags, resources, Runnable::run).join(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(loaded.lookupWithUpdatedTags()); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + var settings = world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(switch (dimension) { + case "the_nether" -> NoiseGeneratorSettings.NETHER; + case "the_end" -> NoiseGeneratorSettings.END; + default -> NoiseGeneratorSettings.OVERWORLD; + }); + var presets = world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); + BiomeSource biomeSource = switch (dimension) { + case "the_nether" -> MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER)); + case "the_end" -> TheEndBiomeSource.create(world.lookupOrThrow(Registries.BIOME)); + default -> MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)); + }; + ResourceKey levelKey = switch (dimension) { + case "the_nether" -> Level.NETHER; + case "the_end" -> Level.END; + default -> Level.OVERWORLD; + }; + var randomState = RandomState.create(world.lookupOrThrow(Registries.NOISE), seed, settings.value()); + var generator = new NoiseBasedChunkGenerator(biomeSource, settings); + String phase = System.getenv().getOrDefault("HORIZON_PHASE", "full"); + if (phase.equals("structures")) { + // Structure pieces only: every biome keeps its carvers but loses its placed features. + java.util.function.Function, BiomeGenerationSettings> noFeatures = biome -> { + var builder = new BiomeGenerationSettings.PlainBuilder(); + for (var carver : biome.value().getGenerationSettings().getCarvers()) builder.addCarver(carver); + return builder.build(); + }; + var field = ChunkGenerator.class.getDeclaredField("generationSettingsGetter"); + field.setAccessible(true); + field.set(generator, noFeatures); + } + var state = ChunkGeneratorStructureState.createForNormal(randomState, seed, new ChunkPos(0, 0), biomeSource, world.lookupOrThrow(Registries.STRUCTURE_SET)); + Path tmp = Files.createTempDirectory("horizon-chunks"); + var storage = LevelStorageSource.createDefault(tmp).createAccess("oracle"); + var templates = new StructureTemplateManager(resources, storage, DataFixers.getDataFixer(), BuiltInRegistries.BLOCK); + var dimensionType = world.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(switch (dimension) { + case "the_nether" -> net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER; + case "the_end" -> net.minecraft.world.level.dimension.BuiltinDimensionTypes.END; + default -> net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD; + }).value(); + LevelHeightAccessor height = dimension.equals("overworld") ? LevelHeightAccessor.create(-64, 384) : LevelHeightAccessor.create(0, 256); + var factory = PalettedContainerFactory.create(access); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + Object unsafe = unsafeField.get(null); + var allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + Map chunks = new HashMap<>(); + OracleCache.state = state; + OracleCache.random = randomState; + OracleCache.generator = generator; + OracleLevel.seed = seed; + OracleLevel.access = access; + OracleLevel.type = dimensionType; + OracleLevel.resolver = biomeSource.createUncachedResolver(randomState); + OracleLevel.cache = (ServerChunkCache) allocate.invoke(unsafe, OracleCache.class); + OracleLevel.key = levelKey; + OracleLevel.minY = height.getMinY(); + OracleLevel.height = height.getHeight(); + OracleLevel.chunks = chunks; + var blockGetter = (BlockGetter) java.lang.reflect.Proxy.newProxyInstance(BlockGetter.class.getClassLoader(), new Class[] {BlockGetter.class}, (proxy, method, values) -> { + switch (method.getName()) { + case "getMinY": return height.getMinY(); + case "getHeight": return height.getHeight(); + } + if (method.isDefault()) return java.lang.reflect.InvocationHandler.invokeDefault(proxy, method, values); + return null; + }); + var lightGetter = new LightChunkGetter() { + public LightChunk getChunkForLighting(int x, int z) { return null; } + public BlockGetter getLevel() { return blockGetter; } + }; + OracleLevel.light = new net.minecraft.world.level.lighting.LevelLightEngine(lightGetter, true, dimensionType.hasSkyLight()); + var check = new StructureCheck((pos, visitor) -> CompletableFuture.completedFuture(null), access, templates, levelKey, generator, randomState, height, biomeSource, seed, DataFixers.getDataFixer()); + var level = (ServerLevel) allocate.invoke(unsafe, OracleLevel.class); + OracleLevel.structures = new StructureManager(level, new WorldOptions(seed, true, false), check); + var pyramid = ChunkPyramid.GENERATION_PYRAMID; + java.util.function.BiFunction chunkAt = (x, z) -> chunks.computeIfAbsent(ChunkPos.pack(x, z), k -> new ProtoChunk(new ChunkPos(x, z), UpgradeData.EMPTY, height, factory, null)); + java.util.function.BiFunction regionFor = (status, chunk) -> { + var step = pyramid.getStepTo(status); + int radius = step.directDependencies().size() - 1; + var cache = StaticCache2D.create(chunk.getPos().x(), chunk.getPos().z(), radius, (x, z) -> new ChunkHolder(chunkAt.apply(x, z))); + return new WorldGenRegion(level, cache, step, chunk); + }; + Runnable noop = () -> {}; + try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + if (mode.equals("scan")) { + int x0 = Integer.parseInt(args[4]), z0 = Integer.parseInt(args[5]), x1 = Integer.parseInt(args[6]), z1 = Integer.parseInt(args[7]); + for (int x = x0; x <= x1; x++) for (int z = z0; z <= z1; z++) { + var chunk = chunkAt.apply(x, z); + generator.createStructures(access, state, OracleLevel.structures, chunk, templates, levelKey); + for (var start : chunk.getAllStarts().values()) { + if (!start.isValid()) continue; + var box = start.getBoundingBox(); + var id = access.lookupOrThrow(Registries.STRUCTURE).getKey(start.getStructure()); + w.println("start " + id + " " + x + " " + z + " " + box.minX() + " " + box.minY() + " " + box.minZ() + " " + box.maxX() + " " + box.maxY() + " " + box.maxZ()); + } + } + return; + } + for (int rect = 4; rect < args.length; rect++) { + chunks.clear(); + String[] corners = args[rect].split(","); + int x0 = Integer.parseInt(corners[0]), z0 = Integer.parseInt(corners[1]), x1 = Integer.parseInt(corners[2]), z1 = Integer.parseInt(corners[3]); + // Margins: FEATURES need TERRAIN at 1, which needs BIOMES at 1 more; STRUCTURE_STARTS reach 8 further. + int m = System.getenv("HORIZON_ISOLATED") != null ? 0 : 1; // diagnostics: decorate the targets only + int fx0 = x0 - m, fz0 = z0 - m, fx1 = x1 + m, fz1 = z1 + m; + int tx0 = fx0 - 1, tz0 = fz0 - 1, tx1 = fx1 + 1, tz1 = fz1 + 1; + int bx0 = tx0 - 1, bz0 = tz0 - 1, bx1 = tx1 + 1, bz1 = tz1 + 1; + int sx0 = tx0 - 8, sz0 = tz0 - 8, sx1 = tx1 + 8, sz1 = tz1 + 8; + for (int z = sz0; z <= sz1; z++) for (int x = sx0; x <= sx1; x++) { + var chunk = chunkAt.apply(x, z); + generator.createStructures(access, state, OracleLevel.structures, chunk, templates, levelKey); + chunk.setPersistedStatus(ChunkStatus.STRUCTURE_STARTS); + } + for (int z = tz0; z <= tz1; z++) for (int x = tx0; x <= tx1; x++) { + var chunk = chunkAt.apply(x, z); + var region = regionFor.apply(ChunkStatus.STRUCTURE_REFERENCES, chunk); + generator.createReferences(region, OracleLevel.structures.forWorldGenRegion(region), chunk); + chunk.setPersistedStatus(ChunkStatus.STRUCTURE_REFERENCES); + } + for (int z = bz0; z <= bz1; z++) for (int x = bx0; x <= bx1; x++) { + var chunk = chunkAt.apply(x, z); + if (chunk.getPersistedStatus() != ChunkStatus.STRUCTURE_STARTS && chunk.getPersistedStatus() != ChunkStatus.EMPTY && chunk.getPersistedStatus() != ChunkStatus.STRUCTURE_REFERENCES) continue; + var region = regionFor.apply(ChunkStatus.BIOMES, chunk); + generator.createBiomes(randomState, Blender.empty(), OracleLevel.structures.forWorldGenRegion(region), chunk).join(); + chunk.setPersistedStatus(ChunkStatus.BIOMES); + } + for (int z = tz0; z <= tz1; z++) for (int x = tx0; x <= tx1; x++) { + var chunk = chunkAt.apply(x, z); + var region = regionFor.apply(ChunkStatus.TERRAIN, chunk); + Set> possible = new HashSet<>(); + for (int dz = -1; dz <= 1; dz++) for (int dx = -1; dx <= 1; dx++) region.getChunk(x + dx, z + dz).collectBiomesInPalette(possible); + generator.buildTerrain(chunk, Blender.empty(), randomState, OracleLevel.structures.forWorldGenRegion(region), region.getBiomeManager(), region, possible).join(); + Heightmap.primeHeightmaps(chunk, EnumSet.of(Heightmap.Types.MOTION_BLOCKING, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Heightmap.Types.OCEAN_FLOOR, Heightmap.Types.WORLD_SURFACE)); + chunk.setPersistedStatus(ChunkStatus.TERRAIN); + } + for (int z = fz0; z <= fz1 && !phase.equals("terrain"); z++) for (int x = fx0; x <= fx1; x++) { + var chunk = chunkAt.apply(x, z); + var region = regionFor.apply(ChunkStatus.FEATURES, chunk); + generator.applyBiomeDecoration(region, chunk, OracleLevel.structures.forWorldGenRegion(region)); + chunk.setPersistedStatus(ChunkStatus.FEATURES); + } + var registry = access; + for (int z = z0; z <= z1; z++) for (int x = x0; x <= x1; x++) { + var target = chunkAt.apply(x, z); + w.println("chunk " + x + " " + z); + // Biomes: one line per quart layer, 16 columns in z-major order. + for (int qy = height.getMinY() >> 2; qy <= height.getMaxY() >> 2; qy++) { + StringBuilder line = new StringBuilder("q " + qy); + for (int qz = 0; qz < 4; qz++) for (int qx = 0; qx < 4; qx++) + line.append(' ').append(target.getNoiseBiome((x << 2) + qx, qy, (z << 2) + qz).unwrapKey().orElseThrow().identifier()); + w.println(line); + } + for (int y = height.getMinY(); y <= height.getMaxY(); y++) { + StringBuilder line = new StringBuilder("y " + y); + for (int zz = 0; zz < 16; zz++) for (int xx = 0; xx < 16; xx++) + line.append(' ').append(Block.getId(target.getBlockState(new BlockPos((x << 4) + xx, y, (z << 4) + zz)))); + w.println(line); + } + var positions = new TreeSet(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + positions.addAll(target.getBlockEntitiesPos()); + for (var pos : positions) { + var tag = target.getBlockEntityNbtForSaving(pos, registry); + if (tag == null) continue; + var st = target.getBlockState(pos); + var fresh = ((net.minecraft.world.level.block.EntityBlock) st.getBlock()).newBlockEntity(pos, st).saveWithFullMetadata(registry); + if ("DUMMY".equals(tag.getStringOr("id", ""))) tag = fresh; + w.println("be " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\t" + canonicalOf(tag) + "\t" + canonicalOf(fresh)); + } + } + } + } + storage.close(); + System.exit(0); + } + + private static String canonicalOf(net.minecraft.nbt.Tag tag) { + var out = new StringBuilder(); + canonical(tag, out); + return out.toString(); + } + + /** Canonical single-line form of a tag: type-prefixed scalars, sorted compound keys. */ + private static void canonical(net.minecraft.nbt.Tag tag, StringBuilder out) { + switch (tag) { + case net.minecraft.nbt.ByteTag t -> out.append("b").append(t.byteValue()); + case net.minecraft.nbt.ShortTag t -> out.append("s").append(t.shortValue()); + case net.minecraft.nbt.IntTag t -> out.append("i").append(t.intValue()); + case net.minecraft.nbt.LongTag t -> out.append("l").append(t.longValue()); + case net.minecraft.nbt.FloatTag t -> out.append("f").append(Float.floatToRawIntBits(t.floatValue())); + case net.minecraft.nbt.DoubleTag t -> out.append("d").append(Double.doubleToRawLongBits(t.doubleValue())); + case net.minecraft.nbt.StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"'); + case net.minecraft.nbt.ByteArrayTag t -> { out.append("B["); for (byte v : t.getAsByteArray()) out.append(v).append(','); out.append(']'); } + case net.minecraft.nbt.IntArrayTag t -> { out.append("I["); for (int v : t.getAsIntArray()) out.append(v).append(','); out.append(']'); } + case net.minecraft.nbt.LongArrayTag t -> { out.append("L["); for (long v : t.getAsLongArray()) out.append(v).append(','); out.append(']'); } + case net.minecraft.nbt.ListTag t -> { out.append('['); for (var item : t) { canonical(item, out); out.append(','); } out.append(']'); } + case net.minecraft.nbt.CompoundTag t -> { + out.append('{'); + for (String key : new TreeSet<>(t.keySet())) { out.append(key).append('='); canonical(t.get(key), out); out.append(','); } + out.append('}'); + } + default -> throw new IllegalStateException(tag.getClass().getName()); + } + } +} diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py new file mode 100644 index 000000000..e7ee17aba --- /dev/null +++ b/tools/test_chunk_generation_parity.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python3 +"""Compare whole generated chunks block-for-block with vanilla. + +Vanilla side: VanillaChunkGenerationOracle drives the actual ChunkGenerator +stages (structure starts and references, biomes, terrain with surface and +carvers, then biome decoration with every placed feature and structure piece) +through real WorldGenRegion instances. Horizon side: the chunk_dump example +runs the same stages in the same order. Every block state, quart biome and +block entity (canonical NBT) of each target chunk is compared. + +Cases: terrain sites for several seeds across the overworld, the Nether and the +End, plus rectangles around vanilla structure starts found by scanning each +seed (villages, mineshafts, strongholds, ancient cities, trial chambers, +monuments, mansions, ...). + +usage: test_chunk_generation_parity.py [--seeds N] [--per-structure K] + [--filter REGEX] [--dimension overworld|the_nether|the_end] [--keep] +""" +import argparse +import json +import os +import random +import re +import subprocess +import sys +import time +from collections import Counter, defaultdict +from pathlib import Path + +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +SEEDS = [12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777] +RESOURCES = lab.LOCAL / 'horizon-client/26.3' +ORACLE = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java' + + +def build_dir(): + path = lab.LOCAL / 'chunk-generation-parity' + path.mkdir(parents=True, exist_ok=True) + return path + + +class Oracle: + def __init__(self): + self.lock, self.jars, self.libraries = base.verify_artifacts() + self.dependencies = os.pathsep.join(map(str, [self.jars['server'], *self.libraries])) + self.classes = build_dir() / 'classes' + self.classes.mkdir(exist_ok=True) + result = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', '-cp', self.dependencies, + '-d', str(self.classes), str(ORACLE)], capture_output=True, text=True) + if result.returncode: + raise SystemExit('javac failed:\n' + result.stderr[-4000:]) + + def run(self, out, args): + result = subprocess.run(['java', '-Xmx8G', '-cp', str(self.classes) + os.pathsep + self.dependencies, + 'dev.horizonlab.parity.VanillaChunkGenerationOracle', *map(str, [args[0], out, *args[1:]])], + capture_output=True, text=True, env=dict(os.environ)) + if result.returncode: + lines = [l for l in (result.stdout + result.stderr).splitlines() if 'Exception' in l or 'Caused' in l or '\tat ' in l] + raise SystemExit('oracle failed: ' + ' | '.join(lines[:10])) + + +def rust_binary(): + subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'chunk_dump'], check=True, cwd=lab.ROOT) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + return Path(metadata['target_directory']) / 'release/examples/chunk_dump' + + +def run_rust(binary, out, seed, dimension, rects, scan=False): + env = dict(os.environ) + if scan: + env['HORIZON_SCAN'] = '1' + with open(out, 'w') as handle: + result = subprocess.run([str(binary), str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) + if result.returncode: + raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:]) + return result.stderr + + +def parse(path): + chunks, current = {}, None + for line in Path(path).read_text().splitlines(): + if line.startswith('chunk '): + _, x, z = line.split() + current = (int(x), int(z)) + chunks[current] = {'q': {}, 'y': {}, 'be': {}} + elif line.startswith('q '): + _, q, row = line.split(' ', 2) + chunks[current]['q'][int(q)] = row + elif line.startswith('y '): + _, y, row = line.split(' ', 2) + chunks[current]['y'][int(y)] = row + elif line.startswith('be '): + head, *forms = line.split('\t') + parts = head.split(' ') + chunks[current]['be'][(int(parts[1]), int(parts[2]), int(parts[3]))] = forms + return chunks + + +def parse_nbt(text, i=0): + """Canonical NBT text -> Python values (typed scalars as (type, text) tuples).""" + c = text[i] + if c == '{': + i += 1 + value = {} + while text[i] != '}': + j = text.index('=', i) + key = text[i:j] + value[key], i = parse_nbt(text, j + 1) + i += 1 # comma + return value, i + 1 + if c == '[': + i += 1 + items = [] + while text[i] != ']': + item, i = parse_nbt(text, i) + items.append(item) + i += 1 + return items, i + 1 + if c == '"': + i += 1 + out = [] + while text[i] != '"': + if text[i] == '\\': + i += 1 + out.append(text[i]) + i += 1 + return ('str', ''.join(out)), i + 1 + if c in 'BIL' and text[i + 1] == '[': + j = text.index(']', i) + return (c, text[i + 2:j]), j + 1 + j = i + 1 + while j < len(text) and text[j] not in ',}]': + j += 1 + return (c, text[i + 1:j]), j + + +def nbt_matches(vanilla, rust, default): + """Horizon stores the placed data only; vanilla saves defaults too. Every key + Horizon sets must match, and every other vanilla key must be the fresh default.""" + if isinstance(vanilla, dict) and isinstance(rust, dict): + default = default if isinstance(default, dict) else {} + for key, value in vanilla.items(): + if key in ('x', 'y', 'z') or (key == 'components' and value == {}): + continue + if key in rust: + if not nbt_matches(value, rust[key], default.get(key)): + return False + elif value != default.get(key): + return False + return all(key in vanilla or key in ('x', 'y', 'z') for key in rust) + return vanilla == rust + + +def entity_matches(vanilla, rust): + if rust is None or vanilla is None: + return False + return nbt_matches(parse_nbt(vanilla[0])[0], parse_nbt(rust[0])[0], parse_nbt(vanilla[1])[0]) + + +def state_names(): + facts = json.loads((RESOURCES / 'facts.json').read_text()) + return [s[3].removeprefix('Block{').replace('}', '', 1) for s in facts['states']] + + +def compare(vanilla, rust, names, label, limit=6, quiet=False): + """Returns (differing chunks, differing blocks, differing biome cells, differing block entities).""" + chunks = blocks = biomes = entities = 0 + for pos in sorted(vanilla): + a, b = vanilla[pos], rust.get(pos) + if b is None: + print(f' {label} chunk {pos}: missing from Horizon output') + chunks += 1 + continue + block_diffs, biome_diffs, entity_diffs = [], [], [] + for y in sorted(a['y']): + ra, rb = a['y'][y], b['y'].get(y) + if ra == rb: + continue + for i, (u, v) in enumerate(zip(ra.split(' '), (rb or '').split(' '))): + if u != v: + block_diffs.append((pos[0] * 16 + i % 16, y, pos[1] * 16 + i // 16, names[int(u)], names[int(v)])) + for q in sorted(a['q']): + if a['q'][q] != b['q'].get(q): + for i, (u, v) in enumerate(zip(a['q'][q].split(' '), b['q'].get(q, '').split(' '))): + if u != v: + biome_diffs.append((pos[0] * 4 + i % 4, q, pos[1] * 4 + i // 4, u, v)) + for key in sorted(set(a['be']) | set(b['be'])): + if not entity_matches(a['be'].get(key), b['be'].get(key)): + entity_diffs.append((key, a['be'].get(key, [None])[0], (b['be'].get(key) or [None])[0])) + if block_diffs or biome_diffs or entity_diffs: + chunks += 1 + blocks += len(block_diffs) + biomes += len(biome_diffs) + entities += len(entity_diffs) + if quiet: + continue + print(f' {label} chunk {pos}: {len(block_diffs)} blocks, {len(biome_diffs)} biome cells, {len(entity_diffs)} block entities') + for d in block_diffs[:limit]: + print(f' block {d[0]} {d[1]} {d[2]}: vanilla {d[3]} / horizon {d[4]}') + for d in biome_diffs[:2]: + print(f' biome quart {d[0]} {d[1]} {d[2]}: vanilla {d[3]} / horizon {d[4]}') + for d in entity_diffs[:3]: + print(f' block entity {d[0]}: vanilla {d[1]} / horizon {d[2]}') + return chunks, blocks, biomes, entities + + +def scan(oracle, binary, seed, dimension, radius): + out = build_dir() / f'scan-{dimension}-{seed}.txt' + oracle.run(out, ['scan', seed, dimension, -radius, -radius, radius, radius]) + starts = [] + for line in out.read_text().splitlines(): + t = line.split() + if t and t[0] == 'start': + starts.append((t[1], int(t[2]), int(t[3]), tuple(map(int, t[4:10])))) + return starts + + +def pick_structures(starts, per_kind, rng): + by_kind = defaultdict(list) + for s in starts: + by_kind[s[0]].append(s) + picked = [] + for kind, items in sorted(by_kind.items()): + items.sort(key=lambda s: abs(s[1]) + abs(s[2])) + # Nearest first, then random ones, so that variants (village types) differ. + chosen = items[:1] + rng.sample(items[1:], min(per_kind - 1, len(items) - 1)) + picked.extend(chosen[:per_kind]) + return picked + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seeds', type=int, default=3) + parser.add_argument('--per-structure', type=int, default=2) + parser.add_argument('--sites', type=int, default=6, help='terrain sites per overworld seed') + parser.add_argument('--radius', type=int, default=1, help='chunk radius around each site') + parser.add_argument('--scan-radius', type=int, default=180) + parser.add_argument('--limit', type=int, default=6, help='block differences shown per chunk') + parser.add_argument('--summary', action='store_true', help='one line per differing site') + parser.add_argument('--rect', action='append', help='compare only this x0,z0,x1,z1 chunk rectangle (repeatable)') + parser.add_argument('--filter', help='regex over structure names') + parser.add_argument('--dimension', action='append') + parser.add_argument('--phase', choices=['terrain', 'structures', 'full'], default='full', help='stop before features, or run structure pieces only') + parser.add_argument('--terrain-only', action='store_true', help='skip the structure sites') + parser.add_argument('--structures-only', action='store_true') + args = parser.parse_args() + os.environ['HORIZON_PHASE'] = args.phase + dimensions = args.dimension or ['overworld', 'the_nether', 'the_end'] + oracle = Oracle() + binary = rust_binary() + names = state_names() + build = build_dir() + totals = Counter() + biome_seen = set() + structure_seen = Counter() + started = time.time() + for seed in SEEDS[:args.seeds]: + rng = random.Random(seed) + for dimension in dimensions: + rects, labels = [], [] + if args.rect: + rects, labels = list(args.rect), [f'rect {r}' for r in args.rect] + r = args.radius + if not args.structures_only and not args.rect: + spread = {'overworld': 5000, 'the_nether': 1500, 'the_end': 1800}[dimension] + sites = [(0, 0)] + [(rng.randint(-spread, spread) // 16, rng.randint(-spread, spread) // 16) for _ in range(args.sites if dimension == 'overworld' else 2)] + for cx, cz in sites: + rects.append(f'{cx - r},{cz - r},{cx + r},{cz + r}') + labels.append(f'terrain {cx},{cz}') + if not args.terrain_only and not args.rect: + starts = scan(oracle, binary, seed, dimension, args.scan_radius if dimension == 'overworld' else 80) + for kind, cx, cz, box in pick_structures(starts, args.per_structure, rng): + if args.filter and not re.search(args.filter, kind): + continue + rects.append(f'{cx - r},{cz - r},{cx + r},{cz + r}') + labels.append(f'{kind} {cx},{cz}') + structure_seen[kind] += 1 + if not rects: + continue + tag = f'{dimension}-{seed}-{args.phase}' + ('-iso' if os.environ.get('HORIZON_ISOLATED') else '') + ('-rect' if args.rect else '') + vanilla_path, rust_path = build / f'vanilla-{tag}.txt', build / f'rust-{tag}.txt' + t0 = time.time() + if not (os.environ.get('REUSE_VANILLA') and vanilla_path.exists()): + oracle.run(vanilla_path, ['dump', seed, dimension, *rects]) + t1 = time.time() + stderr = run_rust(binary, rust_path, seed, dimension, rects) + t2 = time.time() + vanilla, rust = parse(vanilla_path), parse(rust_path) + for line in stderr.splitlines()[:5]: + print(' horizon:', line) + counts = [0, 0, 0, 0] + for rect, label in zip(rects, labels): + x0, z0, x1, z1 = map(int, rect.split(',')) + part = {k: v for k, v in vanilla.items() if x0 <= k[0] <= x1 and z0 <= k[1] <= z1} + one = compare(part, rust, names, f'{tag} {label}', limit=args.limit, quiet=args.summary) + if one[0]: + print(f'{tag} {label}: {one[0]} chunks differ ({one[1]} blocks, {one[2]} biome cells, {one[3]} block entities)') + counts = [a + b for a, b in zip(counts, one)] + totals.update(dict(zip(['chunks', 'blocks', 'biomes', 'entities'], counts))) + totals['compared'] += len(vanilla) + for chunk in vanilla.values(): + for row in chunk['q'].values(): + biome_seen.update(row) + print(f'{tag}: {len(rects)} sites, {len(vanilla)} chunks, differing chunks {counts[0]} (blocks {counts[1]}, biome cells {counts[2]}, block entities {counts[3]}); vanilla {t1 - t0:.0f}s, horizon {t2 - t1:.0f}s', flush=True) + print(f'Compared {totals["compared"]} chunks across {len(biome_seen)} biomes and {sum(structure_seen.values())} structure sites in {time.time() - started:.0f}s') + print('structure sites:', dict(sorted(structure_seen.items()))) + print(f'Differences: {totals["chunks"]} chunks, {totals["blocks"]} blocks, {totals["biomes"]} biome cells, {totals["entities"]} block entities') + if totals['chunks']: + sys.exit(1) + + +if __name__ == '__main__': + main() 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 03/42] 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 04/42] 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 05/42] 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 e0541ece83edfde9b8860f36e5321bd307f4180d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:44:46 +0200 Subject: [PATCH 06/42] Verify entity model animation against vanilla and fix what differed A new Java oracle bakes every vanilla model layer, builds the model's own render state and runs the real setupAnim; tools/test_entity_model_parity.py replays the same states through Horizon's animation code and compares every part pose, visibility and the baked polygon sums (about 3700 cases over 125 layers). Fixes the harness found: model sine and cosine now use vanilla's quantised table, the creeper's swapped leg bindings, humanoid arm poses in vanilla order (held items no longer tilt mob arms, bows pose both arms last, crossbow charge, riding, crouching), swing weapon down, piglin ears and dancing, illager hats, arms and bow pose, zombified piglin ears, baby donkey head and legs, hoglin baby head, ravager neck, vex charging arms, feline sitting and lying poses including babies, camel and zombie/skeleton horse baby models, and new ports of the goat, polar bear, panda, llama, turtle, strider, snow golem, silverfish, endermite, parrot, bee, bat, armadillo, axolotl, frog, rabbit and fox models. Hidden parts are now an explicit flag instead of a zero scale, and skipDraw is supported. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/entity_anim_fixture.rs | 433 +++++++ crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/allay.rs | 18 +- crates/horizon-client/src/mobs/anim.rs | 378 +++--- crates/horizon-client/src/mobs/aquatic.rs | 31 +- crates/horizon-client/src/mobs/body_anim.rs | 1044 +++++++++++++++++ crates/horizon-client/src/mobs/camel.rs | 3 +- crates/horizon-client/src/mobs/data.rs | 8 + crates/horizon-client/src/mobs/equine.rs | 35 +- crates/horizon-client/src/mobs/guardian.rs | 21 +- crates/horizon-client/src/mobs/illager.rs | 96 +- crates/horizon-client/src/mobs/nether.rs | 23 +- crates/horizon-client/src/mobs/phantom.rs | 19 +- crates/horizon-client/src/mobs/piglin.rs | 125 +- crates/horizon-client/src/mobs/ravager.rs | 26 +- crates/horizon-client/src/mobs/render.rs | 7 +- crates/horizon-client/src/mobs/shulker.rs | 9 +- crates/horizon-client/src/mobs/species.rs | 3 + crates/horizon-client/src/mobs/tame.rs | 110 +- crates/horizon-client/src/mobs/vex.rs | 32 +- crates/horizon-client/src/mobs/villager.rs | 7 +- crates/horizon-client/src/mobs/witch.rs | 16 +- crates/horizon-client/src/mobs/wither.rs | 11 +- crates/horizon-core/src/geometry/trig.rs | 14 + .../parity/VanillaEntityAnimOracle.java | 196 ++++ tools/test_entity_model_parity.py | 296 +++++ 26 files changed, 2608 insertions(+), 354 deletions(-) create mode 100644 crates/horizon-client/examples/entity_anim_fixture.rs create mode 100644 crates/horizon-client/src/mobs/body_anim.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java create mode 100644 tools/test_entity_model_parity.py diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs new file mode 100644 index 000000000..df13cbb61 --- /dev/null +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -0,0 +1,433 @@ +//! Replays the render states of the vanilla entity-animation oracle through +//! Horizon's `mobs::anim::setup` and writes every part's pose. +//! +//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ +//! RESOURCES VANILLA.jsonl OUT.jsonl +use horizon_client::mobs::{ + Mob, MobData, MobTypes, Part, Species, allay, + anim::{self, Poses, State}, + aquatic, body_anim as b_anim, equine, guardian, + keyframes::AnimationState, + shulker, species, tame, +}; +use horizon_core::geometry::Vec3; +use serde_json::{Value, json}; +use std::{collections::BTreeMap, fs, path::PathBuf, sync::Arc}; + +fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap) { + let p = poses.pose(part); + let mut polys = 0; + let mut sum = 0.0f64; + for polygon in &part.polygons { + polys += 1; + for v in polygon.vertices { + sum += f64::from(v[0]) + + 2.0 * f64::from(v[1]) + + 3.0 * f64::from(v[2]) + + 5.0 * f64::from(v[3]) + + 7.0 * f64::from(v[4]); + } + } + let visible = !poses.is_hidden(part) && !poses.skips(part); + let mut row: Vec = p.iter().map(|&x| json!(x)).collect(); + row.push(json!(u8::from(visible))); + row.push(json!(polys)); + row.push(json!(sum)); + out.insert(path.to_owned(), Value::Array(row)); + for c in &part.children { + let child = if path.is_empty() { + c.name.clone() + } else { + format!("{path}/{}", c.name) + }; + walk(c, &child, poses, out); + } +} + +/// The entity-side values behind the render-state fields the case sets, for +/// the species whose Horizon animation reads them from the `Mob`. +fn entity_state(mob: &mut Mob, species: Species, case: &Value) { + let flag = |k: &str| case[k].as_bool().unwrap_or(false); + let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + match species { + Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32, + Species::Guardian | Species::ElderGuardian => { + mob.anim.v[guardian::TAIL] = num("tailAnimation"); + mob.anim.vo[guardian::TAIL] = num("tailAnimation"); + mob.anim.v[guardian::SPIKES] = num("spikesAnimation"); + mob.anim.vo[guardian::SPIKES] = num("spikesAnimation"); + } + Species::Shulker => { + mob.anim.v[shulker::PEEK] = num("peekAmount"); + mob.anim.vo[shulker::PEEK] = num("peekAmount"); + } + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + | Species::Giant + | Species::Skeleton + | Species::Stray + | Species::Bogged + | Species::WitherSkeleton + | Species::Parched => { + mob.ai.aggressive = flag("isAggressive"); + mob.extra.crouching = flag("isCrouching"); + mob.extra.passenger = flag("isPassenger"); + if flag("isHoldingBow") { + mob.extra.main_hand = Some("minecraft:bow".into()); + } + } + Species::IronGolem => { + mob.extra.anim_ticks = num("attackTicksRemaining") as i32; + mob.extra.counter = num("offerFlowerTick") as i32; + } + Species::Hoglin | Species::Zoglin => { + mob.extra.anim_ticks = num("attackAnimationRemainingTicks") as i32; + } + Species::Ravager => { + mob.extra.counter2 = num("stunnedTicksRemaining") as i32; + mob.extra.counter = num("attackTicksRemaining") as i32; + let roar = num("roarAnimation"); + if roar > 0.0 { + mob.extra.anim_ticks = (20.0 - roar * 20.0) as i32; + } + } + Species::Vex => mob.extra.flag = flag("isCharging"), + Species::Squid | Species::GlowSquid => { + mob.anim.v[aquatic::TENTACLE_ANGLE] = num("tentacleAngle"); + mob.anim.vo[aquatic::TENTACLE_ANGLE] = num("tentacleAngle"); + } + Species::Dolphin => { + if flag("isMoving") { + mob.velocity.x = 0.1; + } + } + Species::Cod | Species::Salmon | Species::TropicalFish | Species::Tadpole => { + mob.fluids.in_water = flag("isInWater"); + } + Species::Allay => { + mob.extra.flag = flag("isDancing"); + mob.extra.ints[4] = if flag("isSpinning") { 10 } else { 20 }; + mob.anim.v[allay::SPIN] = num("spinningProgress") * 15.0; + mob.anim.vo[allay::SPIN] = num("spinningProgress") * 15.0; + mob.anim.v[allay::HOLD] = num("holdingAnimationProgress") * 5.0; + mob.anim.vo[allay::HOLD] = num("holdingAnimationProgress") * 5.0; + } + Species::Horse + | Species::Donkey + | Species::Mule + | Species::ZombieHorse + | Species::SkeletonHorse => { + for (slot, key) in [ + (equine::EAT, "eatAnimation"), + (equine::STAND, "standAnimation"), + (equine::MOUTH, "feedingAnimation"), + ] { + mob.anim.v[slot] = num(key); + mob.anim.vo[slot] = num(key); + } + mob.fluids.in_water = flag("isInWater"); + mob.extra.chested = flag("hasChest"); + } + Species::Camel => { + for (i, k) in [ + "sitAnimationState", + "sitPoseAnimationState", + "sitUpAnimationState", + "idleAnimationState", + "dashAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + mob.extra.anim_ticks = num("jumpCooldown") as i32; + } + Species::Chicken => { + mob.anim.flap = num("flap"); + mob.anim.flap_o = num("flap"); + mob.anim.flap_speed = num("flapSpeed"); + mob.anim.flap_speed_o = num("flapSpeed"); + } + Species::Wolf => { + mob.extra.sitting = flag("isSitting"); + mob.extra.anger = if flag("isAngry") { 100 } else { 0 }; + mob.anim.v[tame::SHAKE] = num("shakeAnim"); + mob.anim.vo[tame::SHAKE] = num("shakeAnim"); + mob.anim.v[tame::INTEREST] = num("interest"); + mob.anim.vo[tame::INTEREST] = num("interest"); + } + Species::Creaking => { + mob.extra.flag2 = !flag("canMove"); + for (i, k) in [ + "attackAnimationState", + "invulnerabilityAnimationState", + "deathAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + } + Species::Witch if flag("isHoldingItem") => { + mob.extra.main_hand = Some("minecraft:potion".into()); + } + _ => {} + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let root = PathBuf::from(&args[0]); + let types = MobTypes::load(&root)?; + let animations = MobData::load_animations(&root); + let mut out = String::new(); + for line in fs::read_to_string(&args[1])?.lines() { + let v: Value = serde_json::from_str(line)?; + let layer = v["layer"] + .as_str() + .unwrap_or_default() + .trim_start_matches("minecraft:"); + let baby = layer.contains("_baby#"); + let adult = layer.replace("_baby#", "#"); + // Variant layers (sizes, hatless villagers, climate cows...) animate + // like their base model. + let mut base = adult.clone(); + for cut in ["_no_hat", "_small", "_medium", "_large"] { + base = base.replace(cut, ""); + } + let base = base.trim_start_matches("cold_").trim_start_matches("warm_"); + let Some(def) = species::ALL.iter().find(|d| { + d.model == layer + || (baby && d.model == adult) + || d.model == base + || d.model.trim_end_matches("#main") == base.trim_end_matches("#main") + }) else { + out.push_str(&format!("{}\n", json!({"skip": "no species"}))); + continue; + }; + let Some(kind) = types.types.get(&format!("minecraft:{}", def.name)) else { + out.push_str(&format!("{}\n", json!({"skip": "no type"}))); + continue; + }; + let kind = Arc::new(kind.clone()); + let model = kind + .layer(layer) + .cloned() + .unwrap_or_else(|| kind.model.clone()); + let mut mob = Mob::new(7, kind, Vec3::new(0.0, 64.0, 0.0), 0.0); + mob.extra.main_hand = None; + let case = &v["case"]; + let f = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + if baby { + mob.extra.age = -24000; + } + mob.age = f("ageInTicks") as u32; + let state = State { + pos: f("walkAnimationPos"), + speed: f("walkAnimationSpeed"), + age: f("ageInTicks"), + y_rot: f("yRot"), + x_rot: f("xRot"), + swing: f("swingAnimation"), + baby, + partial: 0.0, + }; + let mut poses = Poses::new(&model); + entity_state(&mut mob, def.species, case); + let flag = |k: &str| case[k].as_bool().unwrap_or(false); + let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + let started = |k: &str| AnimationState { + started: case[k].as_f64().map(|v| v as f32), + }; + let (p, s) = (&mut poses, &state); + match def.species { + Species::Goat => b_anim::goat( + p, + s, + &b_anim::Goat { + left_horn: flag("hasLeftHorn"), + right_horn: flag("hasRightHorn"), + ramming_x_head_rot: num("rammingXHeadRot"), + }, + ), + Species::PolarBear => b_anim::polar_bear(p, s, num("standScale")), + Species::Panda => b_anim::panda( + p, + s, + &b_anim::Panda { + unhappy: flag("isUnhappy"), + sneezing: flag("isSneezing"), + sneeze_time: num("sneezeTime") as i32, + eating: flag("isEating"), + scared: flag("isScared"), + sit_amount: num("sitAmount"), + lie_on_back_amount: num("lieOnBackAmount"), + roll_amount: num("rollAmount"), + }, + ), + Species::Llama | Species::TraderLlama => b_anim::llama(p, s, flag("hasChest")), + Species::Turtle => b_anim::turtle( + p, + s, + &b_anim::Turtle { + on_land: flag("isOnLand"), + laying_egg: flag("isLayingEgg"), + has_egg: flag("hasEgg"), + }, + ), + Species::Strider => b_anim::strider(p, s, flag("isRidden")), + Species::SnowGolem => b_anim::snow_golem(p, s), + Species::Silverfish => b_anim::silverfish(p, s), + Species::Endermite => b_anim::endermite(p, s), + Species::Parrot => b_anim::parrot( + p, + s, + match case["pose"].as_str() { + Some("FLYING") => b_anim::ParrotPose::Flying, + Some("ON_SHOULDER") => b_anim::ParrotPose::OnShoulder, + Some("SITTING") => b_anim::ParrotPose::Sitting, + Some("PARTY") => b_anim::ParrotPose::Party, + _ => b_anim::ParrotPose::Standing, + }, + num("flapAngle"), + ), + Species::Bee => b_anim::bee( + p, + s, + &b_anim::Bee { + has_stinger: flag("hasStinger"), + on_ground: flag("isOnGround"), + angry: flag("isAngry"), + roll_amount: num("rollAmount"), + }, + ), + Species::Bat => b_anim::bat( + p, + s, + flag("isResting"), + &started("flyAnimationState"), + &started("restAnimationState"), + &animations, + ), + Species::Armadillo => b_anim::armadillo( + p, + s, + &b_anim::Armadillo { + hiding_in_shell: flag("isHidingInShell"), + roll_out: started("rollOutAnimationState"), + roll_up: started("rollUpAnimationState"), + peek: started("peekAnimationState"), + }, + &animations, + ), + Species::Axolotl => b_anim::axolotl( + p, + s, + &b_anim::Axolotl { + playing_dead: num("playingDeadFactor"), + in_water: num("inWaterFactor"), + on_ground: num("onGroundFactor"), + moving: num("movingFactor"), + swim: started("swimAnimation"), + walk: started("walkAnimationState"), + idle_on_ground: started("idleOnGroundAnimationState"), + idle_underwater_on_ground: started("idleUnderWaterOnGroundAnimationState"), + idle_underwater: started("idleUnderWaterAnimationState"), + play_dead: started("playDeadAnimationState"), + }, + &animations, + ), + Species::Frog => b_anim::frog( + p, + s, + &b_anim::Frog { + swimming: flag("isSwimming"), + jump: started("jumpAnimationState"), + croak: started("croakAnimationState"), + tongue: started("tongueAnimationState"), + swim_idle: started("swimIdleAnimationState"), + }, + &animations, + ), + Species::Rabbit => b_anim::rabbit( + p, + s, + &started("hopAnimationState"), + &started("idleHeadTiltAnimationState"), + &animations, + ), + Species::Fox => b_anim::fox( + p, + s, + &b_anim::Fox { + crouching: flag("isCrouching"), + sleeping: flag("isSleeping"), + sitting: flag("isSitting"), + pouncing: flag("isPouncing"), + faceplanted: flag("isFaceplanted"), + head_roll_angle: num("headRollAngle"), + crouch_amount: num("crouchAmount"), + leg_motion_pos: 0.67, + }, + &animations, + ), + Species::Cat | Species::Ocelot => horizon_client::mobs::tame::feline( + p, + s, + &horizon_client::mobs::tame::Feline { + crouching: flag("isCrouching"), + sprinting: flag("isSprinting"), + sitting: flag("isSitting"), + lie_down: num("lieDownAmount"), + lie_down_tail: num("lieDownAmountTail"), + relax_one: num("relaxStateOneAmount"), + }, + ), + Species::Piglin | Species::PiglinBrute => { + use horizon_client::mobs::piglin::{PiglinPose, piglin_pose}; + let pose = match case["armPose"].as_str() { + Some("DANCING") => PiglinPose::Dancing, + Some("ATTACKING_WITH_MELEE_WEAPON") => PiglinPose::MeleeWeapon, + Some("CROSSBOW_HOLD") => PiglinPose::CrossbowHold, + Some("CROSSBOW_CHARGE") => PiglinPose::CrossbowCharge, + Some("ADMIRING_ITEM") => PiglinPose::AdmiringItem, + _ => PiglinPose::Default, + }; + piglin_pose( + p, + s, + pose, + num("maxCrossbowChageDuration"), + num("ticksUsingItem"), + ); + } + Species::Evoker | Species::Pillager | Species::Vindicator => { + use horizon_client::mobs::illager::{ArmPose, anim_pose}; + let pose = match case["armPose"].as_str() { + Some("CROSSED") => ArmPose::Crossed, + Some("ATTACKING") => ArmPose::Attacking, + Some("SPELLCASTING") => ArmPose::Spellcasting, + Some("BOW_AND_ARROW") => ArmPose::BowAndArrow, + Some("CROSSBOW_HOLD") => ArmPose::CrossbowHold, + Some("CROSSBOW_CHARGE") => ArmPose::CrossbowCharge, + Some("CELEBRATING") => ArmPose::Celebrating, + _ => ArmPose::Neutral, + }; + mob.extra.passenger = flag("isRiding"); + mob.extra.using_item = num("ticksUsingItem") as i32; + anim_pose(&mob, s, p, pose); + } + _ => anim::setup(&mob, s, p, &animations), + } + let mut parts = BTreeMap::new(); + walk(&model, "", &poses, &mut parts); + out.push_str(&format!("{}\n", json!({"parts": parts}))); + } + fs::write(&args[2], out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 9261846a1..093042a2c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -9,6 +9,7 @@ pub mod ai; pub mod allay; pub mod anim; pub mod aquatic; +pub mod body_anim; pub mod camel; pub mod control; pub mod creaking; diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index d371c1be7..2b674fb87 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -8,6 +8,7 @@ use super::{ goals::{Cx, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone}, nav::NavKind, }; +use horizon_core::geometry::trig::Mth; // Allay state: `main_hand` the held item, `ints[1]` how many it carries, // `tame` a liked player, `point` the wanted item (set by the game), @@ -15,8 +16,8 @@ use super::{ // pickup cooldown, `flag` dancing with `ints[4]` the dance clock, // `egg_time` the duplication cooldown. AnimState slots: holding (0), // spinning (1). -const HOLD: usize = 0; -const SPIN: usize = 1; +pub const HOLD: usize = 0; +pub const SPIN: usize = 1; pub fn register(m: &mut Mob) { m.ai.mov.kind = MoveKind::Flying { @@ -151,22 +152,22 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { use std::f32::consts::PI; let (speed, pos) = (s.speed, s.pos); let flap_speed = (s.age * 20.0).to_radians() + pos; - let flap = flap_speed.cos() * PI * 0.15 + speed; + let flap = flap_speed.mcos() * PI * 0.15 + speed; let idle_bob = (s.age * 9.0).to_radians(); let flying = (speed / 0.3).min(1.0); let idle = 1.0 - flying; let hold = m.anim.lerp(HOLD, s.partial) / 5.0; if m.extra.flag { let dance = (s.age * 8.0).to_radians() + speed; - let freq = dance.cos() * 16f32.to_radians(); + let freq = dance.mcos() * 16f32.to_radians(); let spin = m.anim.lerp(SPIN, s.partial) / 15.0; let spinning = (m.extra.ints[4] as f32 % 55.0) < 15.0; if spinning { p.yrot("root", PI * 4.0 * spin); } p.zrot("root", freq * (1.0 - spin)); - p.yrot("head", dance.cos() * 30f32.to_radians() * (1.0 - spin)); - p.zrot("head", dance.cos() * 14f32.to_radians() * (1.0 - spin)); + p.yrot("head", dance.mcos() * 30f32.to_radians() * (1.0 - spin)); + p.zrot("head", dance.mcos() * 14f32.to_radians() * (1.0 - spin)); } else { p.xrot("head", s.x_rot.to_radians()); p.yrot("head", s.y_rot.to_radians()); @@ -177,11 +178,12 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("left_wing", PI / 4.0 - flap); p.xrot("body", flying * PI / 4.0); let arm_x = hold * (-PI / 3.0 + (-1.134_464 + PI / 3.0) * flying); - p.get("root")[1] += idle_bob.cos() * 0.25 * idle; + // `(float) Math.cos`: the exact function, not `Mth.cos`. + p.get("root")[1] += (f64::from(idle_bob).cos() as f32) * 0.25 * idle; p.xrot("right_arm", arm_x); p.xrot("left_arm", arm_x); let arm_bob = idle * (1.0 - hold); - let amount = 0.436_332_32 - (idle_bob + PI * 1.5).cos() * PI * 0.075 * arm_bob; + let amount = 0.436_332_32 - (idle_bob + PI * 1.5).mcos() * PI * 0.075 * arm_bob; p.zrot("left_arm", -amount); p.zrot("right_arm", amount); p.yrot("right_arm", 0.279_252_68 * hold); diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index ae44a2630..ca72c04a7 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -2,6 +2,7 @@ //! (quadrupeds, humanoids, creepers, spiders, chickens...) applied to a map of //! part poses before the model is drawn. use super::{Mob, Part, keyframes::AnimationState, living::wrap}; +use horizon_core::geometry::trig::Mth; use std::collections::HashMap; use std::f32::consts::PI; @@ -98,6 +99,10 @@ impl AnimState { pub struct Poses { map: HashMap, dummy: [f32; 9], + /// Parts with `skipDraw` set: their own cubes are not drawn, children are. + skipped: std::collections::HashSet, + /// Parts with `visible` cleared: neither they nor their children draw. + hidden: std::collections::HashSet, } impl Poses { pub fn new(model: &Part) -> Self { @@ -112,6 +117,8 @@ impl Poses { Self { map, dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), } } pub fn get(&mut self, name: &str) -> &mut [f32; 9] { @@ -123,6 +130,12 @@ impl Poses { pub fn pose(&self, part: &Part) -> [f32; 9] { self.map.get(&part.name).copied().unwrap_or(part.pose) } + pub fn skip_draw(&mut self, name: &str) { + self.skipped.insert(name.to_owned()); + } + pub fn skips(&self, part: &Part) -> bool { + self.skipped.contains(&part.name) + } pub fn has(&self, name: &str) -> bool { self.map.contains_key(name) } @@ -135,14 +148,17 @@ impl Poses { pub fn zrot(&mut self, n: &str, v: f32) { self.get(n)[5] = v; } + /// `ModelPart.visible = v`; a hidden part and its children do not draw. pub fn visible(&mut self, n: &str, v: bool) { - if !v { - let p = self.get(n); - p[6] = 0.0; - p[7] = 0.0; - p[8] = 0.0; + if v { + self.hidden.remove(n); + } else if self.map.contains_key(n) { + self.hidden.insert(n.to_owned()); } } + pub fn is_hidden(&self, part: &Part) -> bool { + self.hidden.contains(&part.name) + } } /// The LivingEntityRenderState values setupAnim reads. #[derive(Clone, Copy, Debug)] @@ -191,21 +207,21 @@ fn head(p: &mut Poses, s: &State) { p.yrot("head", s.y_rot.to_radians()); } /// QuadrupedModel.setupAnim -fn quadruped(p: &mut Poses, s: &State) { +pub(super) fn quadruped(p: &mut Poses, s: &State) { head(p, s); let (pos, sp) = (s.pos, s.speed); - p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp); - p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); - p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * sp); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * sp); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * sp); } /// AnimationUtils.bobModelPart fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) { let q = p.get(n); - q[5] += scale * ((age * 0.09).cos() * 0.05 + 0.05); - q[3] += scale * ((age * 0.067).sin() * 0.05); + q[5] += scale * ((age * 0.09).mcos() * 0.05 + 0.05); + q[3] += scale * ((age * 0.067).msin() * 0.05); } -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum ArmPose { Empty, Item, @@ -213,118 +229,196 @@ pub enum ArmPose { CrossbowHold, CrossbowCharge, } -/// HumanoidModel.setupAnim holding an item or not (piglins). -pub fn humanoid_item(p: &mut Poses, s: &State, holding: bool) { - let right = if holding { - ArmPose::Item - } else { - ArmPose::Empty - }; - humanoid(p, s, right, ArmPose::Empty, None, holding); +/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. +pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { + humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { - humanoid(p, s, ArmPose::Empty, ArmPose::Empty, None, false); + humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// HumanoidModel.setupAnim up to (and including) the attack animation hook. -fn humanoid( - p: &mut Poses, - s: &State, - right: ArmPose, - left: ArmPose, - zombie: Option, - holding: bool, -) { +/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { + let attack2 = (swing * PI).msin(); + let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + p.zrot("right_arm", 0.0); + p.zrot("left_arm", 0.0); + p.yrot("right_arm", PI / 20.0); + p.yrot("left_arm", -PI / 20.0); + p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); + p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; + p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + bob(p, "right_arm", age, 1.0); + bob(p, "left_arm", age, -1.0); +} +/// What `HumanoidModel.setupAnim` reads besides the walk and head inputs. +#[derive(Clone, Copy, Debug)] +pub struct Hum { + pub right: ArmPose, + pub left: ArmPose, + pub crouching: bool, + pub passenger: bool, + /// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`. + pub zombie: Option, + /// The main hand holds something (`getMainHandItemStack() != EMPTY`). + pub holding: bool, + /// `maxCrossbowChargeDuration`, `ticksUsingItem`. + pub charge: (f32, f32), + /// `PiglinModel.setupAttackAnimation`: swing a held weapon down. + pub weapon_swing: bool, +} +impl Hum { + pub fn new(right: ArmPose, left: ArmPose) -> Self { + Self { + right, + left, + crouching: false, + passenger: false, + zombie: None, + holding: false, + charge: (0.0, 0.0), + weapon_swing: false, + } + } +} +impl ArmPose { + fn two_handed(self) -> bool { + matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge) + } + fn affects_offhand(self) -> bool { + self.two_handed() + } +} +/// `AnimationUtils.animateCrossbowHold`. +fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { + let (hold, shoot) = if in_right { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if in_right { -0.3 } else { 0.3 } + hy); + p.yrot(shoot, if in_right { 0.6 } else { -0.6 } + hy); + p.xrot(hold, -PI / 2.0 + hx + 0.1); + p.xrot(shoot, -1.5 + hx); +} +/// `AnimationUtils.animateCrossbowCharge`. +fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { + let (hold, pull) = if in_right { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if in_right { -0.8 } else { 0.8 }); + p.xrot(hold, -0.970_796_35); + p.xrot(pull, -0.970_796_35); + let use_ticks = ticks.clamp(0.0, max); + let alpha = use_ticks / max; + let lerp = |a: f32, p0: f32, p1: f32| p0 + a * (p1 - p0); + p.yrot( + pull, + lerp(alpha, 0.4, 0.85) * if in_right { 1.0 } else { -1.0 }, + ); + let x = lerp(alpha, p.get(pull)[3], -PI / 2.0); + p.xrot(pull, x); +} +/// `HumanoidModel.poseRightArm` / `poseLeftArm`. +fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { + let arm = if right { "right_arm" } else { "left_arm" }; + let (hx, hy) = (p.get("head")[3], p.get("head")[4]); + match pose { + ArmPose::Empty => p.yrot(arm, 0.0), + ArmPose::Item => { + let x = p.get(arm)[3]; + p.xrot(arm, x * 0.5 - PI / 10.0); + p.yrot(arm, 0.0); + } + ArmPose::Bow => { + p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 }); + p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 }); + p.xrot("right_arm", -PI / 2.0 + hx); + p.xrot("left_arm", -PI / 2.0 + hx); + } + ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right), + ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right), + } +} +/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`). +pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { head(p, s); let (pos, sp) = (s.pos, s.speed); - p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5); - p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5); - p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp); - p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); + p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5); + p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5); + p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp); + p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp); p.yrot("right_leg", 0.005); p.yrot("left_leg", -0.005); p.zrot("right_leg", 0.005); p.zrot("left_leg", -0.005); - let (hx, hy) = (p.get("head")[3], p.get("head")[4]); - for (arm, pose) in [("right_arm", right), ("left_arm", left)] { - match pose { - ArmPose::Empty => p.yrot(arm, 0.0), - ArmPose::Item => { - let x = p.get(arm)[3]; - p.xrot(arm, x * 0.5 - PI / 10.0); - p.yrot(arm, 0.0); - } - ArmPose::Bow => { - let right_main = arm == "right_arm"; - p.yrot("right_arm", -0.1 + hy - if right_main { 0.0 } else { 0.4 }); - p.yrot("left_arm", 0.1 + hy + if right_main { 0.4 } else { 0.0 }); - p.xrot("right_arm", -PI / 2.0 + hx); - p.xrot("left_arm", -PI / 2.0 + hx); - } - ArmPose::CrossbowHold => { - let r = arm == "right_arm"; - let (hold, shoot) = if r { - ("right_arm", "left_arm") - } else { - ("left_arm", "right_arm") - }; - p.yrot(hold, if r { -0.3 } else { 0.3 } + hy); - p.yrot(shoot, if r { 0.6 } else { -0.6 } + hy); - p.xrot(hold, -PI / 2.0 + hx + 0.1); - p.xrot(shoot, -1.5 + hx); - } - ArmPose::CrossbowCharge => { - let r = arm == "right_arm"; - let (hold, pull) = if r { - ("right_arm", "left_arm") - } else { - ("left_arm", "right_arm") - }; - p.yrot(hold, if r { -0.8 } else { 0.8 }); - p.xrot(hold, -0.970_796_35); - p.xrot(pull, -0.970_796_35); - p.yrot(pull, 0.6 * if r { 1.0 } else { -1.0 }); - p.xrot(pull, -PI / 2.0); - } + if h.passenger { + p.get("right_arm")[3] += -PI / 5.0; + p.get("left_arm")[3] += -PI / 5.0; + p.xrot("right_leg", -1.413_716_7); + p.yrot("right_leg", PI / 10.0); + p.zrot("right_leg", 0.078_539_82); + p.xrot("left_leg", -1.413_716_7); + p.yrot("left_leg", -PI / 10.0); + p.zrot("left_leg", -0.078_539_82); + } + // The main arm is the right one: the off-hand pose goes first unless it + // needs both hands. + if h.left.two_handed() { + pose_arm(p, h.right, true, h); + if !h.right.affects_offhand() { + pose_arm(p, h.left, false, h); + } + } else { + pose_arm(p, h.left, false, h); + if !h.left.affects_offhand() { + pose_arm(p, h.right, true, h); } } // setupAttackAnimation (WHACK swing with the right arm). + let hx = p.get("head")[3]; let swing = s.swing; - if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2; + if swing > 0.0 && h.weapon_swing { + swing_weapon_down(p, swing, s.age); + } else if swing > 0.0 { + let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; p.yrot("body", body_y); let age_scale = if s.baby { 0.5 } else { 1.0 }; { let r = p.get("right_arm"); - r[2] = body_y.sin() * 5.0 * age_scale; - r[0] = -body_y.cos() * 5.0 * age_scale; + r[2] = body_y.msin() * 5.0 * age_scale; + r[0] = -body_y.mcos() * 5.0 * age_scale; } { let l = p.get("left_arm"); - l[2] = -body_y.sin() * 5.0 * age_scale; - l[0] = body_y.cos() * 5.0 * age_scale; + l[2] = -body_y.msin() * 5.0 * age_scale; + l[0] = body_y.mcos() * 5.0 * age_scale; } p.get("right_arm")[4] += body_y; p.get("left_arm")[4] += body_y; p.get("left_arm")[3] += body_y; + // Ease.outQuart let eased = 1.0 - (1.0 - swing).powi(4); - let aa = (eased * PI).sin(); - let bb = (swing * PI).sin() * -(hx - 0.7) * 0.75; + let aa = (eased * PI).msin(); + let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75; let r = p.get("right_arm"); r[3] -= aa * 1.2 + bb; r[4] += body_y * 2.0; - r[5] += (swing * PI).sin() * -0.4; + r[5] += (swing * PI).msin() * -0.4; } - if let Some(aggressive) = zombie { + if let Some(aggressive) = h.zombie { // AnimationUtils.animateZombieArms - let raise = !s.baby || !holding; + let raise = !s.baby || !h.holding; let drop = if raise { -PI / if aggressive { 1.5 } else { 2.25 } } else { 0.0 }; - let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).sin(); - let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).msin(); + let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); let x = drop + ym * 1.2 - xm * 0.4; let y = 0.1 - ym * 0.6; p.xrot("right_arm", x); @@ -334,6 +428,17 @@ fn humanoid( p.yrot("left_arm", if raise { y } else { -y }); p.zrot("left_arm", 0.0); } + if h.crouching { + p.xrot("body", 0.5); + p.get("right_arm")[3] += 0.4; + p.get("left_arm")[3] += 0.4; + p.get("right_leg")[2] += 4.0; + p.get("left_leg")[2] += 4.0; + p.get("head")[1] += 4.2; + p.get("body")[1] += 3.2; + p.get("left_arm")[1] += 3.2; + p.get("right_arm")[1] += 3.2; + } bob(p, "right_arm", s.age, 1.0); bob(p, "left_arm", s.age, -1.0); } @@ -344,6 +449,9 @@ pub fn setup( p: &mut Poses, w_anims: &HashMap, ) { + if super::body_anim::anim(m, s, p, w_anims) { + return; + } match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), @@ -368,7 +476,7 @@ pub fn setup( }; let angle = if t > 4 && t <= 36 { let f = ((t - 4) as f32 - partial) / 32.0; - PI / 5.0 + 0.219_911_49 * (f * 28.7).sin() + PI / 5.0 + 0.219_911_49 * (f * 28.7).msin() } else if t > 0 { PI / 5.0 } else { @@ -382,9 +490,9 @@ pub fn setup( let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; let flap_speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; - let angle = (flap.sin() + 1.0) * flap_speed; - p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); - p.xrot("left_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed); + let angle = (flap.msin() + 1.0) * flap_speed; + p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed); + p.xrot("left_leg", (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed); p.zrot("right_wing", angle); p.zrot("left_wing", -angle); if !s.baby { @@ -396,57 +504,35 @@ pub fn setup( | Anim::ZombieVillager | Anim::ZombifiedPiglin | Anim::Humanoid { zombie_arms: true } => { - let holding = m.extra.main_hand.is_some(); - let right = if holding { - ArmPose::Item - } else { - ArmPose::Empty - }; - humanoid(p, s, right, ArmPose::Empty, Some(m.ai.aggressive), holding); + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.zombie = Some(m.ai.aggressive); + h.holding = m.extra.main_hand.is_some(); + h.crouching = m.extra.crouching; + h.passenger = m.extra.passenger; + humanoid(p, s, &h); + if m.kind.anim == Anim::ZombifiedPiglin { + super::piglin::ears(p, s); + } } Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => { let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow"); + let player = matches!(m.kind.anim, Anim::Humanoid { .. }); let right = if bow && m.ai.aggressive { ArmPose::Bow - } else if m.extra.main_hand.is_some() { + } else if player && m.extra.main_hand.is_some() { ArmPose::Item } else { ArmPose::Empty }; - humanoid( - p, - s, - right, - ArmPose::Empty, - None, - m.extra.main_hand.is_some(), - ); - if m.extra.passenger { - // HumanoidModel.setupAnim: riding. - p.get("right_arm")[3] -= PI / 5.0; - p.get("left_arm")[3] -= PI / 5.0; - for (leg, side) in [("right_leg", 1.0), ("left_leg", -1.0)] { - p.xrot(leg, -1.413_716_7); - p.yrot(leg, side * PI / 10.0); - p.zrot(leg, side * 0.078_539_82); - } - } - if m.extra.crouching { - p.xrot("body", 0.5); - p.get("right_arm")[3] += 0.4; - p.get("left_arm")[3] += 0.4; - p.get("right_leg")[2] += 4.0; - p.get("left_leg")[2] += 4.0; - p.get("head")[1] += 4.2; - p.get("body")[1] += 3.2; - p.get("left_arm")[1] += 3.2; - p.get("right_arm")[1] += 3.2; - } + let mut h = Hum::new(right, ArmPose::Empty); + h.crouching = m.extra.crouching; + h.passenger = m.extra.passenger; + humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. let sw = s.swing; - let s2 = (sw * PI).sin(); - let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).sin(); + let s2 = (sw * PI).msin(); + let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", -(0.1 - s2 * 0.6)); @@ -474,37 +560,37 @@ pub fn setup( // DonkeyModel: the chests show once fitted. if !m.extra.chested { for part in ["left_chest", "right_chest"] { - if p.has(part) { - let v = p.get(part); - v[6] = 0.0; - v[7] = 0.0; - v[8] = 0.0; - } + p.visible(part, false); } } } Anim::Hoglin => super::piglin::hoglin_anim(m, s, p), Anim::Blaze => super::nether::blaze_anim(s, p), Anim::Ghast => super::nether::ghast_anim(s, p), - Anim::Feline if m.species() == super::Species::Cat => super::tame::cat_anim(m, s, p), + Anim::Feline => super::tame::cat_anim(m, s, p), Anim::Enderman => super::enderman::anim(m, s, p), Anim::Slime | Anim::MagmaCube => super::cube::anim(m, s, p), Anim::Creeper => { head(p, s); - p.xrot("right_hind_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); - p.xrot("left_hind_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed); + // CreeperModel binds its fields to the opposite-side parts, so the + // left formulas drive the right parts and the reverse. + p.xrot("left_hind_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed); p.xrot( - "right_front_leg", - (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed, + "right_hind_leg", + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed, ); - p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); + p.xrot( + "left_front_leg", + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed, + ); + p.xrot("right_front_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed); } Anim::Spider => { head(p, s); let pos = s.pos * 0.6662; let sp = s.speed; - let swing = |o: f32| -((pos * 2.0 + o).cos() * 0.4) * sp; - let step = |o: f32| ((pos + o).sin() * 0.4).abs() * sp; + let swing = |o: f32| -((pos * 2.0 + o).mcos() * 0.4) * sp; + let step = |o: f32| ((pos + o).msin() * 0.4).abs() * sp; let legs = [ ("hind", 0.0f32, 0.0f32), ("middle_hind", PI, PI), diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index d93a138c9..667802b26 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -12,12 +12,13 @@ use super::{ nav::NavKind, }; use crate::blocks::Fluid; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; // Squid animation slots in AnimState.v. const TENTACLE_MOVEMENT: usize = 0; -const TENTACLE_ANGLE: usize = 1; +pub const TENTACLE_ANGLE: usize = 1; const X_BODY_ROT: usize = 2; const Z_BODY_ROT: usize = 3; const TENTACLE_SPEED: usize = 4; @@ -229,7 +230,7 @@ fn squid_ai_step(m: &mut Mob) { if m.fluids.in_water { if v[TENTACLE_MOVEMENT] < PI { let scale = v[TENTACLE_MOVEMENT] / PI; - v[TENTACLE_ANGLE] = (scale * scale * PI).sin() * PI * 0.25; + v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25; if scale > 0.75 { let mv = m.extra.vector; m.velocity = Vec3::new(mv[0], mv[1], mv[2]); @@ -250,7 +251,7 @@ fn squid_ai_step(m: &mut Mob) { v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5; v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1; } else { - v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].sin().abs() * PI * 0.25; + v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25; let yd = m.velocity.y - m.kind.gravity; m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); let v = &mut m.anim.v; @@ -339,9 +340,9 @@ impl Goal for SquidRandomMovement { let angle = m.random.next_float() * PI * 2.0; let y = -0.1 + m.random.next_float() * 0.2; m.extra.vector = [ - f64::from(angle.cos() * 0.2), + f64::from(angle.mcos() * 0.2), f64::from(y), - f64::from(angle.sin() * 0.2), + f64::from(angle.msin() * 0.2), ]; } } @@ -496,23 +497,23 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot(&format!("tentacle{i}"), angle); } } - S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()), + S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).msin()), // TadpoleModel: a stronger tail swing out of water. S::Tadpole => { let a = if m.fluids.in_water { 1.0 } else { 1.5 }; - p.yrot("tail", -a * 0.25 * (0.3 * s.age).sin()) + p.yrot("tail", -a * 0.25 * (0.3 * s.age).msin()) } - S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()), + S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).msin()), S::Salmon => { let (a, k) = if m.fluids.in_water { (1.0, 1.0) } else { (1.3, 1.7) }; - p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin()); + p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).msin()); } S::Pufferfish => { - let fin = 0.2 - 0.4 * (s.age * 0.2).sin(); + let fin = 0.2 - 0.4 * (s.age * 0.2).msin(); if p.has("right_blue_fin") { p.zrot("right_blue_fin", -fin); p.zrot("left_blue_fin", fin); @@ -526,9 +527,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("body", s.y_rot.to_radians()); let moving = m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z > 1.0e-7; if moving { - p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).cos(); - p.xrot("tail", -0.1 * (s.age * 0.3).cos()); - p.xrot("tail_fin", -0.2 * (s.age * 0.3).cos()); + p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).mcos(); + p.xrot("tail", -0.1 * (s.age * 0.3).mcos()); + p.xrot("tail_fin", -0.2 * (s.age * 0.3).mcos()); } } _ => {} @@ -565,7 +566,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { (1.0, 1.0) }; let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians()) - * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians()); + * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).msin()).to_radians()); if !m.fluids.in_water { let off = if m.species() == S::Cod { glam::Vec3::new(0.1, 0.1, -0.1) @@ -577,7 +578,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { Some(t) } S::Pufferfish => Some( - glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0)) + glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).mcos() * 0.08, 0.0)) * glam::Mat4::from_rotation_y((180.0 - body).to_radians()), ), _ => None, diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs new file mode 100644 index 000000000..b6b232b8b --- /dev/null +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -0,0 +1,1044 @@ +//! `EntityModel.setupAnim` ports for the animals and monsters whose models +//! have no species file of their own (goat, polar bear, panda, llama, turtle, +//! strider, snow golem, silverfish, endermite, parrot, bee, bat, armadillo, +//! axolotl, frog, rabbit, fox). Each reads the render-state values vanilla's +//! renderer extracts, as plain structs so the differential harness can set +//! them directly; `from_mob` adapters fill them from what a `Mob` tracks. +use super::{ + Mob, Species, + anim::{Poses, State, quadruped}, + keyframes::{Animation, AnimationState}, +}; +use horizon_core::geometry::trig::Mth; +use std::{collections::HashMap, f64::consts::PI}; + +pub type Animations = HashMap; +const FPI: f32 = PI as f32; +/// `(float) (Math.PI / n)` and friends, evaluated in double like Java. +fn rad(v: f64) -> f32 { + v as f32 +} +fn lerp(a: f32, p: f32, q: f32) -> f32 { + p + a * (q - p) +} +/// `Mth.rotLerpRad`. +fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 { + let mut diff = to - from; + while diff < -FPI { + diff += rad(PI * 2.0); + } + while diff >= FPI { + diff -= rad(PI * 2.0); + } + from + a * diff +} +fn head_look(p: &mut Poses, s: &State) { + p.xrot("head", s.x_rot.to_radians()); + p.yrot("head", s.y_rot.to_radians()); +} +/// `KeyframeAnimation.apply(AnimationState, ageInTicks)`. +fn run(animations: &Animations, name: &str, state: &AnimationState, s: &State, p: &mut Poses) { + if let (Some(ms), Some(a)) = (state.millis(s.age), animations.get(name)) { + a.apply(ms, 1.0, p); + } +} +fn walk(animations: &Animations, name: &str, s: &State, factor: f32, scale: f32, p: &mut Poses) { + if let Some(a) = animations.get(name) { + a.apply_walk(s.pos, s.speed, factor, scale, p); + } +} +fn adds(p: &mut Poses, part: &str, i: usize, v: f32) { + p.get(part)[i] += v; +} + +// ---- goat ----------------------------------------------------------------- +#[derive(Clone, Copy, Debug)] +pub struct Goat { + pub left_horn: bool, + pub right_horn: bool, + pub ramming_x_head_rot: f32, +} +impl Goat { + pub fn from_mob(_m: &Mob) -> Self { + Self { + left_horn: true, + right_horn: true, + ramming_x_head_rot: 0.0, + } + } +} +/// `GoatModel` / `BabyGoatModel.setupAnim`. +pub fn goat(p: &mut Poses, s: &State, g: &Goat) { + quadruped(p, s); + p.visible("left_horn", g.left_horn); + p.visible("right_horn", g.right_horn); + if g.ramming_x_head_rot != 0.0 { + p.xrot("head", g.ramming_x_head_rot); + } + if s.baby && g.ramming_x_head_rot == 0.0 { + p.xrot("head", rad(PI / 8.0)); + } +} + +// ---- polar bear ----------------------------------------------------------- +/// `PolarBearModel.setupAnim`. +pub fn polar_bear(p: &mut Poses, s: &State, stand_scale: f32) { + quadruped(p, s); + let stand = stand_scale * stand_scale; + let age_scale = if s.baby { 0.5 } else { 1.0 }; + adds(p, "body", 3, -(stand * FPI * 0.35)); + adds(p, "body", 1, stand * age_scale * 2.0); + adds(p, "right_front_leg", 1, -(stand * age_scale * 20.0)); + adds(p, "right_front_leg", 2, stand * age_scale * 4.0); + adds(p, "right_front_leg", 3, -(stand * FPI * 0.45)); + let (y, z) = { + let r = p.get("right_front_leg"); + (r[1], r[2]) + }; + let l = p.get("left_front_leg"); + l[1] = y; + l[2] = z; + l[3] -= stand * FPI * 0.45; + adds(p, "head", 1, -(stand * 24.0)); + adds(p, "head", 2, stand * 13.0); + adds(p, "head", 3, stand * FPI * 0.15); +} + +// ---- panda ---------------------------------------------------------------- +#[derive(Clone, Copy, Debug, Default)] +pub struct Panda { + pub unhappy: bool, + pub sneezing: bool, + pub sneeze_time: i32, + pub eating: bool, + pub scared: bool, + pub sit_amount: f32, + pub lie_on_back_amount: f32, + pub roll_amount: f32, +} +/// `PandaModel` / `BabyPandaModel.setupAnim`. +pub fn panda(p: &mut Poses, s: &State, st: &Panda) { + quadruped(p, s); + let age = s.age; + if st.unhappy { + p.yrot("head", 0.35 * (0.6 * age).msin()); + p.zrot("head", 0.35 * (0.6 * age).msin()); + p.xrot("right_front_leg", -0.75 * (0.3 * age).msin()); + p.xrot("left_front_leg", 0.75 * (0.3 * age).msin()); + } else { + p.zrot("head", 0.0); + } + if st.sneezing { + if st.sneeze_time < 15 { + p.xrot("head", rad(-PI / 4.0) * st.sneeze_time as f32 / 14.0); + } else if st.sneeze_time < 20 { + let pos = ((st.sneeze_time - 15) / 5) as f32; + p.xrot("head", rad(-PI / 4.0) + rad(PI / 4.0) * pos); + } + } + if st.sit_amount > 0.0 { + let a = st.sit_amount; + if s.baby { + let x = rot_lerp_rad(a, p.get("body")[3], rad(PI / 18.0)); + p.xrot("body", x); + let v = lerp(a, p.get("body")[2], -1.5); + p.get("body")[2] = v; + let v = lerp(a, p.get("head")[2], -11.5); + p.get("head")[2] = v; + let v = lerp(a, p.get("head")[1], 17.5); + p.get("head")[1] = v; + for (part, z) in [ + ("right_front_leg", -5.0), + ("left_front_leg", -5.0), + ("right_hind_leg", 3.0), + ("left_hind_leg", 3.0), + ] { + let v = lerp(a, p.get(part)[2], z); + p.get(part)[2] = v; + } + } else { + let x = rot_lerp_rad(a, p.get("body")[3], 1.740_796_3); + p.xrot("body", x); + let x = rot_lerp_rad(a, p.get("head")[3], rad(PI / 2.0)); + p.xrot("head", x); + } + p.zrot("right_front_leg", -0.270_796_42); + p.zrot("left_front_leg", 0.270_796_42); + p.zrot("right_hind_leg", 0.570_796_4); + p.zrot("left_hind_leg", -0.570_796_4); + if st.eating { + p.xrot("head", rad(PI / 2.0) + 0.2 * (age * 0.6).msin()); + p.xrot("right_front_leg", -0.4 - 0.2 * (age * 0.6).msin()); + p.xrot("left_front_leg", -0.4 - 0.2 * (age * 0.6).msin()); + } + if st.scared { + p.xrot("head", 2.170_796_4); + p.xrot("right_front_leg", -0.9); + p.xrot("left_front_leg", -0.9); + } + } else { + for leg in [ + "right_hind_leg", + "left_hind_leg", + "right_front_leg", + "left_front_leg", + ] { + p.zrot(leg, 0.0); + } + } + if st.lie_on_back_amount > 0.0 { + p.xrot("right_hind_leg", -0.6 * (age * 0.15).msin()); + p.xrot("left_hind_leg", 0.6 * (age * 0.15).msin()); + p.xrot("right_front_leg", 0.3 * (age * 0.25).msin()); + p.xrot("left_front_leg", -0.3 * (age * 0.25).msin()); + let x = rot_lerp_rad(st.lie_on_back_amount, p.get("head")[3], rad(PI / 2.0)); + p.xrot("head", x); + } + if st.roll_amount > 0.0 { + let x = rot_lerp_rad(st.roll_amount, p.get("head")[3], 2.056_194_5); + p.xrot("head", x); + p.xrot("right_hind_leg", -0.5 * (age * 0.5).msin()); + p.xrot("left_hind_leg", 0.5 * (age * 0.5).msin()); + p.xrot("right_front_leg", 0.5 * (age * 0.5).msin()); + p.xrot("left_front_leg", -0.5 * (age * 0.5).msin()); + } +} + +// ---- llama ---------------------------------------------------------------- +/// `LlamaModel.setupAnim`. +pub fn llama(p: &mut Poses, s: &State, has_chest: bool) { + quadruped(p, s); + p.visible("right_chest", has_chest); + p.visible("left_chest", has_chest); +} + +// ---- turtle --------------------------------------------------------------- +#[derive(Clone, Copy, Debug, Default)] +pub struct Turtle { + pub on_land: bool, + pub laying_egg: bool, + pub has_egg: bool, +} +/// `TurtleModel` / `AdultTurtleModel.setupAnim`. +pub fn turtle(p: &mut Poses, s: &State, t: &Turtle) { + quadruped(p, s); + let (pos, speed) = (s.pos, s.speed); + if t.on_land { + let lay = if t.laying_egg { 4.0 } else { 1.0 }; + let amp = if t.laying_egg { 2.0 } else { 1.0 }; + let swing = pos * 5.0; + let front = (lay * swing).mcos(); + let hind = swing.mcos(); + p.yrot("right_front_leg", -front * 8.0 * speed * amp); + p.yrot("left_front_leg", front * 8.0 * speed * amp); + p.yrot("right_hind_leg", -hind * 3.0 * speed); + p.yrot("left_hind_leg", hind * 3.0 * speed); + } else { + let scale = 0.5 * speed; + let swing = (pos * 0.6662 * 0.6).mcos() * scale; + p.xrot("right_hind_leg", swing); + p.xrot("left_hind_leg", -swing); + p.zrot("right_front_leg", -swing); + p.zrot("left_front_leg", swing); + } + if !s.baby { + p.visible("egg_belly", t.has_egg); + if t.has_egg { + adds(p, "root", 1, -1.0); + } + } +} + +// ---- strider -------------------------------------------------------------- +/// `StriderModel.animateBristle` with the rotation axis the model adds to. +fn bristles(p: &mut Poses, age: f32, flow: f32, parts: [&str; 3], axis: usize) { + adds(p, parts[0], axis, flow * 0.6); + adds(p, parts[1], axis, flow * 1.2); + adds(p, parts[2], axis, flow * 1.3); + adds(p, parts[0], axis, 0.1 * (age * 0.4).msin()); + adds(p, parts[1], axis, 0.1 * (age * 0.2).msin()); + adds(p, parts[2], axis, 0.05 * (age * -0.4).msin()); +} +/// `StriderModel` / `AdultStriderModel` / `BabyStriderModel.setupAnim`. +pub fn strider(p: &mut Poses, s: &State, ridden: bool) { + let pos = s.pos; + let speed = s.speed.min(0.25); + if !ridden { + p.xrot("body", s.x_rot.to_radians()); + p.yrot("body", s.y_rot.to_radians()); + } else { + p.xrot("body", 0.0); + p.yrot("body", 0.0); + } + p.zrot("body", 0.1 * (pos * 1.5).msin() * 4.0 * speed); + p.xrot("left_leg", (pos * 1.5 * 0.5).msin() * 2.0 * speed); + p.xrot("right_leg", (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed); + p.zrot( + "left_leg", + rad(PI / 18.0) * (pos * 1.5 * 0.5).mcos() * speed, + ); + p.zrot( + "right_leg", + rad(PI / 18.0) * (pos * 1.5 * 0.5 + FPI).mcos() * speed, + ); + let flow = (pos * 1.5 + FPI).mcos() * speed; + if !s.baby { + p.zrot("right_bottom_bristle", -1.221_730_5); + p.zrot("right_middle_bristle", -1.134_464); + p.zrot("right_top_bristle", -0.872_664_63); + p.zrot("left_top_bristle", 0.872_664_63); + p.zrot("left_middle_bristle", 1.134_464); + p.zrot("left_bottom_bristle", 1.221_730_5); + bristles( + p, + s.age, + flow, + [ + "right_top_bristle", + "right_middle_bristle", + "right_bottom_bristle", + ], + 5, + ); + bristles( + p, + s.age, + flow, + [ + "left_top_bristle", + "left_middle_bristle", + "left_bottom_bristle", + ], + 5, + ); + p.get("body")[1] = 2.0; + p.get("body")[1] -= 2.0 * (pos * 1.5).mcos() * 2.0 * speed; + p.get("left_leg")[1] = 8.0 + 2.0 * (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed; + p.get("right_leg")[1] = 8.0 + 2.0 * (pos * 1.5 * 0.5).msin() * 2.0 * speed; + } else { + p.get("body")[1] = 17.25; + p.get("body")[1] -= 1.0 * (pos * 1.5).mcos() * 2.0 * speed; + p.get("left_leg")[1] = 20.0 + 2.0 * (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed; + p.get("right_leg")[1] = 20.0 + 2.0 * (pos * 1.5 * 0.5).msin() * 2.0 * speed; + bristles(p, s.age, flow, ["bristle2", "bristle1", "bristle0"], 3); + } +} + +// ---- snow golem ----------------------------------------------------------- +/// `SnowGolemModel.setupAnim`. +pub fn snow_golem(p: &mut Poses, s: &State) { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + p.xrot("head", s.x_rot * rad(PI / 180.0)); + let y = s.y_rot * rad(PI / 180.0) * 0.25; + p.yrot("upper_body", y); + let (sin, cos) = (y.msin(), y.mcos()); + p.yrot("left_arm", y); + p.yrot("right_arm", y + FPI); + p.get("left_arm")[0] = cos * 5.0; + p.get("left_arm")[2] = -sin * 5.0; + p.get("right_arm")[0] = -cos * 5.0; + p.get("right_arm")[2] = sin * 5.0; +} + +// ---- silverfish and endermite --------------------------------------------- +/// `SilverfishModel.setupAnim`. +pub fn silverfish(p: &mut Poses, s: &State) { + let mut ys = [0.0f32; 7]; + let mut xs = [0.0f32; 7]; + for i in 0..7usize { + let d = (i as i32 - 2).abs(); + let phase = s.age * 0.9 + i as f32 * 0.15 * FPI; + ys[i] = phase.mcos() * FPI * 0.05 * (1 + d) as f32; + xs[i] = phase.msin() * FPI * 0.2 * d as f32; + let name = format!("segment{i}"); + p.yrot(&name, ys[i]); + p.get(&name)[0] = xs[i]; + } + p.yrot("layer0", ys[2]); + p.yrot("layer1", ys[4]); + p.get("layer1")[0] = xs[4]; + p.yrot("layer2", ys[1]); + p.get("layer2")[0] = xs[1]; +} +/// `EndermiteModel.setupAnim`. +pub fn endermite(p: &mut Poses, s: &State) { + for i in 0..4usize { + let d = (i as i32 - 2).abs(); + let phase = s.age * 0.9 + i as f32 * 0.15 * FPI; + let name = format!("segment{i}"); + p.yrot(&name, phase.mcos() * FPI * 0.01 * (1 + d) as f32); + p.get(&name)[0] = phase.msin() * FPI * 0.1 * d as f32; + } +} + +// ---- parrot --------------------------------------------------------------- +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ParrotPose { + #[default] + Standing, + Flying, + OnShoulder, + Sitting, + Party, +} +/// `ParrotModel.setupAnim`. +pub fn parrot(p: &mut Poses, s: &State, pose: ParrotPose, flap_angle: f32) { + use ParrotPose as P; + match pose { + P::Flying => { + adds(p, "left_leg", 3, rad(PI * 2.0 / 9.0)); + adds(p, "right_leg", 3, rad(PI * 2.0 / 9.0)); + } + P::Sitting => { + adds(p, "head", 1, 1.9); + adds(p, "tail", 3, rad(PI / 6.0)); + adds(p, "tail", 1, 1.9); + adds(p, "body", 1, 1.9); + p.zrot("left_wing", -0.0873); + adds(p, "left_wing", 1, 1.9); + p.zrot("right_wing", 0.0873); + adds(p, "right_wing", 1, 1.9); + adds(p, "left_leg", 1, 1.9); + adds(p, "right_leg", 1, 1.9); + adds(p, "left_leg", 3, rad(PI / 2.0)); + adds(p, "right_leg", 3, rad(PI / 2.0)); + } + P::Party => { + p.zrot("left_leg", rad(-PI / 9.0)); + p.zrot("right_leg", rad(PI / 9.0)); + } + _ => {} + } + head_look(p, s); + let flutter = |p: &mut Poses| { + let bob = flap_angle * 0.3; + adds(p, "head", 1, bob); + adds(p, "tail", 3, (s.pos * 0.6662).mcos() * 0.3 * s.speed); + adds(p, "tail", 1, bob); + adds(p, "body", 1, bob); + p.zrot("left_wing", -0.0873 - flap_angle); + adds(p, "left_wing", 1, bob); + p.zrot("right_wing", 0.0873 + flap_angle); + adds(p, "right_wing", 1, bob); + adds(p, "left_leg", 1, bob); + adds(p, "right_leg", 1, bob); + }; + match pose { + P::Standing => { + adds(p, "left_leg", 3, (s.pos * 0.6662).mcos() * 1.4 * s.speed); + adds( + p, + "right_leg", + 3, + (s.pos * 0.6662 + FPI).mcos() * 1.4 * s.speed, + ); + flutter(p); + } + P::Flying | P::OnShoulder => flutter(p), + P::Sitting => {} + P::Party => { + let (x, y) = (s.age.mcos(), s.age.msin()); + adds(p, "head", 0, x); + adds(p, "head", 1, y); + p.xrot("head", 0.0); + p.yrot("head", 0.0); + p.zrot("head", s.age.msin() * 0.4); + adds(p, "body", 0, x); + adds(p, "body", 1, y); + p.zrot("left_wing", -0.0873 - flap_angle); + adds(p, "left_wing", 0, x); + adds(p, "left_wing", 1, y); + p.zrot("right_wing", 0.0873 + flap_angle); + adds(p, "right_wing", 0, x); + adds(p, "right_wing", 1, y); + adds(p, "tail", 0, x); + adds(p, "tail", 1, y); + } + } +} + +// ---- bee ------------------------------------------------------------------ +#[derive(Clone, Copy, Debug)] +pub struct Bee { + pub has_stinger: bool, + pub on_ground: bool, + pub angry: bool, + pub roll_amount: f32, +} +/// `BeeModel` / `AdultBeeModel.setupAnim`. +pub fn bee(p: &mut Poses, s: &State, b: &Bee) { + p.visible("stinger", b.has_stinger); + let age = s.age; + if !b.on_ground { + let speed = age * 120.32113 * rad(PI / 180.0); + p.yrot("right_wing", 0.0); + p.zrot("right_wing", speed.mcos() * FPI * 0.15); + let (x, y, z) = { + let r = p.get("right_wing"); + (r[3], r[4], r[5]) + }; + p.xrot("left_wing", x); + p.yrot("left_wing", y); + p.zrot("left_wing", -z); + p.xrot("front_legs", rad(PI / 4.0)); + p.xrot("middle_legs", rad(PI / 4.0)); + p.xrot("back_legs", rad(PI / 4.0)); + } + if !b.angry && !b.on_ground { + let speed = (age * 0.18).mcos(); + p.xrot("bone", 0.1 + speed * FPI * 0.025); + adds(p, "bone", 1, -((age * 0.18).mcos() * 0.9)); + p.xrot("front_legs", -speed * FPI * 0.1 + rad(PI / 8.0)); + p.xrot("back_legs", -speed * FPI * 0.05 + rad(PI / 4.0)); + if !s.baby { + p.xrot("left_antenna", speed * FPI * 0.03); + p.xrot("right_antenna", speed * FPI * 0.03); + } + } + if b.roll_amount > 0.0 { + let x = rot_lerp_rad(b.roll_amount, p.get("bone")[3], 3.091_592_8); + p.xrot("bone", x); + } +} + +// ---- bat ------------------------------------------------------------------ +/// `BatModel.setupAnim`. +pub fn bat( + p: &mut Poses, + s: &State, + resting: bool, + fly: &AnimationState, + rest: &AnimationState, + a: &Animations, +) { + if resting { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + } + run(a, "BatAnimation.BAT_FLYING", fly, s, p); + run(a, "BatAnimation.BAT_RESTING", rest, s, p); +} + +// ---- armadillo ------------------------------------------------------------ +#[derive(Clone, Debug, Default)] +pub struct Armadillo { + pub hiding_in_shell: bool, + pub roll_out: AnimationState, + pub roll_up: AnimationState, + pub peek: AnimationState, +} +/// `ArmadilloModel.setupAnim`. +pub fn armadillo(p: &mut Poses, s: &State, st: &Armadillo, a: &Animations) { + if st.hiding_in_shell { + p.skip_draw("body"); + p.visible("left_hind_leg", false); + p.visible("right_hind_leg", false); + p.visible("tail", false); + } else { + p.visible("cube", false); + p.xrot("head", s.x_rot.clamp(-22.5, 25.0) * rad(PI / 180.0)); + p.yrot("head", s.y_rot.clamp(-32.5, 32.5) * rad(PI / 180.0)); + let prefix = if s.baby { + "BabyArmadilloAnimation.ARMADILLO_BABY_" + } else { + "ArmadilloAnimation.ARMADILLO_" + }; + walk(a, &format!("{prefix}WALK"), s, 16.5, 2.5, p); + } + let prefix = if s.baby { + "BabyArmadilloAnimation.ARMADILLO_BABY_" + } else { + "ArmadilloAnimation.ARMADILLO_" + }; + run(a, &format!("{prefix}ROLL_OUT"), &st.roll_out, s, p); + run(a, &format!("{prefix}ROLL_UP"), &st.roll_up, s, p); + run(a, &format!("{prefix}PEEK"), &st.peek, s, p); +} + +// ---- axolotl -------------------------------------------------------------- +#[derive(Clone, Debug, Default)] +pub struct Axolotl { + pub playing_dead: f32, + pub in_water: f32, + pub on_ground: f32, + pub moving: f32, + pub swim: AnimationState, + pub walk: AnimationState, + pub idle_on_ground: AnimationState, + pub idle_underwater_on_ground: AnimationState, + pub idle_underwater: AnimationState, + pub play_dead: AnimationState, +} +/// `AdultAxolotlModel` / `BabyAxolotlModel.setupAnim`. +pub fn axolotl(p: &mut Poses, s: &State, x: &Axolotl, a: &Animations) { + if s.baby { + if x.walk.started.is_some() { + walk( + a, + "BabyAxolotlAnimation.AXOLOTL_WALK_FLOOR", + s, + 15.0, + 30.0, + p, + ); + } + run(a, "BabyAxolotlAnimation.BABY_AXOLOTL_SWIM", &x.swim, s, p); + run( + a, + "BabyAxolotlAnimation.WALK_FLOOR_UNDERWATER", + // The model reads `walkAnimationState` again here, not the + // underwater state the renderer also copies. + &x.walk, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.BABY_AXOLOTL_IDLE_FLOOR", + &x.idle_on_ground, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.IDLE_UNDERWATER", + &x.idle_underwater, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.IDLE_FLOOR_UNDERWATER", + &x.idle_underwater_on_ground, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.BABY_AXOLOTL_PLAY_DEAD", + &x.play_dead, + s, + p, + ); + return; + } + let not_moving = 1.0 - x.moving; + let mirrored = 1.0 - x.on_ground.min(x.moving); + adds(p, "body", 4, s.y_rot * rad(PI / 180.0)); + axolotl_swim(p, s.age, s.x_rot, x.moving.min(x.in_water)); + axolotl_hover(p, s.age, not_moving.min(x.in_water)); + axolotl_crawl(p, s.age, x.moving.min(x.on_ground)); + axolotl_lay(p, s.age, not_moving.min(x.on_ground)); + axolotl_dead(p, x.playing_dead); + if mirrored > 1.0e-5 { + let l_hind = [ + p.get("left_hind_leg")[3], + p.get("left_hind_leg")[4], + p.get("left_hind_leg")[5], + ]; + let l_front = [ + p.get("left_front_leg")[3], + p.get("left_front_leg")[4], + p.get("left_front_leg")[5], + ]; + for (part, l) in [("right_hind_leg", l_hind), ("right_front_leg", l_front)] { + let r = p.get(part); + r[3] += l[0] * mirrored; + r[4] += -l[1] * mirrored; + r[5] += -l[2] * mirrored; + } + } +} +fn axolotl_lay(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.09; + let sine = sway.msin(); + let cosine = sway.mcos(); + let movement = sine * sine - 2.0 * sine; + let movement2 = cosine * cosine - 3.0 * sine; + adds(p, "head", 3, -0.09 * movement * factor); + adds(p, "head", 5, -0.2 * factor); + adds(p, "tail", 4, (-0.1 + 0.1 * movement) * factor); + let gill = (0.6 + 0.05 * movement2) * factor; + adds(p, "top_gills", 3, gill); + adds(p, "left_gills", 4, -gill); + adds(p, "right_gills", 4, gill); + adds(p, "left_hind_leg", 3, 1.1 * factor); + adds(p, "left_hind_leg", 4, 1.0 * factor); + adds(p, "left_front_leg", 3, 0.8 * factor); + adds(p, "left_front_leg", 4, 2.3 * factor); + adds(p, "left_front_leg", 5, -0.5 * factor); +} +fn axolotl_crawl(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.11; + let cosine = sway.mcos(); + let hind_y = (cosine * cosine - 2.0 * cosine) / 5.0; + let front_y = 0.7 * cosine; + let head_tail = 0.09 * cosine * factor; + adds(p, "head", 4, head_tail); + adds(p, "tail", 4, head_tail); + let gill = (0.6 - 0.08 * (cosine * cosine + 2.0 * sway.msin())) * factor; + adds(p, "top_gills", 3, gill); + adds(p, "left_gills", 4, -gill); + adds(p, "right_gills", 4, gill); + let hind_x = 0.942_477_9 * factor; + let front_x = 1.099_557_4 * factor; + adds(p, "left_hind_leg", 3, hind_x); + adds(p, "left_hind_leg", 4, (1.5 - hind_y) * factor); + adds(p, "left_hind_leg", 5, -0.1 * factor); + adds(p, "left_front_leg", 3, front_x); + adds(p, "left_front_leg", 4, (rad(PI / 2.0) - front_y) * factor); + adds(p, "right_hind_leg", 3, hind_x); + adds(p, "right_hind_leg", 4, (-1.0 - hind_y) * factor); + adds(p, "right_front_leg", 3, front_x); + adds(p, "right_front_leg", 4, (rad(-PI / 2.0) - front_y) * factor); +} +fn axolotl_hover(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.075; + let cosine = sway.mcos(); + let sine = sway.msin() * 0.15; + let body_x = (-0.15 + 0.075 * cosine) * factor; + adds(p, "body", 3, body_x); + adds(p, "body", 1, -(sine * factor)); + adds(p, "head", 3, -body_x); + adds(p, "top_gills", 3, 0.2 * cosine * factor); + let gill_y = (-0.3 * cosine - 0.19) * factor; + adds(p, "left_gills", 4, gill_y); + adds(p, "right_gills", 4, -gill_y); + adds( + p, + "left_hind_leg", + 3, + (rad(PI * 3.0 / 4.0) - cosine * 0.11) * factor, + ); + adds(p, "left_hind_leg", 4, 0.471_238_94 * factor); + adds(p, "left_hind_leg", 5, 1.727_876_1 * factor); + adds( + p, + "left_front_leg", + 3, + (rad(PI / 4.0) - cosine * 0.2) * factor, + ); + adds(p, "left_front_leg", 4, 2.042_035 * factor); + adds(p, "tail", 4, 0.5 * cosine * factor); +} +fn axolotl_swim(p: &mut Poses, age: f32, x_rot: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.33; + let sine = sway.msin(); + let cosine = sway.mcos(); + let body_sway = 0.13 * sine; + adds(p, "body", 3, (x_rot * rad(PI / 180.0) + body_sway) * factor); + adds(p, "head", 3, -(body_sway * 1.8 * factor)); + adds(p, "body", 1, -(0.45 * cosine * factor)); + adds(p, "top_gills", 3, (-0.5 * sine - 0.8) * factor); + let gill_y = (0.3 * sine + 0.9) * factor; + adds(p, "left_gills", 4, gill_y); + adds(p, "right_gills", 4, -gill_y); + let tail = p.get("tail")[4] + 0.3 * (sway * 0.9).mcos() * factor; + p.yrot("tail", tail); + adds(p, "left_hind_leg", 3, 1.884_955_8 * factor); + adds(p, "left_hind_leg", 4, -0.4 * sine * factor); + adds(p, "left_hind_leg", 5, rad(PI / 2.0) * factor); + adds(p, "left_front_leg", 3, 1.884_955_8 * factor); + adds(p, "left_front_leg", 4, (-0.2 * cosine - 0.1) * factor); + adds(p, "left_front_leg", 5, rad(PI / 2.0) * factor); +} +fn axolotl_dead(p: &mut Poses, factor: f32) { + if factor <= 1.0e-5 { + return; + } + adds(p, "left_hind_leg", 3, 1.413_716_7 * factor); + adds(p, "left_hind_leg", 4, 1.099_557_4 * factor); + adds(p, "left_hind_leg", 5, rad(PI / 4.0) * factor); + adds(p, "left_front_leg", 3, rad(PI / 4.0) * factor); + adds(p, "left_front_leg", 4, 2.042_035 * factor); + adds(p, "body", 3, -0.15 * factor); + adds(p, "body", 5, 0.35 * factor); +} + +// ---- frog ----------------------------------------------------------------- +#[derive(Clone, Debug, Default)] +pub struct Frog { + pub swimming: bool, + pub jump: AnimationState, + pub croak: AnimationState, + pub tongue: AnimationState, + pub swim_idle: AnimationState, +} +/// `FrogModel.setupAnim`. +pub fn frog(p: &mut Poses, s: &State, f: &Frog, a: &Animations) { + run(a, "FrogAnimation.FROG_JUMP", &f.jump, s, p); + run(a, "FrogAnimation.FROG_CROAK", &f.croak, s, p); + run(a, "FrogAnimation.FROG_TONGUE", &f.tongue, s, p); + if f.swimming { + walk(a, "FrogAnimation.FROG_SWIM", s, 1.0, 2.5, p); + } else { + walk(a, "FrogAnimation.FROG_WALK", s, 1.5, 2.5, p); + } + run(a, "FrogAnimation.FROG_IDLE_WATER", &f.swim_idle, s, p); + p.visible("croaking_body", f.croak.started.is_some()); +} + +// ---- rabbit --------------------------------------------------------------- +/// `RabbitModel.setupAnim`. +pub fn rabbit( + p: &mut Poses, + s: &State, + hop: &AnimationState, + tilt: &AnimationState, + a: &Animations, +) { + if tilt.started.is_none() { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + p.xrot("head", s.x_rot * rad(PI / 180.0)); + } + let prefix = if s.baby { + "BabyRabbitAnimation." + } else { + "RabbitAnimation." + }; + run(a, &format!("{prefix}HOP"), hop, s, p); + run(a, &format!("{prefix}IDLE_HEAD_TILT"), tilt, s, p); +} + +// ---- fox ------------------------------------------------------------------ +#[derive(Clone, Copy, Debug, Default)] +pub struct Fox { + pub crouching: bool, + pub sleeping: bool, + pub sitting: bool, + pub pouncing: bool, + pub faceplanted: bool, + pub head_roll_angle: f32, + pub crouch_amount: f32, + /// `FoxModel.legMotionPos` after this frame's `+= 0.67`. + pub leg_motion_pos: f32, +} +/// `FoxModel` / `AdultFoxModel` / `BabyFoxModel.setupAnim`. +pub fn fox(p: &mut Poses, s: &State, f: &Fox, a: &Animations) { + let baby = s.baby; + let age_scale = if baby { 0.5 } else { 1.0 }; + // setWalkingPose + p.zrot("head", f.head_roll_angle); + if baby { + walk(a, "FoxBabyAnimation.FOX_BABY_WALK", s, 1.0, 2.5, p); + } else { + let (pos, speed) = (s.pos, s.speed); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed); + p.xrot("left_hind_leg", (pos * 0.6662 + FPI).mcos() * 1.4 * speed); + p.xrot("right_front_leg", (pos * 0.6662 + FPI).mcos() * 1.4 * speed); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed); + } + if f.crouching { + // setCrouchingPose + adds(p, "body", 3, 0.104_719_76); + adds(p, "head", 1, f.crouch_amount * age_scale); + let wiggle = s.age.mcos() * 0.05; + p.yrot("body", wiggle); + p.zrot("right_hind_leg", wiggle); + p.zrot("left_hind_leg", wiggle); + p.zrot("right_front_leg", wiggle / 2.0); + p.zrot("left_front_leg", wiggle / 2.0); + if baby { + adds(p, "body", 1, f.crouch_amount / 6.0); + } else { + adds(p, "body", 1, f.crouch_amount); + } + } else if f.sleeping { + // setSleepingPose + for leg in [ + "right_hind_leg", + "left_hind_leg", + "right_front_leg", + "left_front_leg", + ] { + p.visible(leg, false); + } + if baby { + p.zrot("body", rad(-PI / 2.0)); + p.xrot("body", rad(-PI / 18.0)); + adds(p, "body", 1, 1.5); + adds(p, "body", 2, -1.5); + adds(p, "body", 0, -1.5); + p.xrot("tail", rad(-PI * 5.0 / 6.0)); + p.xrot("tail", -2.181_661_6); + adds(p, "tail", 0, -0.7); + adds(p, "tail", 2, 0.6); + adds(p, "tail", 1, 0.9); + adds(p, "head", 0, -2.0); + adds(p, "head", 1, 2.8); + adds(p, "head", 2, -4.0); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", 0.0); + } else { + p.zrot("body", rad(-PI / 2.0)); + adds(p, "body", 1, 5.0); + p.xrot("tail", rad(-PI * 5.0 / 6.0)); + adds(p, "head", 0, 2.0); + adds(p, "head", 1, 2.99); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", 0.0); + } + } else if f.sitting { + // setSittingPose + p.xrot("head", 0.0); + p.yrot("head", 0.0); + if baby { + p.xrot("body", -0.959_931); + adds(p, "body", 2, -(4.5 * age_scale)); + adds(p, "body", 1, 3.0 * age_scale); + adds(p, "tail", 1, -0.6); + adds(p, "tail", 2, -(2.0 * age_scale)); + p.xrot("tail", 0.959_931_14); + adds(p, "head", 1, -0.75); + adds(p, "head", 2, 0.0); + p.xrot("right_front_leg", rad(-PI / 12.0)); + p.xrot("left_front_leg", rad(-PI / 12.0)); + adds(p, "right_front_leg", 2, -1.5); + adds(p, "left_front_leg", 2, -1.5); + adds(p, "right_front_leg", 0, 0.01); + adds(p, "left_front_leg", 0, -0.01); + adds(p, "right_hind_leg", 2, -3.75); + adds(p, "left_hind_leg", 2, -3.75); + adds(p, "right_hind_leg", 0, 0.01); + adds(p, "left_hind_leg", 0, -0.01); + } else { + p.xrot("body", rad(PI / 6.0)); + adds(p, "body", 1, -7.0); + adds(p, "body", 2, 3.0); + p.xrot("tail", rad(PI / 4.0)); + adds(p, "head", 1, -6.5); + adds(p, "head", 2, 2.75); + p.xrot("right_front_leg", rad(-PI / 12.0)); + p.xrot("left_front_leg", rad(-PI / 12.0)); + p.xrot("right_hind_leg", rad(-PI * 5.0 / 12.0)); + adds(p, "right_hind_leg", 1, 4.0); + adds(p, "right_hind_leg", 2, -0.25); + p.xrot("left_hind_leg", rad(-PI * 5.0 / 12.0)); + adds(p, "left_hind_leg", 1, 4.0); + adds(p, "left_hind_leg", 2, -0.25); + adds(p, "tail", 2, -1.0); + } + } + if f.pouncing && !baby { + let crouch = f.crouch_amount / 2.0; + adds(p, "body", 1, -crouch); + adds(p, "head", 1, -crouch); + } + if !f.sleeping && !f.faceplanted && !f.crouching { + p.xrot("head", s.x_rot * rad(PI / 180.0)); + p.yrot("head", s.y_rot * rad(PI / 180.0)); + } + if f.sleeping { + p.xrot("head", 0.0); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", (s.age * 0.027).mcos() / 22.0); + } + if f.faceplanted { + let m = f.leg_motion_pos; + p.xrot("right_hind_leg", (m * 0.4662).mcos() * 0.1); + p.xrot("left_hind_leg", (m * 0.4662 + FPI).mcos() * 0.1); + p.xrot("right_front_leg", (m * 0.4662 + FPI).mcos() * 0.1); + p.xrot("left_front_leg", (m * 0.4662).mcos() * 0.1); + } +} + +// ---- adapters --------------------------------------------------------------- +/// Dispatch for the species ported here; `false` when `m` is not one of them. +pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { + let st = &m.anim.states; + match m.species() { + Species::Goat => goat(p, s, &Goat::from_mob(m)), + Species::PolarBear => polar_bear(p, s, 0.0), + Species::Panda => panda(p, s, &Panda::default()), + Species::Llama | Species::TraderLlama => { + llama(p, s, m.extra.chested && !s.baby); + } + Species::Turtle => turtle( + p, + s, + &Turtle { + on_land: !m.fluids.in_water && m.on_ground, + laying_egg: false, + has_egg: false, + }, + ), + Species::Strider => strider(p, s, m.rider.is_some()), + Species::SnowGolem => snow_golem(p, s), + Species::Silverfish => silverfish(p, s), + Species::Endermite => endermite(p, s), + Species::Parrot => { + let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; + let speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; + let pose = if m.extra.sitting { + ParrotPose::Sitting + } else if !m.on_ground && !m.fluids.in_water { + ParrotPose::Flying + } else { + ParrotPose::Standing + }; + parrot(p, s, pose, (flap.msin() + 1.0) * speed); + } + Species::Bee => bee( + p, + s, + &Bee { + has_stinger: true, + on_ground: m.on_ground, + angry: m.extra.anger > 0, + roll_amount: 0.0, + }, + ), + Species::Bat => bat(p, s, m.extra.flag, &st[0], &st[1], a), + Species::Armadillo => armadillo( + p, + s, + &Armadillo { + hiding_in_shell: false, + roll_out: st[0], + roll_up: st[1], + peek: st[2], + }, + a, + ), + Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m), a), + Species::Frog => frog( + p, + s, + &Frog { + swimming: m.fluids.in_water, + jump: st[0], + croak: st[1], + tongue: st[2], + swim_idle: st[3], + }, + a, + ), + Species::Rabbit => rabbit(p, s, &st[0], &st[1], a), + Species::Fox => fox(p, s, &Fox::default(), a), + _ => return false, + } + true +} +impl Axolotl { + pub fn from_mob(m: &Mob) -> Self { + let in_water = m.fluids.in_water; + Self { + in_water: if in_water { 1.0 } else { 0.0 }, + on_ground: if m.on_ground { 1.0 } else { 0.0 }, + walk: m.anim.states[0], + swim: m.anim.states[1], + ..Self::default() + } + } +} diff --git a/crates/horizon-client/src/mobs/camel.rs b/crates/horizon-client/src/mobs/camel.rs index 7d1c200b8..741d6a897 100644 --- a/crates/horizon-client/src/mobs/camel.rs +++ b/crates/horizon-client/src/mobs/camel.rs @@ -8,6 +8,7 @@ use super::{ Tempt, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::collections::HashMap; @@ -179,7 +180,7 @@ pub fn dash(m: &mut Mob, amount: f32, events: &mut Vec) { return; } let yaw = m.yaw.to_radians(); - let (dx, dz) = (f64::from(-yaw.sin()), f64::from(yaw.cos())); + let (dx, dz) = (f64::from(-yaw.msin()), f64::from(yaw.mcos())); let speed = m.movement_speed(); let a = f64::from(amount); m.velocity.x += dx * 22.2222 * a * speed; diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 490b207b0..dc9e391aa 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -68,6 +68,14 @@ impl MobData { data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); data } + /// Only the keyframe animation definitions of `mob-data.json`. + pub fn load_animations(root: &Path) -> HashMap { + fs::read(root.join("mob-data.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .map(|v| Self::from_json(&v).animations) + .unwrap_or_default() + } pub fn entity_has(&self, tag: &str, entity: &str) -> bool { self.entity_tags .get(tag) diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 33be2a248..dd56a85a0 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -9,6 +9,7 @@ use super::{ Tempt, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -24,9 +25,9 @@ pub const COLORS: [&str; 7] = [ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackdots"]; // AnimState slots. -const EAT: usize = 0; -const STAND: usize = 1; -const MOUTH: usize = 2; +pub const EAT: usize = 0; +pub const STAND: usize = 1; +pub const MOUTH: usize = 2; /// What a rider asks of its mount this tick. #[derive(Clone, Copy, Debug, Default)] @@ -164,7 +165,7 @@ fn boost_factor(m: &mut Mob) -> f32 { m.extra.counter2 = 0; return 1.0; } - 1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).sin() + 1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).msin() } /// `AbstractHorse.MountPanicGoal`: only without a rider. #[derive(Clone, Debug)] @@ -360,7 +361,7 @@ pub fn ridden_step(m: &mut Mob) { let impulse = m.extra.vector[0] as f32 * r.jump; m.velocity.y = f64::from(impulse); if forward > 0.0 { - let (s, c) = (m.yaw.to_radians().sin(), m.yaw.to_radians().cos()); + let (s, c) = (m.yaw.to_radians().msin(), m.yaw.to_radians().mcos()); m.velocity.x += f64::from(-0.4 * s * r.jump); m.velocity.z += f64::from(0.4 * c * r.jump); } @@ -482,19 +483,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let mut head_x = s.x_rot.to_radians(); let (speed, pos) = (s.speed, s.pos); if speed > 0.2 { - head_x += (pos * 0.8).cos() * 0.15 * speed; + head_x += (pos * 0.8).mcos() * 0.15 * speed; } let eating = m.anim.lerp(EAT, s.partial); let standing = m.anim.lerp(STAND, s.partial); let istand = 1.0 - standing; let feeding = m.anim.lerp(MOUTH, s.partial); let in_water = if m.fluids.in_water { 0.2 } else { 1.0 }; - let leg1 = (in_water * pos * 0.6662 + PI).cos(); + let leg1 = (in_water * pos * 0.6662 + PI).mcos(); let leg_x = leg1 * 0.8 * speed; - let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.sin() * 0.05); + let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05); p.xrot( "head_parts", - standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.sin() * 0.05) + base, + standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.msin() * 0.05) + base, ); p.yrot( "head_parts", @@ -527,7 +528,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { rf[2] = z; } let stand = stand_angle * standing; - let bob = (s.age * 0.6 + PI).cos(); + let bob = (s.age * 0.6 + PI).mcos(); let rleg = (stand_x_off + bob) * standing + leg_x * istand; let lleg = (stand_x_off - bob) * standing - leg_x * istand; p.xrot("left_hind_leg", stand - leg1 * 0.5 * speed * istand); @@ -536,9 +537,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("right_front_leg", lleg); if baby && donkey { let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t; + // BabyDonkeyModel lerps the right leg from the left leg's new height. let y = lerp(standing, p.get("left_hind_leg")[1], -0.3); p.get("left_hind_leg")[1] = y; - p.get("right_hind_leg")[1] = y; + p.get("right_hind_leg")[1] = lerp(standing, y, -0.3); } let age = if baby { 0.5 } else { 1.0 }; p.xrot("tail", tail_off + PI / 6.0 + speed * 0.75); @@ -548,4 +550,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { t[2] += speed * 2.0 * age; } p.yrot("tail", 0.0); + if baby && donkey { + // BabyDonkeyModel overrides the state's pitch with -30 degrees and + // sets the head parts again. + let head_x = -30.0f32 * horizon_core::geometry::trig::DEG_TO_RAD; + let base = + (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05); + p.xrot( + "head_parts", + standing * (PI / 12.0 + head_x) + eating * (PI / 2.0 + s.age.msin() * 0.05) + base, + ); + } } diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 16d5dfa7b..3b773e001 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -12,15 +12,16 @@ use super::{ nav::NavKind, path::PathType, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; // Guardian state: `flag` an active beam target (DATA_ID_ATTACK_TARGET), // `flag2` moving (DATA_ID_MOVING), `counter2` the client attack time. // AnimState slots: tail animation, its speed, spikes animation. -const TAIL: usize = 0; +pub const TAIL: usize = 0; const TAIL_SPEED: usize = 1; -const SPIKES: usize = 2; +pub const SPIKES: usize = 2; const EYE_X: usize = 3; const EYE_Y: usize = 4; @@ -166,8 +167,8 @@ pub fn move_control(m: &mut Mob) { let t = f64::from(m.age as i32 + m.id as i32); let push = (t * 0.5).sin() * 0.05; let (cos, sin) = ( - f64::from(m.yaw.to_radians().cos()), - f64::from(m.yaw.to_radians().sin()), + f64::from(m.yaw.to_radians().mcos()), + f64::from(m.yaw.to_radians().msin()), ); let y_push = (t * 0.75).sin() * 0.05; m.velocity = m.velocity.add_vector(Vec3::new( @@ -277,7 +278,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; let yaw = m.head_yaw.to_radians(); let pitch = m.head_pitch.to_radians(); - let view = [-yaw.sin() * pitch.cos(), yaw.cos() * pitch.cos()]; + let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; let d = [m.position.x - look[0], m.position.z - look[2]]; let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); @@ -365,7 +366,7 @@ pub fn beam_geometry( 128u32.saturating_sub((cs * 64.0) as u32), ); let color = 0xFF00_0000 | (b.min(255) << 16) | (g.min(255) << 8) | r.min(255); - let at = |a: f32, radius: f32| (a.cos() * radius, a.sin() * radius); + let at = |a: f32, radius: f32| (a.mcos() * radius, a.msin() * radius); let quarter = std::f32::consts::FRAC_PI_4; let (wx, wz) = at(rot + PI, 0.2); let (ex, ez) = at(rot, 0.2); @@ -432,7 +433,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { 8.0, -8.0, 0.0, 0.0, -8.0, -8.0, 8.0, 8.0, 8.0, -8.0, 0.0, 0.0, ]; for i in 0..12 { - let offset = 1.0 + (s.age * 1.5 + i as f32).cos() * 0.01 - withdrawal; + let offset = 1.0 + (s.age * 1.5 + i as f32).mcos() * 0.01 - withdrawal; let part = p.get(&format!("spike{i}")); part[0] = X[i] * offset; part[1] = 16.0 + Y[i] * offset; @@ -442,7 +443,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { e[0] = m.anim.v[EYE_X]; e[1] = m.anim.v[EYE_Y]; let tail = m.anim.lerp(TAIL, s.partial); - p.yrot("tail0", tail.sin() * PI * 0.05); - p.yrot("tail1", tail.sin() * PI * 0.1); - p.yrot("tail2", tail.sin() * PI * 0.15); + p.yrot("tail0", tail.msin() * PI * 0.05); + p.yrot("tail1", tail.msin() * PI * 0.1); + p.yrot("tail2", tail.msin() * PI * 0.15); } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 2351916ad..7af4a579a 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -9,6 +9,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; @@ -304,8 +305,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..5 { let a = angle + i as f32 * PI * 0.4; place( - x + f64::from(a.cos()) * 1.5, - z + f64::from(a.sin()) * 1.5, + x + f64::from(a.mcos()) * 1.5, + z + f64::from(a.msin()) * 1.5, a, 0, ); @@ -313,8 +314,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..8 { let a = angle + i as f32 * PI * 2.0 / 8.0 + PI * 2.0 / 5.0; place( - x + f64::from(a.cos()) * 2.5, - z + f64::from(a.sin()) * 2.5, + x + f64::from(a.mcos()) * 2.5, + z + f64::from(a.msin()) * 2.5, a, 3, ); @@ -323,8 +324,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..16 { let reach = 1.25 * f64::from(i + 1); place( - x + f64::from(angle.cos()) * reach, - z + f64::from(angle.sin()) * reach, + x + f64::from(angle.mcos()) * reach, + z + f64::from(angle.msin()) * reach, angle, i, ); @@ -532,8 +533,9 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { pitch, )); } -#[derive(Clone, Copy, PartialEq, Eq)] -enum ArmPose { +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ArmPose { + BowAndArrow, Spellcasting, Crossed, Celebrating, @@ -578,35 +580,53 @@ pub fn shows_item(m: &Mob) -> bool { m.species() != Species::Vindicator || m.ai.aggressive } fn hide(p: &mut Poses, part: &str) { - if p.has(part) { - let v = p.get(part); - v[6] = 0.0; - v[7] = 0.0; - v[8] = 0.0; - } + p.visible(part, false); } /// `IllagerModel.setupAnim`. pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + anim_pose(m, s, p, arm_pose(m)); +} +/// `IllagerModel.setupAnim` for a given arm pose. +pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { + // The hat is hidden by the model's constructor. + hide(p, "hat"); let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); p.yrot("head", hy); p.xrot("head", hx); let (pos, sp) = (s.pos, s.speed); - p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5); - p.yrot("right_arm", 0.0); - p.zrot("right_arm", 0.0); - p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5); - p.yrot("left_arm", 0.0); - 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); - let pose = arm_pose(m); + if m.extra.passenger { + for arm in ["right_arm", "left_arm"] { + p.xrot(arm, -PI / 5.0); + p.yrot(arm, 0.0); + p.zrot(arm, 0.0); + } + p.xrot("right_leg", -1.413_716_7); + p.yrot("right_leg", PI / 10.0); + p.zrot("right_leg", 0.078_539_82); + p.xrot("left_leg", -1.413_716_7); + p.yrot("left_leg", -PI / 10.0); + p.zrot("left_leg", -0.078_539_82); + } else { + p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5); + p.yrot("right_arm", 0.0); + p.zrot("right_arm", 0.0); + p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5); + p.yrot("left_arm", 0.0); + p.zrot("left_arm", 0.0); + p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp * 0.5); + p.yrot("right_leg", 0.0); + p.zrot("right_leg", 0.0); + p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp * 0.5); + p.yrot("left_leg", 0.0); + p.zrot("left_leg", 0.0); + } match pose { ArmPose::Attacking => { if m.extra.main_hand.is_none() { // animateZombieArms + bobArms let swing = s.swing; - let a = (swing * PI).sin(); - let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let a = (swing * PI).msin(); + let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", -(0.1 - a * 0.6)); @@ -617,22 +637,25 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { } else { // swingWeaponDown (right-handed). let swing = s.swing; - let a2 = (swing * PI).sin(); - let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let a2 = (swing * PI).msin(); + let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( "right_arm", - -1.884_955_8 + (s.age * 0.09).cos() * 0.15 + (a2 * 2.2 - a * 0.4), + -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), + ); + p.xrot( + "left_arm", + -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); - p.xrot("left_arm", (s.age * 0.19).cos() * 0.5); } let bob = |p: &mut Poses, part: &str, sign: f32| { let v = p.get(part); - v[5] += sign * ((s.age * 0.09).cos() * 0.05 + 0.05); - v[3] += sign * (s.age * 0.067).sin() * 0.05; + v[5] += sign * ((s.age * 0.09).mcos() * 0.05 + 0.05); + v[3] += sign * (s.age * 0.067).msin() * 0.05; }; bob(p, "right_arm", 1.0); bob(p, "left_arm", -1.0); @@ -659,7 +682,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let v = p.get(arm); v[2] = 0.0; v[0] = x; - v[3] = (s.age * 0.6662).cos() * 0.25; + v[3] = (s.age * 0.6662).mcos() * 0.25; v[4] = 0.0; v[5] = z_rot; } @@ -672,11 +695,18 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let v = p.get(arm); v[2] = 0.0; v[0] = x; - v[3] = (s.age * 0.6662).cos() * 0.05; + v[3] = (s.age * 0.6662).mcos() * 0.05; v[4] = 0.0; v[5] = z_rot; } } + ArmPose::BowAndArrow => { + 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::Crossed | ArmPose::Neutral => {} } if pose == ArmPose::Crossed { diff --git a/crates/horizon-client/src/mobs/nether.rs b/crates/horizon-client/src/mobs/nether.rs index 984ee1b27..e95547f84 100644 --- a/crates/horizon-client/src/mobs/nether.rs +++ b/crates/horizon-client/src/mobs/nether.rs @@ -10,6 +10,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -181,25 +182,25 @@ pub fn blaze_anim(s: &State, p: &mut Poses) { let mut angle = age * PI * -0.1; for i in 0..4 { let part = p.get(&format!("part{i}")); - part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).cos(); - part[0] = angle.cos() * 9.0; - part[2] = angle.sin() * 9.0; + part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).mcos(); + part[0] = angle.mcos() * 9.0; + part[2] = angle.msin() * 9.0; angle += PI / 2.0; } angle = PI / 4.0 + age * PI * 0.03; for i in 4..8 { let part = p.get(&format!("part{i}")); - part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).cos(); - part[0] = angle.cos() * 7.0; - part[2] = angle.sin() * 7.0; + part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).mcos(); + part[0] = angle.mcos() * 7.0; + part[2] = angle.msin() * 7.0; angle += PI / 2.0; } angle = 0.471_238_94 + age * PI * -0.05; for i in 8..12 { let part = p.get(&format!("part{i}")); - part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).cos(); - part[0] = angle.cos() * 5.0; - part[2] = angle.sin() * 5.0; + part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).mcos(); + part[0] = angle.mcos() * 5.0; + part[2] = angle.msin() * 5.0; angle += PI / 2.0; } p.yrot("head", s.y_rot.to_radians()); @@ -365,7 +366,7 @@ impl Goal for GhastShoot { } if self.charge == 20 { let yaw = m.yaw.to_radians(); - let view = [-f64::from(yaw.sin()), f64::from(yaw.cos())]; + let view = [-f64::from(yaw.msin()), f64::from(yaw.mcos())]; let half = f64::from(m.height()) * 0.5; let ty = (t.bounds.min_position().y + t.bounds.max_position().y) * 0.5; let dir = [ @@ -404,7 +405,7 @@ pub fn ghast_anim(s: &State, p: &mut Poses) { for i in 0..9 { let name = format!("tentacle{i}"); if p.has(&name) { - p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).sin() + 0.4); + p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).msin() + 0.4); } } } diff --git a/crates/horizon-client/src/mobs/phantom.rs b/crates/horizon-client/src/mobs/phantom.rs index 33ce2c59d..a6be959ef 100644 --- a/crates/horizon-client/src/mobs/phantom.rs +++ b/crates/horizon-client/src/mobs/phantom.rs @@ -5,6 +5,7 @@ use super::{ control::MoveKind, goals::{Cx, Goal, MOVE, TARGET, goal_clone, reduced}, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; /// Phantom state in `Extra`: `flag` swooping, `home` the anchor, @@ -151,9 +152,9 @@ impl CircleAroundAnchor { ]); self.angle += self.clockwise * 15.0f32.to_radians(); m.extra.vector = [ - f64::from(a[0]) + f64::from(self.distance * self.angle.cos()), + f64::from(a[0]) + f64::from(self.distance * self.angle.mcos()), f64::from(a[1]) + f64::from(-4.0 + self.height), - f64::from(a[2]) + f64::from(self.distance * self.angle.sin()), + f64::from(a[2]) + f64::from(self.distance * self.angle.msin()), ]; } } @@ -319,9 +320,9 @@ pub fn move_control(m: &mut Mob) { let x_rot = -((-dy).atan2(sd) as f32).to_degrees(); m.head_pitch = x_rot; let move_angle = (m.yaw + 90.0).to_radians(); - let tx = f64::from(speed * move_angle.cos()) * (dx / sd2).abs(); - let tz = f64::from(speed * move_angle.sin()) * (dz / sd2).abs(); - let ty = f64::from(speed * x_rot.to_radians().sin()) * (dy / sd2).abs(); + let tx = f64::from(speed * move_angle.mcos()) * (dx / sd2).abs(); + let tz = f64::from(speed * move_angle.msin()) * (dz / sd2).abs(); + let ty = f64::from(speed * x_rot.to_radians().msin()) * (dy / sd2).abs(); let v = m.velocity; m.velocity = Vec3::new( v.x + (tx - v.x) * 0.2, @@ -336,20 +337,20 @@ pub fn move_control(m: &mut Mob) { /// `PhantomModel.setupAnim` (flap time offset by the id). pub fn anim(m: &Mob, s: &super::anim::State, p: &mut super::anim::Poses) { let flap = (m.id as f32 * 3.0 + s.age) * 7.448_451_f32.to_radians(); - let wing = flap.cos() * 16.0f32.to_radians(); + let wing = flap.mcos() * 16.0f32.to_radians(); p.zrot("left_wing_base", wing); p.zrot("left_wing_tip", wing); p.zrot("right_wing_base", -wing); p.zrot("right_wing_tip", -wing); - let tail = -(5.0 + (flap * 2.0).cos() * 5.0f32).to_radians(); + let tail = -(5.0 + (flap * 2.0).mcos() * 5.0f32).to_radians(); p.xrot("tail_base", tail); p.xrot("tail_tip", tail); } /// The flap sound when a wingbeat begins (`Phantom.isFlapping`). pub fn flap_sound(m: &Mob, events: &mut Vec) { let t = m.id as f32 * 3.0 + m.age as f32; - let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); - let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); + let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos(); + let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos(); if a > 0.0 && b <= 0.0 { events.push(MobEvent::Sound( "entity.phantom.flap", diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index f5a70bd6c..410364097 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -9,6 +9,7 @@ use super::{ NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -251,48 +252,112 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }; cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0)); } +/// `AbstractPiglinModel.setupAnim`: the ears flap around their default angle +/// (30 degrees for adults, 5 for babies). +pub fn ears(p: &mut Poses, s: &State) { + use horizon_core::geometry::trig::DEG_TO_RAD; + let default = if s.baby { 5.0 } else { 30.0 } * DEG_TO_RAD; + let freq = s.age * 0.1 + s.pos * 0.5; + let amp = 0.08 + s.speed * 0.4; + p.zrot("left_ear", -default - (freq * 1.2).mcos() * amp); + p.zrot("right_ear", default + freq.mcos() * amp); +} /// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the /// arm pose (`PiglinModel`). pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { - super::anim::humanoid_item(p, s, m.extra.main_hand.is_some()); - let default = PI / 6.0; - let freq = s.age * 0.1 + s.pos * 0.5; - let amp = 0.08 + s.speed * 0.4; - p.zrot("left_ear", -default - (freq * 1.2).cos() * amp); - p.zrot("right_ear", default + freq.cos() * amp); - let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); - if m.extra.using_item > 0 { - // ADMIRING_ITEM: head down at the left hand. - p.xrot("head", 0.5); - p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + let pose = if m.extra.using_item > 0 { + PiglinPose::AdmiringItem } else if m.extra.flag { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - let a = (m.extra.using_item as f32).clamp(0.0, 25.0) / 25.0; - p.yrot("left_arm", 0.4 + 0.45 * a); - p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a); + PiglinPose::CrossbowCharge } else if m.extra.main_hand.as_deref() == Some("minecraft:crossbow") && m.ai.aggressive { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } else if m.ai.aggressive && m.extra.main_hand.is_some() && s.swing == 0.0 { - p.xrot("right_arm", -1.8); + PiglinPose::CrossbowHold + } else if m.ai.aggressive && m.extra.main_hand.is_some() { + PiglinPose::MeleeWeapon + } else { + PiglinPose::Default + }; + piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); +} +/// `PiglinArmPose`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PiglinPose { + Default, + Dancing, + MeleeWeapon, + CrossbowHold, + CrossbowCharge, + AdmiringItem, +} +/// `PiglinModel.setupAnim` for a piglin facing right-handed. +pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { + use super::anim::{ArmPose, Hum, humanoid}; + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.charge = (max_charge, ticks); + humanoid(p, s, &h); + ears(p, s); + let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); + let rad = |v: f64| v as f32; + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + match pose { + PiglinPose::Dancing => { + let dance = s.age / 60.0; + p.zrot( + "right_ear", + rad(std::f64::consts::PI / 6.0) + deg * (dance * 30.0).msin() * 10.0, + ); + p.zrot( + "left_ear", + rad(-std::f64::consts::PI / 6.0) - deg * (dance * 30.0).mcos() * 10.0, + ); + p.get("head")[0] += (dance * 10.0).msin(); + p.get("head")[1] += (dance * 40.0).msin() + 0.4; + let z = deg * (70.0 + (dance * 40.0).mcos() * 10.0); + p.zrot("right_arm", z); + p.zrot("left_arm", -z); + p.get("right_arm")[1] += (dance * 40.0).msin() * 0.5 - 0.5; + p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; + p.get("body")[1] += (dance * 40.0).msin() * 0.35; + } + PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), + PiglinPose::CrossbowHold => { + p.yrot("right_arm", -0.3 + hy); + p.yrot("left_arm", 0.6 + hy); + p.xrot("right_arm", -PI / 2.0 + hx + 0.1); + p.xrot("left_arm", -1.5 + hx); + } + PiglinPose::CrossbowCharge => { + p.yrot("right_arm", -0.8); + p.xrot("right_arm", -0.970_796_35); + p.xrot("left_arm", -0.970_796_35); + let alpha = ticks.clamp(0.0, max_charge) / max_charge; + p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); + let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); + p.xrot("left_arm", x); + } + PiglinPose::AdmiringItem => { + p.xrot("head", 0.5); + p.yrot("head", 0.0); + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } + _ => {} } } /// `HoglinModel.setupAnim`. pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) { let (pos, sp) = (s.pos, s.speed); - p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.sin()); - p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.sin()); + p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.msin()); + p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.msin()); p.yrot("head", s.y_rot.to_radians()); let remaining = m.extra.anim_ticks as f32; let f = 1.0 - (10.0 - 2.0 * remaining).abs() / 10.0; p.xrot("head", 0.872_664_63 + (-PI / 9.0 - 0.872_664_63) * f); - p.xrot("right_front_leg", pos.cos() * 1.2 * sp); - p.xrot("left_front_leg", (pos + PI).cos() * 1.2 * sp); - p.xrot("right_hind_leg", (pos + PI).cos() * 1.2 * sp); - p.xrot("left_hind_leg", pos.cos() * 1.2 * sp); + if s.baby { + p.get("head")[1] += f * 2.5; + } + p.xrot("right_front_leg", pos.mcos() * 1.2 * sp); + p.xrot("left_front_leg", (pos + PI).mcos() * 1.2 * sp); + p.xrot("right_hind_leg", (pos + PI).mcos() * 1.2 * sp); + p.xrot("left_hind_leg", pos.mcos() * 1.2 * sp); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 0166a21c3..be30712f0 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -7,6 +7,7 @@ use super::{ goals::{Float, HurtByTarget, LookAtPlayer, MeleeAttack, NearestTarget, Stroll}, path::PathType, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -134,9 +135,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Particles { kind: "entity_effect", at: [ - m.position.x - width * f64::from(yaw.sin()), + m.position.x - width * f64::from(yaw.msin()), m.position.y + f64::from(m.height()) - 0.3, - m.position.z + width * f64::from(yaw.cos()), + m.position.z + width * f64::from(yaw.mcos()), ], count: 0, }); @@ -225,34 +226,35 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let neck_x_rot = p.get("neck")[3]; let neck = p.get("neck"); neck[2] = -6.5 + head; - neck[1] = -7.0 - head * neck_x_rot.sin(); + neck[1] = -7.0 - head * neck_x_rot.msin(); let mouth = if attack > 5.0 { - ((-4.0 + attack) / 4.0).sin() * PI * 0.4 + ((-4.0 + attack) / 4.0).msin() * PI * 0.4 } else { - PI / 20.0 * (PI * attack / 10.0).sin() + PI / 20.0 * (PI * attack / 10.0).msin() }; p.xrot("mouth", mouth); } else { let is_stunned = stunned > 0.0; let x_rot: f32 = if is_stunned { 0.219_911_49 } else { 0.0 }; let neck = p.get("neck"); + let y_offset = -neck[3].msin(); neck[0] = 0.0; - neck[1] = -7.0 + x_rot.sin(); + neck[1] = -7.0 - y_offset; neck[2] = 5.5; neck[3] = x_rot; p.xrot("mouth", PI * if is_stunned { 0.05 } else { 0.01 }); if is_stunned { - p.get("neck")[0] = ((stunned / 40.0) * 10.0).sin() * 3.0; + p.get("neck")[0] = ((f64::from(stunned) / 40.0) * 10.0).sin() as f32 * 3.0; } else if m.extra.anim_ticks > 0 { let roar = (20.0 - m.extra.anim_ticks as f32 + s.partial) / 20.0; - p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).sin()); + p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).msin()); } } p.xrot("head", s.x_rot.to_radians()); p.yrot("head", s.y_rot.to_radians()); let (pos, leg) = (s.pos, 0.4 * s.speed); - p.xrot("right_hind_leg", (pos * 0.6662).cos() * leg); - p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * leg); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * leg); - p.xrot("left_front_leg", (pos * 0.6662).cos() * leg); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * leg); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * leg); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * leg); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * leg); } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index d640b6973..46513a311 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -8,6 +8,7 @@ use super::{ living::wrap, }; use crate::mesher::Vertex; +use horizon_core::geometry::trig::Mth; use std::f32::consts::PI; /// A texture lookup into the shared atlas (name without namespace -> uv rect). @@ -667,7 +668,7 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha) / 28.0) .clamp(0.0, 1.0); - let wobble = 1.0 + (s * 100.0).sin() * s * 0.01; + let wobble = 1.0 + (s * 100.0).msin() * s * 0.01; let s4 = s * s * s * s; let xz = (1.0 + s4 * 0.4) * wobble; let y = (1.0 + s4 * 0.1) / wobble; @@ -699,10 +700,10 @@ pub fn draw( p[3], )) * glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8])); - if p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 { + if poses.is_hidden(part) || p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 { return; } - for poly in &part.polygons { + for poly in part.polygons.iter().filter(|_| !poses.skips(part)) { for v in poly.vertices { let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); out.push(Vertex { diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index b40ddbf0a..11ebdadb4 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -11,6 +11,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileWorld, STEPS}; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -20,7 +21,7 @@ use std::f32::consts::PI; // Shulker state: `variant3` the attach face (3D data value), `counter` the // raw peek (0..100), `color` the shell colour (16 none). AnimState slot 0 // the current peek amount. -const PEEK: usize = 0; +pub const PEEK: usize = 0; pub const NO_COLOR: u8 = 16; pub fn register(m: &mut Mob) { @@ -335,14 +336,14 @@ pub fn rotations(m: &Mob) -> glam::Mat4 { pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let peek = m.anim.lerp(PEEK, s.partial); let bs = (0.5 + peek) * PI; - let q = -1.0 + bs.sin(); + let q = -1.0 + bs.msin(); let extra = if bs > PI { - (s.age * 0.1).sin() * 0.7 + (s.age * 0.1).msin() * 0.7 } else { 0.0 }; let lid = p.get("lid"); - lid[1] = 16.0 + bs.sin() * 8.0 + extra; + lid[1] = 16.0 + bs.msin() * 8.0 + extra; lid[4] = if peek > 0.3 { q * q * q * q * PI * 0.125 } else { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 1d38d4789..96b98dd78 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1221,6 +1221,9 @@ impl Def { Species::Hoglin => &["hoglin_baby"], Species::Zoglin => &["zoglin_baby"], Species::Strider => &["strider_baby"], + Species::Camel => &["camel_baby"], + Species::ZombieHorse => &["zombie_horse_baby"], + Species::SkeletonHorse => &["skeleton_horse_baby"], _ => &[], }; v.extend_from_slice(extra); diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1b6ef9d66..c00706b89 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -10,6 +10,7 @@ use super::{ reduced, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -54,8 +55,8 @@ pub fn wolf_variant_for(biome: &str, has_tag: &dyn Fn(&str) -> bool) -> u8 { pub const RED: u8 = 14; // AnimState slots: begging interest and the shake animation. -const INTEREST: usize = 0; -const SHAKE: usize = 1; +pub const INTEREST: usize = 0; +pub const SHAKE: usize = 1; pub fn register(m: &mut Mob) { m.extra.color = RED; @@ -537,7 +538,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.anim.vo[SHAKE] = 0.0; } if m.anim.v[SHAKE] > 0.4 { - let count = (((m.anim.v[SHAKE] - 0.4) * PI).sin() * 7.0) as u32; + let count = (((m.anim.v[SHAKE] - 0.4) * PI).msin() * 7.0) as u32; if count > 0 { events.push(MobEvent::Particles { kind: "splash", @@ -576,7 +577,7 @@ fn tail_angle(m: &Mob) -> f32 { /// `WolfRenderState.getBodyRollAngle`. fn body_roll(shake: f32, offset: f32) -> f32 { let p = ((shake + offset) / 1.8).clamp(0.0, 1.0); - (p * PI).sin() * (p * PI * 11.0).sin() * 0.15 * PI + (p * PI).msin() * (p * PI * 11.0).msin() * 0.15 * PI } /// `WolfModel.setupAnim` with the adult and baby overrides. pub fn anim(m: &Mob, s: &State, p: &mut Poses) { @@ -585,7 +586,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { if angry(m) { p.yrot("tail", 0.0); } else { - p.yrot("tail", (pos * 0.6662).cos() * 1.4 * speed); + p.yrot("tail", (pos * 0.6662).mcos() * 1.4 * speed); } if m.extra.sitting { let age = if baby { 0.5 } else { 1.0 }; @@ -615,10 +616,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("upper_body", 0.0); } } else { - p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * speed); - p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed); - p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * speed); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed); } // shakeOffWater let shake = m.anim.lerp(SHAKE, s.partial); @@ -946,26 +947,39 @@ pub fn cat_rotations(m: &Mob, partial: f32) -> glam::Mat4 { glam::Mat4::from_translation(glam::Vec3::new(0.4 * lie, 0.15 * lie, 0.1 * lie)) * glam::Mat4::from_rotation_z((90.0 * lie).to_radians()) } +/// `Mth.rotLerp`: degrees-wrapping, applied by the feline models to radians. fn rot_lerp(t: f32, from: f32, to: f32) -> f32 { - let mut d = (to - from) % (PI * 2.0); - if d < -PI { - d += PI * 2.0; - } - if d >= PI { - d -= PI * 2.0; - } - from + t * d + from + t * super::living::wrap(to - from) } -/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats. +/// `FelineRenderState` values the feline models read. +#[derive(Clone, Copy, Debug, Default)] +pub struct Feline { + pub crouching: bool, + pub sprinting: bool, + pub sitting: bool, + pub lie_down: f32, + pub lie_down_tail: f32, + pub relax_one: f32, +} +/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats and ocelots. pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { - let baby = m.is_baby(); - let age = if baby { 0.5 } else { 1.0 }; let wanted = m.ai.mov.has_wanted(); let speed_mod = m.ai.mov.speed_modifier; // Cat.customServerAiStep: crouch while stalking, sprint while dashing. - let crouching = wanted && (speed_mod - 0.6).abs() < 1e-6; - let sprinting = wanted && (speed_mod - 1.33).abs() < 1e-6; - let sitting = cat_sitting(m); + let st = Feline { + crouching: wanted && (speed_mod - 0.6).abs() < 1e-6, + sprinting: wanted && (speed_mod - 1.33).abs() < 1e-6, + sitting: cat_sitting(m), + lie_down: m.anim.lerp(LIE, s.partial), + lie_down_tail: m.anim.lerp(LIE_TAIL, s.partial), + relax_one: m.anim.lerp(RELAX, s.partial), + }; + feline(p, s, &st); +} +pub fn feline(p: &mut Poses, s: &State, st: &Feline) { + let baby = s.baby; + let age = if baby { 0.5 } else { 1.0 }; + let (crouching, sprinting, sitting) = (st.crouching, st.sprinting, st.sitting); let add = |p: &mut Poses, part: &str, x: f32, y: f32, z: f32| { let v = p.get(part); v[0] += x; @@ -994,18 +1008,18 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("body", PI / 2.0); } if sprinting { - p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp); - p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).cos() * sp); - p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).cos() * sp); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.cos() * sp); + p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp); + p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).mcos() * sp); + p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).mcos() * sp); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.mcos() * sp); } else { - p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp); - p.xrot("right_hind_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("left_front_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("right_front_leg", (pos * 0.6662).cos() * sp); + p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp); + p.xrot("right_hind_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("left_front_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("right_front_leg", (pos * 0.6662).mcos() * sp); let swing = if crouching { 0.471_238_94 } else { PI / 4.0 }; - p.xrot("tail2", 1.727_876_1 + swing * pos.cos() * sp); + p.xrot("tail2", 1.727_876_1 + swing * pos.mcos() * sp); } } else if baby { let x = p.get("body")[3] - 0.436_332_32; @@ -1034,9 +1048,31 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("right_hind_leg", -PI / 2.0); add(p, "right_hind_leg", 0.0, 3.0 * age, -4.0 * age); } - let lie = m.anim.lerp(LIE, s.partial); - let lie_tail = m.anim.lerp(LIE_TAIL, s.partial); - if lie > 0.0 && !baby { + let lie = st.lie_down; + let lie_tail = st.lie_down_tail; + if lie > 0.0 && baby { + add(p, "body", 1.0, 0.0, 0.0); + let hx = p.get("head")[3]; + p.xrot("head", rot_lerp(lie, hx, PI / 18.0)); + let hz = p.get("head")[5]; + p.zrot("head", rot_lerp(lie, hz, -PI * 5.0 / 12.0)); + add(p, "head", 1.5, 0.75, -0.5); + p.xrot("right_front_leg", -PI / 4.0); + add(p, "right_front_leg", 3.5, -0.5, 0.0); + p.xrot("left_front_leg", -PI / 2.0); + add(p, "left_front_leg", 1.5, -1.0, -2.0); + p.xrot("right_hind_leg", PI * 2.0 / 9.0); + p.yrot("right_hind_leg", PI / 9.0); + p.zrot("right_hind_leg", -PI / 9.0); + add(p, "right_hind_leg", 2.5, -0.25, 0.5); + add(p, "left_hind_leg", 1.5, 0.0, -1.0); + let t = p.get("tail1"); + let (tx, ty, tz) = (t[3], t[4], t[5]); + p.xrot("tail1", tx + rot_lerp(lie_tail, tx, -PI / 6.0)); + p.yrot("tail1", ty + rot_lerp(lie_tail, ty, 0.0)); + p.zrot("tail1", tz + rot_lerp(lie_tail, tz, -PI / 18.0)); + add(p, "tail1", 1.0, 0.5, -0.25); + } else if lie > 0.0 { let (hz, hy) = (p.get("head")[5], p.get("head")[4]); p.zrot("head", rot_lerp(lie, hz, -1.270_796_3)); p.yrot("head", rot_lerp(lie, hy, 1.270_796_3)); @@ -1052,7 +1088,7 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("tail1", rot_lerp(lie_tail, t1, 0.8)); p.xrot("tail2", rot_lerp(lie_tail, t2, -0.4)); } - let relax = m.anim.lerp(RELAX, s.partial); + let relax = st.relax_one; if relax > 0.0 { let hx = p.get("head")[3]; p.xrot("head", rot_lerp(relax, hx, -0.581_776_44)); diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index 2ee444d84..19e873cb2 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -9,6 +9,7 @@ use super::{ Cx, Float, Goal, HurtByTarget, LookAtPlayer, MOVE, NearestTarget, goal_clone, reduced, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; @@ -224,19 +225,38 @@ pub fn ai_step(m: &mut Mob, w: &super::MobWorld) { pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("head", s.y_rot.to_radians()); p.xrot("head", s.x_rot.to_radians()); - let bob = (s.age * 5.5).to_radians().cos() * 0.1; + let bob = (s.age * 5.5 * horizon_core::geometry::trig::DEG_TO_RAD).mcos() * 0.1; p.zrot("right_arm", PI / 5.0 + bob); p.zrot("left_arm", -(PI / 5.0 + bob)); if m.extra.flag { p.xrot("body", 0.0); - // Holding the sword in the right hand. - p.xrot("right_arm", PI * 7.0 / 6.0); - p.yrot("right_arm", PI / 12.0); - p.zrot("right_arm", -0.471_238_88 - bob); + // setArmsCharging + let (right, left) = (m.extra.main_hand.is_some(), m.extra.off_hand.is_some()); + if !right && !left { + p.xrot("right_arm", -1.221_730_5); + p.yrot("right_arm", PI / 12.0); + p.zrot("right_arm", -0.471_238_88 - bob); + p.xrot("left_arm", -1.221_730_5); + p.yrot("left_arm", -PI / 12.0); + p.zrot("left_arm", 0.471_238_88 + bob); + } else { + let sword = (std::f64::consts::PI * 7.0 / 6.0) as f32; + if right { + p.xrot("right_arm", sword); + p.yrot("right_arm", PI / 12.0); + p.zrot("right_arm", -0.471_238_88 - bob); + } + if left { + p.xrot("left_arm", sword); + p.yrot("left_arm", -PI / 12.0); + p.zrot("left_arm", 0.471_238_88 + bob); + } + } } else { p.xrot("body", PI / 20.0); } - let wing = 1.099_557_4 + (s.age * 45.836_624).to_radians().cos() * 16.2_f32.to_radians(); + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + let wing = 1.099_557_4 + (s.age * 45.836_624 * deg).mcos() * deg * 16.2; p.yrot("left_wing", wing); p.yrot("right_wing", -wing); p.xrot("left_wing", 0.471_238_88); diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 82e7645bd..7b9df3c33 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -13,6 +13,7 @@ use super::{ }, }; use crate::items::ItemStack; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::{collections::HashMap, f32::consts::PI}; @@ -603,16 +604,16 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("head", if awake { s.y_rot.to_radians() } else { 0.0 }); p.xrot("head", if awake { s.x_rot.to_radians() } else { 0.0 }); if m.extra.ints[0] > 0 { - p.zrot("head", 0.3 * (0.45 * s.age).sin()); + p.zrot("head", 0.3 * (0.45 * s.age).msin()); p.xrot("head", 0.4); } else { p.zrot("head", 0.0); } - let leg = (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5; + let leg = (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5; p.xrot("right_leg", leg); p.xrot( "left_leg", - (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed * 0.5, + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed * 0.5, ); p.yrot("right_leg", 0.0); p.yrot("left_leg", 0.0); diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 9fc0b0171..32fea42c4 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -9,6 +9,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; pub fn register(m: &mut Mob) { @@ -258,20 +259,15 @@ pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("head", s.y_rot.to_radians()); p.xrot("head", s.x_rot.to_radians()); - p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5); + p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5); p.xrot( "left_leg", - (s.pos * 0.6662 + std::f32::consts::PI).cos() * 1.4 * s.speed * 0.5, + (s.pos * 0.6662 + std::f32::consts::PI).mcos() * 1.4 * s.speed * 0.5, ); let speed = 0.01 * (m.id % 10) as f32; - p.xrot( - "nose", - (s.age * speed).sin() * 4.5 * std::f32::consts::PI / 180.0, - ); - p.zrot( - "nose", - (s.age * speed).cos() * 2.5 * std::f32::consts::PI / 180.0, - ); + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + p.xrot("nose", (s.age * speed).msin() * 4.5 * deg); + p.zrot("nose", (s.age * speed).mcos() * 2.5 * deg); if m.extra.main_hand.is_some() { let n = p.get("nose"); n[0] = 0.0; diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index f7e34d2cc..5782723d1 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -13,6 +13,7 @@ use super::{ nav::NavKind, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; // Wither state: `counter` the invulnerable ticks, `counter2` the block @@ -102,9 +103,9 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] { } let a = (m.body_yaw + 180.0 * (i as f32 - 1.0)).to_radians(); [ - m.position.x + f64::from(a.cos()) * 1.3, + m.position.x + f64::from(a.mcos()) * 1.3, m.position.y + 2.2, - m.position.z + f64::from(a.sin()) * 1.3, + m.position.z + f64::from(a.msin()) * 1.3, ] } /// `performRangedAttack`: a skull from a head toward a point. @@ -348,13 +349,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot(head, (y - body).to_radians()); p.xrot(head, x.to_radians()); } - let anim = (s.age * 0.1).cos(); + let anim = (s.age * 0.1).mcos(); let rib = (0.065 + 0.05 * anim) * std::f32::consts::PI; p.xrot("ribcage", rib); let tail = p.get("tail"); tail[0] = -2.0; - tail[1] = 6.9 + rib.cos() * 10.0; - tail[2] = -0.5 + rib.sin() * 10.0; + tail[1] = 6.9 + rib.mcos() * 10.0; + tail[2] = -0.5 + rib.msin() * 10.0; p.xrot("tail", (0.265 + 0.1 * anim) * std::f32::consts::PI); p.yrot("center_head", s.y_rot.to_radians()); p.xrot("center_head", s.x_rot.to_radians()); diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 988f05177..bdc3529cf 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -23,6 +23,20 @@ pub fn cos(angle: f64) -> f32 { sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize] } +/// `Mth.sin` / `Mth.cos` on a float, as the models call them. +pub trait Mth { + fn msin(self) -> f32; + fn mcos(self) -> f32; +} +impl Mth for f32 { + fn msin(self) -> f32 { + sin(f64::from(self)) + } + fn mcos(self) -> f32 { + cos(f64::from(self)) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java new file mode 100644 index 000000000..a99361dc2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java @@ -0,0 +1,196 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.model.EntityModel; +import net.minecraft.client.model.geom.LayerDefinitions; +import net.minecraft.client.model.geom.ModelLayerLocation; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.renderer.entity.state.EntityRenderState; +import net.minecraft.server.Bootstrap; + +/** + * Original oracle for the client's entity model animation: bakes each vanilla model layer, builds + * its own render state class with the given walk/age/head/attack values plus optional extra + * fields, runs the real setupAnim and writes every part's pose. + * + * Input lines: "layer-key ModelClass|case-json" where case-json is an object of state field + * name to value. Output lines: {layer, case, parts:{path:[x,y,z,xRot,yRot,zRot,xScale,yScale,zScale,visible]}}. + */ +public final class VanillaEntityAnimOracle { + private static Field cubes; + private static Field children; + + @SuppressWarnings("unchecked") + private static void dump(String path, ModelPart part, JsonObject out) throws Exception { + var pose = new JsonArray(); + for (float f : new float[] {part.x, part.y, part.z, part.xRot, part.yRot, part.zRot, part.xScale, part.yScale, part.zScale}) + pose.add(f); + pose.add(part.visible && !part.skipDraw ? 1 : 0); + int polys = 0; + double sum = 0; + for (ModelPart.Cube cube : (List) cubes.get(part)) { + for (ModelPart.Polygon polygon : cube.polygons) { + polys++; + for (ModelPart.Vertex v : polygon.vertices()) { + float u = Float.isFinite(v.u()) ? v.u() : 0.0F, w = Float.isFinite(v.v()) ? v.v() : 0.0F; + sum += v.x() + 2.0 * v.y() + 3.0 * v.z() + 5.0 * u + 7.0 * w; + } + } + } + pose.add(polys); + pose.add(sum); + out.add(path, pose); + for (var entry : ((Map) children.get(part)).entrySet()) + dump(path.isEmpty() ? entry.getKey() : path + "/" + entry.getKey(), entry.getValue(), out); + } + + private static Class findClass(String simple) throws Exception { + for (String pkg : new String[] {"net.minecraft.client.model"}) { + // Search subpackages by trying every known class location through the jar index. + for (String name : CLASS_NAMES) { + if (name.endsWith("." + simple) || name.equals(simple)) return Class.forName(name); + } + } + throw new ClassNotFoundException(simple); + } + + private static final List CLASS_NAMES = new ArrayList<>(); + + private static Class raw(java.lang.reflect.Type t, Map, java.lang.reflect.Type> env) { + if (t instanceof Class c) return c; + if (t instanceof java.lang.reflect.ParameterizedType p) return raw(p.getRawType(), env); + if (t instanceof java.lang.reflect.TypeVariable v) { + var bound = env.get(v); + return raw(bound != null ? bound : v.getBounds()[0], env); + } + throw new IllegalArgumentException("cannot resolve " + t); + } + + /** The render state class: the model's `S`, resolved through its generic superclasses. */ + private static Class stateClass(Class model) { + var env = new HashMap, java.lang.reflect.Type>(); + Class current = model; + for (var v : current.getTypeParameters()) env.put(v, raw(v.getBounds()[0], env)); + while (current != net.minecraft.client.model.Model.class) { + var sup = current.getGenericSuperclass(); + if (sup instanceof java.lang.reflect.ParameterizedType p) { + var params = ((Class) p.getRawType()).getTypeParameters(); + for (int i = 0; i < params.length; i++) env.put(params[i], raw(p.getActualTypeArguments()[i], env)); + current = (Class) p.getRawType(); + } else { + current = (Class) sup; + } + } + return raw(net.minecraft.client.model.Model.class.getTypeParameters()[0], env); + } + + private static Field field(Class type, String name) { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredField(name); + } catch (NoSuchFieldException e) { + } + } + return null; + } + + private static void set(Object state, String name, JsonElement value) throws Exception { + boolean optional = name.startsWith("?") || Set.of("walkAnimationPos", "walkAnimationSpeed", "yRot", "xRot", "isBaby", "swingAnimation", "ageScale", "ageInTicks", "entityId", "yHeadRot", "yBodyRot", "eatTick", "flapOffset", "interest").contains(name); + if (name.startsWith("?")) name = name.substring(1); + Field f = field(state.getClass(), name); + if (f == null && optional) return; + if (f == null) throw new IllegalArgumentException("no field " + name + " on " + state.getClass()); + f.setAccessible(true); + Class t = f.getType(); + if (t == float.class) f.setFloat(state, value.getAsFloat()); + else if (t == int.class) f.setInt(state, value.getAsInt()); + else if (t == double.class) f.setDouble(state, value.getAsDouble()); + else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean()); + else if (t.isEnum()) { + for (Object c : t.getEnumConstants()) if (((Enum) c).name().equals(value.getAsString())) f.set(state, c); + } else if (t.getSimpleName().equals("AnimationState")) { + // value = age in ticks since start (negative = stopped) + var a = (net.minecraft.world.entity.AnimationState) f.get(state); + a.stop(); + if (value.getAsJsonPrimitive().isNumber()) a.start(value.getAsInt()); + } else throw new IllegalArgumentException("unsupported type " + t + " for " + name); + } + + /** Render-state values vanilla derives from entity state; the case gives the entity-side input. */ + private static void hooks(EntityRenderState state, JsonObject kase) { + if (state instanceof net.minecraft.client.renderer.entity.state.SheepRenderState sheep && kase.has("eatTick")) { + // Sheep.getHeadEatPositionScale / getHeadEatAngleScale at partial tick 0. + int t = kase.get("eatTick").getAsInt(); + float a = 0.0F; + sheep.headEatPositionScale = t <= 0 ? 0.0F : t >= 4 && t <= 36 ? 1.0F : t < 4 ? (t - a) / 4.0F : -(t - 40 - a) / 4.0F; + if (t > 4 && t <= 36) { + float scale = (t - 4 - a) / 32.0F; + sheep.headEatAngleScale = (float) (Math.PI / 5) + 0.21991149F * net.minecraft.util.Mth.sin(scale * 28.7F); + } else { + sheep.headEatAngleScale = t > 0 ? (float) (Math.PI / 5) : sheep.xRot * (float) (Math.PI / 180.0); + } + } + if (state instanceof net.minecraft.client.renderer.entity.state.WolfRenderState wolf && kase.has("interest")) + wolf.headRollAngle = kase.get("interest").getAsFloat() * 0.15F * (float) Math.PI; + if (state instanceof net.minecraft.client.renderer.entity.state.PhantomRenderState phantom && kase.has("flapOffset")) + phantom.flapTime = kase.get("flapOffset").getAsFloat() + phantom.ageInTicks; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + cubes = ModelPart.class.getDeclaredField("cubes"); + cubes.setAccessible(true); + children = ModelPart.class.getDeclaredField("children"); + children.setAccessible(true); + try (var zip = new java.util.zip.ZipFile(args[2])) { + zip.stream().map(e -> e.getName()).filter(n -> n.startsWith("net/minecraft/client/model/") && n.endsWith(".class")) + .forEach(n -> CLASS_NAMES.add(n.substring(0, n.length() - 6).replace('/', '.'))); + } + var roots = LayerDefinitions.createRoots(); + var byName = new HashMap(); + for (var key : roots.keySet()) byName.put(key.toString(), key); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + var halves = line.split("\\|", 2); + var head = halves[0].split(" "); + var layer = head[0]; + var kase = JsonParser.parseString(halves[1]).getAsJsonObject(); + var result = new JsonObject(); + result.addProperty("layer", layer); + result.add("case", kase); + try { + var location = byName.get(layer); + if (location == null) throw new IllegalArgumentException("no layer " + layer); + var cls = findClass(head[1]); + var baked = roots.get(location).bakeRoot(); + var model = (net.minecraft.client.model.Model) cls.getConstructor(ModelPart.class).newInstance(baked); + var type = stateClass(cls); + var state = (EntityRenderState) type.getDeclaredConstructor().newInstance(); + state.getClass(); + for (var entry : kase.entrySet()) set(state, entry.getKey(), entry.getValue()); + hooks(state, kase); + if (state instanceof net.minecraft.client.renderer.entity.state.ArmedEntityRenderState armed && armed.swingAnimation > 0) + armed.currentSwing = new net.minecraft.world.entity.LivingEntity.SwingDescription(net.minecraft.world.InteractionHand.MAIN_HAND, net.minecraft.world.item.component.SwingAnimation.DEFAULT, 6); + model.setupAnim(state); + var parts = new JsonObject(); + dump("", baked, parts); + result.add("parts", parts); + } catch (Throwable error) { + var cause = error.getCause() != null ? error.getCause() : error; + result.addProperty("error", cause.toString()); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py new file mode 100644 index 000000000..ed83a3b0e --- /dev/null +++ b/tools/test_entity_model_parity.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""Compare entity model geometry and setupAnim poses with the vanilla 26.3 client. + +The Java oracle bakes each vanilla model layer, builds the model's own render +state class with the generated walk/age/head/attack inputs (plus per-species +state fields), runs the real `setupAnim` and writes every part's pose. +`examples/entity_anim_fixture` replays the same inputs through Horizon's +`mobs::anim::setup` and the loaded model tree; the two must agree on every part +pose and on the baked polygon count and vertex sums. + + test_entity_model_parity.py [--filter SUBSTRING] [--detail LAYER] [--tolerance EPS] +""" +import argparse +import json +import math +import os +from pathlib import Path +import random +import re +import subprocess +import sys + +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 + +CLIENT = lab.LOCAL / 'minecraft' / '26.3' / 'sources' / 'client' / 'net' / 'minecraft' / 'client' + +# Models that no renderer builds with a plain `new Model(context.bakeLayer(CONSTANT))`. +EXTRAS = [ + ('minecraft:zombie#main', 'ZombieModel'), ('minecraft:zombie_baby#main', 'BabyZombieModel'), + ('minecraft:husk#main', 'ZombieModel'), ('minecraft:husk_baby#main', 'BabyZombieModel'), + ('minecraft:zombie_villager#main', 'ZombieVillagerModel'), + ('minecraft:zombie_villager_baby#main', 'BabyZombieVillagerModel'), + ('minecraft:zombified_piglin#main', 'AdultZombifiedPiglinModel'), + ('minecraft:zombified_piglin_baby#main', 'BabyZombifiedPiglinModel'), + ('minecraft:skeleton#main', 'SkeletonModel'), ('minecraft:stray#main', 'SkeletonModel'), + ('minecraft:wither_skeleton#main', 'SkeletonModel'), + ('minecraft:spider#main', 'SpiderModel'), ('minecraft:cave_spider#main', 'SpiderModel'), + ('minecraft:enderman#main', 'EndermanModel'), ('minecraft:endermite#main', 'EndermiteModel'), + ('minecraft:piglin#main', 'AdultPiglinModel'), ('minecraft:piglin_brute#main', 'AdultPiglinModel'), + ('minecraft:piglin_baby#main', 'BabyPiglinModel'), + ('minecraft:hoglin#main', 'HoglinModel'), ('minecraft:zoglin#main', 'HoglinModel'), + ('minecraft:hoglin_baby#main', 'BabyHoglinModel'), ('minecraft:zoglin_baby#main', 'BabyHoglinModel'), + ('minecraft:guardian#main', 'GuardianModel'), ('minecraft:elder_guardian#main', 'GuardianModel'), + ('minecraft:evoker#main', 'IllagerModel'), ('minecraft:illusioner#main', 'IllagerModel'), + ('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'), + ('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'), + ('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'), + ('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'), + ('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'), + ('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'), + ('minecraft:skeleton_horse_baby#main', 'BabyHorseModel'), ('minecraft:zombie_horse_baby#main', 'BabyHorseModel'), + ('minecraft:cave_spider#main', 'SpiderModel'), + ('minecraft:stray#main', 'SkeletonModel'), +] +# Layers a renderer reuses for another entity under a different constant. +SKIP_LAYERS = re.compile(r'(banner|bell|book|skull|head|chest|shulker_box|boat|cushion|conduit|leash|arrow|trident|' + r'shield|elytra|spin_attack|ears|cape|decorated_pot|minecart|wind_charge|evoker_fangs|' + r'llama_spit|shulker_bullet|bee_stinger|end_crystal|armor_stand|copper_golem|#(helmet|chestplate|leggings|' + r'boots|outer|armor|decor|saddle|collar|wool|wool_undercoat|eyes|wind|inner|pattern|tendrils|' + r'heart|bioluminescent|pulsating_spots|water_patch|flag|cage|shell)$)') + + +def layer_constant(name): + """minecraft:cow_baby#main -> constant COW_BABY (the main layer of a model).""" + return name.split(':')[1].split('#')[0].upper() + + +def renderer_pairs(): + pairs = {} + pattern = re.compile(r'new (\w+)\(\s*(?:context|this\.context|\w*)\.bakeLayer\(ModelLayers\.(\w+)\)') + for path in sorted((CLIENT / 'renderer').rglob('*.java')): + for match in pattern.finditer(path.read_text()): + pairs[match.group(2)] = match.group(1) + return pairs + + +def layers(models): + chosen = {} + pairs = renderer_pairs() + for key in models: + if not key.endswith('#main') or SKIP_LAYERS.search(key): + continue + constant = layer_constant(key) + if constant in pairs: + chosen[key] = pairs[constant] + for key, cls in EXTRAS: + if key in models: + chosen[key] = cls + return chosen + + +def cases(layer): + rng = random.Random(0x414e494d + sum(map(ord, layer))) + baby = '_baby#' in layer + base_cases = [ + (0.0, 0.0, 0.0, 0.0, 0.0, 0.0), + (1.0, 0.5, 10.0, 0.0, 0.0, 0.0), + (3.7, 0.6, 57.3, 20.0, -15.0, 0.0), + (12.25, 1.0, 123.5, -35.0, 40.0, 0.0), + (7.5, 0.3, 33.3, 5.0, 5.0, 0.35), + (2.0, 0.0, 77.7, 45.0, -60.0, 0.8), + ] + for _ in range(14): + base_cases.append((rng.uniform(0, 30), rng.uniform(0, 1), rng.uniform(0, 400), + rng.uniform(-50, 50), rng.uniform(-70, 70), + rng.choice([0.0, rng.uniform(0.01, 0.99)]))) + cases_out = [] + for pos, speed, age, y, x, attack in base_cases: + cases_out.append({'walkAnimationPos': pos, 'walkAnimationSpeed': speed, 'ageInTicks': age, + 'yRot': y, 'xRot': x, 'swingAnimation': attack, 'isBaby': baby, 'ageScale': 0.5 if baby else 1.0, + 'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0}) + name = layer.split(':')[1].split('#')[0].removesuffix('_baby') + cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out] + yield from cases_out + yield from species_cases(layer, cases_out) + + +T, F = True, False +FOX = [{'isCrouching': T, 'crouchAmount': 0.8}, {'isSleeping': T}, {'isSitting': T}, {'isPouncing': T, 'crouchAmount': 0.6}, + {'isFaceplanted': T}, {'headRollAngle': 0.3}, {'isCrouching': T, 'isPouncing': T, 'crouchAmount': 0.4}] +ILLAGER = [{'armPose': pose, 'maxCrossbowChargeDuration': 25, 'ticksUsingItem': 10.0} + for pose in ['NEUTRAL', 'CROSSED', 'ATTACKING', 'SPELLCASTING', 'BOW_AND_ARROW', 'CROSSBOW_HOLD', + 'CROSSBOW_CHARGE', 'CELEBRATING']] + [{'isRiding': T, 'armPose': 'CROSSED'}] +FELINE = [{'isCrouching': T}, {'isSprinting': T}, {'isSitting': T}, {'lieDownAmount': 0.7, 'lieDownAmountTail': 0.5}, + {'relaxStateOneAmount': 0.6}, {'isSitting': T, 'lieDownAmount': 1.0, 'lieDownAmountTail': 0.2}] +ZOMBIE = [{'isAggressive': T}, {'isCrouching': T}, {'isPassenger': T}, {'isAggressive': T, 'isPassenger': T, 'isCrouching': T}] +SKELETON = ZOMBIE + [{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW'}, {'isHoldingBow': T}, + {'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW', 'isCrouching': T}] +PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': 12.0} + for pose in ['DEFAULT', 'DANCING', 'ATTACKING_WITH_MELEE_WEAPON', 'CROSSBOW_HOLD', 'CROSSBOW_CHARGE', 'ADMIRING_ITEM']] +EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7}, + {'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}] +WATER = [{'isInWater': T}, {'isInWater': F}] +SPECIES = { + 'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE, + 'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}], + 'hoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)], + 'zoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)], + 'ravager': [{'stunnedTicksRemaining': 20.0}, {'attackTicksRemaining': 8.0}, {'attackTicksRemaining': 3.0}, + {'roarAnimation': 0.5}], + 'vex': [{'isCharging': T}, {'isCharging': F}], + 'squid': [{'tentacleAngle': 0.7}], 'glow_squid': [{'tentacleAngle': 1.2}], + 'dolphin': [{'isMoving': T}, {'isMoving': F}], + 'cod': WATER, 'salmon': WATER, 'tropical_fish_small': WATER, + 'allay': [{'isDancing': T, 'isSpinning': T, 'spinningProgress': 0.6}, {'isDancing': T, 'isSpinning': F, 'spinningProgress': 0.2}, + {'holdingAnimationProgress': 0.8}, {'holdingAnimationProgress': 1.0}], + 'camel': [{'sitAnimationState': 2}, {'sitPoseAnimationState': 3}, {'sitUpAnimationState': 1}, {'idleAnimationState': 4}, + {'dashAnimationState': 2}, {'jumpCooldown': 20.0}], + 'chicken': [{'flap': 2.0, 'flapSpeed': 0.7}, {'flap': 5.3, 'flapSpeed': 1.0}], + 'wolf': [{'isSitting': T}, {'isAngry': T, 'tailAngle': 1.5393804}, {'shakeAnim': 0.9}, {'interest': 0.6}, + {'isSitting': T, 'shakeAnim': 0.5, 'interest': 0.3}], + 'zombie': ZOMBIE, 'husk': ZOMBIE, 'drowned': ZOMBIE, 'zombie_villager': ZOMBIE, 'zombified_piglin': ZOMBIE, 'giant': ZOMBIE, + 'skeleton': SKELETON, 'stray': SKELETON, 'wither_skeleton': SKELETON, 'bogged': SKELETON, + 'piglin': PIGLIN, 'piglin_brute': PIGLIN, + 'cat': FELINE, 'ocelot': FELINE, + 'creaking': [{'canMove': F}, {'attackAnimationState': 2}, {'invulnerabilityAnimationState': 3}, {'deathAnimationState': 1}], + 'evoker': ILLAGER, 'pillager': ILLAGER, 'vindicator': ILLAGER, + 'sheep': [{'eatTick': t} for t in (2, 10, 36, 39)], + 'guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}, {'tailAnimation': 0.0, 'spikesAnimation': 0.0}], + 'elder_guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}], + 'shulker': [{'peekAmount': v} for v in (0.0, 0.2, 0.5, 1.0)], + 'witch': [{'isHoldingItem': T}, {'isHoldingItem': F}], + 'goat': [{'hasLeftHorn': T, 'hasRightHorn': T}, {'hasLeftHorn': F, 'hasRightHorn': T, 'rammingXHeadRot': 0.6}, + {'hasLeftHorn': T, 'hasRightHorn': F}], + 'polar_bear': [{'standScale': 0.0}, {'standScale': 0.5}, {'standScale': 1.0}], + 'panda': [{'isUnhappy': T}, {'isSneezing': T, 'sneezeTime': 5}, {'isSneezing': T, 'sneezeTime': 16}, + {'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3}, + {'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}], + 'llama': [{'hasChest': T}, {'hasChest': F}], + 'trader_llama': [{'hasChest': T}, {'hasChest': F}], + 'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}], + 'strider': [{'isRidden': T}, {'isRidden': F}], + 'parrot': [{'pose': pose, 'flapAngle': 0.4} for pose in ['STANDING', 'FLYING', 'ON_SHOULDER', 'SITTING', 'PARTY']], + 'bee': [{'hasStinger': T}, {'hasStinger': F, 'isOnGround': T}, {'isAngry': T}, {'rollAmount': 0.6, 'isAngry': T}, + {'isOnGround': T, 'hasStinger': T}], + 'bat': [{'isResting': T, 'restAnimationState': 3}, {'flyAnimationState': 2}, {'isResting': F, 'flyAnimationState': 0}], + 'armadillo': [{'isHidingInShell': T}, {'isHidingInShell': T, 'rollUpAnimationState': 2}, + {'rollOutAnimationState': 4}, {'peekAnimationState': 1}], + 'axolotl': [{'playingDeadFactor': 0.0, 'inWaterFactor': 1.0, 'onGroundFactor': 0.0, 'movingFactor': 1.0}, + {'inWaterFactor': 1.0, 'movingFactor': 0.0}, {'onGroundFactor': 1.0, 'movingFactor': 1.0}, + {'onGroundFactor': 1.0, 'movingFactor': 0.0}, {'inWaterFactor': 0.5, 'onGroundFactor': 0.5, 'movingFactor': 0.5}, + {'playingDeadFactor': 1.0, 'inWaterFactor': 1.0}, + {'walkAnimationState': 1}, {'swimAnimation': 2}, {'idleOnGroundAnimationState': 3}, + {'idleUnderWaterAnimationState': 2}, {'idleUnderWaterOnGroundAnimationState': 1}, {'playDeadAnimationState': 4}], + 'frog': [{'isSwimming': T}, {'isSwimming': F}, {'jumpAnimationState': 2}, {'croakAnimationState': 1}, + {'tongueAnimationState': 3}, {'swimIdleAnimationState': 2, 'isSwimming': T}], + 'rabbit': [{'hopAnimationState': 2}, {'idleHeadTiltAnimationState': 1}], + 'fox': FOX, +} + + +# Render-state defaults that are not zero/false in vanilla. +DEFAULTS = {'creaking': {'canMove': T}, 'wolf': {'tailAngle': 0.6283185307179586}, 'axolotl': {'inWaterFactor': 1.0}, 'bee': {'hasStinger': T}, 'sheep': {'eatTick': 0}, + 'goat': {'hasLeftHorn': T, 'hasRightHorn': T}, 'parrot': {'pose': 'STANDING'}, + 'phantom': {'flapOffset': 21.0}, 'guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}, + 'elder_guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}} + + +def species_cases(layer, base_cases): + name = layer.split(':')[1].split('#')[0].removesuffix('_baby') + for extra in SPECIES.get(name, []): + for index in (2, 3, 6): + yield {**base_cases[index], **extra} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--filter', default='') + parser.add_argument('--detail', default='') + parser.add_argument('--tolerance', type=float, default=5e-7) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-entity-model-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + models = json.loads((resources / 'entity-models.json').read_text()) + chosen = {k: v for k, v in layers(models).items() if args.filter in k} + extra_cases = json.loads((Path(__file__).with_suffix('.cases.json')).read_text()) \ + if Path(__file__).with_suffix('.cases.json').exists() else {} + lines = [] + for layer, cls in sorted(chosen.items()): + for case in cases(layer): + lines.append(f'{layer} {cls}|{json.dumps(case)}') + for case in extra_cases.get(layer.split(':')[1].split('#')[0], []): + lines.append(f'{layer} {cls}|{json.dumps(case)}') + inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(lines) + '\n') + classes = build / 'classes'; classes.mkdir(exist_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java' + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', + inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--', + resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust), (len(vanilla), len(rust)) + errors, skipped, mismatched, checked = {}, set(), {}, 0 + for v, r in zip(vanilla, rust): + layer = v['layer'] + if 'error' in v: + errors[layer] = v['error']; continue + if 'skip' in r: + skipped.add(layer); continue + checked += 1 + bad = [] + for path, expected in v['parts'].items(): + got = r['parts'].get(path) + if got is None: + bad.append((path, 'missing in Horizon')); continue + names = ['x', 'y', 'z', 'xRot', 'yRot', 'zRot', 'xScale', 'yScale', 'zScale', 'visible', 'polys', 'vsum'] + for i, (a, b) in enumerate(zip(expected, got)): + if i == 11 and abs(a - b) <= 1e-3 * max(1, abs(a)): + continue + if i == 9: + a, b = bool(a), bool(b) + if a != b: + bad.append((path, f'visible {a} != {b}')) + continue + if abs(a - b) > args.tolerance * (1.0 + abs(a)): + bad.append((path, f'{names[i]} {a!r} != {b!r}')) + for path in r['parts']: + if path not in v['parts']: + bad.append((path, 'extra in Horizon')) + if bad: + mismatched.setdefault(layer, []).append((v['case'], bad)) + print(f'{checked} cases compared over {len(chosen) - len(skipped) - len(errors)} layers') + if errors: + print('oracle errors:'); [print(' ', k, v) for k, v in sorted(errors.items())] + if skipped: + print('layers without a Horizon species:', ', '.join(sorted(skipped))) + for layer, items in sorted(mismatched.items()): + parts = {} + for case, bad in items: + for path, why in bad: + parts.setdefault(path, (why, case)) + total = sum(1 for x in vanilla if x['layer'] == layer) + print(f'MISMATCH {layer}: {len(items)}/{total} cases, {len(parts)} parts') + detailed = args.detail == layer + for path, (why, case) in list(parts.items())[:(10 ** 6 if detailed else 4)]: + print(f' {path or ""}: {why}' + (f' case={json.dumps(case)}' if detailed else '')) + if mismatched or errors: + sys.exit(f'{len(mismatched)} layers differ from vanilla') + print('entity model parity ok') + + +if __name__ == '__main__': + main() From 1d6b7b5a0cb27165be5ad33d7e3f392b22aae258 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:47:54 +0200 Subject: [PATCH 07/42] WIP: chunk parity structure fixes Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-world/examples/chunk_dump.rs | 15 ++++ crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/generator_structures.rs | 21 +++++ crates/horizon-world/src/worldgen/long_set.rs | 83 +++++++++++++++++++ .../horizon-world/src/worldgen/structure.rs | 16 ++++ .../parity/VanillaChunkGenerationOracle.java | 20 +++++ .../parity/VanillaStructureBlockExporter.java | 13 ++- 7 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/long_set.rs diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/chunk_dump.rs index e7e440252..199f7e26f 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/chunk_dump.rs @@ -128,6 +128,21 @@ fn main() -> Result<(), Error> { for z in z0..=z1 { for s in worker.structure_starts(ChunkPos::new(x, z)) { if s.chunk == ChunkPos::new(x, z) { + if std::env::var_os("HORIZON_PIECES").is_some() { + for piece in &s.pieces { + let b = piece.bounding_box(); + println!( + "piece {x} {z} {} {} {} {} {} {} {}", + piece.type_name(), + b.min[0], + b.min[1], + b.min[2], + b.max[0], + b.max[1], + b.max[2] + ); + } + } println!( "start {} {x} {z} {} {} {} {} {} {}", s.name, diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 36fb43fb3..4c9295af7 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -44,6 +44,7 @@ mod generator_structures; pub mod height_provider; pub mod iceberg; pub mod live; +mod long_set; pub mod material_condition; pub mod material_extensions; pub mod material_stage; diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 136c85264..ce584eaa4 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -10,6 +10,7 @@ use super::{ }; use horizon_core::{density::Beardifier, position::ChunkPos}; use serde_json::Value; +use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, sync::{Arc, Mutex, OnceLock}, @@ -252,6 +253,26 @@ impl StructureState { } } } + // Vanilla keeps each structure's references in a LongOpenHashSet and + // places the starts in its iteration order; reorder each structure's + // starts within the slots they already occupy. + let mut slots: BTreeMap> = BTreeMap::new(); + for (i, start) in out.iter().enumerate() { + slots.entry(start.structure).or_default().push(i); + } + let original = out.clone(); + for slots in slots.values().filter(|s| s.len() > 1) { + let keys: Vec = slots + .iter() + .map(|&i| { + let c = original[i].chunk; + i64::from(c.x as u32) | (i64::from(c.z as u32) << 32) + }) + .collect(); + for (&slot, &from) in slots.iter().zip(&super::long_set::iteration_order(&keys)) { + out[slot] = original[slots[from]].clone(); + } + } out } pub(super) fn beardifier( diff --git a/crates/horizon-world/src/worldgen/long_set.rs b/crates/horizon-world/src/worldgen/long_set.rs new file mode 100644 index 000000000..cfb79899e --- /dev/null +++ b/crates/horizon-world/src/worldgen/long_set.rs @@ -0,0 +1,83 @@ +//! Iteration order of fastutil's `LongOpenHashSet`, which vanilla uses for +//! structure references. Placing a structure's pieces consumes one shared +//! random stream, so starts must be visited in the set's order. + +const PHI: i64 = 0x9E37_79B9_7F4A_7C15_u64 as i64; +const LOAD_FACTOR: f64 = 0.75; + +fn mix(key: i64) -> usize { + let mut h = key.wrapping_mul(PHI); + h ^= ((h as u64) >> 32) as i64; + (h ^ (((h as u64) >> 16) as i64)) as i32 as u32 as usize +} + +fn array_size(expected: usize) -> usize { + ((expected as f64 / LOAD_FACTOR).ceil() as usize) + .next_power_of_two() + .max(2) +} + +fn max_fill(n: usize) -> usize { + ((n as f64 * LOAD_FACTOR).ceil() as usize).min(n - 1) +} + +/// Indices of `keys` (distinct, in insertion order) in the order a default +/// `LongOpenHashSet` holding them iterates: the zero key first, then the table +/// from its last slot down to its first. +pub fn iteration_order(keys: &[i64]) -> Vec { + let mut n = array_size(16); + let mut table: Vec> = vec![None; n]; + let mut contains_zero = None; + let mut size = 0; + for (index, &key) in keys.iter().enumerate() { + if key == 0 { + contains_zero = Some(index); + } else { + let mask = n - 1; + let mut pos = mix(key) & mask; + while table[pos].is_some() { + pos = (pos + 1) & mask; + } + table[pos] = Some(index); + } + size += 1; + if size - 1 >= max_fill(n) { + let new_n = array_size(size + 1); + let mut grown: Vec> = vec![None; new_n]; + for slot in table.iter().rev().flatten() { + let mask = new_n - 1; + let mut pos = mix(keys[*slot]) & mask; + while grown[pos].is_some() { + pos = (pos + 1) & mask; + } + grown[pos] = Some(*slot); + } + table = grown; + n = new_n; + } + } + contains_zero + .into_iter() + .chain(table.iter().rev().flatten().copied()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_and_zero_keys() { + assert_eq!(iteration_order(&[]), Vec::::new()); + assert_eq!(iteration_order(&[5]), vec![0]); + assert_eq!(iteration_order(&[7, 0]), vec![1, 0]); + } + + #[test] + fn every_key_is_visited_once_after_growth() { + let keys: Vec = (0..100).map(|i| i * 4_294_967_297 + 3).collect(); + let mut order = iteration_order(&keys); + order.sort_unstable(); + assert_eq!(order, (0..100).collect::>()); + } +} diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 9f4108377..4b4c1cdbb 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -152,6 +152,8 @@ pub struct StateTransforms { mirror: Vec<[u32; 2]>, full: Vec, loot: BTreeSet, + /// Block entity type of every state that has one (`BlockState.hasBlockEntity`). + entity_types: HashMap>, } impl StateTransforms { pub fn from_json(json: &str, states: usize) -> Result { @@ -197,13 +199,27 @@ impl StateTransforms { .into_iter() .map(BlockStateId) .collect(); + let mut entity_types = HashMap::new(); + if let Some(types) = value["block_entities"].as_object() { + for (name, states) in types { + let name: Arc = Arc::from(name.as_str()); + for id in ids(states) { + entity_types.insert(BlockStateId(id), name.clone()); + } + } + } Ok(Self { rotate, mirror, full, loot, + entity_types, }) } + /// The block entity type a state carries, when it has one. + pub fn entity_type(&self, state: BlockStateId) -> Option<&Arc> { + self.entity_types.get(&state) + } pub fn rotate(&self, state: BlockStateId, rotation: Rotation) -> BlockStateId { match rotation { Rotation::None => state, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index b381298ae..dad85d820 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -282,6 +282,22 @@ public final class VanillaChunkGenerationOracle { }; Runnable noop = () -> {}; try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + if (mode.equals("random")) { + // diagnostics: first floats after setFeatureSeed for chunk X0,Z0 (args 4..) index step + int cx = Integer.parseInt(args[4]), cz = Integer.parseInt(args[5]), idx = Integer.parseInt(args[6]), step = Integer.parseInt(args[7]); + WorldgenRandom r = new WorldgenRandom(new XoroshiroRandomSource(0L)); + long ds = r.setDecorationSeed(seed, cx << 4, cz << 4); + r.setFeatureSeed(ds, idx, step); + w.println("random " + ds + " " + r.nextFloat() + " " + r.nextFloat() + " " + r.nextFloat()); + return; + } + if (mode.equals("order")) { + var byStep = new TreeMap>(); + var registry = access.lookupOrThrow(Registries.STRUCTURE); + registry.stream().forEach(st -> byStep.computeIfAbsent(st.step().ordinal(), k -> new ArrayList<>()).add(registry.getKey(st).toString())); + byStep.forEach((step, names) -> { for (int i = 0; i < names.size(); i++) w.println("order " + step + " " + i + " " + names.get(i)); }); + return; + } if (mode.equals("scan")) { int x0 = Integer.parseInt(args[4]), z0 = Integer.parseInt(args[5]), x1 = Integer.parseInt(args[6]), z1 = Integer.parseInt(args[7]); for (int x = x0; x <= x1; x++) for (int z = z0; z <= z1; z++) { @@ -291,6 +307,10 @@ public final class VanillaChunkGenerationOracle { if (!start.isValid()) continue; var box = start.getBoundingBox(); var id = access.lookupOrThrow(Registries.STRUCTURE).getKey(start.getStructure()); + if (System.getenv("HORIZON_PIECES") != null) for (var piece : start.getPieces()) { + var pb = piece.getBoundingBox(); + w.println("piece " + x + " " + z + " " + net.minecraft.core.registries.BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()) + " " + pb.minX() + " " + pb.minY() + " " + pb.minZ() + " " + pb.maxX() + " " + pb.maxY() + " " + pb.maxZ()); + } w.println("start " + id + " " + x + " " + z + " " + box.minX() + " " + box.minY() + " " + box.minZ() + " " + box.maxX() + " " + box.maxY() + " " + box.maxZ()); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java index 0e37d5cda..de6d02f99 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java @@ -14,11 +14,13 @@ import net.minecraft.world.level.block.state.BlockState; /** * Original exporter of per-state structure-template behavior: BlockState.rotate * and BlockState.mirror results, StructureTemplate's full-block ordering class - * and whether the state's block entity is a RandomizableContainer. + * whether the state's block entity is a RandomizableContainer, and the block + * entity type of every state that has one. */ public final class VanillaStructureBlockExporter { public static void main(String[] args) throws Exception { SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + var entityTypes=new JsonObject(); var rotate=new JsonArray();var mirror=new JsonArray();var full=new JsonArray();var loot=new JsonArray(); Rotation[] rotations={Rotation.CLOCKWISE_90,Rotation.CLOCKWISE_180,Rotation.COUNTERCLOCKWISE_90}; Mirror[] mirrors={Mirror.LEFT_RIGHT,Mirror.FRONT_BACK}; @@ -31,10 +33,17 @@ public final class VanillaStructureBlockExporter { try{container=entityBlock.newBlockEntity(BlockPos.ZERO,state) instanceof RandomizableContainer;}catch(Throwable ignored){} } if(container)loot.add(Block.getId(state)); + if(state.hasBlockEntity()&&state.getBlock() instanceof EntityBlock entityBlock) { + try { + var type=net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(entityBlock.newBlockEntity(BlockPos.ZERO,state).getType()).toString(); + if(!entityTypes.has(type))entityTypes.add(type,new JsonArray()); + entityTypes.getAsJsonArray(type).add(Block.getId(state)); + }catch(Throwable ignored){} + } } var result=new JsonObject(); result.addProperty("states",Block.BLOCK_STATE_REGISTRY.size()); - result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot); + result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot);result.add("block_entities",entityTypes); Files.writeString(Path.of(args[0]),new Gson().toJson(result),StandardCharsets.UTF_8); } } 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 08/42] 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 09/42] 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 2ed4a4b06fc9e3175a6b32fc01ef1bb18e01a4dc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:00:58 +0200 Subject: [PATCH 10/42] WIP: chunk oracle tweak Co-Authored-By: Claude Sonnet 5.5 --- .../horizonlab/parity/VanillaChunkGenerationOracle.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index dad85d820..97844fe80 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -82,7 +82,12 @@ public final class VanillaChunkGenerationOracle { static StructureManager structures; static BiomeResolver resolver; static ServerChunkCache cache; + static net.minecraft.server.MinecraftServer server; static ResourceKey key; + @Override + public net.minecraft.server.MinecraftServer getServer() { + return server; + } static int minY, height; static Map chunks; static net.minecraft.world.level.lighting.LevelLightEngine light; @@ -252,6 +257,10 @@ public final class VanillaChunkGenerationOracle { OracleLevel.type = dimensionType; OracleLevel.resolver = biomeSource.createUncachedResolver(randomState); OracleLevel.cache = (ServerChunkCache) allocate.invoke(unsafe, OracleCache.class); + OracleLevel.server = (net.minecraft.server.MinecraftServer) allocate.invoke(unsafe, net.minecraft.server.dedicated.DedicatedServer.class); + var templateField = net.minecraft.server.MinecraftServer.class.getDeclaredField("structureTemplateManager"); + templateField.setAccessible(true); + templateField.set(OracleLevel.server, templates); OracleLevel.key = levelKey; OracleLevel.minY = height.getMinY(); OracleLevel.height = height.getHeight(); 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 11/42] 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 a7e63b5c18881859855d5d4890f820480a8fad5e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:02:13 +0200 Subject: [PATCH 12/42] WIP: environment render parity harness Work in progress on the environment rendering differential harness: a Rust fixture example, a vanilla oracle and the driver script. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/environment_fixture.rs | 64 ++++++++++++ .../parity/VanillaEnvironmentOracle.java | 98 +++++++++++++++++++ tools/test_environment_render_parity.py | 91 +++++++++++++++++ 3 files changed, 253 insertions(+) create mode 100644 crates/horizon-client/examples/environment_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java create mode 100755 tools/test_environment_render_parity.py diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs new file mode 100644 index 000000000..261411d51 --- /dev/null +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -0,0 +1,64 @@ +//! Environment attributes for differential tests against vanilla +//! (tools/test_environment_render_parity.py): reads "dimension ticks rain +//! thunder biome" lines and prints the sampled sky state as JSON lines. +//! +//! usage: environment_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + biome::Biomes, + environment::{Environment, apply_weather}, +}; +use std::{collections::HashMap, fmt::Write as _, 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: environment_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let biomes = Biomes::load(root)?; + let mut environments: HashMap = HashMap::new(); + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let dimension = f[0]; + let environment = match environments.entry(dimension.to_owned()) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => e.insert(Environment::load_dimension( + root, + dimension, + dimension == "overworld", + )?), + }; + let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4]))); + let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog); + if dimension == "overworld" { + apply_weather(&mut sky, f[2].parse()?, f[3].parse()?); + } + let v3 = |c: [f32; 3]| format!("[{:?},{:?},{:?}]", c[0], c[1], c[2]); + let v4 = |c: [f32; 4]| format!("[{:?},{:?},{:?},{:?}]", c[0], c[1], c[2], c[3]); + let mut row = format!("{{\"case\":\"{line}\""); + let mut put = |name: &str, value: String| { + let _ = write!(row, ",\"minecraft:{name}\":{value}"); + }; + put("visual/sky_color", v3(sky.sky_color)); + put("visual/fog_color", v3(sky.fog_color)); + put("visual/cloud_color", v4(sky.cloud_color)); + put("visual/sunrise_sunset_color", v4(sky.sunrise_color)); + put("visual/sky_light_factor", format!("{:?}", sky.sky_light_factor)); + put("visual/sky_light_color", v3(sky.sky_light_color)); + put("visual/block_light_tint", v3(sky.block_light_tint)); + put("visual/ambient_light_color", v3(sky.ambient_light_color)); + put("visual/sun_angle", format!("{:?}", sky.sun_angle)); + put("visual/moon_angle", format!("{:?}", sky.moon_angle)); + put("visual/star_angle", format!("{:?}", sky.star_angle)); + put("visual/star_brightness", format!("{:?}", sky.star_brightness)); + put("gameplay/sky_light_level", format!("{:?}", sky.sky_light_level * 15.0)); + put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); + put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); + out.push_str(&row); + out.push_str("}\n"); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java new file mode 100644 index 000000000..df1d7b028 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java @@ -0,0 +1,98 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +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.attribute.*; +import net.minecraft.world.clock.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3fc; +import org.joml.Vector4fc; + +/** + * Original oracle: builds the vanilla EnvironmentAttributeSystem (dimension + * layer, biome layer for one fixed biome, dimension timelines, weather layers) + * from the vanilla data pack and prints every visual/gameplay attribute for + * fixture lines "dimension ticks rain thunder biome". + */ +public final class VanillaEnvironmentOracle { + private static String fmt(Object v) { + if (v instanceof Vector3fc c) return String.format("[%s,%s,%s]", c.x(), c.y(), c.z()); + if (v instanceof Vector4fc c) return String.format("[%s,%s,%s,%s]", c.x(), c.y(), c.z(), c.w()); + if (v instanceof Float f) return f.toString(); + if (v instanceof Boolean b) return b.toString(); + if (v instanceof Enum e) return "\"" + e.name() + "\""; + return null; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) { + b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base)); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Path in = Path.of(args[0]), out = Path.of(args[1]); + 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(); + staticTags.forEach(Registry.PendingTags::apply); + var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE); + var biomes = world.lookupOrThrow(Registries.BIOME); + try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + for (String line : Files.readAllLines(in, StandardCharsets.UTF_8)) { + String[] f = line.split(" "); + DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.withDefaultNamespace(f[0]))).value(); + long ticks = Long.parseLong(f[1]); + float rain = Float.parseFloat(f[2]), thunder = Float.parseFloat(f[3]); + Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.withDefaultNamespace(f[4]))).value(); + ClockManager clocks = h -> new ClockInstance() { + public long totalTicks() { return ticks; } + public float partialTick() { return 0.0F; } + public float rate() { return 1.0F; } + public boolean isPaused() { return false; } + }; + var b = EnvironmentAttributeSystem.builder(); + b.addConstantLayer(dim.attributes()); + for (EnvironmentAttribute attr : biome.getAttributes().keySet()) addBiome(b, attr, biome); + dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks)); + if (dim.hasSkyLight() && !dim.hasCeiling()) { + WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() { + public float rainLevel() { return rain; } + public float thunderLevel() { return thunder; } + }); + } + var system = b.build(); + StringBuilder sb = new StringBuilder("{\"case\":\"" + line + "\""); + for (var entry : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.entrySet()) { + EnvironmentAttribute attr = entry.getValue(); + String s = fmt(system.getValue(attr, Vec3.ZERO)); + if (s != null) sb.append(",\"").append(entry.getKey().identifier()).append("\":").append(s); + } + w.println(sb.append("}")); + } + } + } +} diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py new file mode 100755 index 000000000..006f540ec --- /dev/null +++ b/tools/test_environment_render_parity.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Compare Horizon's environment attributes with the vanilla 26.3 attribute system. + +The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack +(dimension attributes, one biome's attributes, the dimension timelines and the +weather layers) and prints every visual/gameplay attribute for a grid of +dimensions, world times, rain/thunder levels and biomes. +`examples/environment_fixture` samples the same cases through Horizon's +`Environment::sample` + `apply_weather`; every attribute Horizon computes must +agree with vanilla. + + test_environment_render_parity.py [--tolerance EPS] +""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +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 cases(resources): + biomes = sorted(p.stem for p in (resources / 'data/minecraft/worldgen/biome').glob('*.json')) + out = [] + for dim in ['overworld', 'overworld_caves', 'the_nether', 'the_end']: + for ticks in list(range(0, 48000, 250)) + [23999, 24001, 1234567]: + for rain, thunder in [(0, 0), (0.5, 0), (1, 0), (1, 1), (0.7, 0.3)] if dim == 'overworld' else [(0, 0)]: + out.append(f'{dim} {ticks} {rain} {thunder} plains') + for dim in ['overworld', 'the_nether', 'the_end']: + for biome in biomes: + for ticks in (0, 6000, 12500, 18000): + for rain, thunder in [(0, 0), (1, 0.4)] if dim == 'overworld' else [(0, 0)]: + out.append(f'{dim} {ticks} {rain} {thunder} {biome}') + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--tolerance', type=float, default=2e-5) + args = parser.parse_args() + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / 'rust-environment-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(cases(resources)) + '\n') + classes = build / 'classes'; classes.mkdir(exist_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java' + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--', + resources, inputs, build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust), (len(vanilla), len(rust)) + bad = {} + uncovered = set() + for v, r in zip(vanilla, rust): + for key, expected in v.items(): + if key == 'case': + continue + if key not in r: + uncovered.add(key); continue + got = r[key] + pairs = zip(expected, got) if isinstance(expected, list) else [(expected, got)] + if any(abs(a - b) > args.tolerance * (1 + abs(a)) for a, b in pairs): + bad.setdefault(key, []).append((v['case'], expected, got)) + print(f'{len(vanilla)} cases compared') + for key, items in sorted(bad.items()): + print(f'MISMATCH {key}: {len(items)} cases, e.g. {items[0]}') + if uncovered: + print('attributes Horizon does not model:', ', '.join(sorted(uncovered))) + if bad: + sys.exit(f'{len(bad)} attributes differ from vanilla') + print('environment parity ok') + + +if __name__ == '__main__': + main() From 50084d03d42f473954440933329ff03d3290aa61 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:00:31 +0200 Subject: [PATCH 13/42] Ignore sections above the noise height and NBT integer widths in the chunk harness The Nether roof and End sky sections are all air in vanilla and Horizon keeps none, and structure templates keep their stored integer width while vanilla re-saves block entities with its own, so neither is a generation difference. Co-Authored-By: Claude Sonnet 5.5 --- tools/test_chunk_generation_parity.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index e7ee17aba..2a1a13177 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -153,6 +153,11 @@ def nbt_matches(vanilla, rust, default): elif value != default.get(key): return False return all(key in vanilla or key in ('x', 'y', 'z') for key in rust) + if isinstance(vanilla, list) and isinstance(rust, list): + return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust)) + if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil': + # Structure templates keep their stored integer width; vanilla re-saves block entities with its own. + return vanilla[1] == rust[1] return vanilla == rust @@ -167,6 +172,9 @@ def state_names(): return [s[3].removeprefix('Block{').replace('}', '', 1) for s in facts['states']] +AIR = '0' + + def compare(vanilla, rust, names, label, limit=6, quiet=False): """Returns (differing chunks, differing blocks, differing biome cells, differing block entities).""" chunks = blocks = biomes = entities = 0 @@ -181,10 +189,17 @@ def compare(vanilla, rust, names, label, limit=6, quiet=False): ra, rb = a['y'][y], b['y'].get(y) if ra == rb: continue - for i, (u, v) in enumerate(zip(ra.split(' '), (rb or '').split(' '))): + if rb is None: + # Above the noise height (Nether roof, End sky) Horizon keeps no section; vanilla's is all air. + if set(ra.split(' ')) != {AIR}: + block_diffs.append((pos[0] * 16, y, pos[1] * 16, 'non-air section', 'section missing')) + continue + for i, (u, v) in enumerate(zip(ra.split(' '), rb.split(' '))): if u != v: block_diffs.append((pos[0] * 16 + i % 16, y, pos[1] * 16 + i // 16, names[int(u)], names[int(v)])) for q in sorted(a['q']): + if q not in b['q']: + continue # biomes of sections Horizon does not generate (above the noise height) if a['q'][q] != b['q'].get(q): for i, (u, v) in enumerate(zip(a['q'][q].split(' '), b['q'].get(q, '').split(' '))): if u != v: 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 14/42] 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 15/42] 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 16/42] 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 353d8491267e8e1f6c3a575a92d248cda53eed32 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:59 +0200 Subject: [PATCH 17/42] Match vanilla weather colours and dimension sky defaults The environment differential harness now passes for every dimension, biome, time and weather level. Weather colour multipliers are floored to 8-bit channels as vanilla does. A biome without its own fog or sky colour falls back to its dimension's, which fixes the End's dark purple fog, and the missing cloud colour is transparent. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/environment_fixture.rs | 30 +++++++++++------- crates/horizon-client/src/biome.rs | 16 +++------- crates/horizon-client/src/environment.rs | 31 +++++++++++++------ tools/test_environment_render_parity.py | 8 ++++- 4 files changed, 52 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs index 261411d51..3300df232 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -22,14 +22,13 @@ fn main() -> horizon_client::Result<()> { for line in input.lines() { let f: Vec<&str> = line.split(' ').collect(); let dimension = f[0]; - let environment = match environments.entry(dimension.to_owned()) { - std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), - std::collections::hash_map::Entry::Vacant(e) => e.insert(Environment::load_dimension( - root, - dimension, - dimension == "overworld", - )?), - }; + let environment = + match environments.entry(dimension.to_owned()) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => e.insert( + Environment::load_dimension(root, dimension, dimension == "overworld")?, + ), + }; let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4]))); let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog); if dimension == "overworld" { @@ -45,15 +44,24 @@ fn main() -> horizon_client::Result<()> { put("visual/fog_color", v3(sky.fog_color)); put("visual/cloud_color", v4(sky.cloud_color)); put("visual/sunrise_sunset_color", v4(sky.sunrise_color)); - put("visual/sky_light_factor", format!("{:?}", sky.sky_light_factor)); + put( + "visual/sky_light_factor", + format!("{:?}", sky.sky_light_factor), + ); put("visual/sky_light_color", v3(sky.sky_light_color)); put("visual/block_light_tint", v3(sky.block_light_tint)); put("visual/ambient_light_color", v3(sky.ambient_light_color)); put("visual/sun_angle", format!("{:?}", sky.sun_angle)); put("visual/moon_angle", format!("{:?}", sky.moon_angle)); put("visual/star_angle", format!("{:?}", sky.star_angle)); - put("visual/star_brightness", format!("{:?}", sky.star_brightness)); - put("gameplay/sky_light_level", format!("{:?}", sky.sky_light_level * 15.0)); + put( + "visual/star_brightness", + format!("{:?}", sky.star_brightness), + ); + put( + "gameplay/sky_light_level", + format!("{:?}", sky.sky_light_level * 15.0), + ); put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); out.push_str(&row); diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 5fd6f3e4b..1be7a4ce9 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -32,8 +32,9 @@ pub struct BiomeInfo { pub foliage: u32, pub dry_foliage: u32, pub water: u32, - pub sky: u32, - pub fog: u32, + pub sky: Option, + /// The biome's own fog colour attribute; otherwise the dimension's applies. + pub fog: Option, pub water_fog: u32, } pub struct Biomes { @@ -77,13 +78,6 @@ impl Biomes { let grass = colormap(root, "grass")?; let foliage = colormap(root, "foliage")?; let dry = colormap(root, "dry_foliage")?; - let dimension: Value = serde_json::from_slice(&fs::read( - root.join("data/minecraft/dimension_type/overworld.json"), - )?)?; - let default_fog = - color(&dimension["attributes"]["minecraft:visual/fog_color"]).unwrap_or(0xC0D8FF); - let default_sky = - color(&dimension["attributes"]["minecraft:visual/sky_color"]).unwrap_or(0x78A7FF); let mut list = Vec::new(); let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))? .filter_map(|e| e.ok()) @@ -151,8 +145,8 @@ impl Biomes { dry_foliage: color(&effects["dry_foliage_color"]) .unwrap_or_else(|| sample(&dry, temperature, downfall, 0x5D4930)), water: color(&effects["water_color"]).unwrap_or(0x3F76E4), - sky: color(&attributes["minecraft:visual/sky_color"]).unwrap_or(default_sky), - fog: color(&attributes["minecraft:visual/fog_color"]).unwrap_or(default_fog), + sky: color(&attributes["minecraft:visual/sky_color"]), + fog: color(&attributes["minecraft:visual/fog_color"]), water_fog: color(&attributes["minecraft:visual/water_fog_color"]) .unwrap_or(0x050533), name, diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs index a7d87e75e..43c48af4e 100644 --- a/crates/horizon-client/src/environment.rs +++ b/crates/horizon-client/src/environment.rs @@ -229,7 +229,7 @@ impl Environment { self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) } /// Sky state for a time of day, with the biome's sky and fog colours as base values. - pub fn sample(&self, ticks: i64, biome_sky: u32, biome_fog: u32) -> Sky { + pub fn sample(&self, ticks: i64, biome_sky: Option, biome_fog: Option) -> Sky { let rgb = |c: u32| { [ (c >> 16 & 255) as f32 / 255.0, @@ -260,8 +260,14 @@ impl Environment { .map_or(0.0, |t| t.sample(ticks, self.period)[0]) }; Sky { - sky_color: three(v("minecraft:visual/sky_color", rgb(biome_sky))), - fog_color: three(v("minecraft:visual/fog_color", rgb(biome_fog))), + sky_color: three(v( + "minecraft:visual/sky_color", + biome_sky.map_or_else(|| self.base("minecraft:visual/sky_color"), rgb), + )), + fog_color: three(v( + "minecraft:visual/fog_color", + biome_fog.map_or_else(|| self.base("minecraft:visual/fog_color"), rgb), + )), sky_light_factor: scalar("minecraft:visual/sky_light_factor"), sky_light_color: three(v( "minecraft:visual/sky_light_color", @@ -279,7 +285,10 @@ impl Environment { .map_or([0.0; 4], |t| t.sample(ticks, self.period)), cloud_color: v( "minecraft:visual/cloud_color", - self.base("minecraft:visual/cloud_color"), + self.base + .get("minecraft:visual/cloud_color") + .copied() + .unwrap_or([0.0; 4]), ), sky_light_level: scalar("minecraft:gameplay/sky_light_level") / 15.0, fog_start: self @@ -304,24 +313,26 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) }; let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t; - let night = [0.48, 0.48, 1.0]; + // Vanilla stores these colours as 8-bit ARGB (`ARGB.colorFromFloat` floors). + let q = |v: f32| (v * 255.0).floor() / 255.0; + let night = [q(0.48), q(0.48), 1.0]; // (level, sky gray (brightness, factor), fog multiplier, cloud gray, alpha, sunrise multiplier) let layers = [ ( rain - thunder, (0.6, 0.75), - [0.5, 0.5, 0.6], + [q(0.5), q(0.5), q(0.6)], (0.24, 0.5), 0.3125, - [0.5, 0.5, 0.6], + [q(0.5), q(0.5), q(0.6)], ), ( thunder, (0.24, 0.94), - [0.25, 0.25, 0.3], + [q(0.25), q(0.25), q(0.3)], (0.095, 0.94), 0.527_343_75, - [0.25, 0.25, 0.3], + [q(0.25), q(0.25), q(0.3)], ), ]; for (level, (sb, sf), fog, (cb, cf), alpha, sunrise) in layers { @@ -347,7 +358,7 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { sky.sky_light_color = lerp3( level, sky.sky_light_color, - lerp3(alpha, sky.sky_light_color, night), + lerp3(q(alpha), sky.sky_light_color, night), ); sky.sky_light_factor = lerp( level, diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 006f540ec..4a1979fc2 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -27,12 +27,18 @@ except ImportError: def cases(resources): biomes = sorted(p.stem for p in (resources / 'data/minecraft/worldgen/biome').glob('*.json')) out = [] - for dim in ['overworld', 'overworld_caves', 'the_nether', 'the_end']: + for dim in ['overworld', 'the_nether', 'the_end']: for ticks in list(range(0, 48000, 250)) + [23999, 24001, 1234567]: for rain, thunder in [(0, 0), (0.5, 0), (1, 0), (1, 1), (0.7, 0.3)] if dim == 'overworld' else [(0, 0)]: out.append(f'{dim} {ticks} {rain} {thunder} plains') + own = {'the_nether': {'nether_wastes', 'soul_sand_valley', 'crimson_forest', 'warped_forest', 'basalt_deltas'}, + 'the_end': {'the_end', 'small_end_islands', 'end_midlands', 'end_highlands', 'end_barrens'}} for dim in ['overworld', 'the_nether', 'the_end']: for biome in biomes: + if dim in own and biome not in own[dim]: + continue + if dim == 'overworld' and any(biome in b for b in own.values()): + continue for ticks in (0, 6000, 12500, 18000): for rain, thunder in [(0, 0), (1, 0.4)] if dim == 'overworld' else [(0, 0)]: out.append(f'{dim} {ticks} {rain} {thunder} {biome}') From f5fa9b5026b481b77e58beb9542141b4d4463611 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:59 +0200 Subject: [PATCH 18/42] Add night vision and torch flicker to the lightmap and rebuild the health HUD The lightmap now brightens with night vision and conduit water vision and flickers its block light like vanilla's extractor. The hearts, armour and food rows follow Hud.extractPlayerHealth: absorption rows, hardcore sprites, poison and wither tints, the regeneration hop, low-health shaking, the damage blink and hunger jitter, driven by vanilla's java.util.Random. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/fog.rs | 22 ++ crates/horizon-client/src/game.rs | 72 +++--- crates/horizon-client/src/game/health_hud.rs | 226 ++++++++++++++++++ crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/game/sculk.rs | 23 ++ crates/horizon-client/src/gfx.rs | 21 +- 6 files changed, 332 insertions(+), 33 deletions(-) create mode 100644 crates/horizon-client/src/game/health_hud.rs diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 4146de4f6..dffcf7280 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -68,8 +68,30 @@ pub struct FogState { pub water_vision_time: i32, /// `AtmosphericFogEnvironment.rainFogMultiplier`. pub rain_fog_multiplier: f32, + /// `LightmapRenderStateExtractor.blockLightFlicker`. + pub block_light_flicker: f32, + flicker_seed: u64, } impl FogState { + fn next_float(&mut self) -> f32 { + // splitmix64: the vanilla source is unseeded `RandomSource.create()`. + self.flicker_seed = self.flicker_seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.flicker_seed; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + ((z ^ (z >> 31)) >> 40) as f32 / (1u32 << 24) as f32 + } + /// `LightmapRenderStateExtractor.tick`: the torch light flickers. + pub fn tick_flicker(&mut self) { + let (a, b, c, d) = ( + self.next_float(), + self.next_float(), + self.next_float(), + self.next_float(), + ); + self.block_light_flicker += (a - b) * c * d * 0.1; + self.block_light_flicker *= 0.9; + } /// `LocalPlayer.aiStep`: water vision ramps up while the eye is in water. pub fn tick(&mut self, eye_in_water: bool) { self.water_vision_time = if eye_in_water { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 882905617..5c1422098 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -32,6 +32,7 @@ mod functions; mod game_mode; mod golems; mod growth; +mod health_hud; mod jukebox; mod lightning; mod loom; @@ -525,6 +526,7 @@ struct Game<'a> { fps_frames: u64, fps_at: Instant, ticks: u64, + health_hud: health_hud::HealthHud, error: Option, message: Option<(String, Instant)>, save: Arc, @@ -2928,7 +2930,7 @@ impl Game<'_> { let atlas = &self.res.atlas; if !self.creative && !spectator - && let Some(p) = &self.player + && let Some(p) = &mut self.player { // Experience bar and hearts/food (Gui.renderPlayerHealth). let saddled_mount = mounted @@ -2964,33 +2966,37 @@ impl Game<'_> { } batch.text(atlas, &text, x, y, rgba(128, 255, 32, 255), false); } - let health = p.health.health().ceil() as i32; - let top = h - 39.0; - for i in 0..10 { - let x = w / 2.0 - 91.0 + i as f32 * 8.0; - let y = if health <= 4 { - top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 - } else { - top - }; - batch.sprite(atlas, "gui/sprites/hud/heart/container", x, y); - let v = health - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/heart/full", x, y); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/heart/half", x, y); - } - } - let food = p.health.food.food; - for i in (0..10).filter(|_| !mounted) { - let x = w / 2.0 + 91.0 - i as f32 * 8.0 - 9.0; - batch.sprite(atlas, "gui/sprites/hud/food_empty", x, top); - let v = food - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/food_full", x, top); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/food_half", x, top); - } + let effects = &self.potions.effects; + let kind = if effects.get("poison").is_some() { + health_hud::HeartKind::Poisoned + } else if effects.get("wither").is_some() { + health_hud::HeartKind::Withered + } else { + health_hud::HeartKind::Normal + }; + let inputs = health_hud::HealthInputs { + tick: self.ticks, + health: p.health.health(), + max_health: p.attribute("minecraft:max_health").unwrap_or(20.0) as f32, + absorption: p.health.absorption(), + armor: p + .attribute("minecraft:armor") + .or_else(|_| p.attribute("armor")) + .unwrap_or(0.0) as i32, + food: p.health.food.food, + saturation: p.health.food.saturation, + kind, + regeneration: effects.get("regeneration").is_some(), + hunger: effects.get("hunger").is_some(), + hardcore: self.level.hardcore, + damage_cooldown: p.health.hurt.cooldown > 0, + show_food: !mounted, + }; + for (name, x, y) in + self.health_hud + .layout(&inputs, w as i32, h as i32, std::time::Instant::now()) + { + batch.sprite(atlas, &name, x as f32, y as f32); } } if self.debug { @@ -4220,10 +4226,13 @@ impl Game<'_> { return 11; } if self.dim == Dim::End { - let sky = self.res.end_environment.sample(self.world.day_time, 0, 0); + let sky = self + .res + .end_environment + .sample(self.world.day_time, None, None); return (15.0 - 15.0 * sky.sky_light_level).round() as i32; } - let mut sky = self.res.environment.sample(self.world.day_time, 0, 0); + let mut sky = self.res.environment.sample(self.world.day_time, None, None); let (rain, thunder) = self.world.weather.levels(1.0); horizon_client::environment::apply_weather(&mut sky, rain, thunder); // Level.updateSkyBrightness: darkening from the sky light level. @@ -6923,6 +6932,8 @@ impl Game<'_> { game_time: self.world.game_time as f32, ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), + night_vision: self.night_vision_intensity(), + block_flicker: self.res.fog.state.block_light_flicker, }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } @@ -7749,6 +7760,7 @@ pub fn run() -> Result<()> { screen: Screen::Playing, window: None, renderer: None, + health_hud: health_hud::HealthHud::default(), started: now, previous: now, frames: 0, diff --git a/crates/horizon-client/src/game/health_hud.rs b/crates/horizon-client/src/game/health_hud.rs new file mode 100644 index 000000000..4e9aaee0a --- /dev/null +++ b/crates/horizon-client/src/game/health_hud.rs @@ -0,0 +1,226 @@ +//! `Hud.extractPlayerHealth`: armour, hearts, food. The layout is computed as +//! a list of sprites so it can be tested without drawing. +use std::time::Instant; + +/// `java.util.Random`, for the HUD's per-tick jitter. +pub(super) struct JavaRandom(i64); +impl JavaRandom { + pub fn new(seed: i64) -> Self { + Self((seed ^ 0x5_DEEC_E66D) & ((1 << 48) - 1)) + } + fn next(&mut self, bits: u32) -> i32 { + self.0 = (self.0.wrapping_mul(0x5_DEEC_E66D).wrapping_add(0xB)) & ((1 << 48) - 1); + (self.0 >> (48 - bits)) as i32 + } + pub fn next_int(&mut self, bound: i32) -> i32 { + let mut r = self.next(31); + let m = bound - 1; + if bound & m == 0 { + return ((i64::from(bound) * i64::from(r)) >> 31) as i32; + } + let mut u = r; + loop { + r = u % bound; + if u.wrapping_sub(r).wrapping_add(m) >= 0 { + return r; + } + u = self.next(31); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum HeartKind { + Normal, + Poisoned, + Withered, + Absorbing, +} +impl HeartKind { + fn prefix(self) -> &'static str { + match self { + Self::Normal => "", + Self::Poisoned => "poisoned_", + Self::Withered => "withered_", + Self::Absorbing => "absorbing_", + } + } +} + +/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...). +pub(super) struct HealthHud { + last_health: i32, + display_health: i32, + last_health_time: Instant, + health_blink_time: i64, +} +impl Default for HealthHud { + fn default() -> Self { + Self { + last_health: 0, + display_health: 0, + last_health_time: Instant::now(), + health_blink_time: 0, + } + } +} + +pub(super) struct HealthInputs { + pub tick: u64, + pub health: f32, + pub max_health: f32, + pub absorption: f32, + pub armor: i32, + pub food: i32, + pub saturation: f32, + pub kind: HeartKind, + pub regeneration: bool, + pub hunger: bool, + pub hardcore: bool, + /// `damageCooldownTime > 0`. + pub damage_cooldown: bool, + /// A mount with its own hearts replaces the food bar. + pub show_food: bool, +} + +fn heart_sprite(kind: HeartKind, hardcore: bool, half: bool, blink: bool) -> String { + let (hc, h) = ( + if hardcore { "hardcore_" } else { "" }, + if half { "half" } else { "full" }, + ); + let b = if blink { "_blinking" } else { "" }; + format!("gui/sprites/hud/heart/{}{hc}{h}{b}", kind.prefix()) +} + +impl HealthHud { + /// Sprites (name, x, y) in draw order for a screen of `w` x `h` GUI pixels. + pub fn layout( + &mut self, + i: &HealthInputs, + w: i32, + h: i32, + now: Instant, + ) -> Vec<(String, i32, i32)> { + let mut out = Vec::new(); + let tick = i64::try_from(i.tick).unwrap_or(i64::MAX); + let current = i.health.ceil() as i32; + let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1; + if current < self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 20; + } else if current > self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 10; + } + if now.duration_since(self.last_health_time).as_millis() > 1000 { + self.display_health = current; + self.last_health_time = now; + } + self.last_health = current; + let old = self.display_health; + let mut random = JavaRandom::new(i64::from((i.tick as i32).wrapping_mul(312_871))); + let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39); + let max_health = i.max_health.max(old.max(current) as f32); + let absorption = i.absorption.ceil() as i32; + let rows = ((max_health + absorption as f32) / 2.0 / 10.0).ceil() as i32; + let row_height = (10 - (rows - 2)).max(3); + let offset_index = if i.regeneration { + (i.tick as i32).rem_euclid((max_health + 5.0).ceil() as i32) + } else { + -1 + }; + if i.armor > 0 { + let y = y_base - (rows - 1) * row_height - 10; + for n in 0..10 { + let name = match (n * 2 + 1).cmp(&i.armor) { + std::cmp::Ordering::Less => "armor_full", + std::cmp::Ordering::Equal => "armor_half", + std::cmp::Ordering::Greater => "armor_empty", + }; + out.push((format!("gui/sprites/hud/{name}"), x_left + n * 8, y)); + } + } + let containers = (max_health / 2.0).ceil() as i32; + let absorb_containers = (absorption as f32 / 2.0).ceil() as i32; + let container = |hardcore: bool, blink: bool| { + format!( + "gui/sprites/hud/heart/container{}{}", + if hardcore { "_hardcore" } else { "" }, + if blink { "_blinking" } else { "" } + ) + }; + for c in (0..containers + absorb_containers).rev() { + let (row, column) = (c / 10, c % 10); + let x = x_left + column * 8; + let mut y = y_base - row * row_height; + if current + absorption <= 4 { + y += random.next_int(2); + } + if c < containers && c == offset_index { + y -= 2; + } + out.push((container(i.hardcore, blink), x, y)); + let halves = c * 2; + if c >= containers { + let ah = halves - containers * 2; + if ah < absorption { + let kind = if i.kind == HeartKind::Withered { + i.kind + } else { + HeartKind::Absorbing + }; + out.push(( + heart_sprite(kind, i.hardcore, ah + 1 == absorption, false), + x, + y, + )); + } + } + if blink && halves < old { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == old, true), + x, + y, + )); + } + if halves < current { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == current, false), + x, + y, + )); + } + } + if i.show_food { + let suffix = if i.hunger { "_hunger" } else { "" }; + for n in 0..10 { + let mut y = y_base; + if i.saturation <= 0.0 && (i.tick as i32).rem_euclid(i.food * 3 + 1) == 0 { + y += random.next_int(3) - 1; + } + let x = x_right - n * 8 - 9; + out.push((format!("gui/sprites/hud/food_empty{suffix}"), x, y)); + if n * 2 + 1 < i.food { + out.push((format!("gui/sprites/hud/food_full{suffix}"), x, y)); + } + if n * 2 + 1 == i.food { + out.push((format!("gui/sprites/hud/food_half{suffix}"), x, y)); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn java_random_matches_reference() { + // new Random(42).nextInt(10) sequence: 0, 3, 8, 4, 0. + let mut r = JavaRandom::new(42); + let v: Vec = (0..5).map(|_| r.next_int(10)).collect(); + assert_eq!(v, [0, 3, 8, 4, 0]); + } +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index c13973e95..c7605f257 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -172,6 +172,7 @@ impl Game<'_> { lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) } pub(super) fn tick_particles(&mut self) { + self.res.fog.state.tick_flicker(); let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index e2d985417..07fbfcfac 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1096,6 +1096,29 @@ impl Game<'_> { (modifier, pulse.max(0.0)) } + /// `LightmapRenderStateExtractor`: the night vision effect's intensity + /// (`GameRenderer.nightVisionScale`), or conduit power's water vision. + pub(super) fn night_vision_intensity(&self) -> f32 { + use horizon_client::fog::FogType; + if let Some(e) = self.potions.effects.get("night_vision") { + // MobEffectInstance.endsWithin(200); -1 is infinite. + return if e.duration < 0 || e.duration > 200 { + 1.0 + } else { + 0.7 + (e.duration as f32 * std::f32::consts::PI * 0.2).sin() * 0.3 + }; + } + if self.potions.effects.get("conduit_power").is_some() + && let Some(eye) = self.eye_position() + { + let in_water = + horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) + == FogType::Water; + return self.res.fog.state.water_vision(in_water); + } + 0.0 + } + /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index ce51c2475..d58550502 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -80,6 +80,10 @@ pub struct Frame<'a> { /// The darkness effect on the lightmap: the brightness it takes off the /// gamma option and the pulsing scale subtracted from the light. pub darkness: (f32, f32), + /// Night vision (or conduit water vision) intensity on the lightmap. + pub night_vision: f32, + /// Torch flicker added to the block light factor of 1.4. + pub block_flicker: f32, } pub struct Renderer { instance: wgpu::Instance, @@ -1077,7 +1081,14 @@ impl Renderer { * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) } - fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) { + fn update_lightmap( + &self, + sky: &Sky, + darkness: f32, + gamma: f32, + night_vision: f32, + flicker: f32, + ) { // lightmap.fsh: per (block, sky) level. let brightness = |level: f32| level / (4.0 - 3.0 * level); let mut pixels = [0u8; 16 * 16 * 4]; @@ -1085,9 +1096,11 @@ impl Renderer { for b in 0..16 { let block_level = b as f32 / 15.0; let sky_level = s as f32 / 15.0; - let block_brightness = brightness(block_level) * 1.4; + let block_brightness = brightness(block_level) * (1.4 + flicker); let sky_brightness = brightness(sky_level) * sky.sky_light_factor; - let mut color = Vec3::from(sky.ambient_light_color); + // NightVisionColor defaults to 0x999999. + let mut color = + Vec3::from(sky.ambient_light_color).max(Vec3::splat(0.6 * night_vision)); color += Vec3::from(sky.sky_light_color) * sky_brightness; let parabolic = (2.0 * block_level - 1.0).powi(2); let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic); @@ -1193,6 +1206,8 @@ impl Renderer { &frame.sky, frame.darkness.1, (self.gamma - frame.darkness.0).max(0.0), + frame.night_vision, + frame.block_flicker, ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; 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 19/42] 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 20/42] 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 21/42] 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 22/42] 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 afb92f7c8415f2fb321050a0d69a7b928e7bb277 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:25:59 +0200 Subject: [PATCH 23/42] Fix the chunk oracle's enabled features so jigsaw final states parse Co-Authored-By: Claude Sonnet 5.5 --- .../src/worldgen/generator_decoration.rs | 51 +++++++++++++++++-- .../parity/VanillaChunkGenerationOracle.java | 4 +- tools/test_chunk_generation_parity.py | 9 +++- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 7cef04bd9..1f35b08fa 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -634,14 +634,55 @@ impl PlacementContext for World<'_> { .map(|shape| shape.is_empty()) .map_err(query) } - /// Block entities are not stored in proto chunks; loot tables are no-ops. + /// RandomizableContainer.setBlockEntityLootTable: only a container block that + /// is actually there takes the table, and then it draws the loot seed. fn set_block_entity_loot_table( &mut self, - _: [i32; 3], - _: &str, - _: &mut impl horizon_core::random::RandomSource, + position: [i32; 3], + table: &str, + random: &mut impl horizon_core::random::RandomSource, ) -> Result<(), PlacementQueryError> { - Ok(()) + use crate::nbt::Tag; + let chunk = self.region.chunk(position[0] >> 4, position[2] >> 4)?; + let state = chunk.block(position[0], position[1], position[2]); + let registry = self.decoration.bindings.registry(); + let Some(name) = registry.state(state).map(|s| s.name.to_string()) else { + return Ok(()); + }; + if !matches!( + name.as_str(), + "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" + ) { + return Ok(()); + } + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String(name.as_str().into())); + nbt.insert("LootTable".into(), Tag::String(table.into())); + nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); + self.set_block_entity(position, nbt) + } + /// SpawnerBlockEntity.setEntityId: the next spawn data and no potentials. + fn configure_spawner( + &mut self, + position: [i32; 3], + entity: &str, + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let chunk = self.region.chunk(position[0] >> 4, position[2] >> 4)?; + let state = chunk.block(position[0], position[1], position[2]); + let registry = self.decoration.bindings.registry(); + if registry.state(state).map(|s| s.name.as_str()) != Some("minecraft:spawner") { + return Ok(()); + } + let mut mob = crate::nbt::Compound::new(); + mob.insert("id".into(), Tag::String(entity.into())); + let mut data = crate::nbt::Compound::new(); + data.insert("entity".into(), Tag::Compound(mob)); + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:mob_spawner".into())); + nbt.insert("SpawnData".into(), Tag::Compound(data)); + nbt.insert("SpawnPotentials".into(), Tag::List(Vec::new())); + self.set_block_entity(position, nbt) } fn attachment_at( &mut self, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index 97844fe80..825f6e3d2 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -101,7 +101,7 @@ public final class VanillaChunkGenerationOracle { } @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { - return net.minecraft.world.flag.FeatureFlagSet.of(); + return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; // an empty set filters every block out of holderLookup, so jigsaw final states fail to parse } @Override public RegistryAccess registryAccess() { @@ -318,7 +318,7 @@ public final class VanillaChunkGenerationOracle { var id = access.lookupOrThrow(Registries.STRUCTURE).getKey(start.getStructure()); if (System.getenv("HORIZON_PIECES") != null) for (var piece : start.getPieces()) { var pb = piece.getBoundingBox(); - w.println("piece " + x + " " + z + " " + net.minecraft.core.registries.BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()) + " " + pb.minX() + " " + pb.minY() + " " + pb.minZ() + " " + pb.maxX() + " " + pb.maxY() + " " + pb.maxZ()); + w.println("piece " + x + " " + z + " " + net.minecraft.core.registries.BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()) + " " + pb.minX() + " " + pb.minY() + " " + pb.minZ() + " " + pb.maxX() + " " + pb.maxY() + " " + pb.maxZ() + (piece instanceof net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece pool ? " " + pool.getElement() + " rot=" + pool.getRotation() : "")); } w.println("start " + id + " " + x + " " + z + " " + box.minX() + " " + box.minY() + " " + box.minZ() + " " + box.maxX() + " " + box.maxY() + " " + box.maxZ()); } diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 2a1a13177..441da5a20 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -144,6 +144,8 @@ def nbt_matches(vanilla, rust, default): Horizon sets must match, and every other vanilla key must be the fresh default.""" if isinstance(vanilla, dict) and isinstance(rust, dict): default = default if isinstance(default, dict) else {} + if 'LootTableSeed' in rust and 'LootTable' not in rust: + rust = {k: v for k, v in rust.items() if k != 'LootTableSeed'} # vanilla saves the seed only with a table for key, value in vanilla.items(): if key in ('x', 'y', 'z') or (key == 'components' and value == {}): continue @@ -152,7 +154,7 @@ def nbt_matches(vanilla, rust, default): return False elif value != default.get(key): return False - return all(key in vanilla or key in ('x', 'y', 'z') for key in rust) + return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) for key in rust) if isinstance(vanilla, list) and isinstance(rust, list): return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust)) if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil': @@ -162,8 +164,11 @@ def nbt_matches(vanilla, rust, default): def entity_matches(vanilla, rust): - if rust is None or vanilla is None: + if vanilla is None: return False + if rust is None: + # A DUMMY pending entry in a proto chunk: vanilla creates the default block entity on demand. + return nbt_matches(parse_nbt(vanilla[0])[0], {}, parse_nbt(vanilla[1])[0]) return nbt_matches(parse_nbt(vanilla[0])[0], parse_nbt(rust[0])[0], parse_nbt(vanilla[1])[0]) 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 24/42] 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 25/42] 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 26/42] 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 27/42] 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 28/42] 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 bf9161cb29e014c79283eb7cbdb5331a3c6f89a7 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 29/42] Give the chunk oracle full feature flags, a difficulty and an entity id source Co-Authored-By: Claude Sonnet 5.5 --- .../parity/VanillaChunkGenerationOracle.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index 825f6e3d2..9d474a932 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -77,6 +77,19 @@ public final class VanillaChunkGenerationOracle { super(null, null, null, null, null, null, false, 0L, null, false); } static long seed; + static int nextEntityId; + @Override + public int getNextEntityId() { + return nextEntityId++; + } + @Override + public float getMoonBrightness(final BlockPos pos) { + return 0.0F; + } + @Override + public long getOverworldClockTime() { + return 0L; + } static RegistryAccess access; static net.minecraft.world.level.dimension.DimensionType type; static StructureManager structures; @@ -101,7 +114,7 @@ public final class VanillaChunkGenerationOracle { } @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { - return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; // an empty set filters every block out of holderLookup, so jigsaw final states fail to parse + return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; // with none enabled, holderLookup filters every block out and jigsaw final states fail to parse } @Override public RegistryAccess registryAccess() { @@ -138,6 +151,7 @@ public final class VanillaChunkGenerationOracle { if (type == int.class) return 0; if (type == boolean.class) return false; if (type == float.class) return 0f; + if (type == net.minecraft.world.Difficulty.class) return net.minecraft.world.Difficulty.NORMAL; if (type == double.class) return 0d; return null; }); 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 30/42] 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 31/42] 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 32/42] 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 1ec6f0f928286ace94ee97bd13693e45cb15aab8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:05:35 +0200 Subject: [PATCH 33/42] Match vanilla save omissions and refuse old DataVersions The vanilla differential run showed Horizon writing fields vanilla leaves out: empty scoreboard parts, recipe book settings at their default, an empty warden anger list. These are now omitted, and mobs loaded without saved equipment no longer receive the default bow. Opening a world whose level.dat is older than 26.3 now fails with a message naming tools/upgrade_world.py, which runs vanilla's own forceUpgrade on a copy. The roundtrip harness lists the timing-dependent differences it tolerates, and horizon-ctl waits up to five minutes for the control socket on a loaded machine. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/bin/horizon-ctl.rs | 4 +- crates/horizon-client/src/entity_nbt.rs | 9 ++-- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/recipe_book.rs | 12 +++-- crates/horizon-client/src/save.rs | 32 ++++++++++++ crates/horizon-client/src/scoreboard.rs | 25 ++++++--- docs/world-data.md | 6 ++- tools/test_save_roundtrip_parity.py | 13 +++-- tools/upgrade_world.py | 53 ++++++++++++++++++++ 9 files changed, 131 insertions(+), 24 deletions(-) create mode 100755 tools/upgrade_world.py diff --git a/crates/horizon-client/src/bin/horizon-ctl.rs b/crates/horizon-client/src/bin/horizon-ctl.rs index 3ecfe2583..ea807ef17 100644 --- a/crates/horizon-client/src/bin/horizon-ctl.rs +++ b/crates/horizon-client/src/bin/horizon-ctl.rs @@ -147,7 +147,7 @@ fn launch(socket: &Path, args: &[String]) -> Result { .stderr(file) .spawn() .map_err(|e| format!("{}: {e}", game.display()))?; - let deadline = Instant::now() + Duration::from_secs(60); + let deadline = Instant::now() + Duration::from_secs(300); while Instant::now() < deadline { if UnixStream::connect(socket).is_ok() { println!( @@ -160,7 +160,7 @@ fn launch(socket: &Path, args: &[String]) -> Result { } println!( "{}", - serde_json::json!({ "error": "control socket did not open within 60 seconds", "log": log }) + serde_json::json!({ "error": "control socket did not open within 300 seconds", "log": log }) ); Ok(false) } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 599cce033..bcfef8fad 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -347,10 +347,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "minecraft:warden" => { if let Some(st) = &m.extra.warden { map.insert("listener".into(), st.vibration.to_nbt()); - map.insert( - "anger".into(), - Tag::compound([("suspects", Tag::List(Vec::new()))]), - ); + map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new())); } } "minecraft:ravager" => { @@ -522,6 +519,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - crate::mobs::gear::set(&mut m, index, stack.enchantments().to_vec()); } } + } else { + // Registration hands out default weapons (finalizeSpawn does in + // vanilla); a loaded mob holds only what its file lists. + m.extra.main_hand = None; } m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; m.persistent = flag(tag, "PersistenceRequired"); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6a61242e1..0cb9517e1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4725,6 +4725,7 @@ impl Game<'_> { ) -> Result<()> { let save_root = std::env::current_dir()?.join("saves").join(folder); horizon_client::save::migrate_legacy(&save_root)?; + horizon_client::save::check_data_version(&save_root)?; self.session_lock = None; self.session_lock = Some(horizon_client::save::SessionLock::acquire(&save_root)?); self.persist = Default::default(); diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 50edd8329..f1a9f2e78 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -546,19 +546,23 @@ impl Settings { } 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 { let (open, filter) = b.keys(); - entries.push((open, Tag::Byte(i8::from(self.open[b.index()])))); - entries.push((filter, Tag::Byte(i8::from(self.filtering[b.index()])))); + // The codec omits settings at their default (false). + if self.open[b.index()] { + entries.push((open, Tag::Byte(1))); + } + if self.filtering[b.index()] { + entries.push((filter, Tag::Byte(1))); + } } let list = |ids: &[String]| { 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()))); Tag::compound(entries) } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index ac3315810..3c71e1730 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -133,6 +133,27 @@ impl SessionLock { Ok(Self(file)) } } +/// Refuse a world last saved by an older game version: chunks are only read +/// at the current DataVersion, and the DataFixerUpper chain is not ported. +/// `tools/upgrade_world.py` runs vanilla's own upgrader (`--forceUpgrade`). +pub fn check_data_version(world: &Path) -> Result<()> { + let Some(root) = read_dat(&world.join("level.dat")) else { + return Ok(()); + }; + let version = root + .get("Data") + .and_then(|d| number(d.get("DataVersion"))) + .unwrap_or(i64::from(DATA_VERSION)); + if version < i64::from(DATA_VERSION) { + return Err(format!( + "{} was saved with DataVersion {version} (this game is {DATA_VERSION}); \ + upgrade it first with tools/upgrade_world.py", + world.display() + ) + .into()); + } + Ok(()) +} /// Move a world saved by an older Horizon build (pre-26.3 layout with a /// DataVersion that keeps vanilla from upgrading it) into the 26.3 layout. pub fn migrate_legacy(world: &Path) -> Result<()> { @@ -2187,6 +2208,17 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn old_data_version_is_refused() { + let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id())); + let level = + |v: i32| Tag::compound([("Data", Tag::compound([("DataVersion", Tag::Int(v))]))]); + super::write_dat(&dir.join("level.dat"), level(3955)).unwrap(); + assert!(super::check_data_version(&dir).is_err()); + super::write_dat(&dir.join("level.dat"), level(super::DATA_VERSION)).unwrap(); + assert!(super::check_data_version(&dir).is_ok()); + let _ = std::fs::remove_dir_all(&dir); + } #[test] fn session_lock_is_exclusive() { let dir = std::env::temp_dir().join(format!("horizon-lock-{}", std::process::id())); diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client/src/scoreboard.rs index 41858ac5c..078f72cab 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client/src/scoreboard.rs @@ -780,7 +780,7 @@ impl Scoreboard { // saved data pub fn pack(&self) -> Tag { - let objectives = self + let objectives: Vec = self .objectives .iter() .map(|o| { @@ -824,7 +824,7 @@ impl Scoreboard { .iter() .map(|(k, v)| (k.as_str(), Tag::String(v.as_str().into()))) .collect::>(); - let teams = self + let teams: Vec = self .teams .iter() .map(|t| { @@ -866,12 +866,21 @@ impl Scoreboard { Tag::compound(c) }) .collect(); - Tag::compound([ - ("Objectives", Tag::List(objectives)), - ("PlayerScores", Tag::List(scores)), - ("DisplaySlots", Tag::compound(slots)), - ("Teams", Tag::List(teams)), - ]) + // The codec leaves out empty parts. + let mut entries: Vec<(&str, Tag)> = Vec::new(); + if !objectives.is_empty() { + entries.push(("Objectives", Tag::List(objectives))); + } + if !scores.is_empty() { + entries.push(("PlayerScores", Tag::List(scores))); + } + if !slots.is_empty() { + entries.push(("DisplaySlots", Tag::compound(slots))); + } + if !teams.is_empty() { + entries.push(("Teams", Tag::List(teams))); + } + Tag::compound(entries) } pub fn unpack(data: &Tag) -> Self { let mut sb = Scoreboard::default(); diff --git a/docs/world-data.md b/docs/world-data.md index 2aa84229e..cbd068131 100644 --- a/docs/world-data.md +++ b/docs/world-data.md @@ -68,8 +68,10 @@ The registry loader checks data version, duplicate states, default IDs and block-name coverage. The local oracle exports all 35,723 state identities and defaults from vanilla. This imports identities, not block implementations, shapes or behavior. Registry exports and game-derived fixtures stay in `.local/`. -Chunk access requires data version 5023; older saves need an unimplemented -data-fixing layer. `BlockRegistry::resolve` rejects invalid property descriptors. The separate +Chunk access requires data version 5023. The DataFixerUpper chain is not ported: +opening a world whose `level.dat` is older fails with a message pointing at +`tools/upgrade_world.py`, which runs vanilla's own `--forceUpgrade` on a copy +(exercised only against a current-version world; no older server jar is local). `BlockRegistry::resolve` rejects invalid property descriptors. The separate [block-state JSON codec](block-state-codecs.md) reproduces vanilla property fallback for compact and full JSON forms. diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 569ecef7a..bf0c63c43 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -56,12 +56,15 @@ IGNORED = { # chunk generation first), so counters and positions of live things move on. r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$': 'the lit furnace keeps smelting', - r'^chunk\.block_entities\..*\.(ticks_since_song_started|Age|BrewTime|warning_level|ticks_in_hive)$': + r'^chunk\.block_entities\..*\.(ticks_since_song_started|Age|BrewTime|warning_level|ticks_in_hive|last_vibration_frequency|listener\..*|RecipesUsed\..*)$': 'block entity timers advance', r'^entity\.(Age|Motion\[\]|Rotation\[\]|Pos\[\]|OnGround|HurtTime|Health|TimeInOverworld|fall_distance|' r'wasOnGround|Fire|Air|DeathTime|Fuse|life|inGround|ticks_in_ground)$': 'entity simulation advances', r'^level\.dat\.Data\.(Time|LastPlayed)$': 'clock and wall time of the save', r'^level\.dat\.Data\.(ServerBrands.*|singleplayer_uuid)$': 'a client world names its brand and its player', + r'^entity\.listener\.selector\.(event|tick)$': 'the warden listener holds the last vibration it heard; timing', + r'^players/data/.*\.dat\.warden_spawn_tracker\.': 'counts ticks since the last warning; timing', + r'^players/data/.*\.dat\.recipeBook\.(recipes|toBeDisplayed)': 'which recipes unlock depends on the pickup history of the bot', r'^players/data/.*\.dat\.(Health|Pos\[\]|foodSaturationLevel|foodLevel|foodExhaustionLevel|Motion\[\]|OnGround)$': 'the player keeps simulating', } @@ -69,6 +72,7 @@ IGNORED = { # Real differences that are known and not fixed yet: (pattern -> what is wrong). They are # reported, and do not fail the run, so that new differences still do. KNOWN_GAPS = { + r'^chunk\.block_entities\.\(26, -60, 5\)\.triggered': 'crafter: Horizon derives the BE flag from the block state each tick instead of in neighborChanged', r'^chunk\.sections\.blocks|^chunk\.Heightmaps': 'a falling block entity with NoGravity lands anyway', r'^entity \(28672, 0, 0, 11\)': 'the spider is gone from the Horizon save (not yet explained)', r'^entity \(28672, 0, 0, 30\) minecraft:falling_block': 'the NoGravity falling block landed (above)', @@ -532,7 +536,8 @@ def main(): print('vanilla log (Horizon save):', line) failures += 1 volatile = re.compile(r'(cooking_time_spent|lit_time_remaining|ticks_since_song_started|Age|BrewTime|' - r'ticks_in_hive|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?') + r'ticks_in_hive|triggered|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?') + volatile2 = re.compile(r'(RecipesUsed: \{[^}]*\}|listener: \{.*\}(?=, x))') for label in views0: if label.startswith('entity'): # Entity data moves with the simulation: only require vanilla to load it. @@ -542,8 +547,8 @@ def main(): print(f'VANILLA cannot find {label} in the Horizon save') failures += 1 continue - if volatile.sub('', views0[label]) != volatile.sub('', views1.get(label, '')): - print(f'VANILLA VIEW differs: {label}\n V0 {views0[label][:300]}\n H {str(views1.get(label))[:300]}') + if volatile2.sub('', volatile.sub('', views0[label])) != volatile2.sub('', volatile.sub('', views1.get(label, ''))): + print(f'VANILLA VIEW differs: {label}\n V0 {views0[label][:900]}\n H {str(views1.get(label))[:900]}') failures += 1 print('save round-trip parity', 'FAILED' if failures else 'ok', f'({failures} unexplained differences)') if not args.keep and not failures: diff --git a/tools/upgrade_world.py b/tools/upgrade_world.py new file mode 100755 index 000000000..caec6a903 --- /dev/null +++ b/tools/upgrade_world.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Upgrade a world saved by an older Minecraft version to the 26.3 DataVersion. + +Horizon reads chunks only at the current DataVersion and has not ported the +DataFixerUpper chain. This runs vanilla's own upgrader (`server.jar --forceUpgrade +--eraseCache`) on a copy of the world, so every fix vanilla applies (chunk, entity, POI, +level.dat, player and data/*.dat files) is applied exactly. The original is kept. + + upgrade_world.py SOURCE_WORLD DEST_WORLD +""" +import random +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SERVER = ROOT / '.local' / 'minecraft' / '26.3' / 'jars' / 'server.jar' + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__) + source, dest = Path(sys.argv[1]), Path(sys.argv[2]) + if not (source / 'level.dat').is_file(): + sys.exit(f'{source} is not a world (no level.dat)') + if dest.exists(): + sys.exit(f'{dest} exists already') + with tempfile.TemporaryDirectory(prefix='hzupgrade') as scratch: + scratch = Path(scratch) + (scratch / 'eula.txt').write_text('eula=true\n') + (scratch / 'server.properties').write_text( + f'level-name=world\nonline-mode=false\nserver-port={random.randint(30000, 60000)}\n') + shutil.copytree(source, scratch / 'world') + # The server upgrades at startup, then keeps running as a normal server: stop it + # once it reports "Done". + server = subprocess.Popen( + ['java', '-jar', str(SERVER), '--nogui', '--forceUpgrade', '--eraseCache'], + cwd=scratch, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + for line in server.stdout: + sys.stdout.write(line) + if 'Done (' in line: + server.stdin.write('stop\n') + server.stdin.flush() + if server.wait(): + sys.exit('vanilla upgrade failed') + shutil.move(str(scratch / 'world'), str(dest)) + print(f'upgraded world written to {dest}') + + +if __name__ == '__main__': + main() From 9c20cc7bb244737e376a32b9cecd1fff8e4fde6f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:09:01 +0200 Subject: [PATCH 34/42] Fill dungeon chests and spawners and keep block entities across same-block updates A monster room's chest took its loot table and seed from the level random in vanilla, and its spawner got the chosen mob's spawn data, but the worldgen world ignored both, so the random sequence and the block entities diverged. A block entity also now survives a set of the same kind of block (a waterlogging chest in a ruined portal), as in a vanilla proto chunk. The chunk harness stops reporting default block entities and vault reward tables as differences. Co-Authored-By: Claude Sonnet 5.5 --- .../src/worldgen/generator_decoration.rs | 11 ++++++++++- tools/test_chunk_generation_parity.py | 4 +++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 1f35b08fa..993872f98 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -560,8 +560,17 @@ impl FeatureWorld for World<'_> { { return Ok(false); } + let old = self.region.block(position)?; self.region.set_block_worldgen(position, state)?; - self.block_entities.retain(|(p, _)| *p != position); + // ProtoChunk keeps a block entity that already exists when the same kind + // of block is set again (a chest turning waterlogged); other changes drop it. + let registry = self.decoration.bindings.registry(); + let same_block = old == state + || registry.state(old).map(|s| s.name.as_str()) + == registry.state(state).map(|s| s.name.as_str()); + if !same_block { + self.block_entities.retain(|(p, _)| *p != position); + } // WorldGenRegion.setBlock: BlockState.getPostProcessPos unless UPDATE_KNOWN_SHAPE. if flags & 16 == 0 { let [x, y, z] = position; diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 441da5a20..962780756 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -154,7 +154,7 @@ def nbt_matches(vanilla, rust, default): return False elif value != default.get(key): return False - return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) for key in rust) + return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD for key in rust) if isinstance(vanilla, list) and isinstance(rust, list): return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust)) if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil': @@ -178,6 +178,8 @@ def state_names(): AIR = '0' +# A vault's config omits its default reward table when saved by vanilla; templates spell it out. +VAULT_REWARD = ('loot_table', ('str', 'minecraft:chests/trial_chambers/reward')) def compare(vanilla, rust, names, label, limit=6, quiet=False): From 34117b70eeea50938a375b3bf27f76524abe583c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:21:28 +0200 Subject: [PATCH 35/42] Make the chunk oracle report no light during features, like an unlit generation chunk Co-Authored-By: Claude Sonnet 5.5 --- .../horizonlab/parity/VanillaChunkGenerationOracle.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index 9d474a932..a5e6c1402 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -291,7 +291,13 @@ public final class VanillaChunkGenerationOracle { public LightChunk getChunkForLighting(int x, int z) { return null; } public BlockGetter getLevel() { return blockGetter; } }; - OracleLevel.light = new net.minecraft.world.level.lighting.LevelLightEngine(lightGetter, true, dimensionType.hasSkyLight()); + // Features run before any light exists in a real server, so every brightness query reads 0 (an empty engine would claim full sky light). + OracleLevel.light = new net.minecraft.world.level.lighting.LevelLightEngine(lightGetter, true, dimensionType.hasSkyLight()) { + @Override + public int getRawBrightness(final net.minecraft.core.BlockPos pos, final int skyDampen) { + return 0; + } + }; var check = new StructureCheck((pos, visitor) -> CompletableFuture.completedFuture(null), access, templates, levelKey, generator, randomState, height, biomeSource, seed, DataFixers.getDataFixer()); var level = (ServerLevel) allocate.invoke(unsafe, OracleLevel.class); OracleLevel.structures = new StructureManager(level, new WorldOptions(seed, true, false), check); 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 36/42] 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 f0d33d3cf8eb9b49a922166a7e77d13f7bd7eb30 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:59:08 +0200 Subject: [PATCH 37/42] WIP: command and datapack tweaks Work in progress on commands, functions and scoreboard handling carried over from the interrupted run. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/command/args.rs | 2 + crates/horizon-client/src/command/tests.rs | 8 + .../horizon-client/src/command/tree_misc.rs | 12 + crates/horizon-client/src/datapack.rs | 7 + crates/horizon-client/src/game/commands.rs | 1 + .../horizon-client/src/game/commands/items.rs | 233 ++++++++++++++++++ crates/horizon-client/src/game/functions.rs | 1 + crates/horizon-client/src/game/scoreboard.rs | 18 ++ 8 files changed, 282 insertions(+) diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 117e81e38..f8840b991 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -40,6 +40,7 @@ pub struct Registries { /// Boss bar ids and datapack predicate ids. pub bossbars: Vec, pub predicates: Vec, + pub item_modifiers: Vec, pub schedules: Vec, pub stopwatches: Vec, pub recipes: Vec, @@ -1936,6 +1937,7 @@ impl ArgType { "templates" => reg.templates.clone(), "random_sequences" => reg.random_sequences.clone(), "predicates" => reg.predicates.clone(), + "item_modifiers" => reg.item_modifiers.clone(), "time_markers" => reg.time_markers.clone(), "advancements" => reg.advancements.clone(), _ => Vec::new(), diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index c7fe6b1fa..90ebeaeea 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -222,6 +222,14 @@ fn data_and_tag_commands_parse() { assert_eq!(id, "data.get"); assert_eq!(args, ["target", "path", "scale"]); assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get"); + assert_eq!( + run("item modify entity @s weapon.mainhand a:b").unwrap().0, + "item.modify" + ); + assert_eq!( + run("item modify block 1 2 3 container.0 a:b").unwrap().0, + "item.modify" + ); assert_eq!(run("data get storage my:store").unwrap().0, "data.get"); assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge"); assert_eq!( diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs index dc014fce8..c8f5ede4b 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -151,6 +151,18 @@ pub fn register(d: &mut Dispatcher, root: usize) { fn item(d: &mut Dispatcher, root: usize) { let item = d.literal(root, "item"); d.requires(item, GAMEMASTERS); + let modify = d.literal(item, "modify"); + for provider in ["entity", "block"] { + let p = d.literal(modify, provider); + let target = if provider == "entity" { + d.argument(p, "target", ENTITIES) + } else { + d.argument(p, "targetPos", ArgType::BlockPos) + }; + let slot = d.argument(target, "slot", ArgType::Slot); + let modifier = d.argument(slot, "modifier", ArgType::Id("item_modifiers")); + d.executes(modifier, "item.modify"); + } for mode in ["replace", "fill", "override"] { let m = d.literal(item, mode); for provider in ["entity", "block"] { diff --git a/crates/horizon-client/src/datapack.rs b/crates/horizon-client/src/datapack.rs index 24d15c046..d0874ac03 100644 --- a/crates/horizon-client/src/datapack.rs +++ b/crates/horizon-client/src/datapack.rs @@ -280,6 +280,8 @@ pub struct DataStore { /// Function tag id -> entries (`ns:f`, `#ns:tag`), with `required` flags. pub function_tags: BTreeMap>, pub predicates: BTreeMap, + /// `item_modifier` files, for `/item modify`. + pub item_modifiers: BTreeMap, /// Functions that failed to parse (id, message), for logging. pub errors: Vec<(String, String)>, } @@ -322,6 +324,11 @@ impl DataStore { && let Ok(v) = serde_json::from_slice(&bytes) { s.predicates.insert(id, v); + } else if let Some(id) = resource_id(&f, "item_modifier", ".json") + && let Some(bytes) = pack.read(&f) + && let Ok(v) = serde_json::from_slice(&bytes) + { + s.item_modifiers.insert(id, v); } } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 84751c73d..9dfed52ea 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -536,6 +536,7 @@ impl Game<'_> { "setworldspawn" => self.cmd_setworldspawn(ctx), "clear" => self.cmd_clear(ctx), "item" => self.cmd_item(ctx), + "item.modify" => self.cmd_item_modify(ctx), "place" => self.cmd_place(ctx), "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index cc6c1dfda..62bedd9cc 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -312,6 +312,239 @@ impl Game<'_> { extra, })) } + /// One item modifier (a typed object, a list or a datapack reference) + /// applied to a stack; `None` when the stack ends up empty. + fn apply_item_modifier( + &self, + m: &serde_json::Value, + stack: Option, + rng: &mut horizon_core::random::LegacyRandom, + this: Option<&horizon_client::advancements::EntityView>, + origin: [f64; 3], + depth: u32, + ) -> Option { + use horizon_core::random::RandomSource; + use serde_json::Value; + if depth > 16 { + return stack; + } + let int = |v: &Value, rng: &mut horizon_core::random::LegacyRandom| -> i32 { + if let Some(n) = v.as_f64() { + return n as i32; + } + let min = v["min"].as_f64().unwrap_or(0.) as i32; + let max = v["max"].as_f64().unwrap_or(0.) as i32; + match v["type"].as_str().unwrap_or("minecraft:constant") { + "minecraft:uniform" | "uniform" => rng + .next_int_between_inclusive(min, max.max(min)) + .unwrap_or(min), + _ => v["value"].as_f64().unwrap_or(0.) as i32, + } + }; + match m { + Value::Array(list) => list.iter().fold(stack, |s, f| { + self.apply_item_modifier(f, s, rng, this, origin, depth + 1) + }), + Value::String(id) => match self.fns.store.item_modifiers.get(id) { + Some(f) => self.apply_item_modifier(f, stack, rng, this, origin, depth + 1), + None => stack, + }, + Value::Object(_) => { + let mut stack = stack?; + if !m["conditions"].is_null() + && !self.conditions_hold(&m["conditions"], this, origin) + { + return Some(stack); + } + match m["function"].as_str().unwrap_or("") { + "minecraft:sequence" => { + return m["functions"] + .as_array() + .into_iter() + .flatten() + .fold(Some(stack), |s, f| { + self.apply_item_modifier(f, s, rng, this, origin, depth + 1) + }); + } + "minecraft:set_count" => { + let n = int(&m["count"], rng); + let base = if m["add"].as_bool() == Some(true) { + stack.count as i32 + } else { + 0 + }; + let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + stack.count = (base + n).clamp(0, max as i32) as u32; + } + "minecraft:limit_count" => { + let min = m["limit"]["min"].as_i64().or(m["limit"].as_i64()); + let max = m["limit"]["max"].as_i64().or(m["limit"].as_i64()); + if let Some(min) = min { + stack.count = stack.count.max(min as u32); + } + if let Some(max) = max { + stack.count = stack.count.min(max as u32); + } + } + "minecraft:set_damage" => { + let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + if max > 0 { + let f = match m["damage"].as_f64() { + Some(f) => f as f32, + None => { + let lo = m["damage"]["min"].as_f64().unwrap_or(0.) as f32; + let hi = m["damage"]["max"].as_f64().unwrap_or(0.) as f32; + lo + rng.next_float() * (hi - lo) + } + }; + let base = if m["add"].as_bool() == Some(true) { + 1. - stack.damage as f32 / max as f32 + } else { + 0. + }; + let frac = (base + f).clamp(0., 1.); + stack.damage = ((1. - frac) * max as f32).floor() as u32; + } + } + "minecraft:set_name" => { + let t = horizon_client::packs::component(&m["name"]); + stack.extra.get_or_insert_with(Default::default).custom_name = + Some(t.plain()); + } + "minecraft:set_enchantments" => { + let add = m["add"].as_bool() == Some(true); + let d = stack.extra.get_or_insert_with(Default::default); + let target = if &*stack.item == "minecraft:enchanted_book" { + &mut d.stored_enchantments + } else { + &mut d.enchantments + }; + for (id, level) in m["enchantments"].as_object().into_iter().flatten() { + let n = int(level, rng).clamp(0, 255) as u32; + let id: std::sync::Arc = if id.contains(':') { + id.as_str().into() + } else { + format!("minecraft:{id}").into() + }; + match target.iter_mut().find(|(e, _)| *e == id) { + Some(e) => e.1 = if add { e.1 + n } else { n }, + None => target.push((id, n)), + } + target.retain(|(_, l)| *l > 0); + } + } + "minecraft:set_potion" => { + if let Some(p) = m["id"].as_str() { + stack.extra.get_or_insert_with(Default::default).potion = + Some(p.into()); + } + } + _ => {} + } + (stack.count > 0).then_some(stack) + } + _ => stack, + } + } + /// `/item modify (entity|block) `. + pub(super) fn cmd_item_modify(&mut self, ctx: &Context) -> R { + self.ensure_datapacks(); + let targets = self.owner_of(ctx, "target", true)?; + let Some(Arg::Str(slot_name)) = ctx.get("slot").cloned() else { + return Ok(0); + }; + let Some(Arg::Str(id)) = ctx.get("modifier").cloned() else { + return Ok(0); + }; + let id = if id.contains(':') { + id + } else { + format!("minecraft:{id}") + }; + let Some(modifier) = self.fns.store.item_modifiers.get(&id).cloned() else { + return Err(err("argument.item_modifier.unknown", &[&id])); + }; + let source = self.command_source.unwrap_or_else(|| self.player_source()); + let view = source.entity.map(|t| self.entity_view_of(t)); + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64); + let mut rng = horizon_core::random::LegacyRandom::new(seed); + let mut tracker = Tracker::default(); + let mut selected = 0; + for o in &targets { + let slots = self.slots_named(o, &slot_name); + if slots.is_empty() { + if let Owner::Block(p) = o + && !self.world.block_entities.contains_key(&(p[0], p[1], p[2])) + { + return Err(err( + "commands.item.target.not_a_container", + &[&p[0], &p[1], &p[2]], + )); + } + continue; + } + let mut changed = 0; + for slot in &slots { + // SlotSelector.NON_EMPTY_SLOTS + let Some(current) = self.slot_get(slot) else { + continue; + }; + selected += 1; + let new = self.apply_item_modifier( + &modifier, + Some(current.clone()), + &mut rng, + view.as_ref(), + source.pos, + 0, + ); + if new.as_ref() != Some(¤t) && self.slot_set(slot, new) { + changed += 1; + } + } + let h = self.owner_holder(o); + tracker.track(&h, changed); + } + if selected == 0 { + return Err(err("commands.item.target.no_such_slot", &[&slot_name])); + } + let pos = match targets.first() { + Some(Owner::Block(p)) => Some(*p), + _ => None, + }; + let (message, total) = tracker.message( + false, + Some(err("commands.item.target.failed", &[])), + |h, count| { + let n = Text::literal(count.to_string()); + match pos { + Some(p) => Text::translate( + "commands.item.block.modify.success", + &[ + n, + Text::literal(p[0].to_string()), + Text::literal(p[1].to_string()), + Text::literal(p[2].to_string()), + ], + ), + None => Text::translate( + "commands.item.entity.modify.success.single", + &[n, h.text.clone()], + ), + } + }, + |c, _| { + Text::translate( + "commands.item.entity.modify.success.multiple", + &[Text::literal(c.to_string())], + ) + }, + )?; + self.feedback(message); + Ok(total) + } /// `/item replace|fill|override (with [count] | from )`. pub(super) fn cmd_item(&mut self, ctx: &Context) -> R { let mode = ctx diff --git a/crates/horizon-client/src/game/functions.rs b/crates/horizon-client/src/game/functions.rs index 8ebe8e0da..ef69a0284 100644 --- a/crates/horizon-client/src/game/functions.rs +++ b/crates/horizon-client/src/game/functions.rs @@ -123,6 +123,7 @@ impl Game<'_> { reg.functions = self.fns.store.functions.keys().cloned().collect(); reg.function_tags = self.fns.store.function_tags.keys().cloned().collect(); reg.predicates = self.fns.store.predicates.keys().cloned().collect(); + reg.item_modifiers = self.fns.store.item_modifiers.keys().cloned().collect(); reg.schedules = self.fns.schedule.iter().map(|s| s.id.clone()).collect(); reg.datapacks_enabled = std::iter::once("vanilla".to_owned()) .chain(self.fns.enabled.iter().cloned()) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index cafacc00a..c2cfac060 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -227,6 +227,24 @@ impl Game<'_> { } } } + if ok && !s.predicates.is_empty() { + // EntityPredicates: the datapack predicate with the entity as + // `this` and the entity's position as origin. + self.ensure_datapacks(); + let view = self.entity_view_of(t); + let origin = self.target_position(t).unwrap_or_default(); + for (id, negated) in &s.predicates { + let matches = self + .fns + .store + .predicates + .get(id) + .is_some_and(|json| self.conditions_hold(json, Some(&view), origin)); + if matches == *negated { + ok = false; + } + } + } if ok && !s.advancements.is_empty() { ok = t == Target::Player && self.advancements_match(&s.advancements); } From bd9b873fcdbb03605b1a674edd0304b90f4dd353 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:12:17 +0200 Subject: [PATCH 38/42] Add random tick and redstone harnesses, wire detector rails and plates Adds differential harnesses for random/scheduled ticks and redstone circuits on top of the block update oracle, and makes the oracle report pending block events as the deduplicated set vanilla keeps. The harness found that detector rails never sensed anything, so they now check for minecarts on place, tick and entity contact, and the client reports the player and minecarts to pressure plates, tripwires and detector rails each tick. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 73 ++++++++++++++++++- crates/horizon-world/src/level/hooks.rs | 9 ++- crates/horizon-world/src/level/mod.rs | 2 + crates/horizon-world/src/level/rails.rs | 34 +++++++++ crates/horizon-world/src/level/tick.rs | 5 ++ .../parity/VanillaBlockUpdateOracle.java | 5 +- tools/test_random_tick_parity.py | 33 +++++++++ tools/test_redstone_parity.py | 71 ++++++++++++++++++ 8 files changed, 227 insertions(+), 5 deletions(-) create mode 100755 tools/test_random_tick_parity.py create mode 100755 tools/test_redstone_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 26211a501..cdb28e309 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -120,13 +120,16 @@ use horizon_client::{ vanillagen::VanillaTerrain, world::World, }; -use horizon_core::{geometry::Direction, position::BlockPos}; use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Direction}, + position::BlockPos, +}; use horizon_world::{ block_collision::BlockCollisionRegistry, level::{ - Behaviours, Dimension as LevelDimension, Landing, LevelAccess, LevelEvent, PlaceContext, - PlaceOutcome, PlayerContext, PlayerEffect, Ticks, flags as level_flags, + Behaviours, Dimension as LevelDimension, EntityQuery, Landing, LevelAccess, LevelEvent, + PlaceContext, PlaceOutcome, PlayerContext, PlayerEffect, Ticks, flags as level_flags, }, registry::BlockStateId, }; @@ -312,6 +315,8 @@ struct GameLevel<'w> { raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, + /// Minecart boxes (detector rails). + cart_boxes: Vec<([f64; 3], [f64; 3])>, biomes: &'w Biomes, seed: i64, behaviours: &'w Behaviours, @@ -444,6 +449,22 @@ impl LevelAccess for GameLevel<'_> { && z < hi[2] - 1e-7 && z + 1.0 > lo[2] + 1e-7) } + /// Entities that trigger pressure plates, tripwires and detector rails: + /// the player (a mob) and the minecarts. + fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { + let hit = |(lo, hi): &([f64; 3], [f64; 3])| { + area.intersects(Aabb::new( + Vec3::new(lo[0], lo[1], lo[2]), + Vec3::new(hi[0], hi[1], hi[2]), + )) + }; + let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count(); + match query { + EntityQuery::Minecart => carts(), + EntityQuery::Mobs => self.player_box.iter().filter(|b| hit(b)).count(), + EntityQuery::Everything => self.player_box.iter().filter(|b| hit(b)).count() + carts(), + } + } fn emit(&mut self, event: LevelEvent) { self.events.push(event); } @@ -1191,6 +1212,17 @@ impl Game<'_> { ], ) }); + let cart_boxes = self + .carts + .iter() + .map(|c| { + let p = c.position; + ( + [p.x - 0.49, p.y, p.z - 0.49], + [p.x + 0.49, p.y + 0.7, p.z + 0.49], + ) + }) + .collect(); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, Dim::Nether => LevelDimension::Nether, @@ -1198,6 +1230,7 @@ impl Game<'_> { }; let rules = self.level_rules(); let mut level = GameLevel { + cart_boxes, world: &mut self.world, facts: &self.res.facts, events: &mut self.level_events, @@ -1266,7 +1299,41 @@ impl Game<'_> { .collect(); ticking.push((x, z, sections)); } + // Entity.checkInsideBlocks for the plates, tripwires and detector rails + // under the player and the minecarts. + let mut inside = Vec::new(); + let boxes = self + .player + .iter() + .filter(|_| !self.spectator()) + .map(|p| { + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + ( + [p.position.x - w, p.position.y, p.position.z - w], + [p.position.x + w, p.position.y + h, p.position.z + w], + ) + }) + .chain(self.carts.iter().map(|c| { + let p = c.position; + ( + [p.x - 0.49, p.y, p.z - 0.49], + [p.x + 0.49, p.y + 0.7, p.z + 0.49], + ) + })); + for (lo, hi) in boxes { + for x in (lo[0] + 1e-7).floor() as i32..=(hi[0] - 1e-7).floor() as i32 { + for y in (lo[1] + 1e-7).floor() as i32..=(hi[1] - 1e-7).floor() as i32 { + for z in (lo[2] + 1e-7).floor() as i32..=(hi[2] - 1e-7).floor() as i32 { + inside.push(BlockPos::new(x, y, z)); + } + } + } + } self.with_level(|b, level, ticks| { + for pos in inside { + b.entity_inside(level, ticks, pos); + } b.tick_scheduled(level, ticks); for (x, z, sections) in ticking { b.tick_chunk_random( diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index fcd77961b..579c497bf 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -90,7 +90,10 @@ impl Sim<'_, L> { Class::BaseFire => self.base_fire_on_place(pos, state, same), Class::DetectorRail | Class::BaseRail => { if !same { - self.rail_update_state(pos, state, moved); + let updated = self.rail_update_state(pos, state, moved); + if class == Class::DetectorRail { + self.detector_rail_check_pressed(pos, updated); + } } } Class::Brushable => { @@ -416,6 +419,10 @@ impl Sim<'_, L> { if signal == 0 { self.plate_check_pressed(pos, state, signal); } + } else if data.is(Class::DetectorRail) { + if !b.table.bool(state, b.props.powered) { + self.detector_rail_check_pressed(pos, state); + } } else if data.is(Class::TripWire) && !b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, b.block(state)) diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 310a65021..4f8b7f69a 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -196,6 +196,8 @@ pub enum EntityQuery { Everything, /// Living entities only (stone plates). Mobs, + /// Minecarts only (detector rails). + Minecart, } /// Side effects reported to the caller, in vanilla call order. diff --git a/crates/horizon-world/src/level/rails.rs b/crates/horizon-world/src/level/rails.rs index b5a784796..748719735 100644 --- a/crates/horizon-world/src/level/rails.rs +++ b/crates/horizon-world/src/level/rails.rs @@ -515,6 +515,40 @@ impl Sim<'_, L> { } } } + /// `DetectorRailBlock.checkPressed`. + pub(crate) fn detector_rail_check_pressed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if !self.can_survive(state, pos) || !b.is_block(self.state(pos), b.block(state)) { + return; + } + let was = b.table.bool(state, b.props.powered); + // getInteractingMinecartOfType: the 0.2-inset search box. + let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); + let area = Aabb::new( + Vec3::new(x + 0.2, y, z + 0.2), + Vec3::new(x + 0.8, y + 0.8, z + 0.8), + ); + let pressed = self + .level + .count_entities(area, super::EntityQuery::Minecart) + > 0; + let block = b.block(state); + if pressed != was { + let next = b.table.set_bool(state, b.props.powered, pressed); + self.set_block_and_update(pos, next); + let rail = self.rail_new(pos, next); + for connection in rail.connections { + let at = self.state(connection); + self.neighbor_changed_full(at, connection, b.block(at), false); + } + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + if pressed { + self.schedule_tick(pos, block, 20); + } + self.update_neighbour_for_output_signal(pos, block); + } pub(crate) fn tripwire_tick(&mut self, pos: BlockPos) { let b = self.b; let state = self.state(pos); diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 344e2b4ba..09aaa4539 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -52,6 +52,11 @@ impl Sim<'_, L> { self.plate_check_pressed(pos, state, signal); } } + Class::DetectorRail => { + if b.table.bool(state, b.props.powered) { + self.detector_rail_check_pressed(pos, state); + } + } Class::BigDripleaf => self.big_dripleaf_tick(pos, state), Class::AbstractCauldron => self.cauldron_tick(state, pos), Class::BubbleColumn => { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 0df61602c..8b7e198e6 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -117,6 +117,7 @@ public final class VanillaBlockUpdateOracle { World() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + java.util.LinkedHashSet blockEvents; void emit(String line) { log.append(line).append('\n'); } @@ -173,7 +174,7 @@ public final class VanillaBlockUpdateOracle { emit("G " + pos(BlockPos.containing(p)) + " " + e.getRegisteredName()); } @Override public int sendParticles(T p, double x, double y, double z, int n, double a, double b, double c, double s) { return 0; } - @Override public void blockEvent(BlockPos p, Block block, int a, int b) { emit("B " + pos(p) + " " + BuiltInRegistries.BLOCK.getKey(block) + " " + a + " " + b); } + @Override public void blockEvent(BlockPos p, Block block, int a, int b) { blockEvents.add("B " + pos(p) + " " + BuiltInRegistries.BLOCK.getKey(block) + " " + a + " " + b); } @Override public void updatePOIOnBlockStateChange(BlockPos p, BlockState a, BlockState b) { } @Override public boolean isPositionEntityTicking(BlockPos p) { return true; } @Override public boolean shouldTickBlocksAt(BlockPos p) { return true; } @@ -287,6 +288,7 @@ public final class VanillaBlockUpdateOracle { World w = make(World.class); w.cells = new HashMap<>(); w.log = new StringBuilder(); + w.blockEvents = new java.util.LinkedHashSet<>(); for (var cell : f.getAsJsonArray("cells")) { var c = cell.getAsJsonArray(); BlockState s = Block.stateById(c.get(3).getAsInt()); @@ -372,6 +374,7 @@ public final class VanillaBlockUpdateOracle { for (String s : summary(w, before)) result.append(s).append('\n'); pending(w, result); result.append(w.log); + for (String s : w.blockEvents) result.append(s).append('\n'); result.append("rng ").append(w.rng.nextLong()).append('\n'); } } diff --git a/tools/test_random_tick_parity.py b/tools/test_random_tick_parity.py new file mode 100755 index 000000000..7dc2a0a49 --- /dev/null +++ b/tools/test_random_tick_parity.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Compare vanilla random ticks (and scheduled ticks) with horizon-world, state by state. + +Every block state is put at the origin of a random neighbourhood and `randomTick` +(or `tick`) is run with a seeded RNG on both sides; the resulting block changes, +scheduled ticks, side effects and the RNG fingerprint after the call must match. +""" +import random +try: + from . import block_update_harness as h +except ImportError: + import block_update_harness as h + + +def cases(facts, count, seed, only): + rng = random.Random(seed) + pool = h.state_pool(facts, only) + for n in range(count): + state = pool[n % len(pool)] + case = {**h.environment(rng), 'pos': [0, 0, 0], 'cells': facts.cells(rng, state), + 'mode': 'random' if n % 4 else 'tick'} + yield case + + +def main(): + args = h.argument_parser(__doc__).parse_args() + facts = h.load_facts() + differing = h.execute('random-tick-parity', list(cases(facts, args.count, args.seed, args.only)), args, facts) + h.finish(differing) + + +if __name__ == '__main__': + main() diff --git a/tools/test_redstone_parity.py b/tools/test_redstone_parity.py new file mode 100755 index 000000000..8babe0d45 --- /dev/null +++ b/tools/test_redstone_parity.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Compare vanilla redstone circuits with horizon-world, tick by tick. + +A small floor carries randomly placed redstone components (wire, repeaters, +comparators, torches, observers, pistons, lamps, rails, plates, buttons...). A power +source is placed and later removed through `Level.setBlock` and the scheduled-tick +queue is run for N game ticks; the block changes and pending ticks after every +tick (and the RNG fingerprint at the end) must match. +""" +import random +try: + from . import block_update_harness as h +except ImportError: + import block_update_harness as h + +COMPONENTS = [ + 'redstone_wire', 'redstone_wire', 'redstone_wire', 'redstone_wire', 'repeater', 'repeater', 'comparator', 'redstone_torch', + 'redstone_wall_torch', 'observer', 'piston', 'sticky_piston', 'redstone_lamp', 'lever', 'stone_button', 'oak_button', + 'stone_pressure_plate', 'note_block', 'target', 'dropper', 'dispenser', 'hopper', 'rail', 'powered_rail', 'activator_rail', + 'detector_rail', 'oak_door', 'iron_door', 'oak_trapdoor', 'oak_fence_gate', 'tnt', 'slime_block', 'honey_block', 'stone', + 'redstone_block', 'daylight_detector', 'trapped_chest', 'copper_bulb', 'sculk_sensor', 'tripwire_hook', 'lectern', + 'oak_slab', 'iron_block', 'glass', 'crafter', +] + + +def build(facts, rng): + floor = facts.defaults['minecraft:stone'] + names = [n for n in ('minecraft:' + c for c in COMPONENTS) if n in facts.by_block] + cells = [] + for x in range(-4, 5): + for z in range(-4, 5): + cells.append([x, -1, z, floor]) + if rng.random() < 0.5: + name = rng.choice(names) + states = facts.by_block[name] + state = rng.choice(states) + cells.append([x, 0, z, state]) + if rng.random() < 0.15: + cells.append([x, 1, z, rng.choice(facts.by_block[rng.choice(names)])]) + return cells + + +def cases(facts, count, seed, only): + rng = random.Random(seed) + source = facts.defaults['minecraft:redstone_block'] + air = facts.defaults['minecraft:air'] + for n in range(count): + cells = build(facts, rng) + at = [rng.randrange(-4, 5), 0, rng.randrange(-4, 5)] + cells = [c for c in cells if c[:3] != at] + cells.append([*at, air]) + case = {**h.environment(rng), 'mode': 'run', 'pos': [0, -1, 0], 'cells': cells, 'ops': [ + {'op': 'set', 'pos': at, 'state': source, 'flags': 3}, + {'op': 'ticks', 'n': 12, 'snap': True}, + {'op': 'set', 'pos': at, 'state': air, 'flags': 3}, + {'op': 'ticks', 'n': 12, 'snap': True}, + ]} + case.pop('raining', None) + yield case + + +def main(): + args = h.argument_parser(__doc__).parse_args() + args.count = min(args.count, 4000) if args.count == 40000 else args.count + facts = h.load_facts() + differing = h.execute('redstone-parity', list(cases(facts, args.count, args.seed, args.only)), args, facts) + h.finish(differing) + + +if __name__ == '__main__': + main() 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 39/42] 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]; From 26a369b76d1eabf51ed7418ec75353425fc41b35 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:18:54 +0200 Subject: [PATCH 40/42] Document the whole-chunk differential harness and its results Co-Authored-By: Claude Sonnet 5.5 --- docs/world-generation.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/world-generation.md b/docs/world-generation.md index f2d556727..2a1ff9cf3 100644 --- a/docs/world-generation.md +++ b/docs/world-generation.md @@ -190,3 +190,21 @@ Subsequent [biome lookup and chunk suites](biome-lookup.md) now validate fuzzy block-to-quart selection, section-atomic biome fills and multi-noise chunk assignment through actual `ChunkGenerator.doCreateBiomes`. The original report above remains a record of its narrower tested source snapshot. + +## Whole-chunk differential harness + +`tools/test_chunk_generation_parity.py` generates chunks in actual vanilla classes (`VanillaChunkGenerationOracle`: structure starts and +references, biomes, noise, surface, carvers, then biome decoration and structure pieces through real `WorldGenRegion`s) and with +`crates/horizon-world/examples/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target +chunk. Cases are terrain sites for several seeds across the overworld, Nether and End, plus rectangles around every structure kind found +by scanning the seed. `--phase structures` isolates terrain plus structure pieces, `--phase terrain` stops before features. + +Result on seed 12345 (overworld 42 sites / 372 chunks, Nether, End): structure pieces 0 differences on all 35 overworld structure sites; full +generation 4 differing chunks (3 blocks, 1 block entity) out of 372; Nether and End terrain sites 0 differences. + +Harness normalisations (not generation differences): sections above the noise height (Nether roof, End sky) are all air in vanilla and +absent in Horizon; structure templates keep their stored NBT integer width; a vanilla block entity left as a `DUMMY` default is equal to no +Horizon entry; `LootTableSeed` without a `LootTable` and a vault's default reward table are ignored. + +Remaining known differences: a handful of single blocks near structure pieces in full generation (abandoned camps, shipwreck, villages) that +need per-feature tracing, and tree features only through `tools/test_tree_feature_parity.py` (8,898 fixtures, all equal). From d511cffa1148dd6d66a6f77bbbb95600cf16491b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:31:13 +0200 Subject: [PATCH 41/42] Satisfy clippy in the long set size check Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-world/src/worldgen/long_set.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-world/src/worldgen/long_set.rs b/crates/horizon-world/src/worldgen/long_set.rs index cfb79899e..55b2b0130 100644 --- a/crates/horizon-world/src/worldgen/long_set.rs +++ b/crates/horizon-world/src/worldgen/long_set.rs @@ -41,7 +41,7 @@ pub fn iteration_order(keys: &[i64]) -> Vec { table[pos] = Some(index); } size += 1; - if size - 1 >= max_fill(n) { + if size > max_fill(n) { let new_n = array_size(size + 1); let mut grown: Vec> = vec![None; new_n]; for slot in table.iter().rev().flatten() { From a08f6c7c7aaf7e1b76a04d1a2482162d9b6572c2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:57:38 +0200 Subject: [PATCH 42/42] Fix clippy lint in item modifier sequence The sequence loot function folds over an Option accumulator, which clippy flags as a manual try_fold. The fold is intentional, so allow the lint there. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/commands/items.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index 62bedd9cc..fb1bf3c27 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -358,6 +358,7 @@ impl Game<'_> { } match m["function"].as_str().unwrap_or("") { "minecraft:sequence" => { + #[allow(clippy::manual_try_fold)] return m["functions"] .as_array() .into_iter()