From abb7a971363bf2244b63585a8daf9a9d7c620744 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:45:18 +0200 Subject: [PATCH] Animated sprites on the GPU: frames uploaded once, one dispatch per mip level Every animation frame's mip chain goes to video memory once, at the sprite's own size, as vanilla keeps its animated sprites' frames on the GPU. A tick that changes sprites writes one 20-byte job per changed sprite, and a compute dispatch per mip level repeats the chain into the array's larger layers and mixes interpolated frames (animate_sprite_interpolate), instead of blending on the CPU at the array's size and copying each sprite level by level. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 365 +------------ crates/horizon-client/src/gfx/animate.rs | 590 +++++++++++++++++++++ crates/horizon-client/src/gfx/animate.wgsl | 48 ++ crates/horizon-client/src/sprites.rs | 13 +- 4 files changed, 663 insertions(+), 353 deletions(-) create mode 100644 crates/horizon-client/src/gfx/animate.rs create mode 100644 crates/horizon-client/src/gfx/animate.wgsl diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..7298d4292 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -59,6 +59,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] .collect() } +mod animate; mod arena; mod cull; mod flat; @@ -363,8 +364,6 @@ pub struct Renderer { sprite_textures: Vec, /// A 1-layer array bound where a pack needs fewer arrays. sprite_unused: wgpu::TextureView, - /// Layers per sprite array ([`SPRITE_SPLIT`] but in tests). - sprite_split: u32, mip_levels: u32, /// The mipmap levels sampled (the Mipmap Levels option), at most `mip_levels - 1`. mipmaps: u32, @@ -372,7 +371,7 @@ pub struct Renderer { sprite_sampler: wgpu::Sampler, lightmap_view: wgpu::TextureView, lightmap_sampler: wgpu::Sampler, - animations: AnimatedSprites, + animations: animate::SpriteAnimator, uploads: upload::Uploads, /// Section meshes are staged through their own belt into /// `section_copies`, which the next frame records its commands after: @@ -1274,7 +1273,9 @@ impl Renderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::STORAGE_BINDING, view_formats: &[], }, wgpu::util::TextureDataOrder::LayerMajor, @@ -1282,6 +1283,14 @@ impl Renderer { ) }) .collect(); + let animations = animate::SpriteAnimator::new( + &device, + animations, + sprite_size, + sprite_mips, + &sprite_textures, + split, + ); let sprite_unused = device .create_texture(&wgpu::TextureDescriptor { label: Some("Block sprites (unused)"), @@ -2133,14 +2142,13 @@ impl Renderer { lightmap, sprite_textures, sprite_unused, - sprite_split: split, mip_levels, mipmaps: mip_levels - 1, terrain_layout: bindings, sprite_sampler, lightmap_view, lightmap_sampler, - animations: AnimatedSprites::new(animations, sprite_size, sprite_mips), + animations, uploads, section_uploads, section_copies: None, @@ -2733,29 +2741,7 @@ impl Renderer { self.lightmap_uploaded = true; } fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) { - animate_sprites( - &mut self.animations, - tick, - self.mip_levels, - |layer, level, size, pixels| { - self.uploads.texture( - encoder, - wgpu::TexelCopyTextureInfo { - texture: &self.sprite_textures[(layer / self.sprite_split) as usize], - mip_level: level, - origin: wgpu::Origin3d { - x: 0, - y: 0, - z: layer % self.sprite_split, - }, - aspect: wgpu::TextureAspect::All, - }, - size, - size, - pixels, - ); - }, - ); + self.animations.animate(encoder, &mut self.uploads, tick); } pub fn render(&mut self, frame: &Frame) -> Result { let rendered = self.draw_frame(frame); @@ -4427,171 +4413,10 @@ pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, avail let upscale = (size / minimum.max(1)).max(1).ilog2(); requested.saturating_add(upscale).min(available - 1) } -/// Room for every frame of the vanilla animations (594 frames, 13 MB of mip -/// chains in 64-pixel layers), so no frame's chain is rebuilt on the render -/// thread when its animation comes back to it; larger packs stay bounded. -const ANIMATION_MIP_BUDGET: usize = 32 << 20; -const ANIMATION_MIP_ENTRIES: usize = 4096; - -/// One immutable resource snapshot and its lazily generated frame mips. A new -/// renderer on resource reload drops this entire snapshot, including its cache: -/// frame indices can never alias another resource's pixels, size or settings. -struct AnimatedSprites { - /// Each animated sprite and what its layer holds (`None`: not uploaded yet). - animations: Vec<(SpriteAnimation, Option)>, - size: u32, - settings: Vec, - // Cache bookkeeping must not consume randomness or affect other maps' seeding. - cache: crate::fast_hash::FxHashMap<(usize, usize), Vec>, - /// Retained pixel-buffer capacities, not just their initialized lengths. - cache_bytes: usize, - budget: usize, -} -impl AnimatedSprites { - fn new( - animations: &[SpriteAnimation], - size: u32, - settings: &[crate::mipmap::Settings], - ) -> Self { - Self { - animations: animations.iter().cloned().map(|a| (a, None)).collect(), - size, - settings: settings.to_vec(), - cache: Default::default(), - cache_bytes: 0, - budget: ANIMATION_MIP_BUDGET, - } - } -} -fn animate_sprites( - state: &mut AnimatedSprites, - tick: u64, - max_levels: u32, - mut write: impl FnMut(u32, u32, u32, &[u8]), -) { - let size = state.size; - let levels = size.trailing_zeros() + 1; - let AnimatedSprites { - animations, - settings, - cache, - cache_bytes, - budget, - .. - } = state; - for (index, (animation, previous)) in animations.iter_mut().enumerate() { - let blend = animation.blend(tick); - if *previous == Some(blend) { - continue; - } - *previous = Some(blend); - let (animation, settings) = (&*animation, &**settings); - let chain = |frame: usize| { - move || mip_chain(animation.pixels(frame), size, settings, animation.layer, 1).0 - }; - let (current, mixed); - let mips: &[u8] = if blend.millis > 0 { - let mut mix = frame_mips( - cache, - cache_bytes, - *budget, - (index, blend.frame), - chain(blend.frame), - ) - .into_owned(); - let next = frame_mips( - cache, - cache_bytes, - *budget, - (index, blend.next), - chain(blend.next), - ); - mix_frames(&mut mix, &next, blend.millis); - mixed = mix; - &mixed - } else { - current = frame_mips( - cache, - cache_bytes, - *budget, - (index, blend.frame), - chain(blend.frame), - ); - ¤t - }; - let mut offset = 0; - for level in 0..levels.min(max_levels) { - let edge = size >> level; - let bytes = (edge * edge * 4) as usize; - write(animation.layer, level, edge, &mips[offset..offset + bytes]); - offset += bytes; - } - } -} -/// `animate_sprite_interpolate.fsh`: `mix(current, next, millis / 1000)` per -/// channel of every mipmap level, stored as 8-bit unorm. -/// One frame's mip chain: from the cache, or generated and kept while the budget has room. -/// Frames that do not fit still go through the same generation path. -fn frame_mips<'a>( - cache: &'a mut crate::fast_hash::FxHashMap<(usize, usize), Vec>, - cache_bytes: &mut usize, - budget: usize, - key: (usize, usize), - generate: impl FnOnce() -> Vec, -) -> std::borrow::Cow<'a, [u8]> { - let room = cache.len() < ANIMATION_MIP_ENTRIES; - match cache.entry(key) { - std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut().as_slice().into(), - std::collections::hash_map::Entry::Vacant(entry) => { - let pixels = generate(); - // Bound both pixel storage and map metadata. Keep admitted frames - // rather than churning them on large/unique workloads. - if room && pixels.capacity() <= budget - *cache_bytes { - *cache_bytes += pixels.capacity(); - entry.insert(pixels).as_slice().into() - } else { - pixels.into() - } - } - } -} -fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) { - let t = millis as f32 / 1000.0; - for (c, n) in current.iter_mut().zip(next) { - let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0); - *c = round_unorm8((a * (1.0 - t) + b * t) * 255.0); - } -} -/// `x.round() as u8` for `x >= 0`, without the `roundf` library call that -/// x86-64 makes for every `f32::round` (it has no rounding instruction before -/// SSE4.1): the fraction `x - trunc(x)` is exact below 2^23, so rounding half -/// away from zero is adding one when it is at least a half. -#[inline] -fn round_unorm8(x: f32) -> u8 { - let whole = x as u8; - whole.saturating_add(u8::from(x - f32::from(whole) >= 0.5)) -} #[cfg(test)] mod sprite_upload_tests { use super::*; #[test] - fn blended_frames_round_like_f32_round() { - for millis in (0..1000).step_by(7).chain([999]) { - let t = millis as f32 / 1000.0; - for a in 0..=255u8 { - for b in 0..=255u8 { - let x = (f32::from(a) / 255.0 * (1.0 - t) + f32::from(b) / 255.0 * t) * 255.0; - assert_eq!(round_unorm8(x), x.round() as u8, "{a} {b} {millis}"); - } - } - } - for x in [ - 0.0, 0.49999997, 0.5, 1.5, 2.5, 254.49998, 254.5, 255.0, 255.00002, 300.0, - ] { - assert_eq!(round_unorm8(x), x.round() as u8, "{x}"); - } - } - #[test] fn real_rail_mips_do_not_change_with_larger_array_layers() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") @@ -4654,84 +4479,6 @@ mod sprite_upload_tests { assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels); } } - #[test] - fn animation_updates_entire_layer_every_mip_once() { - for size in [16, 32] { - let animation = crate::sprites::test_animation(size, 7); - let pixels = animation.pixels(animation.frame(1)).to_vec(); - let settings = []; - let (expected, levels) = mip_chain(&pixels, size, &settings, 7, 1); - let mut animations = AnimatedSprites::new(&[animation], size, &settings); - animations.animations[0].1 = Some(animations.animations[0].0.blend(0)); - let mut writes = Vec::new(); - let mut record = |layer, level, edge, data: &[u8]| { - assert_eq!(layer, 7); - assert_eq!(edge, size >> level); - assert_eq!(data.len(), (edge * edge * 4) as usize); - writes.push(data.to_vec()); - }; - animate_sprites(&mut animations, 0, levels, &mut record); - animate_sprites(&mut animations, 1, levels, &mut record); - animate_sprites(&mut animations, 1, levels, &mut record); - assert_eq!(writes.len(), levels as usize); - assert_eq!(writes[0], pixels); - assert_eq!(writes.concat(), expected); - } - } - - #[test] - fn cached_and_uncached_uploads_match_through_loops_and_mip_changes() { - for size in [16, 32] { - let animations = [crate::sprites::test_animation(size, 7)]; - let settings = vec![ - crate::mipmap::Settings { - strategy: crate::mipmap::Strategy::StrictCutout, - alpha_cutoff_bias: -0.2, - ..Default::default() - }; - 8 - ]; - let mut cached = AnimatedSprites::new(&animations, size, &settings); - let mut uncached = AnimatedSprites::new(&animations, size, &settings); - uncached.budget = 0; - for tick in [0, 0, 1, 2, 3, 33, 32, 32, 1, 0] { - let levels = (tick % 7) as u32; - let mut expected = Vec::new(); - let mut actual = Vec::new(); - animate_sprites(&mut uncached, tick, levels, |layer, level, edge, bytes| { - expected.push((layer, level, edge, bytes.to_vec())); - }); - animate_sprites(&mut cached, tick, levels, |layer, level, edge, bytes| { - actual.push((layer, level, edge, bytes.to_vec())); - }); - assert_eq!(actual, expected); - } - assert_eq!(cached.cache.len(), 2); - assert_eq!(uncached.cache_bytes, 0); - assert_eq!( - cached.cache_bytes, - cached.cache.values().map(Vec::capacity).sum::() - ); - } - } - - #[test] - fn budget_exhaustion_keeps_admitted_frames_and_uploads_misses() { - let size = 16; - let animation = crate::sprites::test_animation(size, 0); - let bytes = mip_chain(animation.pixels(0), size, &[], 0, 1).0.capacity(); - let mut state = AnimatedSprites::new(&[animation], size, &[]); - state.budget = bytes; - for tick in 0..8 { - let mut writes = 0; - animate_sprites(&mut state, tick, 5, |_, _, _, _| writes += 1); - assert_eq!(writes, 5); - assert_eq!(state.cache_bytes, bytes); - assert_eq!(state.cache.len(), 1); - assert!(state.cache.contains_key(&(0, 0))); - } - } - #[test] fn prepared_texture_uploads_preserve_layer_order_and_settings() { let size = 4; @@ -4784,86 +4531,4 @@ mod sprite_upload_tests { assert_eq!(chain.capacity(), chain.len()); } } - - #[test] - fn every_vanilla_animation_frame_stays_cached() { - // Vanilla's 594 animation frames in 64-pixel layers: 297 two-frame clips. - let animations: Vec<_> = (0..297) - .map(|layer| crate::sprites::test_animation(64, layer)) - .collect(); - let mut state = AnimatedSprites::new(&animations, 64, &[]); - for tick in 0..4 { - animate_sprites(&mut state, tick, 7, |_, _, _, _| {}); - } - assert_eq!(state.cache.len(), 594); - assert!(state.cache_bytes <= ANIMATION_MIP_BUDGET); - } - - #[test] - fn entry_limit_also_bounds_metadata_for_tiny_frames() { - let animation = crate::sprites::test_animation(1, 0); - let animations = vec![animation; ANIMATION_MIP_ENTRIES + 1]; - let mut state = AnimatedSprites::new(&animations, 1, &[]); - for tick in 0..2 { - let mut writes = 0; - animate_sprites(&mut state, tick, 1, |_, _, _, _| writes += 1); - assert_eq!(writes, animations.len()); - assert_eq!(state.cache.len(), ANIMATION_MIP_ENTRIES); - assert!(state.cache_bytes <= ANIMATION_MIP_BUDGET); - } - } - - #[test] - fn resource_snapshot_replacement_discards_pixels_size_and_settings() { - let old = crate::sprites::test_animation(16, 0); - let mut state = AnimatedSprites::new(&[old], 16, &[]); - animate_sprites(&mut state, 0, 5, |_, _, _, _| {}); - assert!(!state.cache.is_empty()); - let animation = crate::sprites::test_animation(32, 0); - let settings = [crate::mipmap::Settings { - strategy: crate::mipmap::Strategy::StrictCutout, - alpha_cutoff_bias: -0.4, - ..Default::default() - }]; - let expected = mip_chain(animation.pixels(0), 32, &settings, 0, 1).0; - state = AnimatedSprites::new(&[animation], 32, &settings); - assert_eq!(state.cache_bytes, 0); - assert!(state.cache.is_empty()); - let mut actual = Vec::new(); - animate_sprites(&mut state, 0, 6, |_, _, _, bytes| { - actual.extend_from_slice(bytes) - }); - assert_eq!(actual, expected); - } - - #[test] - fn interpolated_animation_uploads_the_mix_every_tick() { - let animation = crate::sprites::test_clip(16, 3, r#"{"frametime":4,"interpolate":true}"#); - let settings = []; - let (_, levels) = mip_chain(animation.pixels(0), 16, &settings, 3, 1); - let mut cached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings); - let mut uncached = AnimatedSprites::new(std::slice::from_ref(&animation), 16, &settings); - uncached.budget = 0; - for state in [&mut cached, &mut uncached] { - state.animations[0].1 = Some(animation.blend(0)); - } - let mut blues = Vec::new(); - let mut uncached_blues = Vec::new(); - let mut record = |_, level, _, data: &[u8]| { - if level == 0 { - blues.push(data[2]); - } - }; - for tick in [0, 1, 1, 2, 4] { - animate_sprites(&mut cached, tick, levels, &mut record); - animate_sprites(&mut uncached, tick, levels, |_, level, _, data: &[u8]| { - if level == 0 { - uncached_blues.push(data[2]); - } - }); - } - // Frame 0 is blue 0, frame 1 blue 99: a quarter, a half, then frame 1. - assert_eq!(blues, [25, 50, 99]); - assert_eq!(uncached_blues, blues); - } } diff --git a/crates/horizon-client/src/gfx/animate.rs b/crates/horizon-client/src/gfx/animate.rs new file mode 100644 index 000000000..f4528902b --- /dev/null +++ b/crates/horizon-client/src/gfx/animate.rs @@ -0,0 +1,590 @@ +//! Animated block sprites, drawn on the GPU as vanilla 26.3 draws them: +//! `SpriteContents.AnimatedTexture` keeps every frame in video memory, and +//! each tick `animate_sprite_blit` or `animate_sprite_interpolate` draws the +//! frame shown (mixed with the next one for `interpolate`) into the atlas. +//! +//! Every frame's mip chain is uploaded once, at the sprite's own size. A tick +//! that changes sprites writes one small job per changed sprite and runs one +//! compute dispatch per mip level (`animate.wgsl`), which repeats the chain +//! into the array's larger layers by whole pixels and mixes interpolated +//! frames. Blending on the CPU at the array's size and copying every changed +//! sprite level by level (a copy command each, a blit each in Mesa) was about +//! a fifth of the render thread on an integrated GPU. +use super::upload::Uploads; +use crate::mipmap::Settings; +use crate::sprites::{FrameBlend, SpriteAnimation}; +use wgpu::util::DeviceExt; + +/// Bytes of `animate.wgsl`'s `Job`. +const JOB_BYTES: usize = 20; +/// `animate.wgsl`'s workgroup edge. +const WORKGROUP: u32 = 8; + +struct Sprite { + animation: SpriteAnimation, + /// What its layer shows (`None`: the frame the array was created with, + /// rewritten on the first tick). + shown: Option, + /// Its layer in its sprite array. + layer: u32, + /// Each frame's mip chain: its offset in words in the group's frames. + frames: Vec, + /// Edge of the chains' first level. + edge: u32, + group: usize, +} + +/// The animated sprites of one sprite array whose frames share one buffer. +struct Group { + /// Where its jobs start in `SpriteAnimator::jobs`, in bytes. + offset: u64, + /// One bind group per mip level of the array. + levels: Vec, + /// This tick's jobs. + jobs: Vec, +} + +pub(super) struct SpriteAnimator { + sprites: Vec, + groups: Vec, + jobs: wgpu::Buffer, + pipeline: wgpu::ComputePipeline, + /// Edge of the arrays' layers. + size: u32, +} + +impl SpriteAnimator { + /// `textures` are the sprite arrays, `split` layers each, `size` pixels + /// wide; `animations` hold their frames at that size. + pub fn new( + device: &wgpu::Device, + animations: &[SpriteAnimation], + size: u32, + settings: &[Settings], + textures: &[wgpu::Texture], + split: u32, + ) -> Self { + let limits = device.limits(); + let limit = limits + .max_storage_buffer_binding_size + .min(limits.max_buffer_size); + let mut frames: Vec> = Vec::new(); + // Each group's sprite array and frames buffer. + let mut keys: Vec<(u32, usize)> = Vec::new(); + let mut counts: Vec = Vec::new(); + let mut sprites = Vec::with_capacity(animations.len()); + for animation in animations { + let chains: Vec<_> = (0..animation.frame_count()) + .map(|frame| source_chain(animation.pixels(frame), size, settings, animation.layer)) + .collect(); + let bytes: u64 = chains.iter().map(|(chain, _)| chain.len() as u64).sum(); + if bytes > limit { + log::warn!( + "Horizon: layer {}'s animation ({bytes} bytes) does not fit in a storage buffer; it stays still", + animation.layer + ); + continue; + } + if frames + .last() + .is_none_or(|data| data.len() as u64 + bytes > limit) + { + frames.push(Vec::new()); + } + let buffer = frames.len() - 1; + let data = &mut frames[buffer]; + let offsets = chains + .iter() + .map(|(chain, _)| { + let offset = (data.len() / 4) as u32; + data.extend_from_slice(chain); + offset + }) + .collect(); + let key = (animation.layer / split, buffer); + let group = keys.iter().position(|&k| k == key).unwrap_or_else(|| { + keys.push(key); + counts.push(0); + keys.len() - 1 + }); + counts[group] += 1; + sprites.push(Sprite { + animation: animation.clone(), + shown: None, + layer: animation.layer % split, + frames: offsets, + edge: chains[0].1, + group, + }); + } + let frames: Vec<_> = frames + .iter() + .map(|data| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Animated sprite frames"), + contents: data, + usage: wgpu::BufferUsages::STORAGE, + }) + }) + .collect(); + let align = u64::from(limits.min_storage_buffer_offset_alignment); + let mut offsets = Vec::with_capacity(counts.len()); + let mut total = 0; + for &count in &counts { + offsets.push(total); + total = (total + (count * JOB_BYTES) as u64).next_multiple_of(align); + } + let jobs = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Animated sprite jobs"), + size: total.max(align), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Animated sprites"), + source: wgpu::ShaderSource::Wgsl(include_str!("animate.wgsl").into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Animated sprites"), + layout: None, + module: &module, + entry_point: Some("animate"), + compilation_options: Default::default(), + cache: None, + }); + let layout = pipeline.get_bind_group_layout(0); + let groups = keys + .iter() + .zip(&counts) + .zip(offsets) + .map(|((&(array, buffer), &count), offset)| { + let texture = &textures[array as usize]; + let levels = (0..texture.mip_level_count()) + .map(|level| { + let view = texture.create_view(&wgpu::TextureViewDescriptor { + label: Some("Animated sprites"), + dimension: Some(wgpu::TextureViewDimension::D2Array), + base_mip_level: level, + mip_level_count: Some(1), + ..Default::default() + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Animated sprites"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: frames[buffer].as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &jobs, + offset, + size: wgpu::BufferSize::new((count * JOB_BYTES) as u64), + }), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&view), + }, + ], + }) + }) + .collect(); + Group { + offset, + levels, + jobs: Vec::with_capacity(count * JOB_BYTES), + } + }) + .collect(); + Self { + sprites, + groups, + jobs, + pipeline, + size, + } + } + + /// Show every sprite's frame at `tick`, rewriting only the sprites whose + /// frame or mix changed (`SpriteContents.AnimationState.tick`). + pub fn animate( + &mut self, + encoder: &mut wgpu::CommandEncoder, + uploads: &mut Uploads, + tick: u64, + ) { + if self.collect(tick) == 0 { + return; + } + for group in &self.groups { + uploads.buffer(encoder, &self.jobs, group.offset, &group.jobs); + } + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Animated sprites"), + timestamp_writes: None, + }); + pass.set_pipeline(&self.pipeline); + for group in &mut self.groups { + let count = (group.jobs.len() / JOB_BYTES) as u32; + if count == 0 { + continue; + } + for (level, bind) in group.levels.iter().enumerate() { + let groups = (self.size >> level).div_ceil(WORKGROUP); + pass.set_bind_group(0, bind, &[]); + pass.dispatch_workgroups(groups, groups, count); + } + group.jobs.clear(); + } + } + + /// Queue a job for every sprite whose blend at `tick` differs from what + /// its layer shows; the number of jobs. + fn collect(&mut self, tick: u64) -> usize { + let mut count = 0; + for sprite in &mut self.sprites { + let blend = sprite.animation.blend(tick); + if sprite.shown == Some(blend) { + continue; + } + sprite.shown = Some(blend); + let job = [ + sprite.layer, + sprite.frames[blend.frame], + sprite.frames[blend.next], + blend.millis, + sprite.edge, + ]; + let jobs = &mut self.groups[sprite.group].jobs; + for word in job { + jobs.extend_from_slice(&word.to_le_bytes()); + } + count += 1; + } + count + } +} + +/// The mip chain a frame's layer is made of, and its first level's edge. +/// `mipmap::generate` makes a sprite scaled up by whole pixels to the +/// array's size from its own size's chain, its first level repeated into the +/// larger levels: that chain, which the shader repeats. Any other sprite: its +/// chain at the array's size. +fn source_chain(pixels: &[u8], size: u32, settings: &[Settings], layer: u32) -> (Vec, u32) { + let native = settings.get(layer as usize).map_or(0, |s| s.native_size); + let edge = if native.is_power_of_two() && native < size { + native + } else { + size + }; + let frame = crate::sprites::resample(pixels, size, edge); + (super::mip_chain(&frame, edge, settings, layer, 1).0, edge) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mipmap::Strategy; + + /// `animate.wgsl` on the CPU: `chain` (first level `edge` wide) as the + /// full chain of a `size` layer, mixed `millis` thousandths of the way + /// towards `next`. + fn reference(chain: &[u8], next: &[u8], millis: u32, edge: u32, size: u32) -> Vec { + let levels = size.trailing_zeros() + 1; + let mut out = Vec::new(); + for level in 0..levels { + let width = size >> level; + for y in 0..width { + for x in 0..width { + let texel = if width >= edge { + let scale = width / edge; + y / scale * edge + x / scale + } else { + 4 * (edge * edge - width * width) / 3 + y * width + x + } as usize; + for c in 0..4 { + let (a, b) = ( + u32::from(chain[texel * 4 + c]), + u32::from(next[texel * 4 + c]), + ); + out.push(((a * (1000 - millis) + b * millis + 500) / 1000) as u8); + } + } + } + } + out + } + + fn frame(size: u32, seed: u32) -> Vec { + (0..size * size) + .flat_map(|i| { + let v = i + .wrapping_mul(2654435761) + .wrapping_add(seed.wrapping_mul(40503)); + let alpha = match v >> 29 { + 0 => 0, + 1 => 77, + _ => 255, + }; + [(v >> 3) as u8, (v >> 11) as u8, (v >> 19) as u8, alpha] + }) + .collect() + } + + fn settings(native: u32, strategy: Strategy) -> Settings { + Settings { + native_size: native, + strategy, + alpha_cutoff_bias: -0.1, + ..Default::default() + } + } + + #[test] + fn source_chains_repeat_into_the_array_chain() { + // Sprites scaled up by whole pixels, at the array's size, and of a + // size that is not a power of two (scaled up to the next one). + for (native, size) in [(16, 16), (16, 64), (8, 32), (32, 64), (1, 16), (24, 32)] { + for strategy in [ + Strategy::Auto, + Strategy::Mean, + Strategy::Cutout, + Strategy::StrictCutout, + Strategy::DarkCutout, + ] { + for item in [false, true] { + let settings = [ + Settings::default(), + Settings { + item, + ..settings(native, strategy) + }, + ]; + let pixels = crate::sprites::resample(&frame(native, 3), native, size); + let (expected, _) = super::super::mip_chain(&pixels, size, &settings, 1, 1); + let (chain, edge) = source_chain(&pixels, size, &settings, 1); + let fits = native.is_power_of_two() && native < size; + assert_eq!(edge, if fits { native } else { size }); + assert_eq!( + reference(&chain, &chain, 0, edge, size), + expected, + "{native} in {size}, {strategy:?}, item {item}" + ); + } + } + } + } + + #[test] + fn real_animation_chains_repeat_into_the_array_chain() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root + .join("assets/minecraft/textures/block/water_still.png") + .exists() + { + return; + } + let mut sprites = crate::sprites::Sprites::default(); + for name in [ + "water_still", + "water_flow", + "lava_still", + "fire_0", + "nether_portal", + "sea_lantern", + "prismarine", + "magma", + "kelp", + "straw_bed", + ] { + sprites + .insert(&root, &format!("minecraft:block/{name}")) + .unwrap(); + } + sprites.finish(); + assert_eq!(sprites.size, 64); + assert_eq!(sprites.animations.len(), 9); + for animation in &sprites.animations { + for frame in 0..animation.frame_count() { + let pixels = animation.pixels(frame); + let (expected, _) = + super::super::mip_chain(pixels, 64, &sprites.mips, animation.layer, 1); + let (chain, edge) = source_chain(pixels, 64, &sprites.mips, animation.layer); + assert!(edge < 64, "layer {}", animation.layer); + assert_eq!(reference(&chain, &chain, 0, edge, 64), expected); + } + } + } + + #[test] + fn rounding_matches_f32_mix_but_for_exact_halves() { + // The CPU blend this replaced: f32 mix, then rounded. They differ + // only where the exact mix is a half, which f32 rounded either way. + for millis in 1..1000u32 { + let t = millis as f32 / 1000.0; + for a in 0..=255u32 { + for b in (0..=255u32).step_by(3) { + let f = ((a as f32 / 255.0) * (1.0 - t) + (b as f32 / 255.0) * t) * 255.0; + let exact = a * (1000 - millis) + b * millis; + let ours = (exact + 500) / 1000; + if exact % 1000 != 500 { + assert_eq!(ours, f.round() as u32, "{a} {b} {millis}"); + } + } + } + } + } + + fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; + pollster::block_on(adapter.request_device(&Default::default())).ok() + } + + /// Every layer's full mip chain, layer major. + fn read_back( + device: &wgpu::Device, + queue: &wgpu::Queue, + texture: &wgpu::Texture, + ) -> Vec> { + let layers = texture.depth_or_array_layers(); + let mut out = vec![Vec::new(); layers as usize]; + for level in 0..texture.mip_level_count() { + let edge = texture.width() >> level; + let padded = (edge * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: u64::from(padded * edge * layers), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: level, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded), + rows_per_image: Some(edge), + }, + }, + wgpu::Extent3d { + width: edge, + height: edge, + depth_or_array_layers: layers, + }, + ); + queue.submit([encoder.finish()]); + buffer + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let data = buffer.slice(..).get_mapped_range().unwrap(); + for (layer, image) in data.chunks((padded * edge) as usize).enumerate() { + for row in image.chunks(padded as usize) { + out[layer].extend_from_slice(&row[..edge as usize * 4]); + } + } + } + out + } + + #[test] + fn gpu_layers_match_the_cpu_chains_every_tick() { + let Some((device, queue)) = device() else { + return; + }; + let size = 32; + // Layers 1 and 3: 8-pixel sprites with and without interpolation; + // layer 4: one at the array's size. Two layers per array. + let clips = [ + ( + 1, + 8, + r#"{"frametime":3,"interpolate":true,"frames":[0,2,1]}"#, + ), + (3, 8, r#"{"frametime":2}"#), + (4, 32, r#"{"frametime":5,"interpolate":true}"#), + ]; + let mut mips = vec![Settings::default(); 6]; + let animations: Vec<_> = clips + .iter() + .map(|&(layer, native, metadata)| { + mips[layer as usize] = settings(native, Strategy::Cutout); + let frames = (0..3) + .map(|f| crate::sprites::resample(&frame(native, layer * 7 + f), native, size)) + .collect(); + crate::sprites::test_frames(layer, frames, metadata) + }) + .collect(); + let split = 2; + let textures: Vec<_> = (0..3) + .map(|_| { + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: size, + height: size, + depth_or_array_layers: split, + }, + mip_level_count: size.trailing_zeros() + 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }) + .collect(); + let mut animator = SpriteAnimator::new(&device, &animations, size, &mips, &textures, split); + let mut uploads = Uploads::new(&device); + let mut writes = Vec::new(); + for tick in [0, 0, 1, 2, 3, 4, 7, 7, 12, 30] { + let mut encoder = device.create_command_encoder(&Default::default()); + let shown: Vec<_> = animator.sprites.iter().map(|s| s.shown).collect(); + animator.animate(&mut encoder, &mut uploads, tick); + writes.push( + animator + .sprites + .iter() + .zip(shown) + .filter(|(s, shown)| s.shown != *shown) + .count(), + ); + uploads.finish(&encoder); + queue.submit([encoder.finish()]); + for animation in &animations { + let blend = animation.blend(tick); + let chain = |f| source_chain(animation.pixels(f), size, &mips, animation.layer); + let ((current, edge), (next, _)) = (chain(blend.frame), chain(blend.next)); + let layers = read_back( + &device, + &queue, + &textures[(animation.layer / split) as usize], + ); + assert_eq!( + layers[(animation.layer % split) as usize], + reference(¤t, &next, blend.millis, edge, size), + "layer {} at tick {tick}", + animation.layer + ); + } + } + // Every sprite on the first tick, then only those whose frame or mix + // changed since they were written: the interpolated ones every tick + // but layer 1 at tick 30 (two 9-tick loops after 12), layer 3 when + // its frame turns over (every 2 ticks, but 12 shows 7's frame). + assert_eq!(writes, [3, 0, 2, 3, 2, 3, 3, 0, 2, 1]); + } +} diff --git a/crates/horizon-client/src/gfx/animate.wgsl b/crates/horizon-client/src/gfx/animate.wgsl new file mode 100644 index 000000000..8998a1aa1 --- /dev/null +++ b/crates/horizon-client/src/gfx/animate.wgsl @@ -0,0 +1,48 @@ +// Animated block sprites (gfx/animate.rs), as vanilla's animate_sprite_blit +// and animate_sprite_interpolate shaders draw them: each job writes its +// frame, or the frame mixed with the next one, into one mip level of its +// sprite array layer. One invocation per texel; the job is the z coordinate. +struct Job { + layer: u32, + // Word offsets of the two frames' mip chains in `frames`. + current: u32, + next: u32, + // Thousandths of the way from `current` to `next` (0: `current` alone). + millis: u32, + // Edge of the chains' first level. + edge: u32, +} +@group(0) @binding(0) var frames: array; +@group(0) @binding(1) var jobs: array; +@group(0) @binding(2) var level: texture_storage_2d_array; + +fn channels(rgba: u32) -> vec4 { + return vec4(rgba & 0xffu, (rgba >> 8u) & 0xffu, (rgba >> 16u) & 0xffu, rgba >> 24u); +} + +@compute @workgroup_size(8, 8) +fn animate(@builtin(global_invocation_id) id: vec3) { + let size = textureDimensions(level).x; + if id.x >= size || id.y >= size { + return; + } + let job = jobs[id.z]; + // mipmap::generate: the levels at least as large as the chain's first + // repeat it by whole pixels, the smaller ones are the chain's own. + var texel: u32; + if size >= job.edge { + let scale = size / job.edge; + texel = id.y / scale * job.edge + id.x / scale; + } else { + // Every level above this one, each a quarter of the one before. + texel = 4u * (job.edge * job.edge - size * size) / 3u + id.y * size + id.x; + } + var color = channels(frames[job.current + texel]); + if job.millis > 0u { + // mix(current, next, millis / 1000), rounded to the nearest 8-bit + // value (halves up) in integers: the same on every GPU. + let next = channels(frames[job.next + texel]); + color = (color * (1000u - job.millis) + next * job.millis + 500u) / 1000u; + } + textureStore(level, id.xy, job.layer, vec4(color) / 255.0); +} diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index b89983966..6d754894a 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -63,6 +63,9 @@ impl SpriteAnimation { pub fn pixels(&self, frame: usize) -> &[u8] { &self.frames[frame] } + pub fn frame_count(&self) -> usize { + self.frames.len() + } } #[derive(Default)] @@ -93,7 +96,7 @@ pub const SPRITE_SIZE: u32 = 16; /// with bigger textures are sampled down to fit. const MAX_ARRAY_BYTES: u64 = 256 << 20; /// Nearest-resample a square RGBA frame to another square size. -fn resample(frame: &[u8], from: u32, to: u32) -> Vec { +pub(crate) fn resample(frame: &[u8], from: u32, to: u32) -> Vec { if from == to { return frame.to_vec(); } @@ -327,11 +330,15 @@ pub(crate) fn test_clip(size: u32, layer: u32, metadata: &str) -> SpriteAnimatio .flat_map(|i| [(i % size) as u8, (i / size) as u8, blue, 255]) .collect() }; + test_frames(layer, vec![frame(0), frame(99)], metadata) +} +#[cfg(test)] +pub(crate) fn test_frames(layer: u32, frames: Vec>, metadata: &str) -> SpriteAnimation { let metadata = AnimationMetadata::from_json(metadata).unwrap(); SpriteAnimation { layer, - frames: Arc::new(vec![frame(0), frame(99)]), - clip: Arc::new(metadata.clip(2).unwrap().unwrap()), + clip: Arc::new(metadata.clip(frames.len() as u32).unwrap().unwrap()), + frames: Arc::new(frames), } }