From 024415e09dff8438725dfb68dd5fe78bb691ea91 Mon Sep 17 00:00:00 2001 From: masa-masa-0314 <348336850+masa-masa-0314@users.noreply.github.com> Date: Tue, 27 Oct 2026 05:11:35 +0800 Subject: [PATCH 1/2] Inventory: animate every animated block and item sprite The shared atlas packs animated block and item textures as their first frame, and only fire re-drew itself: an animated block held or previewed in the GUI (sculk, magma) sat still, while the same block animated in the world. The atlas now keeps every animated block or item sprite's frame list and re-uploads the current frame into its rect as the animation ticks, with the mcmeta's interpolation mixing the frame into the next one the way the world's sprite arrays already do, so GUI items animate like vanilla's stitched atlas. Co-Authored-By: ZCode --- crates/horizon-client/src/game.rs | 12 ++-- crates/horizon-client/src/gfx.rs | 2 +- crates/horizon-client/src/hud.rs | 114 +++++++++++++++++++----------- 3 files changed, 78 insertions(+), 50 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..e93911e65 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -13505,10 +13505,10 @@ fn build_renderer( previous, api, ))?; - renderer.hud.fire_animations = atlas - .fire_animations + renderer.hud.sprite_animations = atlas + .sprite_animations .iter() - .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0))) .collect(); Ok(renderer) } @@ -13558,10 +13558,10 @@ fn loading_renderer( api, ))?; if let Some(atlas) = atlas { - renderer.hud.fire_animations = atlas - .fire_animations + renderer.hud.sprite_animations = atlas + .sprite_animations .iter() - .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0))) .collect(); } Ok(renderer) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 70d882a98..74c544168 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3390,7 +3390,7 @@ impl Renderer { if self.animated_textures { self.animate(&mut encoder, frame.ticks); self.hud - .animate_fire(&mut self.uploads, &mut encoder, frame.ticks); + .animate_sprites(&mut self.uploads, &mut encoder, frame.ticks); } self.update_lightmap( &mut encoder, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 2b6acda41..d2bef127e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -64,7 +64,10 @@ pub struct HudAtlas { /// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others /// sample as vanilla's defaults (nearest, repeat). pub flags: HashMap, - pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, + /// Every animated block or item sprite the atlas packs: its atlas rect + /// and the mcmeta-driven frame list, re-uploaded into the rect as the + /// frames turn (vanilla's stitched atlas animates all of these). + pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). pub font: crate::font::Font, white: Rect, @@ -373,7 +376,7 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - type Decoded = (PackedImage, Option, Option<(u32, u32)>); + type Decoded = (PackedImage, Option, Option<(u32, u32)>, bool); let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) @@ -396,14 +399,20 @@ impl HudAtlas { .and_then(|d| png_size(&d.join(format!("{name}.png")))) .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) .filter(|&size| size != (w, h)); - let flags = fs::read_to_string(path.with_extension("png.mcmeta")) - .ok() - .and_then(|json| TextureFlags::from_mcmeta(&json)); + let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); + let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta); + let animated = frames + && mcmeta.as_deref().is_some_and(|json| { + serde_json::from_str::(json) + .ok() + .is_some_and(|meta| meta.get("animation").is_some()) + }); let (gw, gh) = gui_size.unwrap_or((w, h)); (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( (name, w, h, pixels), flags, gui_size, + animated, )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); @@ -422,14 +431,18 @@ impl HudAtlas { }); let mut flags = HashMap::new(); let mut gui_sizes = HashMap::new(); + let mut animated: Vec = Vec::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags, gui_size) in decoded { + for (image, image_flags, gui_size, is_animated) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } if let Some(size) = gui_size { gui_sizes.insert(image.0.clone(), size); } + if is_animated { + animated.push(image.0.clone()); + } images.push(image); } if full { @@ -495,35 +508,32 @@ impl HudAtlas { }, ); } - let mut fire_sprites = crate::sprites::Sprites::default(); - let mut fire_animations = Vec::new(); - for name in [ - "block/fire_0", - "block/fire_1", - "block/soul_fire_0", - "block/soul_fire_1", - ] { - if let Some(rect) = sprites.get(name).copied() { - let layer = fire_sprites.insert(root, &format!("minecraft:{name}"))?; - if let Some(animation) = fire_sprites - .animations - .iter() - .find(|a| a.layer == layer) - .cloned() - { - let (tw, th) = rect.texels((width, height)); - let image = animation.resized_pixels(animation.frame(0), tw, th); - let x = (rect.u0 * width as f32).round() as usize; - let y = (rect.v0 * height as f32).round() as usize; - let row_bytes = tw as usize * 4; - for row in 0..th as usize { - let dst = ((y + row) * width as usize + x) * 4; - let src = row * row_bytes; - pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); - } - fire_animations.push((rect, animation)); - } + // Every animated sprite animates: the packed strip is the raw first + // frame, while the mcmeta's frame list may start anywhere, so each + // animation's frame(0) overwrites its atlas rect before drawing. + let mut loaded = crate::sprites::Sprites::default(); + let mut sprite_animations = Vec::new(); + animated.sort(); + for name in animated { + let Some(rect) = sprites.get(&name).copied() else { + continue; + }; + let layer = loaded.insert(root, &format!("minecraft:{name}"))?; + let Some(animation) = loaded.animations.iter().find(|a| a.layer == layer).cloned() + else { + continue; + }; + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); + let x = (rect.u0 * width as f32).round() as usize; + let y = (rect.v0 * height as f32).round() as usize; + let row_bytes = tw as usize * 4; + for row in 0..th as usize { + let dst = ((y + row) * width as usize + x) * 4; + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } + sprite_animations.push((rect, animation)); } let white = sprites["horizon/white"]; let font = crate::font::Font::load( @@ -541,7 +551,7 @@ impl HudAtlas { sprites, translucent, flags, - fire_animations, + sprite_animations, font, white, }) @@ -1033,7 +1043,7 @@ impl HudUniform { } } pub struct HudRenderer { - pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>, + pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation, (usize, usize, u32))>, /// The shared atlas texture, for run-time glyph uploads. pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, @@ -1235,7 +1245,7 @@ impl HudRenderer { }); Ok(Self { atlas_texture: None, - fire_animations: Vec::new(), + sprite_animations: Vec::new(), pipeline, invert_pipeline, additive_pipeline, @@ -1248,7 +1258,7 @@ impl HudRenderer { capacity, }) } - pub fn animate_fire( + pub fn animate_sprites( &mut self, uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, @@ -1257,13 +1267,31 @@ impl HudRenderer { let Some(texture) = &self.atlas_texture else { return; }; - for (rect, animation, previous) in &mut self.fire_animations { - let frame = animation.frame(tick); - if frame == *previous { + for (rect, animation, previous) in &mut self.sprite_animations { + // `SpriteContents.AnimationState`: the frame from the mcmeta's + // list, blended into the next one by the sub-frame's thousandths + // when the sprite interpolates. + let blend = animation.blend(tick); + let state = (blend.frame, blend.next, blend.millis); + if state == *previous { continue; } let (w, h) = rect.texels((texture.width(), texture.height())); - let pixels = animation.resized_pixels(frame, w, h); + let pixels = if blend.millis == 0 { + animation.resized_pixels(blend.frame, w, h) + } else { + let current = animation.resized_pixels(blend.frame, w, h); + let next = animation.resized_pixels(blend.next, w, h); + let millis = blend.millis; + current + .iter() + .zip(next) + .map(|(&a, b)| { + ((u32::from(a) * (1000 - millis) + u32::from(b) * millis + 500) / 1000) + as u8 + }) + .collect() + }; uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1280,7 +1308,7 @@ impl HudRenderer { h, &pixels, ); - *previous = frame; + *previous = state; } } /// Stage the batch's atlas patches, vertices and uniform: before the From 18b544770fa39df42ccd6c708f4b70d417c2cbff Mon Sep 17 00:00:00 2001 From: masa-masa-0314 <348336850+masa-masa-0314@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:17:54 +0800 Subject: [PATCH 2/2] Inventory: frame strips by the mcmeta's frame size `decode_one` cropped an animated block or item strip as `h > w -> w x w`, ignoring the mcmeta's `animation.width`/`height`: a pack texture that names its frame dimensions, or lays its frames along a row, packed the whole image as "frame 0" and was then drawn as a square frame over a rect sized for the image. The first frame now comes from `AnimationMetadataSection.frameSize`, resampled to its longer side the way the world's sprite arrays keep a frame square, and the sprite's GUI size is that square too. The atlas also gains the regression test the review asked for: a synthetic two-frame block strip whose mcmeta starts on the second frame registers in `sprite_animations`, and the atlas holds that frame at the sprite's rect; a row strip with explicit frame dimensions packs only its left frame. Co-Authored-By: ZCode --- crates/horizon-client/src/hud.rs | 136 ++++++++++++++++++++++++++++--- 1 file changed, 123 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index d2bef127e..2abed308e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -2,6 +2,7 @@ //! textures, and a batch of textured quads in GUI pixels (vanilla's automatic //! GUI scale is applied when drawing). use crate::Result; +use horizon_assets::animation::AnimationMetadata; use std::{ collections::{HashMap, HashSet}, fs, @@ -145,6 +146,21 @@ fn walk(dir: &Path, out: &mut Vec) { } /// A packed atlas image: sprite name, size and RGBA pixels. type PackedImage = (String, u32, u32, Vec); +/// A frame of an animated strip at `x, y`, nearest-resampled to the longer +/// side of the frame: array layers are square, as `Sprites::load` keeps them +/// for the world's sprite arrays. +fn strip_frame(pixels: &[u8], stride: u32, x: u32, y: u32, w: u32, h: u32) -> Vec { + let side = w.max(h); + let mut out = Vec::with_capacity((side * side * 4) as usize); + for row in 0..side { + let source_row = y + row * h / side; + for column in 0..side { + let at = ((source_row * stride + x + column * w / side) * 4) as usize; + out.extend_from_slice(&pixels[at..at + 4]); + } + } + out +} /// `image` inside a one-texel border copied from its opposite edges, the /// texels repeat addressing reads past each edge. fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage { @@ -384,12 +400,35 @@ impl HudAtlas { .with_extension("") .to_string_lossy() .replace('\\', "/"); - let (w, mut h, pixels) = decode(path).ok()?; - // Animated strips keep their first frame. + let (mut w, mut h, pixels) = decode(path).ok()?; + let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); + let animation = mcmeta + .as_deref() + .and_then(|json| serde_json::from_str::(json).ok()) + .and_then(|meta| { + meta.get("animation") + .and_then(|section| AnimationMetadata::from_json(§ion.to_string()).ok()) + }); + // An animated strip keeps its first frame: the region the mcmeta's + // frame size picks (`AnimationMetadataSection.frameSize`), which is + // the top-left square unless it names other dimensions or the + // frames run along a row. let frames = name.starts_with("block/") || name.starts_with("item/"); - let pixels = if frames && h > w { - h = w; - pixels[..(w * w * 4) as usize].to_vec() + let pixels = if frames { + let stride = w; + let [fw, fh] = animation.as_ref().map_or([w.min(h) as i32; 2], |meta| { + meta.frame_size(w as i32, h as i32) + }); + match (u32::try_from(fw), u32::try_from(fh)) { + (Ok(fw), Ok(fh)) + if fw > 0 && fh > 0 && w % fw == 0 && h % fh == 0 && (fw, fh) != (w, h) => + { + let side = fw.max(fh); + (w, h) = (side, side); + strip_frame(&pixels, stride, 0, 0, fw, fh) + } + _ => pixels, + } } else { pixels }; @@ -397,16 +436,13 @@ impl HudAtlas { let gui_size = default_textures .as_ref() .and_then(|d| png_size(&d.join(format!("{name}.png")))) - .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .map(|(dw, dh)| { + let side = dw.min(dh); + if frames { (side, side) } else { (dw, dh) } + }) .filter(|&size| size != (w, h)); - let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta); - let animated = frames - && mcmeta.as_deref().is_some_and(|json| { - serde_json::from_str::(json) - .ok() - .is_some_and(|meta| meta.get("animation").is_some()) - }); + let animated = frames && animation.is_some(); let (gw, gh) = gui_size.unwrap_or((w, h)); (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( (name, w, h, pixels), @@ -1469,6 +1505,80 @@ impl HudRenderer { mod tests { use super::*; + /// Write a PNG `width x height` whose `frames` stacked rows are solid + /// colours, then its mcmeta beside it. + fn write_strip(path: &Path, width: u32, height: u32, frames: &[[u8; 4]], mcmeta: Option<&str>) { + let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); + let mut encoder = png::Encoder::new(file, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + let mut pixels = Vec::with_capacity((width * height * 4) as usize); + for frame in frames { + let rows = height / frames.len() as u32; + pixels.extend((0..width * rows).flat_map(|_| *frame)); + } + writer.write_image_data(&pixels).unwrap(); + writer.finish().unwrap(); + if let Some(mcmeta) = mcmeta { + let meta = path.with_extension("png.mcmeta"); + fs::write(meta, mcmeta).unwrap(); + } + } + /// A resource root holding one animated block texture: a strip of two + /// 16x16 frames, red then blue, whose mcmeta starts on the blue one. + fn animated_root() -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-atlas-anim-{}", std::process::id())); + let block = root.join("assets/minecraft/textures/block"); + fs::create_dir_all(&block).unwrap(); + write_strip( + &block.join("test_anim.png"), + 16, + 32, + &[[255, 0, 0, 255], [0, 0, 255, 255]], + Some(r#"{"animation": {"frames": [1, 0]}}"#), + ); + root + } + fn texel_at(atlas: &HudAtlas, rect: Rect, x: u32, y: u32) -> [u8; 4] { + let px = (rect.u0 * atlas.width as f32).round() as u32 + x; + let py = (rect.v0 * atlas.height as f32).round() as u32 + y; + let at = ((py * atlas.width + px) * 4) as usize; + atlas.pixels[at..at + 4].try_into().unwrap() + } + #[test] + fn animated_block_sprites_register_and_pack_their_first_mcmeta_frame() { + let root = animated_root(); + let atlas = HudAtlas::build(&root).unwrap(); + let (rect, animation) = atlas + .sprite_animations + .iter() + .find(|(_, animation)| animation.frame_count() == 2) + .expect("the animated block sprite"); + // The mcmeta's list starts on the strip's second (blue) frame. + assert_eq!(animation.frame(0), 1); + assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16)); + assert_eq!(texel_at(&atlas, *rect, 0, 0), [0, 0, 255, 255]); + assert_eq!(texel_at(&atlas, *rect, 15, 15), [0, 0, 255, 255]); + } + #[test] + fn a_strip_frames_size_comes_from_its_mcmeta() { + let root = animated_root(); + let block = root.join("assets/minecraft/textures/block"); + // A row of two frames with the animation's own frame size. + write_strip( + &block.join("test_row.png"), + 32, + 16, + &[[0, 255, 0, 255], [255, 255, 0, 255]], + Some(r#"{"animation": {"width": 16, "height": 16}}"#), + ); + let atlas = HudAtlas::build(&root).unwrap(); + let rect = atlas.sprites["block/test_row"]; + // The first frame is the left 16x16, not the whole row. + assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16)); + assert_eq!(texel_at(&atlas, rect, 0, 0), [0, 255, 0, 255]); + } /// `count` images of `w x h`; layout reads only their sizes. fn sized(count: usize, w: u32, h: u32) -> Vec { (0..count)