diff --git a/benchmarks/rust-sprite-animation-2026-10-06/scoped-parity.json b/benchmarks/rust-sprite-animation-2026-10-06/scoped-parity.json new file mode 100644 index 000000000..ee6ec6ac4 --- /dev/null +++ b/benchmarks/rust-sprite-animation-2026-10-06/scoped-parity.json @@ -0,0 +1,48 @@ +{ + "schema": 1, + "minecraft": "26.3", + "manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3", + "platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43", + "java": "openjdk 25.0.4.1 2026-08-18", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "resource_animations": 63, + "native_tick_states": 258996, + "fixtures": 907, + "rejected": 203, + "sources_sha256": { + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpriteAnimationOracle.java": "90b291abb0b76620f9ca719162393d4fe305ecfb9388d4675d3df89ac1ba136b", + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCuboidModelOracle.java": "7526f20513c549483122ab0d5ad24b9e87f38dc2f6aae55addd701a91ac85e43", + "tools/test_sprite_animation_parity.py": "ea5961ff5e7770eeec6e91a916fedd3ec72dbf05e87cbeb8a8d2429440407d48", + "tools/test_model_baking_parity.py": "392ffec44918fb91740ca4a1316d684480d39f14bd34d46175f7f44946d15bd7", + "tools/test_cuboid_model_parity.py": "3b7c018570b0f609aae43cef60ff3139c543d5d629be804a5aa257e3ab2dd67c", + "tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64", + "tools/test_rust_parity.py": "29d3db08005873528894b45ca10dcd6278753650473b3eb574e53e06ede40ec6", + "Cargo.toml": "3f93319c1eb70dbd7ba25cd74ef343fbf35c52c7c4752f955605c58699cbff9d", + "Cargo.lock": "fed441cad861a44e9919087307cdb9b3d8165fe36ae05ab03f72dde23758cbd5", + "crates/horizon-assets/Cargo.toml": "fadb78cf819e026500606c45d27138ed67fcbbc967ae8cee6c1e7c82c9046b36", + "crates/horizon-assets/examples/cuboid_model_fixture.rs": "97609d90e3f6ce340f3590296db2dc778113bb2b33c7d1b54080a1d6f3023f40", + "crates/horizon-assets/examples/model_baking_fixture.rs": "59caca09dd5afd0b70a2e8fdb8e949deb9322f00adc617918b33d1e7e5b0b522", + "crates/horizon-assets/examples/model_resolution_fixture.rs": "c071067140299e49345a6ebd94e15b3b6d853cb9ae11d8de46e3cbdfb8b01f0e", + "crates/horizon-assets/examples/sprite_animation_fixture.rs": "254314d52deda129ab461221d3d8b95323a60730d374e566c1cd599fba85f072", + "crates/horizon-assets/examples/support/mod.rs": "bcf5a6d8a54845982191e037911c24139237771d6afa4b01b1e83c011489c3f5", + "crates/horizon-assets/src/animation.rs": "ccd51499549d0aa040076406092e35420db56c52f8797a099a0c2468dd8665b1", + "crates/horizon-assets/src/bake.rs": "0bc519e93ad8200d89543ceb5c811dd82bbeb0e9003b143385c8a03e758dfe65", + "crates/horizon-assets/src/json.rs": "e7b89bf4852f561a0e5bf1a984857c61e755961dfd86fcc326b6d55558615f39", + "crates/horizon-assets/src/lib.rs": "92482e4ff4ca46ff5c11a9618ed5007e205762be6390d91648f95068510f0390", + "crates/horizon-assets/src/model.rs": "57ddb3d65e88e7a8aa22c62bc298a2dae7f4e994326a873a31f06c0f36ed051b", + "crates/horizon-assets/src/resolve.rs": "3927ac926cdcbd7d334901cc32d0ecc1e498b1bec98f76a46bca6d4964c13541" + }, + "fixtures_sha256": { + ".local/rust-sprite-animation-parity/inputs.jsonl": "72ccfab50067a4e578c5ce498e395abfdc55df65c487cea758c1e723cabf4da7" + }, + "rust_output_sha256": "842c6693d75234d93b5623be5f55c2fbe739e94b3ec32241b96c81cd6d81317e", + "references": [ + { + "side": "client", + "jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d", + "output_sha256": "842c6693d75234d93b5623be5f55c2fbe739e94b3ec32241b96c81cd6d81317e", + "matched_output_lines": 907 + } + ], + "scope": "Actual AnimationMetadataSection JsonOps codec, frame-size calculation, SpriteContents sequence construction and AnimationState ticks. All bundled animated texture metadata plus synthetic numeric, null, invalid, repeated and out-of-image frame cases. Valid image grids only for SpriteContents construction. No resource-loader fallback, image decoding, GPU interpolation pixels, atlas packing or gameplay parity claim." +} diff --git a/benchmarks/rust-sprite-animation-2026-10-06/startup-smoke.json b/benchmarks/rust-sprite-animation-2026-10-06/startup-smoke.json new file mode 100644 index 000000000..064b842ef --- /dev/null +++ b/benchmarks/rust-sprite-animation-2026-10-06/startup-smoke.json @@ -0,0 +1,76 @@ +{ + "adapter": { + "backend": "Vulkan", + "device": 0, + "device_type": "Cpu", + "name": "llvmpipe (LLVM 21.1.8, 256 bits)", + "vendor": 65541 + }, + "animated_sprites": 1, + "animation_uploads": 1, + "arch": "x86_64", + "camera_pitch": -0.3839724354387525, + "camera_position": [ + 25.0, + 18.0, + 25.0 + ], + "camera_yaw": -2.356194490192345, + "elapsed_seconds": 0.885915504, + "error": null, + "merged_quads": 166, + "model_gallery": [ + "oak_stairs", + "stone_slab", + "anvil", + "torch", + "lantern", + "oak_fence_post", + "oak_fence_gate", + "iron_bars_post", + "cobweb", + "grindstone", + "ladder", + "amethyst_cluster" + ], + "model_quads": 145, + "os": "linux", + "presented_frames": 30, + "project": "Horizon", + "resident_chunks": 9, + "schema": 1, + "scope": "Native cube and cuboid-model renderer with binary cutouts, stepped sprite animation and free camera; no gameplay simulation", + "sprite_layers": 18, + "window_size": [ + 1280, + 720 + ], + "resource_files": { + "files": 5579, + "sha256": "0bc95c8e4b10ef7401f4b948e9a151ea2f9d9112e8dadb9f6807a51e143fcf6f" + }, + "executable_sha256": "e71e99a994250a22e530fe713c3323c7336f80eed04b1104828e5203857b4a82", + "resource_manifest_sha256": "eda44ebee6904eab880c15458dbd1212dc2799d320a4419fc810e2ceb0e5d9d6", + "sources": { + "Cargo.toml": "3f93319c1eb70dbd7ba25cd74ef343fbf35c52c7c4752f955605c58699cbff9d", + "Cargo.lock": "fed441cad861a44e9919087307cdb9b3d8165fe36ae05ab03f72dde23758cbd5", + "tools/test_native_client.py": "e47a866cffd20fcd6fdab62fca573227ca9837488e72384f08f8c33fd4b6228c", + "crates/horizon-client/Cargo.toml": "d56524457d761c2613c0699b20e21ad6977d93e009d59ef150bbd9fc20d7a025", + "crates/horizon-assets/Cargo.toml": "fadb78cf819e026500606c45d27138ed67fcbbc967ae8cee6c1e7c82c9046b36", + "crates/horizon-client/src/assets.rs": "c953a42820cb8d19d8964d4807df401614d4d6621bb47d8ba591c8db38f3e214", + "crates/horizon-client/src/camera.rs": "f9821c8a51a004dd4ad9c0952e746eb07926f6040cf8660bc26da5a0728ae572", + "crates/horizon-client/src/main.rs": "7fb00e89b963a77f124c8e7ad59c5506a4a2f3e6c69720944dec00677ed15239", + "crates/horizon-client/src/mesh.rs": "e2fa00435ec8239ba8a3c6539022bb50a10ff9c3850c6faab72f86aabea896ef", + "crates/horizon-client/src/models.rs": "70b0273100e83afbfc5c013c79afae1e6b13565845e067ad3303244c3f0bbe68", + "crates/horizon-client/src/render.rs": "0f8929d9061b20adbc5ddd0adcbe9f90ce76227b7bb9bafe3f4474961ee2984c", + "crates/horizon-client/src/sprites.rs": "4dd10998581f901bd1c72ed49c27671f362f18285e86e795ddadd11cbc255f69", + "crates/horizon-client/src/world.rs": "901aa59c23ea084e926eec014589f4d511c41691a8dc1520534e039c28cfc76c", + "crates/horizon-client/src/world.wgsl": "82873c131f46a31aef35106f89a53589f179048362d0f8877eca6d20aa6274a4", + "crates/horizon-assets/src/animation.rs": "ccd51499549d0aa040076406092e35420db56c52f8797a099a0c2468dd8665b1", + "crates/horizon-assets/src/bake.rs": "0bc519e93ad8200d89543ceb5c811dd82bbeb0e9003b143385c8a03e758dfe65", + "crates/horizon-assets/src/json.rs": "e7b89bf4852f561a0e5bf1a984857c61e755961dfd86fcc326b6d55558615f39", + "crates/horizon-assets/src/lib.rs": "92482e4ff4ca46ff5c11a9618ed5007e205762be6390d91648f95068510f0390", + "crates/horizon-assets/src/model.rs": "57ddb3d65e88e7a8aa22c62bc298a2dae7f4e994326a873a31f06c0f36ed051b", + "crates/horizon-assets/src/resolve.rs": "3927ac926cdcbd7d334901cc32d0ecc1e498b1bec98f76a46bca6d4964c13541" + } +} diff --git a/crates/horizon-assets/examples/sprite_animation_fixture.rs b/crates/horizon-assets/examples/sprite_animation_fixture.rs new file mode 100644 index 000000000..1b9d016a7 --- /dev/null +++ b/crates/horizon-assets/examples/sprite_animation_fixture.rs @@ -0,0 +1,68 @@ +use horizon_assets::animation::{AnimationMetadata, AnimationSample}; +use serde_json::{Value, json}; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; +fn probe(row: &Value) -> Result> { + let m = AnimationMetadata::from_json(row["json"].as_str().unwrap())?; + let width = row["width"].as_i64().unwrap() as i32; + let height = row["height"].as_i64().unwrap() as i32; + let size = m.frame_size(width, height); + let frames = m.frames.as_ref().map(|frames| { + frames + .iter() + .map(|f| json!({"index":f.index,"time":f.time})) + .collect::>() + }); + let mut result = json!({"metadata":{"frames":frames,"width":m.width,"height":m.height,"frametime":m.frame_time,"interpolate":m.interpolate},"size":size}); + if size[0] > width || size[1] > height || width % size[0] != 0 || height % size[1] != 0 { + return Ok(result); + } + result["animation"] = match m.clip(((width / size[0]) * (height / size[1])) as u32)? { + None => Value::Null, + Some(clip) => { + let samples: Vec<_> = (0..=row["ticks"].as_u64().unwrap()) + .map(|tick| sample(clip.sample(tick))) + .collect(); + let mut edges = Vec::new(); + let mut start = 0u64; + for &(_, duration) in clip.sequence() { + let duration = i64::from(duration); + for sub in [0, 1, duration / 2, duration - 2, duration - 1] { + if sub >= 0 && sub < duration { + edges.push(sample(clip.sample(start + sub as u64 + 1))); + } + } + start += duration as u64; + } + json!({"sequence":clip.sequence(),"columns":width/size[0],"samples":samples,"edges":edges}) + } + }; + Ok(result) +} +fn sample(v: AnimationSample) -> Value { + json!([ + v.sequence_index, + v.sub_frame, + v.frame, + v.next_frame, + v.dirty, + v.needs_draw, + v.interpolation_millis + ]) +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut output = BufWriter::new(File::create(&args[2])?); + for line in input.lines() { + let row: Value = serde_json::from_str(&line?)?; + let result = match probe(&row) { + Ok(value) => json!({"name":row["name"],"value":value}), + Err(_) => json!({"name":row["name"],"error":true}), + }; + writeln!(output, "{result}")?; + } + Ok(()) +} diff --git a/crates/horizon-assets/src/animation.rs b/crates/horizon-assets/src/animation.rs new file mode 100644 index 000000000..00d905b74 --- /dev/null +++ b/crates/horizon-assets/src/animation.rs @@ -0,0 +1,203 @@ +//! Java Edition 26.3 animation metadata and sprite tick selection. +use crate::json::*; +use serde_json::value::RawValue; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AnimationFrame { + pub index: i32, + pub time: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AnimationMetadata { + pub frames: Option>, + pub width: Option, + pub height: Option, + pub frame_time: i32, + pub interpolate: bool, +} + +fn optional<'a>(object: &Object<'a>, name: &str) -> Option<&'a RawValue> { + object.get(name).copied().filter(|v| v.get() != "null") +} +fn bounded_integer(value: &RawValue, minimum: i32) -> Result { + // JsonReader stops recognizing a number at its buffer limit. Its integer + // scanner also keeps wrapping a negative i64 accumulator after overflow: + // if that accumulator becomes zero, a following digit triggers the same + // rejection as a leading zero. JsonParser then exposes a string, which the + // uncompressed integer codec rejects. + let token = value.get(); + if token.len() >= 1024 { + return Err(error("animation number exceeds native reader buffer")); + } + let mut accumulator = 0i64; + for (index, digit) in token + .trim_start_matches('-') + .bytes() + .take_while(u8::is_ascii_digit) + .enumerate() + { + if index > 0 && accumulator == 0 { + return Err(error( + "native reader classifies animation number as a string", + )); + } + accumulator = accumulator + .wrapping_mul(10) + .wrapping_sub(i64::from(digit - b'0')); + } + let value = integer(value)?; + if value < minimum { + return Err(error("animation integer outside codec range")); + } + Ok(value) +} +impl AnimationMetadata { + /// Decode the animation section itself, using the uncompressed JsonOps codec + /// rules. Numeric primitives truncate and wrap as Java Number.intValue does; + /// strings and booleans are not numbers. Null optional fields are absent. + pub fn from_json(text: &str) -> Result { + let raw: &RawValue = serde_json::from_str(text)?; + let fields = object(raw)?; + let positive = |name| { + optional(&fields, name) + .map(|v| bounded_integer(v, 1)) + .transpose() + }; + let frames = optional(&fields, "frames") + .map(|v| { + array(v)? + .into_iter() + .map(|v| { + if v.get().starts_with('{') { + let fields = object(v)?; + Ok(AnimationFrame { + index: bounded_integer(required(&fields, "index")?, 0)?, + time: optional(&fields, "time") + .map(|v| bounded_integer(v, 1)) + .transpose()?, + }) + } else { + Ok(AnimationFrame { + index: bounded_integer(v, 0)?, + time: None, + }) + } + }) + .collect::>>() + }) + .transpose()?; + Ok(Self { + frames, + width: positive("width")?, + height: positive("height")?, + frame_time: positive("frametime")?.unwrap_or(1), + interpolate: optional(&fields, "interpolate") + .map(|v| serde_json::from_str(v.get())) + .transpose()? + .unwrap_or(false), + }) + } + + pub fn frame_size(&self, image_width: i32, image_height: i32) -> [i32; 2] { + match (self.width, self.height) { + (Some(w), Some(h)) => [w, h], + (Some(w), None) => [w, image_height], + (None, Some(h)) => [image_width, h], + (None, None) => [image_width.min(image_height); 2], + } + } + + /// Build the animation after image/frame dimensions have been validated by + /// the resource loader. Out-of-image indices are removed, preserving order + /// and repeats. Zero or one remaining entries mean static physical frame 0. + pub fn clip(&self, physical_frames: u32) -> Result> { + if self.frame_time <= 0 { + return Err(error("nonpositive default animation duration")); + } + let sequence: Vec<_> = match &self.frames { + Some(frames) => frames + .iter() + .filter_map(|v| { + let time = v.time.unwrap_or(self.frame_time); + (v.index >= 0 && (v.index as u32) < physical_frames && time > 0) + .then_some((v.index as u32, time as u32)) + }) + .collect(), + None => (0..physical_frames) + .map(|i| (i, self.frame_time as u32)) + .collect(), + }; + if sequence.len() <= 1 { + return Ok(None); + } + let mut duration = 0u64; + let ends = sequence + .iter() + .map(|&(_, time)| { + duration = duration + .checked_add(u64::from(time)) + .ok_or_else(|| error("animation duration overflow"))?; + Ok(duration) + }) + .collect::>>()?; + Ok(Some(AnimationClip { + sequence, + ends, + duration, + interpolate: self.interpolate, + })) + } +} + +#[derive(Clone, Debug)] +pub struct AnimationClip { + sequence: Vec<(u32, u32)>, + ends: Vec, + duration: u64, + interpolate: bool, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AnimationSample { + pub sequence_index: usize, + pub sub_frame: u32, + pub frame: u32, + pub next_frame: u32, + pub dirty: bool, + pub needs_draw: bool, + /// Native drawToAtlas encodes floor((subFrame / time) * 1000) in its + /// first-vertex argument. This is not a claim about GPU interpolation pixels. + pub interpolation_millis: u32, +} +impl AnimationClip { + pub fn sequence(&self) -> &[(u32, u32)] { + &self.sequence + } + pub fn duration(&self) -> u64 { + self.duration + } + pub fn interpolates(&self) -> bool { + self.interpolate + } + + /// Random access to the state after `tick` native ticks. Binary search avoids + /// advancing every missed tick when a render frame takes longer than 50 ms. + pub fn sample(&self, tick: u64) -> AnimationSample { + let time = tick % self.duration; + let index = self.ends.partition_point(|end| *end <= time); + let start = if index == 0 { 0 } else { self.ends[index - 1] }; + let sub_frame = (time - start) as u32; + let (frame, duration) = self.sequence[index]; + let previous = (index + self.sequence.len() - 1) % self.sequence.len(); + let dirty = tick == 0 || (sub_frame == 0 && frame != self.sequence[previous].0); + AnimationSample { + sequence_index: index, + sub_frame, + frame, + next_frame: self.sequence[(index + 1) % self.sequence.len()].0, + dirty, + needs_draw: self.interpolate || dirty, + interpolation_millis: ((sub_frame as f32 / duration as f32) * 1000.0) as u32, + } + } +} diff --git a/crates/horizon-assets/src/lib.rs b/crates/horizon-assets/src/lib.rs index 31ab2d6b9..f487ac555 100644 --- a/crates/horizon-assets/src/lib.rs +++ b/crates/horizon-assets/src/lib.rs @@ -1,6 +1,7 @@ //! Resource decoding for the pinned Java Edition client. #![forbid(unsafe_code)] +pub mod animation; pub mod bake; mod json; pub mod model; diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 8fb88ff23..4bf34c0f5 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -16,4 +16,4 @@ pollster = "0.4" bytemuck = { version = "1.24", features = ["derive"] } glam = "0.30" png = "0.18" -serde_json = "1.0.151" +serde_json = { version = "1.0.151", features = ["raw_value"] } diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index e5681a030..b8e9c4eb0 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -1,5 +1,6 @@ //! Shared nearest-sampled sprite array for the controlled scene. use crate::Result; +use horizon_assets::animation::{AnimationClip, AnimationMetadata}; use std::{ collections::BTreeMap, fs::{self, File}, @@ -12,19 +13,11 @@ use std::{ pub struct SpriteAnimation { pub layer: u32, frames: Arc>>, - sequence: Arc>, - duration: u64, + clip: Arc, } impl SpriteAnimation { pub fn frame(&self, tick: u64) -> usize { - let mut time = tick % self.duration; - for &(index, duration) in self.sequence.iter() { - if time < u64::from(duration) { - return index; - } - time -= u64::from(duration); - } - unreachable!("validated animation duration") + self.clip.sample(tick).frame as usize } pub fn pixels(&self, frame: usize) -> &[u8] { &self.frames[frame] @@ -46,11 +39,17 @@ impl Sprites { let (namespace, path) = name.split_once(':').ok_or("invalid sprite identifier")?; let path = root.join(format!("assets/{namespace}/textures/{path}.png")); let metadata = match fs::read_to_string(path.with_extension("png.mcmeta")) { - Ok(text) => Some(serde_json::from_str::(&text)?), + Ok(text) => Some(serde_json::from_str::< + BTreeMap>, + >(&text)?), Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(error.into()), }; - let animation = metadata.as_ref().and_then(|v| v.get("animation")); + let animation = metadata + .as_ref() + .and_then(|v| v.get("animation")) + .map(|v| AnimationMetadata::from_json(v.get())) + .transpose()?; let mut decoder = png::Decoder::new(BufReader::new(File::open(path)?)); decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); let mut reader = decoder.read_info()?; @@ -61,38 +60,15 @@ impl Sprites { .ok_or("sprite exceeds decoder limits")? ]; let info = reader.next_frame(&mut bytes)?; - let positive = |value: &serde_json::Value| -> Result { - let value = value - .as_u64() - .filter(|v| *v > 0 && *v <= i32::MAX as u64) - .ok_or("invalid positive animation integer")?; - Ok(value as u32) - }; - let (width, height) = if let Some(animation) = animation { - if !animation.is_object() { - return Err("invalid animation metadata".into()); - } - if animation - .get("interpolate") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { + let (width, height) = if let Some(animation) = &animation { + if animation.interpolate { return Err( "interpolated animation is not yet supported by the inspection renderer".into(), ); } - match ( - animation.get("width").map(positive).transpose()?, - animation.get("height").map(positive).transpose()?, - ) { - (Some(w), Some(h)) => (w, h), - (Some(w), None) => (w, info.height), - (None, Some(h)) => (info.width, h), - (None, None) => { - let size = info.width.min(info.height); - (size, size) - } - } + let [width, height] = + animation.frame_size(i32::try_from(info.width)?, i32::try_from(info.height)?); + (u32::try_from(width)?, u32::try_from(height)?) } else { (info.width, info.height) }; @@ -141,45 +117,18 @@ impl Sprites { } let frames = Arc::new(frames); let mut initial = 0; - if let Some(metadata) = animation { - let default_time = metadata - .get("frametime") - .map(positive) - .transpose()? - .unwrap_or(1); - let sequence = if let Some(values) = metadata.get("frames") { - let mut sequence = Vec::new(); - for value in values.as_array().ok_or("invalid animation frame list")? { - let (index, time) = if value.is_object() { - ( - value.get("index").and_then(serde_json::Value::as_u64), - value - .get("time") - .map(positive) - .transpose()? - .unwrap_or(default_time), - ) - } else { - (value.as_u64(), default_time) - }; - if let Some(index) = index.filter(|i| *i < u64::from(count)) { - sequence.push((index as usize, time)); - } - } - sequence - } else { - (0..count).map(|i| (i as usize, default_time)).collect() - }; - if sequence.len() > 1 { - initial = sequence[0].0; - let duration = sequence.iter().map(|(_, time)| u64::from(*time)).sum(); - self.animations.push(SpriteAnimation { - layer, - frames: frames.clone(), - sequence: Arc::new(sequence), - duration, - }); - } + if let Some(clip) = animation + .as_ref() + .map(|m| m.clip(count)) + .transpose()? + .flatten() + { + initial = clip.sample(0).frame as usize; + self.animations.push(SpriteAnimation { + layer, + frames: frames.clone(), + clip: Arc::new(clip), + }); } self.layers.insert(name.to_owned(), layer); self.size = width; @@ -196,8 +145,7 @@ mod tests { let animation = SpriteAnimation { layer: 0, frames: Arc::new(vec![vec![], vec![], vec![]]), - sequence: Arc::new(vec![(2, 8), (1, 3), (1, 2), (0, 1)]), - duration: 14, + clip: Arc::new(AnimationMetadata::from_json(r#"{"frames":[{"index":2,"time":8},{"index":1,"time":3},{"index":1,"time":2},0]}"#).unwrap().clip(3).unwrap().unwrap()), }; for (tick, frame) in [ (0, 2), diff --git a/docs/native-client.md b/docs/native-client.md index 37970b2d7..cb9eb6667 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -21,9 +21,10 @@ an anvil, a torch, a lantern, fence parts, iron bars, a cobweb, a grindstone, a ladder and an amethyst cluster. These are explicit model selections for geometry inspection, not simulated block placements. Binary-alpha cutouts are rendered; the lantern's three frames advance every eight inspection ticks at 20 ticks/s. -General animation metadata compatibility, interpolation and synchronization with -the eventual game loop still need validation. Sprites currently require matching -square frame dimensions. +The animation metadata codec and frame selection now use the shared +`horizon-assets` implementation checked against the pinned client. GPU +interpolation and synchronization with the eventual game loop remain unfinished. +Sprites currently require matching square frame dimensions. ## Run from a checkout @@ -121,6 +122,28 @@ transparency classification, actual tint/light evaluation and GPU rendering remain separate from the geometry result. Other operating systems still need their native validation runs. +The sprite animation module reproduces the pinned metadata codec's integer +conversion, strict primitive types, optional null fields and frame dimensions. +It preserves repeated frames, filters out-of-image frame indices, and treats +sequences with fewer than two valid entries as static physical frame zero. +Frame lookup uses cumulative durations and binary search, so skipped rendering +frames do not require replaying all elapsed animation ticks. The native oracle +also checks dirty flags, draw requirements and interpolation timing, including +transitions near the maximum Java integer duration. Interpolation pixel output +and resource-loader failure recovery are outside this comparison. + +```sh +python3 tools/test_sprite_animation_parity.py +``` + +The [animation comparison](../benchmarks/rust-sprite-animation-2026-10-06/scoped-parity.json) +records 907 fixtures and 258,996 native tick states from the actual client codec +and `SpriteContents.AnimationState.tick`, including all 63 bundled animated +texture metadata sections and synthetic boundary cases. The associated +[startup report](../benchmarks/rust-sprite-animation-2026-10-06/startup-smoke.json) +checks the renderer using this shared implementation. Images, input +fixtures and native traces stay private under `.local/`. + ```sh cargo +stable test -p horizon-client cargo +stable clippy --workspace --all-targets -- -D warnings diff --git a/docs/rust-parity.md b/docs/rust-parity.md index 496a74f12..950e8f0f1 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -22,6 +22,9 @@ also include parent/texture resolution over 5,648 roots and cuboid baking over models and UV locking remain unfinished. The native renderer now draws an inspection gallery from the decoded/resolved/baked models, including binary cutouts and stepped lantern animation; these are not yet gameplay blocks. +Animation metadata, frame sequences and tick-state selection now have native +differential coverage, including all bundled animated texture metadata. GPU +interpolation and game-loop synchronization remain unfinished. The playable Java performance packs remain available during development. ## Completion criteria and playable builds diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpriteAnimationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpriteAnimationOracle.java new file mode 100644 index 000000000..0ee728951 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpriteAnimationOracle.java @@ -0,0 +1,80 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.serialization.JsonOps; +import com.mojang.renderpearl.api.buffers.GpuBufferSlice; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.resources.metadata.animation.*; +import net.minecraft.resources.Identifier; +import static dev.horizonlab.parity.VanillaCuboidModelOracle.map; + +/** Invokes the pinned metadata codec and real animation tick state, without GPU draws. */ +public final class VanillaSpriteAnimationOracle { + private static final Gson JSON = new GsonBuilder().serializeNulls().create(); + private static Object field(Object target, String name) throws Exception { + var field=target.getClass().getDeclaredField(name); field.setAccessible(true); return field.get(target); + } + private static Object probe(JsonObject row) throws Exception { + AnimationMetadataSection metadata; + try { metadata=AnimationMetadataSection.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(row.get("json").getAsString())).getOrThrow(); } + catch(RuntimeException error) { return null; } + int width=row.get("width").getAsInt(),height=row.get("height").getAsInt(); + var size=metadata.calculateFrameSize(width,height); + Object frames=metadata.frames().map(list->list.stream().map(f->map("index",f.index(),"time",f.time().orElse(null))).toList()).orElse(null); + var result=map("metadata",map("frames",frames,"width",metadata.frameWidth().orElse(null),"height",metadata.frameHeight().orElse(null),"frametime",metadata.defaultFrameTime(),"interpolate",metadata.interpolatedFrames()),"size",new int[]{size.width(),size.height()}); + // This guard scopes allocation to valid sprite grids. Frame-size calculation + // above remains tested for impossible dimensions; loader errors are separate. + if(size.width()>width || size.height()>height || width%size.width()!=0 || height%size.height()!=0) return result; + try(var contents=new SpriteContents(Identifier.parse("horizon:probe"),size,new NativeImage(width,height,true),Optional.of(metadata),List.of(),Optional.empty())) { + var animation=field(contents,"animatedTexture"); + if(animation==null) { result.put("animation",null); return result; } + var nativeFrames=(List)field(animation,"frames"); var sequence=new ArrayList(); + for(var frame:nativeFrames) sequence.add(new int[]{(int)field(frame,"index"),(int)field(frame,"time")}); + var type=Class.forName("net.minecraft.client.renderer.texture.SpriteContents$AnimationState"); + var constructor=type.getDeclaredConstructors()[0];constructor.setAccessible(true); + var state=(SpriteContents.AnimationState)constructor.newInstance(contents,animation,new Int2ObjectOpenHashMap<>(),new GpuBufferSlice[0]); + var samples=new ArrayList(); + int ticks=row.get("ticks").getAsInt(); + for(int tick=0;tick<=ticks;tick++) { + samples.add(sample(state,sequence)); + state.tick(); + } + // Probe native tick transitions near very long frame durations too. + var edges=new ArrayList(); + var frameField=type.getDeclaredField("frame");frameField.setAccessible(true); + var subField=type.getDeclaredField("subFrame");subField.setAccessible(true); + for(int index=0;index=duration)continue; + frameField.setInt(state,index);subField.setInt(state,sub);state.tick(); + edges.add(sample(state,sequence)); + } + } + result.put("animation",map("sequence",sequence,"columns",field(animation,"frameRowSize"),"samples",samples,"edges",edges)); + } + return result; + } + private static Object sample(SpriteContents.AnimationState state,List sequence) throws Exception { + int index=(int)field(state,"frame"),sub=(int)field(state,"subFrame");var current=sequence.get(index); + int blend=(int)((float)sub/(float)current[1]*1000.0f); + return Arrays.asList(index,sub,current[0],sequence.get((index+1)%sequence.size())[0],field(state,"isDirty"),state.needsToDraw(),blend); + } + 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;) { + var row=JsonParser.parseString(line).getAsJsonObject();Object value; + var probe=probe(row); + value=probe==null ? map("name",row.get("name").getAsString(),"error",true) : map("name",row.get("name").getAsString(),"value",probe); + output.write(JSON.toJson(value));output.newLine(); + } + } + } +} diff --git a/tools/test_sprite_animation_parity.py b/tools/test_sprite_animation_parity.py new file mode 100644 index 000000000..06ca25c96 --- /dev/null +++ b/tools/test_sprite_animation_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare animation metadata, frame selection and tick state with the pinned client.""" +import json +import os +from pathlib import Path +import platform +import random +import struct +import subprocess +import zipfile +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking, test_cuboid_model_parity as decoding +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking, test_cuboid_model_parity as decoding + + +def corpus(): + def row(name, metadata, width=16, height=64, ticks=128): + return dict(name=name,json=json.dumps(metadata),width=width,height=height,ticks=ticks) + yield row('default', {}) + for key in ['width','height','frametime','interpolate','frames']: + for i,value in enumerate([None,True,False,0,1,-1,1.9,-0.9,4294967297,2147483648,1e100,'1','true',{},[],[0,1], [None], [{'index':1,'time':2}]]): + yield row(f'field-{key}-{i}',{key:value}) + for key in ['index','time']: + for i,value in enumerate([None,True,False,0,1,-1,1.9,-0.9,4294967297,2147483648,1e100,'1',{},[],[1]]): + yield row(f'frame-{key}-{i}',{'frames':[0,dict(index=1,**{key:value})]}) if key=='time' else row(f'frame-{key}-{i}',{'frames':[0,{'index':value}]}) + for i,frames in enumerate([[],[3],[99],[1,99],[2,2],[0,1,0],[3,2,1,0],[3,99,1,2],[{},0],[{'index':2,'time':None},0],[0,{'index':1,'time':2147483647}]]): + for interpolate in [False,True]: yield row(f'sequence-{i}-{interpolate}',{'frames':frames,'interpolate':interpolate}) + for width,height in [(16,16),(16,48),(48,16),(32,48),(15,32),(1,4),(64,64)]: + for w,h in [(None,None),(8,None),(None,8),(8,8),(16,32),(32,16),(1,1),(65,65)]: + yield row(f'dim-{width}-{height}-{w}-{h}',{'width':w,'height':h},width,height,16) + rng=random.Random(0x535052495445) + for i in range(512): + frames=[{'index':rng.randrange(7),'time':rng.choice([1,2,3,7,19,31,2147483647])} for _ in range(rng.randrange(12))] + yield row(f'random-{i}',{'frames':frames,'frametime':rng.randrange(1,20),'interpolate':bool(rng.randrange(2))},ticks=512) + for i,raw in enumerate(['null','[]','true','1','"x"','{"width":1e9999}','{"frametime":1e-9999}','{"width":4294967312.9}','{"frames":[0.9,1.9,2.9]}']): + item=row(f'raw-{i}',{}); item['json']=raw;yield item + + numbers=['-0.0','4294967296','4294967297','4294967295','9223372036854775809', + '-9223372036854775809','1e9999','1e10000','1e-9999','1e-10000', + '1e2147483647','1e2147483648','1.0e10000','1.0e10001', + '1'*1023,'1'*1024,'1'*10000,'1'*10001, + *('1'+'0'*(n-2)+'1' for n in [20,64,65,66,100,1023,1024,10000,10001]), + '1844674407370955161601','-1844674407370955161601', + '18446744073709551616.1','18446744073709551616e-18'] + for i,number in enumerate(numbers): + for key in ['width','frametime','interpolate']: + item=row(f'number-{key}-{i}',{});item['json']='{"'+key+'":'+number+'}';yield item + item=row(f'number-index-{i}',{});item['json']='{"frames":[0,'+number+']}';yield item + + +def main(): + lock,jars,_=base.verify_artifacts() + build=lab.LOCAL/'rust-sprite-animation-parity';build.mkdir(parents=True,exist_ok=True) + report_path=build/'report.json';report_path.unlink(missing_ok=True) + oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpriteAnimationOracle.java' + helper=oracle.with_name('VanillaCuboidModelOracle.java');crate=lab.ROOT/'crates/horizon-assets' + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/test_cuboid_model_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',crate/'Cargo.toml',*sorted(crate.rglob('*.rs'))] + tested=base.source_hashes(sources) + rows=[] + with zipfile.ZipFile(jars['client']) as archive: + for name in sorted(archive.namelist()): + if not name.startswith('assets/minecraft/textures/') or not name.endswith('.png.mcmeta'):continue + metadata=json.loads(archive.read(name)) + if 'animation' not in metadata:continue + width,height=struct.unpack('>II',archive.read(name.removesuffix('.mcmeta'))[16:24]) + rows.append(dict(name=name,json=json.dumps(metadata['animation']),width=width,height=height,ticks=512)) + resources=len(rows);rows.extend(corpus()) + inputs=build/'inputs.jsonl';inputs.write_text(''.join(json.dumps(row)+'\n' for row in rows));fixtures=base.source_hashes([inputs]) + classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) + dependencies=os.pathsep.join(map(str,[jars['client'],*baking.client_libraries()])) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',dependencies,'-d',classes,oracle,helper],'compile-java') + run(['cargo','build','--locked','-p','horizon-assets','--example','sprite_animation_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'])/'debug/examples'/('sprite_animation_fixture.exe' if os.name=='nt' else 'sprite_animation_fixture') + run([binary,inputs,build/'rust.jsonl'],'rust') + run(['java','-Xmx512M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaSpriteAnimationOracle',inputs,build/'client.jsonl'],'client') + rejected=decoding.canonicalize(build/'client.jsonl');decoding.canonicalize(build/'rust.jsonl') + native=[json.loads(line) for line in (build/'client.jsonl').read_text().splitlines()] + rust=[json.loads(line) for line in (build/'rust.jsonl').read_text().splitlines()] + for left,right in zip(native,rust,strict=True): + if left!=right: raise AssertionError('Sprite animation mismatch: '+left['name']) + matched=base.compare(build/'client.jsonl',build/'rust.jsonl') + assert all('error' not in row for row in native[:resources]), 'Bundled resource was rejected' + states=sum(len(row['value']['animation']['samples'])+len(row['value']['animation']['edges']) for row in native if row.get('value',{}).get('animation')) + base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged([inputs],fixtures) + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'resource_animations':resources,'native_tick_states':states,'fixtures':len(rows),'rejected':rejected,'sources_sha256':tested,'fixtures_sha256':fixtures,'rust_output_sha256':lab.digest(build/'rust.jsonl','sha256'),'references':[{'side':'client','jar_sha256':lab.digest(jars['client'],'sha256'),'output_sha256':lab.digest(build/'client.jsonl','sha256'),'matched_output_lines':matched}],'scope':'Actual AnimationMetadataSection JsonOps codec, frame-size calculation, SpriteContents sequence construction and AnimationState ticks. All bundled animated texture metadata plus synthetic numeric, null, invalid, repeated and out-of-image frame cases. Valid image grids only for SpriteContents construction. No resource-loader fallback, image decoding, GPU interpolation pixels, atlas packing or gameplay parity claim.'} + lab.write_json(report_path,report);print(f'Native sprite animation: {matched:,} fixtures match ({rejected:,} rejected); {report_path}',flush=True) + + +if __name__=='__main__':main()