diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 41e4d7f645cc72b4e267e6b4053f9c47cf7b238f..bae634197ad45b431c0fa886b186eba037cc4856 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,7 @@ pub mod eval; #[cfg(not(target_arch = "wasm32"))] pub mod export; pub mod media; +pub mod motion_blur; pub mod optflow; pub mod particles; pub mod profile; diff --git a/crates/engine/src/motion_blur.rs b/crates/engine/src/motion_blur.rs new file mode 100644 index 0000000000000000000000000000000000000000..5ed6b78f8da488a0272e4f50b6637d21e1bce0da --- /dev/null +++ b/crates/engine/src/motion_blur.rs @@ -0,0 +1,1172 @@ +//! Temporal `MotionBlur` configuration and WebGPU-safe GPU sub-frame accumulator. +//! +//! Fusion tools that enable `MotionBlur >= 0.5` evaluate `Quality` sub-frames across +//! `[time + (-0.5 + CenterBias * 0.5) * shutter_frames, time + (+0.5 + CenterBias * 0.5) * shutter_frames]`, +//! where `shutter_frames = (ShutterAngle / 360.0) * SampleSpread`, and average them +//! with equal weights `1.0 / N` in an `Rgba32Float` DoD-aligned accumulation buffer. + +use crate::cache::CachedTexture; +use bytemuck::{Pod, Zeroable}; +use model::{BitDepth, Comp, ExprEngine, Node}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::num::NonZeroU64; +use std::sync::OnceLock; + +const MOTION_BLUR_WGSL: &str = include_str!("shaders/motion_blur.wgsl"); +const WORKGROUP_SIZE: u32 = 8; + +/// Returns `true` for Fusion tool kinds that support node-level temporal motion blur. +pub fn node_supports_motion_blur(kind: &str) -> bool { + matches!( + kind, + "Transform" + | "Merge" + | "TextPlus" + | "Renderer3D" + | "DVE" + | "CornerPositioner" + | "PerspectivePositioner" + | "EllipseMask" + | "RectangleMask" + | "PolylineMask" + | "BSplineMask" + | "Shadow" + | "GridWarp" + | "Displace" + ) +} + +/// Active temporal motion blur parameters read from a Fusion node at `time`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MotionBlurConfig { + pub quality: u32, + pub shutter_angle: f64, + pub center_bias: f64, + pub sample_spread: f64, +} + +fn canonical_f64_bits(v: f64) -> u64 { + if v == 0.0 { 0.0_f64.to_bits() } else { v.to_bits() } +} + +impl MotionBlurConfig { + /// Computes the `quality` sub-frame timestamps centered on `time`. + /// + /// Uses endpoint-spanning shutter offsets `u_k = k / (N - 1) - 0.5`: + /// - On the Snow Globe probe (`Quality = 5, ShutterAngle = 180, CenterBias = 0`, 4px bar at + /// `+3.84 px/frame`), endpoint coverage yields `[0.288, 0.712, 1.0, 1.0, 0.712, 0.288]` + /// (diff `0.026` vs Fusion `0.262 / 0.738`), closer than midpoint `(k + 0.5) / N - 0.5` + /// (`0.2304 / 0.7696`, diff `0.0316`), and spans the full shutter for `Quality = 2`. + pub fn shutter_times(&self, time: f64) -> Vec { + if !time.is_finite() + || !self.shutter_angle.is_finite() + || !self.sample_spread.is_finite() + || !self.center_bias.is_finite() + { + return Vec::new(); + } + if self.quality <= 1 { + return vec![time]; + } + let n = self.quality.clamp(2, 16) as usize; + let shutter_frames = + (self.shutter_angle.clamp(0.0, 720.0) / 360.0) * self.sample_spread.clamp(0.0, 10.0); + let bias_shift = self.center_bias.clamp(-1.0, 1.0) * 0.5; + let denom = (n - 1) as f64; + (0..n) + .map(|k| { + let u_k = (k as f64) / denom - 0.5; + time + (u_k + bias_shift) * shutter_frames + }) + .collect() + } + + /// Deterministic hash of `(quality, shutter_angle, center_bias, sample_spread)` for `NodeCache`. + pub fn cache_key_bits(&self) -> u64 { + let mut h = DefaultHasher::new(); + self.quality.hash(&mut h); + canonical_f64_bits(self.shutter_angle).hash(&mut h); + canonical_f64_bits(self.center_bias).hash(&mut h); + canonical_f64_bits(self.sample_spread).hash(&mut h); + h.finish() + } +} + +/// Reads and clamps temporal motion blur parameters for `node` at `time`. +/// +/// Returns `None` immediately when `!node_supports_motion_blur(&node.kind)`, `time` is +/// non-finite, `MotionBlur < 0.5`, `ShutterAngle <= 1e-4`, `SampleSpread <= 1e-4`, or +/// `Quality < 2`. +pub fn read_motion_blur_config( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, +) -> Option { + if !time.is_finite() || !node_supports_motion_blur(&node.kind) { + return None; + } + let enabled = comp.eval_number(node, "MotionBlur", time, 0.0, expr); + if !enabled.is_finite() || enabled < 0.5 { + return None; + } + let raw_shutter = comp.eval_number(node, "ShutterAngle", time, 180.0, expr); + if !raw_shutter.is_finite() || raw_shutter <= 1e-4 { + return None; + } + let raw_spread = comp.eval_number(node, "SampleSpread", time, 1.0, expr); + if !raw_spread.is_finite() || raw_spread <= 1e-4 { + return None; + } + let raw_quality = comp.eval_number(node, "Quality", time, 2.0, expr); + let quality_round = if raw_quality.is_finite() { + raw_quality.round() + } else { + 2.0 + }; + if quality_round < 2.0 { + return None; + } + let quality = if quality_round >= 16.0 { + 16 + } else { + (quality_round as u32).clamp(2, 16) + }; + let raw_bias = comp.eval_number(node, "CenterBias", time, 0.0, expr); + let center_bias = if raw_bias.is_finite() { + raw_bias.clamp(-1.0, 1.0) + } else { + 0.0 + }; + Some(MotionBlurConfig { + quality, + shutter_angle: raw_shutter.clamp(0.0, 720.0), + center_bias, + sample_spread: raw_spread.clamp(0.0, 10.0), + }) +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct MotionBlurUniform { + origins: [i32; 4], + params: [f32; 4], +} + +struct FinalizePipeline { + bgl: wgpu::BindGroupLayout, + pipeline: wgpu::ComputePipeline, +} + +impl FinalizePipeline { + fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let (storage_fmt, clamp_unorm) = match format { + wgpu::TextureFormat::Rgba16Float => ("rgba16float", false), + wgpu::TextureFormat::Rgba32Float => ("rgba32float", false), + _ => ("rgba8unorm", true), + }; + let mut src = MOTION_BLUR_WGSL.to_owned(); + if storage_fmt != "rgba8unorm" { + src = src.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + } + if !clamp_unorm { + src = src.replace("const CLAMP_UNORM: bool = true;", "const CLAMP_UNORM: bool = false;"); + } + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("motion-blur-finalize-shader"), + source: wgpu::ShaderSource::Wgsl(src.into()), + }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("motion-blur-finalize-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("motion-blur-finalize-layout"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("motion-blur-finalize"), + layout: Some(&layout), + module: &shader, + entry_point: Some("accum_finalize"), + compilation_options: Default::default(), + cache: None, + }); + Self { bgl, pipeline } + } +} + +struct MotionBlurInner { + bgl_clear: wgpu::BindGroupLayout, + bgl_add: wgpu::BindGroupLayout, + pipeline_clear: wgpu::ComputePipeline, + pipeline_add: wgpu::ComputePipeline, + uniform_stride: u32, + finalize_rgba8: OnceLock, + finalize_f16: OnceLock, + finalize_f32: OnceLock, +} + +impl MotionBlurInner { + fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("motion-blur-shader"), + source: wgpu::ShaderSource::Wgsl(MOTION_BLUR_WGSL.into()), + }); + let bgl_clear = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("motion-blur-clear-bgl"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }], + }); + let uniform_size = std::mem::size_of::() as u32; + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + let uniform_stride = uniform_size.div_ceil(min_align) * min_align; + let non_filterable_tex = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let bgl_add = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("motion-blur-add-bgl"), + entries: &[ + non_filterable_tex(0), + non_filterable_tex(1), + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::Rgba32Float, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(u64::from(uniform_size)), + }, + count: None, + }, + ], + }); + let clear_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("motion-blur-clear-layout"), + bind_group_layouts: &[Some(&bgl_clear)], + immediate_size: 0, + }); + let add_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("motion-blur-add-layout"), + bind_group_layouts: &[Some(&bgl_add)], + immediate_size: 0, + }); + let pipeline_clear = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("motion-blur-clear"), + layout: Some(&clear_layout), + module: &shader, + entry_point: Some("accum_clear"), + compilation_options: Default::default(), + cache: None, + }); + let pipeline_add = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("motion-blur-add"), + layout: Some(&add_layout), + module: &shader, + entry_point: Some("accum_add"), + compilation_options: Default::default(), + cache: None, + }); + Self { + bgl_clear, + bgl_add, + pipeline_clear, + pipeline_add, + uniform_stride, + finalize_rgba8: OnceLock::new(), + finalize_f16: OnceLock::new(), + finalize_f32: OnceLock::new(), + } + } + + fn finalize_for(&self, device: &wgpu::Device, format: wgpu::TextureFormat) -> &FinalizePipeline { + match format { + wgpu::TextureFormat::Rgba16Float => self + .finalize_f16 + .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba16Float)), + wgpu::TextureFormat::Rgba32Float => self + .finalize_f32 + .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba32Float)), + _ => self + .finalize_rgba8 + .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba8Unorm)), + } + } +} + +/// Lazily initialized GPU compute pipelines for DoD-aware temporal motion blur accumulation. +#[derive(Default)] +pub struct MotionBlurPipelines { + inner: OnceLock, +} + +fn compute_union_dod(samples: &[CachedTexture], max_dim: u32) -> ([i32; 2], [u32; 2]) { + let mut min_x = i64::MAX; + let mut min_y = i64::MAX; + let mut max_x = i64::MIN; + let mut max_y = i64::MIN; + for s in samples { + let x0 = i64::from(s.origin[0]); + let y0 = i64::from(s.origin[1]); + let x1 = x0 + i64::from(s.size[0].max(1)); + let y1 = y0 + i64::from(s.size[1].max(1)); + min_x = min_x.min(x0); + min_y = min_y.min(y0); + max_x = max_x.max(x1); + max_y = max_y.max(y1); + } + let max_d = i64::from(max_dim.max(1)); + let span_w = (max_x - min_x).max(1); + let span_h = (max_y - min_y).max(1); + let (ox, uw) = if span_w > max_d { + let center_x = min_x + span_w / 2; + ((center_x - max_d / 2) as i32, max_d as u32) + } else { + (min_x as i32, span_w as u32) + }; + let (oy, uh) = if span_h > max_d { + let center_y = min_y + span_h / 2; + ((center_y - max_d / 2) as i32, max_d as u32) + } else { + (min_y as i32, span_h as u32) + }; + ([ox, oy], [uw, uh]) +} + +fn create_accum_scratch(device: &wgpu::Device, size: [u32; 2], label: &str) -> (wgpu::Texture, wgpu::TextureView) { + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size[0].max(1), + height: size[1].max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING, + view_formats: &[], + }); + let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); + (tex, view) +} + +fn create_output_texture( + device: &wgpu::Device, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + depth: BitDepth, + format: wgpu::TextureFormat, + content_hash: u64, +) -> CachedTexture { + let mut usage = wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST; + // WebGPU baseline does not guarantee RENDER_ATTACHMENT on Rgba32Float. + if format != wgpu::TextureFormat::Rgba32Float { + usage |= wgpu::TextureUsages::RENDER_ATTACHMENT; + } + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("motion-blur-out"), + size: wgpu::Extent3d { + width: size[0].max(1), + height: size[1].max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + CachedTexture::from_texture_dod_depth( + tex, + [size[0].max(1), size[1].max(1)], + origin, + [canvas_size[0].max(1), canvas_size[1].max(1)], + depth, + content_hash, + ) +} + +impl MotionBlurPipelines { + /// Creates and initializes the motion blur compute pipelines on `device`. + pub fn new(device: &wgpu::Device) -> Self { + let pipelines = Self::default(); + pipelines.inner.get_or_init(|| MotionBlurInner::new(device)); + pipelines + } + + /// Accumulates `samples` with equal weight `1.0 / samples.len()` over their union DoD, + /// aligns each sample's `origin` to the union DoD, and writes the finalized output in + /// `dst_format` while preserving `aux` from the center sample. + #[allow(clippy::too_many_arguments)] + pub fn accumulate_samples( + &self, + device: &wgpu::Device, + _queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + samples: &[CachedTexture], + dst_depth: BitDepth, + dst_format: wgpu::TextureFormat, + content_hash: u64, + ) -> CachedTexture { + let target_fmt = match dst_format { + wgpu::TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float, + wgpu::TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float, + _ => wgpu::TextureFormat::Rgba8Unorm, + }; + if samples.is_empty() { + return create_output_texture( + device, + [1, 1], + [0, 0], + [1, 1], + dst_depth, + target_fmt, + content_hash, + ); + } + + let inner = self.inner.get_or_init(|| MotionBlurInner::new(device)); + let max_dim = device.limits().max_texture_dimension_2d.max(1); + let (union_origin, [uw, uh]) = compute_union_dod(samples, max_dim); + let wg_x = uw.div_ceil(WORKGROUP_SIZE); + let wg_y = uh.div_ceil(WORKGROUP_SIZE); + + let (_accum_a, accum_a_view) = create_accum_scratch(device, [uw, uh], "motion-blur-accum-a"); + let (_accum_b, accum_b_view) = create_accum_scratch(device, [uw, uh], "motion-blur-accum-b"); + + // 1. Clear accum_a to (0, 0, 0, 0). + let clear_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("motion-blur-clear-bg"), + layout: &inner.bgl_clear, + entries: &[wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&accum_a_view), + }], + }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("motion-blur-clear"), + timestamp_writes: None, + }); + pass.set_pipeline(&inner.pipeline_clear); + pass.set_bind_group(0, &clear_bg, &[]); + pass.dispatch_workgroups(wg_x, wg_y, 1); + } + + // 2. Upload all per-sample uniforms into one dynamic-offset buffer mapped at creation so + // multiple `accumulate_samples` calls in one encoder never clobber each other. + let uniform_size = std::mem::size_of::() as u64; + let stride = u64::from(inner.uniform_stride); + let total_buf_bytes = (samples.len() as u64) * stride; + let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("motion-blur-uniforms"), + size: total_buf_bytes, + usage: wgpu::BufferUsages::UNIFORM, + mapped_at_creation: true, + }); + let weight = 1.0_f32 / (samples.len() as f32); + { + let mut mapped = uniform_buf + .slice(..) + .get_mapped_range_mut() + .expect("uniform buffer mapped at creation"); + for (idx, sample) in samples.iter().enumerate() { + let u = MotionBlurUniform { + origins: [union_origin[0], union_origin[1], sample.origin[0], sample.origin[1]], + params: [weight, 0.0, 0.0, 0.0], + }; + let start = (idx as u64 * stride) as usize; + let end = start + uniform_size as usize; + mapped.slice(start..end).copy_from_slice(bytemuck::bytes_of(&u)); + } + } + uniform_buf.unmap(); + + // 3. Ping-pong accumulate each sample into Rgba32Float. + for (idx, sample) in samples.iter().enumerate() { + let (src_view, dst_view) = if idx % 2 == 0 { + (&accum_a_view, &accum_b_view) + } else { + (&accum_b_view, &accum_a_view) + }; + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("motion-blur-add-bg"), + layout: &inner.bgl_add, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(src_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&sample.view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(dst_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniform_buf, + offset: 0, + size: NonZeroU64::new(uniform_size), + }), + }, + ], + }); + let dyn_offset = (idx as u32) * inner.uniform_stride; + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("motion-blur-add"), + timestamp_writes: None, + }); + pass.set_pipeline(&inner.pipeline_add); + pass.set_bind_group(0, &bg, &[dyn_offset]); + pass.dispatch_workgroups(wg_x, wg_y, 1); + } + + // 4. Finalize accumulated buffer into destination format, preserving center sample metadata. + let center = &samples[samples.len() / 2]; + let mut out = create_output_texture( + device, + [uw, uh], + union_origin, + center.canvas_size, + dst_depth, + target_fmt, + content_hash, + ); + out.tex_scale = center.tex_scale; + out.edge_mode = center.edge_mode; + if let Some(aux) = ¢er.aux { + out.set_aux(Some(aux.clone())); + } + + let final_accum_view = if samples.len() % 2 == 1 { + &accum_b_view + } else { + &accum_a_view + }; + let finalize = inner.finalize_for(device, target_fmt); + let finalize_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("motion-blur-finalize-bg"), + layout: &finalize.bgl, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(final_accum_view), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&out.view), + }, + ], + }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("motion-blur-finalize"), + timestamp_writes: None, + }); + pass.set_pipeline(&finalize.pipeline); + pass.set_bind_group(0, &finalize_bg, &[]); + pass.dispatch_workgroups(wg_x, wg_y, 1); + } + + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_single_node_comp(kind: &str, inputs_lua: &str) -> (Comp, Node) { + let src = format!( + r#"Composition {{ + CurrentTime = 5, + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + TestNode = {kind} {{ + Inputs = {{ + {inputs_lua} + }}, + }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).expect("valid test comp"); + let id = comp.find_node("TestNode").expect("TestNode present"); + let node = comp.node(id).clone(); + (comp, node) + } + + #[test] + fn node_support_matches_fusion_tool_set() { + for supported in [ + "Transform", + "Merge", + "TextPlus", + "Renderer3D", + "DVE", + "CornerPositioner", + "PerspectivePositioner", + "EllipseMask", + "RectangleMask", + "PolylineMask", + "BSplineMask", + "Shadow", + "GridWarp", + "Displace", + ] { + assert!(node_supports_motion_blur(supported), "{supported} should support MB"); + } + for unsupported in ["Background", "ColorCorrector", "Blur", "Loader", "Saver", "Merge3D"] { + assert!(!node_supports_motion_blur(unsupported), "{unsupported} should not support MB"); + } + } + + #[test] + fn read_motion_blur_config_defaults_and_clamping() { + let expr = ExprEngine::new(); + + // Off by default + let (comp, node) = parse_single_node_comp("Transform", ""); + assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None); + + // MotionBlur = 1 uses Fusion defaults: Quality=2, ShutterAngle=180, CenterBias=0, SampleSpread=1 + let (comp, node) = parse_single_node_comp("Transform", "MotionBlur = Input { Value = 1, },"); + assert_eq!( + read_motion_blur_config(&comp, &node, 5.0, &expr), + Some(MotionBlurConfig { + quality: 2, + shutter_angle: 180.0, + center_bias: 0.0, + sample_spread: 1.0, + }) + ); + + // Non-MB node kind always returns None even with MotionBlur = 1 + let (comp, node) = parse_single_node_comp("Blur", "MotionBlur = Input { Value = 1, },"); + assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None); + + // Extreme upper clamping + let (comp, node) = parse_single_node_comp( + "Merge", + "MotionBlur = Input { Value = 1, }, + Quality = Input { Value = 99, }, + ShutterAngle = Input { Value = 1440.0, }, + CenterBias = Input { Value = 5.0, }, + SampleSpread = Input { Value = 25.0, },", + ); + assert_eq!( + read_motion_blur_config(&comp, &node, 5.0, &expr), + Some(MotionBlurConfig { + quality: 16, + shutter_angle: 720.0, + center_bias: 1.0, + sample_spread: 10.0, + }) + ); + + // Extreme negative CenterBias clamping + let (comp, node) = parse_single_node_comp( + "TextPlus", + "MotionBlur = Input { Value = 1, }, + Quality = Input { Value = 5, }, + CenterBias = Input { Value = -4.5, },", + ); + assert_eq!( + read_motion_blur_config(&comp, &node, 5.0, &expr).map(|c| c.center_bias), + Some(-1.0) + ); + + // Degenerate disabling thresholds + for inputs in [ + "MotionBlur = Input { Value = 0.49, },", + "MotionBlur = Input { Value = 1, }, ShutterAngle = Input { Value = 0.0, },", + "MotionBlur = Input { Value = 1, }, SampleSpread = Input { Value = 0.0, },", + "MotionBlur = Input { Value = 1, }, Quality = Input { Value = 1, },", + ] { + let (comp, node) = parse_single_node_comp("Transform", inputs); + assert_eq!( + read_motion_blur_config(&comp, &node, 5.0, &expr), + None, + "expected None for {inputs}" + ); + } + } + + #[test] + fn shutter_times_symmetry_bias_and_360_angle() { + let cfg = MotionBlurConfig { + quality: 5, + shutter_angle: 180.0, + center_bias: 0.0, + sample_spread: 1.0, + }; + let ts = cfg.shutter_times(5.0); + assert_eq!(ts.len(), 5); + assert!((ts[0] - 4.75).abs() < 1e-12); + assert!((ts[1] - 4.875).abs() < 1e-12); + assert!((ts[2] - 5.0).abs() < 1e-12); + assert!((ts[3] - 5.125).abs() < 1e-12); + assert!((ts[4] - 5.25).abs() < 1e-12); + assert!(((ts[0] + ts[4]) * 0.5 - 5.0).abs() < 1e-12); + assert!(((ts[1] + ts[3]) * 0.5 - 5.0).abs() < 1e-12); + + // ShutterAngle = 360 spans 1.0 full frame + let cfg360 = MotionBlurConfig { + shutter_angle: 360.0, + ..cfg + }; + let ts360 = cfg360.shutter_times(5.0); + assert!((ts360[0] - 4.5).abs() < 1e-12); + assert!((ts360[4] - 5.5).abs() < 1e-12); + + // CenterBias = +1 shifts window to [time, time + shutter_frames] + let cfg_lead = MotionBlurConfig { + center_bias: 1.0, + ..cfg + }; + let ts_lead = cfg_lead.shutter_times(5.0); + assert!((ts_lead[0] - 5.0).abs() < 1e-12); + assert!((ts_lead[4] - 5.5).abs() < 1e-12); + + // CenterBias = -1 shifts window to [time - shutter_frames, time] + let cfg_trail = MotionBlurConfig { + center_bias: -1.0, + ..cfg + }; + let ts_trail = cfg_trail.shutter_times(5.0); + assert!((ts_trail[0] - 4.5).abs() < 1e-12); + assert!((ts_trail[4] - 5.0).abs() < 1e-12); + + // Non-finite time guard + assert!(cfg.shutter_times(f64::NAN).is_empty()); + assert!(cfg.shutter_times(f64::INFINITY).is_empty()); + + // Cache key distinguishes parameters and normalizes -0.0 + let cfg_neg_zero = MotionBlurConfig { + center_bias: -0.0, + ..cfg + }; + assert_eq!(cfg.cache_key_bits(), cfg_neg_zero.cache_key_bits()); + assert_ne!(cfg.cache_key_bits(), cfg360.cache_key_bits()); + } + + #[cfg(not(target_arch = "wasm32"))] + mod gpu_tests { + use super::*; + use crate::cache::{AuxChannelTex, AuxChannels}; + use std::sync::Arc; + + fn create_webgpu_baseline_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()?; + // Request EMPTY features to prove zero reliance on FLOAT32_FILTERABLE or + // TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES (WebGPU baseline safe). + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_features: wgpu::Features::empty(), + ..Default::default() + })) + .ok() + } + + fn upload_rgba32f_dod( + device: &wgpu::Device, + queue: &wgpu::Queue, + size: [u32; 2], + origin: [i32; 2], + canvas_size: [u32; 2], + rgba: &[[f32; 4]], + hash: u64, + ) -> CachedTexture { + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("mb-test-src-f32"), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let bytes: &[u8] = bytemuck::cast_slice(rgba); + queue.write_texture( + tex.as_image_copy(), + bytes, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(size[0] * 16), + rows_per_image: Some(size[1]), + }, + wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + ); + CachedTexture::from_texture_dod_depth( + tex, + size, + origin, + canvas_size, + BitDepth::Float32, + hash, + ) + } + + fn readback_bytes( + device: &wgpu::Device, + queue: &wgpu::Queue, + tex: &CachedTexture, + bpp: u32, + ) -> Vec { + let [w, h] = tex.size; + let unpadded_bpr = w * bpp; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mb-test-readback"), + size: u64::from(padded_bpr) * u64::from(h), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("mb-test-readback-enc"), + }); + enc.copy_texture_to_buffer( + tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + queue.submit(Some(enc.finish())); + + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + device + .poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }) + .expect("device poll failed"); + rx.recv().expect("channel closed").expect("map_async failed"); + let data = slice.get_mapped_range().expect("get_mapped_range failed"); + let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); + for row in 0..h as usize { + let start = row * padded_bpr as usize; + out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); + } + drop(data); + buf.unmap(); + out + } + + fn f16_to_f32(bits: u16) -> f32 { + let sign = ((bits >> 15) as u32) << 31; + let exp = ((bits >> 10) & 0x1f) as u32; + let frac = (bits & 0x03ff) as u32; + if exp == 0 { + if frac == 0 { + f32::from_bits(sign) + } else { + let val = (frac as f32) * (2.0_f32).powi(-24); + if sign != 0 { -val } else { val } + } + } else if exp == 31 { + f32::from_bits(sign | 0x7f80_0000 | (frac << 13)) + } else { + f32::from_bits(sign | ((exp + 112) << 23) | (frac << 13)) + } + } + + /// Renders a 64x64 image with a 4px wide vertical white bar at `[bar_x, bar_x + 4)` + /// shifted sub-pixel by `dx` using exact bilinear coverage. + fn render_shifted_4px_bar(w: u32, h: u32, origin: [i32; 2], bar_x: f32) -> Vec<[f32; 4]> { + let mut px = vec![[0.0_f32; 4]; (w * h) as usize]; + for y in 0..h { + for x in 0..w { + let gx = (origin[0] + x as i32) as f32; + // Overlap of pixel interval [gx, gx+1] with bar [bar_x, bar_x+4] + let lo = gx.max(bar_x); + let hi = (gx + 1.0).min(bar_x + 4.0); + let cov = (hi - lo).clamp(0.0, 1.0); + px[(y * w + x) as usize] = [cov, cov, cov, cov]; + } + } + px + } + + #[test] + fn gpu_accumulate_samples_snow_globe_probe_dod_union_and_all_formats() { + let Some((device, queue)) = create_webgpu_baseline_device() else { + return; + }; + let pipelines = MotionBlurPipelines::new(&device); + + // Replicate the Snow Globe 4px bar probe: + // Quality=5, ShutterAngle=180, CenterBias=0, velocity=+3.84 px/frame at frame=5.0. + let cfg = MotionBlurConfig { + quality: 5, + shutter_angle: 180.0, + center_bias: 0.0, + sample_spread: 1.0, + }; + let times = cfg.shutter_times(5.0); + assert_eq!(times.len(), 5); + + // Give each sub-frame a slightly shifted DoD origin so DoD union & origin alignment + // are exercised simultaneously. + let origins = [[-4, -2], [-2, 0], [0, 0], [2, 1], [4, 2]]; + let base_x = 30.0_f32; + let vel = 3.84_f32; + let mut samples: Vec = times + .iter() + .zip(origins.iter()) + .enumerate() + .map(|(i, (&t, &org))| { + let bar_x = base_x + ((t - 5.0) as f32) * vel; + let data = render_shifted_4px_bar(64, 64, org, bar_x); + upload_rgba32f_dod(&device, &queue, [64, 64], org, [64, 64], &data, i as u64 + 1) + }) + .collect(); + + // Attach an AuxChannels Z buffer to the center sample (index 2) to verify preservation. + let center_aux = Arc::new(AuxChannels { + z: Some(AuxChannelTex::new( + &device, + [64, 64], + wgpu::TextureFormat::R32Float, + "mb-test-aux-z", + )), + ..Default::default() + }); + samples[2].set_aux(Some(center_aux)); + + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("mb-test-all-formats"), + }); + let out_u8 = pipelines.accumulate_samples( + &device, + &queue, + &mut enc, + &samples, + BitDepth::Int8, + wgpu::TextureFormat::Rgba8Unorm, + 101, + ); + let out_f16 = pipelines.accumulate_samples( + &device, + &queue, + &mut enc, + &samples, + BitDepth::Float16, + wgpu::TextureFormat::Rgba16Float, + 102, + ); + let out_f32 = pipelines.accumulate_samples( + &device, + &queue, + &mut enc, + &samples, + BitDepth::Float32, + wgpu::TextureFormat::Rgba32Float, + 103, + ); + queue.submit(Some(enc.finish())); + + // Union of [-4..-4+64]..=[4..4+64] in X is [-4, 68) -> width 72. + // Union of [-2..-2+64]..=[2..2+64] in Y is [-2, 66) -> height 68. + for (tex, fmt, depth) in [ + (&out_u8, wgpu::TextureFormat::Rgba8Unorm, BitDepth::Int8), + (&out_f16, wgpu::TextureFormat::Rgba16Float, BitDepth::Float16), + (&out_f32, wgpu::TextureFormat::Rgba32Float, BitDepth::Float32), + ] { + assert_eq!(tex.origin, [-4, -2]); + assert_eq!(tex.size, [72, 68]); + assert_eq!(tex.canvas_size, [64, 64]); + assert_eq!(tex.format, fmt); + assert_eq!(tex.depth, depth); + assert!(tex.aux.as_ref().is_some_and(|a| a.z.is_some())); + } + + // Readback Rgba32Float at row y=32 (local row 32 - (-2) = 34) and verify Snow Globe + // symmetry and exact energy conservation (sum = 4.000). + let raw_f32 = readback_bytes(&device, &queue, &out_f32, 16); + let floats: Vec = raw_f32 + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + let row_y = 34usize; + let row_offset = row_y * 72; + let mut row_sum = 0.0_f32; + let mut profile = Vec::new(); + for gx in 28..=35 { + let lx = (gx - (-4)) as usize; + let r = floats[(row_offset + lx) * 4]; + profile.push(r); + row_sum += r; + } + assert!( + (row_sum - 4.0).abs() < 1e-4, + "energy conservation broken: sum={row_sum}, profile={profile:?}" + ); + // Expected profile: [0.0, 0.288, 0.712, 1.0, 1.0, 0.712, 0.288, 0.0] + assert!(profile[0].abs() < 1e-5); + assert!((profile[1] - 0.288).abs() < 1e-4, "p[1]={}", profile[1]); + assert!((profile[2] - 0.712).abs() < 1e-4, "p[2]={}", profile[2]); + assert!((profile[3] - 1.0).abs() < 1e-4); + assert!((profile[4] - 1.0).abs() < 1e-4); + assert!((profile[1] - profile[6]).abs() < 1e-5, "asymmetric left/right outer"); + assert!((profile[2] - profile[5]).abs() < 1e-5, "asymmetric left/right inner"); + assert!(profile[7].abs() < 1e-5); + + // Verify Rgba16Float matches Rgba32Float closely + let raw_f16 = readback_bytes(&device, &queue, &out_f16, 8); + let f16_vals: Vec = raw_f16 + .chunks_exact(2) + .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))) + .collect(); + for gx in 28..=35 { + let lx = (gx - (-4)) as usize; + let r32 = floats[(row_offset + lx) * 4]; + let r16 = f16_vals[(row_offset + lx) * 4]; + assert!((r32 - r16).abs() < 2e-3, "f16 mismatch at x={gx}: {r16} vs {r32}"); + } + + // Verify Rgba8Unorm matches quantized [0, 1] profile + let raw_u8 = readback_bytes(&device, &queue, &out_u8, 4); + for gx in 28..=35 { + let lx = (gx - (-4)) as usize; + let r32 = floats[(row_offset + lx) * 4]; + let ru8 = f32::from(raw_u8[(row_offset + lx) * 4]) / 255.0; + assert!((r32 - ru8).abs() < 0.01, "u8 mismatch at x={gx}: {ru8} vs {r32}"); + } + } + + #[test] + fn gpu_accumulate_samples_clamps_hdr_only_for_unorm() { + let Some((device, queue)) = create_webgpu_baseline_device() else { + return; + }; + let pipelines = MotionBlurPipelines::new(&device); + let hdr_a = vec![[2.5_f32, -0.5, 0.5, 1.0]; 4 * 4]; + let hdr_b = vec![[1.5_f32, 0.5, 0.5, 1.0]; 4 * 4]; + let s_a = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_a, 1); + let s_b = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_b, 2); + + let mut enc = device.create_command_encoder(&Default::default()); + let out_u8 = pipelines.accumulate_samples( + &device, + &queue, + &mut enc, + &[s_a.clone(), s_b.clone()], + BitDepth::Int8, + wgpu::TextureFormat::Rgba8Unorm, + 201, + ); + let out_f32 = pipelines.accumulate_samples( + &device, + &queue, + &mut enc, + &[s_a, s_b], + BitDepth::Float32, + wgpu::TextureFormat::Rgba32Float, + 202, + ); + queue.submit(Some(enc.finish())); + + let u8_bytes = readback_bytes(&device, &queue, &out_u8, 4); + assert_eq!(u8_bytes[0], 255); + assert_eq!(u8_bytes[1], 0); + assert!((u8_bytes[2] as i32 - 128).abs() <= 1); + assert_eq!(u8_bytes[3], 255); + + let f32_bytes = readback_bytes(&device, &queue, &out_f32, 16); + let r = f32::from_le_bytes([f32_bytes[0], f32_bytes[1], f32_bytes[2], f32_bytes[3]]); + let g = f32::from_le_bytes([f32_bytes[4], f32_bytes[5], f32_bytes[6], f32_bytes[7]]); + assert!((r - 2.0).abs() < 1e-5, "HDR should preserve >1.0: {r}"); + assert!((g - 0.0).abs() < 1e-5); + } + } +} diff --git a/crates/engine/src/shaders/motion_blur.wgsl b/crates/engine/src/shaders/motion_blur.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..43884716abc8fccc9f15576d2ea252642154e109 --- /dev/null +++ b/crates/engine/src/shaders/motion_blur.wgsl @@ -0,0 +1,62 @@ +// Temporal MotionBlur GPU accumulator compute shaders (WebGPU-safe). +// +// Accumulation uses Rgba32Float ping-pong textures accessed strictly via +// `textureLoad` and write-only `textureStore` (never `textureSample` on +// Rgba32Float and never `read_write` storage textures). + +struct MotionBlurUniform { + // [dst_origin.x, dst_origin.y, sample_origin.x, sample_origin.y] + origins: vec4, + // [weight, 0.0, 0.0, 0.0] + params: vec4, +}; + +@group(0) @binding(0) var accum_src: texture_2d; +@group(0) @binding(1) var sample_tex: texture_2d; +@group(0) @binding(2) var accum_dst: texture_storage_2d; +@group(0) @binding(3) var final_dst: texture_storage_2d; +@group(0) @binding(4) var u: MotionBlurUniform; + +// Overridden to `false` when building Rgba16Float / Rgba32Float finalize pipelines. +const CLAMP_UNORM: bool = true; + +@compute @workgroup_size(8, 8) +fn accum_clear(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(accum_dst); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + textureStore(accum_dst, vec2(gid.xy), vec4(0.0)); +} + +@compute @workgroup_size(8, 8) +fn accum_add(@builtin(global_invocation_id) gid: vec3) { + let dst_dims = textureDimensions(accum_dst); + if (gid.x >= dst_dims.x || gid.y >= dst_dims.y) { + return; + } + let px = vec2(gid.xy); + let prev = textureLoad(accum_src, px, 0); + let sample_px = px + u.origins.xy - u.origins.zw; + let sample_dims = vec2(textureDimensions(sample_tex)); + var col = vec4(0.0); + if (sample_px.x >= 0 && sample_px.y >= 0 && sample_px.x < sample_dims.x && sample_px.y < sample_dims.y) { + col = textureLoad(sample_tex, sample_px, 0); + } + textureStore(accum_dst, px, prev + u.params.x * col); +} + +@compute @workgroup_size(8, 8) +fn accum_finalize(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(final_dst); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let px = vec2(gid.xy); + let col = textureLoad(accum_src, px, 0); + if (CLAMP_UNORM) { + textureStore(final_dst, px, clamp(col, vec4(0.0), vec4(1.0))); + } else { + textureStore(final_dst, px, col); + } +}