1//! Temporal `MotionBlur` configuration and WebGPU-safe GPU sub-frame accumulator.
2//!
3//! Fusion tools that enable `MotionBlur >= 0.5` evaluate `Quality` sub-frames across
4//! `[time + (-0.5 + CenterBias * 0.5) * shutter_frames, time + (+0.5 + CenterBias * 0.5) * shutter_frames]`,
5//! where `shutter_frames = (ShutterAngle / 360.0) * SampleSpread`, and average them
6//! with equal weights `1.0 / N` in an `Rgba32Float` DoD-aligned accumulation buffer.
7
8use crate::cache::CachedTexture;
9use bytemuck::{Pod, Zeroable};
10use model::{BitDepth, Comp, ExprEngine, Node};
11use std::collections::hash_map::DefaultHasher;
12use std::hash::{Hash, Hasher};
13use std::num::NonZeroU64;
14use std::sync::OnceLock;
15
16const MOTION_BLUR_WGSL: &str = include_str!("shaders/motion_blur.wgsl");
17const WORKGROUP_SIZE: u32 = 8;
18
19/// Returns `true` for Fusion tool kinds that support node-level temporal motion blur.
20pub fn node_supports_motion_blur(kind: &str) -> bool {
21 matches!(
22 kind,
23 "Transform"
24 | "Merge"
25 | "TextPlus"
26 | "Renderer3D"
27 | "DVE"
28 | "CornerPositioner"
29 | "PerspectivePositioner"
30 | "EllipseMask"
31 | "RectangleMask"
32 | "PolylineMask"
33 | "BSplineMask"
34 | "Shadow"
35 | "GridWarp"
36 | "Displace"
37 )
38}
39
40/// Active temporal motion blur parameters read from a Fusion node at `time`.
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct MotionBlurConfig {
43 pub quality: u32,
44 pub shutter_angle: f64,
45 pub center_bias: f64,
46 pub sample_spread: f64,
47}
48
49fn canonical_f64_bits(v: f64) -> u64 {
50 if v == 0.0 { 0.0_f64.to_bits() } else { v.to_bits() }
51}
52
53impl MotionBlurConfig {
54 /// Computes the `quality` sub-frame timestamps centered on `time`.
55 ///
56 /// Uses endpoint-spanning shutter offsets `u_k = k / (N - 1) - 0.5`:
57 /// - On the Snow Globe probe (`Quality = 5, ShutterAngle = 180, CenterBias = 0`, 4px bar at
58 /// `+3.84 px/frame`), endpoint coverage yields `[0.288, 0.712, 1.0, 1.0, 0.712, 0.288]`
59 /// (diff `0.026` vs Fusion `0.262 / 0.738`), closer than midpoint `(k + 0.5) / N - 0.5`
60 /// (`0.2304 / 0.7696`, diff `0.0316`), and spans the full shutter for `Quality = 2`.
61 pub fn shutter_times(&self, time: f64) -> Vec<f64> {
62 if !time.is_finite()
63 || !self.shutter_angle.is_finite()
64 || !self.sample_spread.is_finite()
65 || !self.center_bias.is_finite()
66 {
67 return Vec::new();
68 }
69 if self.quality <= 1 {
70 return vec![time];
71 }
72 let n = self.quality.clamp(2, 16) as usize;
73 let shutter_frames =
74 (self.shutter_angle.clamp(0.0, 720.0) / 360.0) * self.sample_spread.clamp(0.0, 10.0);
75 let bias_shift = self.center_bias.clamp(-1.0, 1.0) * 0.5;
76 let denom = (n - 1) as f64;
77 (0..n)
78 .map(|k| {
79 let u_k = (k as f64) / denom - 0.5;
80 time + (u_k + bias_shift) * shutter_frames
81 })
82 .collect()
83 }
84
85 /// Deterministic hash of `(quality, shutter_angle, center_bias, sample_spread)` for `NodeCache`.
86 pub fn cache_key_bits(&self) -> u64 {
87 let mut h = DefaultHasher::new();
88 self.quality.hash(&mut h);
89 canonical_f64_bits(self.shutter_angle).hash(&mut h);
90 canonical_f64_bits(self.center_bias).hash(&mut h);
91 canonical_f64_bits(self.sample_spread).hash(&mut h);
92 h.finish()
93 }
94}
95
96/// Reads and clamps temporal motion blur parameters for `node` at `time`.
97///
98/// Returns `None` immediately when `!node_supports_motion_blur(&node.kind)`, `time` is
99/// non-finite, `MotionBlur < 0.5`, `ShutterAngle <= 1e-4`, `SampleSpread <= 1e-4`, or
100/// `Quality < 2`.
101pub fn read_motion_blur_config(
102 comp: &Comp,
103 node: &Node,
104 time: f64,
105 expr: &ExprEngine,
106) -> Option<MotionBlurConfig> {
107 if !time.is_finite() || !node_supports_motion_blur(&node.kind) {
108 return None;
109 }
110 let enabled = comp.eval_number(node, "MotionBlur", time, 0.0, expr);
111 if !enabled.is_finite() || enabled < 0.5 {
112 return None;
113 }
114 let raw_shutter = comp.eval_number(node, "ShutterAngle", time, 180.0, expr);
115 if !raw_shutter.is_finite() || raw_shutter <= 1e-4 {
116 return None;
117 }
118 let raw_spread = comp.eval_number(node, "SampleSpread", time, 1.0, expr);
119 if !raw_spread.is_finite() || raw_spread <= 1e-4 {
120 return None;
121 }
122 let raw_quality = comp.eval_number(node, "Quality", time, 2.0, expr);
123 let quality_round = if raw_quality.is_finite() {
124 raw_quality.round()
125 } else {
126 2.0
127 };
128 if quality_round < 2.0 {
129 return None;
130 }
131 let quality = if quality_round >= 16.0 {
132 16
133 } else {
134 (quality_round as u32).clamp(2, 16)
135 };
136 let raw_bias = comp.eval_number(node, "CenterBias", time, 0.0, expr);
137 let center_bias = if raw_bias.is_finite() {
138 raw_bias.clamp(-1.0, 1.0)
139 } else {
140 0.0
141 };
142 Some(MotionBlurConfig {
143 quality,
144 shutter_angle: raw_shutter.clamp(0.0, 720.0),
145 center_bias,
146 sample_spread: raw_spread.clamp(0.0, 10.0),
147 })
148}
149
150#[repr(C)]
151#[derive(Clone, Copy, Pod, Zeroable)]
152struct MotionBlurUniform {
153 origins: [i32; 4],
154 params: [f32; 4],
155}
156
157struct FinalizePipeline {
158 bgl: wgpu::BindGroupLayout,
159 pipeline: wgpu::ComputePipeline,
160}
161
162impl FinalizePipeline {
163 fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
164 let (storage_fmt, clamp_unorm) = match format {
165 wgpu::TextureFormat::Rgba16Float => ("rgba16float", false),
166 wgpu::TextureFormat::Rgba32Float => ("rgba32float", false),
167 _ => ("rgba8unorm", true),
168 };
169 let mut src = MOTION_BLUR_WGSL.to_owned();
170 if storage_fmt != "rgba8unorm" {
171 src = src.replace(
172 "texture_storage_2d<rgba8unorm, write>",
173 &format!("texture_storage_2d<{storage_fmt}, write>"),
174 );
175 }
176 if !clamp_unorm {
177 src = src.replace("const CLAMP_UNORM: bool = true;", "const CLAMP_UNORM: bool = false;");
178 }
179 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
180 label: Some("motion-blur-finalize-shader"),
181 source: wgpu::ShaderSource::Wgsl(src.into()),
182 });
183 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
184 label: Some("motion-blur-finalize-bgl"),
185 entries: &[
186 wgpu::BindGroupLayoutEntry {
187 binding: 0,
188 visibility: wgpu::ShaderStages::COMPUTE,
189 ty: wgpu::BindingType::Texture {
190 sample_type: wgpu::TextureSampleType::Float { filterable: false },
191 view_dimension: wgpu::TextureViewDimension::D2,
192 multisampled: false,
193 },
194 count: None,
195 },
196 wgpu::BindGroupLayoutEntry {
197 binding: 3,
198 visibility: wgpu::ShaderStages::COMPUTE,
199 ty: wgpu::BindingType::StorageTexture {
200 access: wgpu::StorageTextureAccess::WriteOnly,
201 format,
202 view_dimension: wgpu::TextureViewDimension::D2,
203 },
204 count: None,
205 },
206 ],
207 });
208 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
209 label: Some("motion-blur-finalize-layout"),
210 bind_group_layouts: &[Some(&bgl)],
211 immediate_size: 0,
212 });
213 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
214 label: Some("motion-blur-finalize"),
215 layout: Some(&layout),
216 module: &shader,
217 entry_point: Some("accum_finalize"),
218 compilation_options: Default::default(),
219 cache: None,
220 });
221 Self { bgl, pipeline }
222 }
223}
224
225struct MotionBlurInner {
226 bgl_clear: wgpu::BindGroupLayout,
227 bgl_add: wgpu::BindGroupLayout,
228 pipeline_clear: wgpu::ComputePipeline,
229 pipeline_add: wgpu::ComputePipeline,
230 uniform_stride: u32,
231 finalize_rgba8: OnceLock<FinalizePipeline>,
232 finalize_f16: OnceLock<FinalizePipeline>,
233 finalize_f32: OnceLock<FinalizePipeline>,
234}
235
236impl MotionBlurInner {
237 fn new(device: &wgpu::Device) -> Self {
238 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
239 label: Some("motion-blur-shader"),
240 source: wgpu::ShaderSource::Wgsl(MOTION_BLUR_WGSL.into()),
241 });
242 let bgl_clear = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
243 label: Some("motion-blur-clear-bgl"),
244 entries: &[wgpu::BindGroupLayoutEntry {
245 binding: 2,
246 visibility: wgpu::ShaderStages::COMPUTE,
247 ty: wgpu::BindingType::StorageTexture {
248 access: wgpu::StorageTextureAccess::WriteOnly,
249 format: wgpu::TextureFormat::Rgba32Float,
250 view_dimension: wgpu::TextureViewDimension::D2,
251 },
252 count: None,
253 }],
254 });
255 let uniform_size = std::mem::size_of::<MotionBlurUniform>() as u32;
256 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
257 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
258 let non_filterable_tex = |binding| wgpu::BindGroupLayoutEntry {
259 binding,
260 visibility: wgpu::ShaderStages::COMPUTE,
261 ty: wgpu::BindingType::Texture {
262 sample_type: wgpu::TextureSampleType::Float { filterable: false },
263 view_dimension: wgpu::TextureViewDimension::D2,
264 multisampled: false,
265 },
266 count: None,
267 };
268 let bgl_add = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
269 label: Some("motion-blur-add-bgl"),
270 entries: &[
271 non_filterable_tex(0),
272 non_filterable_tex(1),
273 wgpu::BindGroupLayoutEntry {
274 binding: 2,
275 visibility: wgpu::ShaderStages::COMPUTE,
276 ty: wgpu::BindingType::StorageTexture {
277 access: wgpu::StorageTextureAccess::WriteOnly,
278 format: wgpu::TextureFormat::Rgba32Float,
279 view_dimension: wgpu::TextureViewDimension::D2,
280 },
281 count: None,
282 },
283 wgpu::BindGroupLayoutEntry {
284 binding: 4,
285 visibility: wgpu::ShaderStages::COMPUTE,
286 ty: wgpu::BindingType::Buffer {
287 ty: wgpu::BufferBindingType::Uniform,
288 has_dynamic_offset: true,
289 min_binding_size: NonZeroU64::new(u64::from(uniform_size)),
290 },
291 count: None,
292 },
293 ],
294 });
295 let clear_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
296 label: Some("motion-blur-clear-layout"),
297 bind_group_layouts: &[Some(&bgl_clear)],
298 immediate_size: 0,
299 });
300 let add_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
301 label: Some("motion-blur-add-layout"),
302 bind_group_layouts: &[Some(&bgl_add)],
303 immediate_size: 0,
304 });
305 let pipeline_clear = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
306 label: Some("motion-blur-clear"),
307 layout: Some(&clear_layout),
308 module: &shader,
309 entry_point: Some("accum_clear"),
310 compilation_options: Default::default(),
311 cache: None,
312 });
313 let pipeline_add = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
314 label: Some("motion-blur-add"),
315 layout: Some(&add_layout),
316 module: &shader,
317 entry_point: Some("accum_add"),
318 compilation_options: Default::default(),
319 cache: None,
320 });
321 Self {
322 bgl_clear,
323 bgl_add,
324 pipeline_clear,
325 pipeline_add,
326 uniform_stride,
327 finalize_rgba8: OnceLock::new(),
328 finalize_f16: OnceLock::new(),
329 finalize_f32: OnceLock::new(),
330 }
331 }
332
333 fn finalize_for(&self, device: &wgpu::Device, format: wgpu::TextureFormat) -> &FinalizePipeline {
334 match format {
335 wgpu::TextureFormat::Rgba16Float => self
336 .finalize_f16
337 .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba16Float)),
338 wgpu::TextureFormat::Rgba32Float => self
339 .finalize_f32
340 .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba32Float)),
341 _ => self
342 .finalize_rgba8
343 .get_or_init(|| FinalizePipeline::new(device, wgpu::TextureFormat::Rgba8Unorm)),
344 }
345 }
346}
347
348/// Lazily initialized GPU compute pipelines for DoD-aware temporal motion blur accumulation.
349#[derive(Default)]
350pub struct MotionBlurPipelines {
351 inner: OnceLock<MotionBlurInner>,
352}
353
354fn compute_union_dod(samples: &[CachedTexture], max_dim: u32) -> ([i32; 2], [u32; 2]) {
355 let mut min_x = i64::MAX;
356 let mut min_y = i64::MAX;
357 let mut max_x = i64::MIN;
358 let mut max_y = i64::MIN;
359 for s in samples {
360 let x0 = i64::from(s.origin[0]);
361 let y0 = i64::from(s.origin[1]);
362 let x1 = x0 + i64::from(s.size[0].max(1));
363 let y1 = y0 + i64::from(s.size[1].max(1));
364 min_x = min_x.min(x0);
365 min_y = min_y.min(y0);
366 max_x = max_x.max(x1);
367 max_y = max_y.max(y1);
368 }
369 let max_d = i64::from(max_dim.max(1));
370 let span_w = (max_x - min_x).max(1);
371 let span_h = (max_y - min_y).max(1);
372 let (ox, uw) = if span_w > max_d {
373 let center_x = min_x + span_w / 2;
374 ((center_x - max_d / 2) as i32, max_d as u32)
375 } else {
376 (min_x as i32, span_w as u32)
377 };
378 let (oy, uh) = if span_h > max_d {
379 let center_y = min_y + span_h / 2;
380 ((center_y - max_d / 2) as i32, max_d as u32)
381 } else {
382 (min_y as i32, span_h as u32)
383 };
384 ([ox, oy], [uw, uh])
385}
386
387fn create_accum_scratch(device: &wgpu::Device, size: [u32; 2], label: &str) -> (wgpu::Texture, wgpu::TextureView) {
388 let tex = device.create_texture(&wgpu::TextureDescriptor {
389 label: Some(label),
390 size: wgpu::Extent3d {
391 width: size[0].max(1),
392 height: size[1].max(1),
393 depth_or_array_layers: 1,
394 },
395 mip_level_count: 1,
396 sample_count: 1,
397 dimension: wgpu::TextureDimension::D2,
398 format: wgpu::TextureFormat::Rgba32Float,
399 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::STORAGE_BINDING,
400 view_formats: &[],
401 });
402 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
403 (tex, view)
404}
405
406fn create_output_texture(
407 device: &wgpu::Device,
408 size: [u32; 2],
409 origin: [i32; 2],
410 canvas_size: [u32; 2],
411 depth: BitDepth,
412 format: wgpu::TextureFormat,
413 content_hash: u64,
414) -> CachedTexture {
415 let mut usage = wgpu::TextureUsages::TEXTURE_BINDING
416 | wgpu::TextureUsages::STORAGE_BINDING
417 | wgpu::TextureUsages::COPY_SRC
418 | wgpu::TextureUsages::COPY_DST;
419 // WebGPU baseline does not guarantee RENDER_ATTACHMENT on Rgba32Float.
420 if format != wgpu::TextureFormat::Rgba32Float {
421 usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
422 }
423 let tex = device.create_texture(&wgpu::TextureDescriptor {
424 label: Some("motion-blur-out"),
425 size: wgpu::Extent3d {
426 width: size[0].max(1),
427 height: size[1].max(1),
428 depth_or_array_layers: 1,
429 },
430 mip_level_count: 1,
431 sample_count: 1,
432 dimension: wgpu::TextureDimension::D2,
433 format,
434 usage,
435 view_formats: &[],
436 });
437 CachedTexture::from_texture_dod_depth(
438 tex,
439 [size[0].max(1), size[1].max(1)],
440 origin,
441 [canvas_size[0].max(1), canvas_size[1].max(1)],
442 depth,
443 content_hash,
444 )
445}
446
447impl MotionBlurPipelines {
448 /// Creates and initializes the motion blur compute pipelines on `device`.
449 pub fn new(device: &wgpu::Device) -> Self {
450 let pipelines = Self::default();
451 pipelines.inner.get_or_init(|| MotionBlurInner::new(device));
452 pipelines
453 }
454
455 /// Accumulates `samples` with equal weight `1.0 / samples.len()` over their union DoD,
456 /// aligns each sample's `origin` to the union DoD, and writes the finalized output in
457 /// `dst_format` while preserving `aux` from the center sample.
458 #[allow(clippy::too_many_arguments)]
459 pub fn accumulate_samples(
460 &self,
461 device: &wgpu::Device,
462 _queue: &wgpu::Queue,
463 enc: &mut wgpu::CommandEncoder,
464 samples: &[CachedTexture],
465 dst_depth: BitDepth,
466 dst_format: wgpu::TextureFormat,
467 content_hash: u64,
468 ) -> CachedTexture {
469 let target_fmt = match dst_format {
470 wgpu::TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
471 wgpu::TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float,
472 _ => wgpu::TextureFormat::Rgba8Unorm,
473 };
474 if samples.is_empty() {
475 return create_output_texture(
476 device,
477 [1, 1],
478 [0, 0],
479 [1, 1],
480 dst_depth,
481 target_fmt,
482 content_hash,
483 );
484 }
485
486 let inner = self.inner.get_or_init(|| MotionBlurInner::new(device));
487 let max_dim = device.limits().max_texture_dimension_2d.max(1);
488 let (union_origin, [uw, uh]) = compute_union_dod(samples, max_dim);
489 let wg_x = uw.div_ceil(WORKGROUP_SIZE);
490 let wg_y = uh.div_ceil(WORKGROUP_SIZE);
491
492 let (_accum_a, accum_a_view) = create_accum_scratch(device, [uw, uh], "motion-blur-accum-a");
493 let (_accum_b, accum_b_view) = create_accum_scratch(device, [uw, uh], "motion-blur-accum-b");
494
495 // 1. Clear accum_a to (0, 0, 0, 0).
496 let clear_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
497 label: Some("motion-blur-clear-bg"),
498 layout: &inner.bgl_clear,
499 entries: &[wgpu::BindGroupEntry {
500 binding: 2,
501 resource: wgpu::BindingResource::TextureView(&accum_a_view),
502 }],
503 });
504 {
505 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
506 label: Some("motion-blur-clear"),
507 timestamp_writes: None,
508 });
509 pass.set_pipeline(&inner.pipeline_clear);
510 pass.set_bind_group(0, &clear_bg, &[]);
511 pass.dispatch_workgroups(wg_x, wg_y, 1);
512 }
513
514 // 2. Upload all per-sample uniforms into one dynamic-offset buffer mapped at creation so
515 // multiple `accumulate_samples` calls in one encoder never clobber each other.
516 let uniform_size = std::mem::size_of::<MotionBlurUniform>() as u64;
517 let stride = u64::from(inner.uniform_stride);
518 let total_buf_bytes = (samples.len() as u64) * stride;
519 let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
520 label: Some("motion-blur-uniforms"),
521 size: total_buf_bytes,
522 usage: wgpu::BufferUsages::UNIFORM,
523 mapped_at_creation: true,
524 });
525 let weight = 1.0_f32 / (samples.len() as f32);
526 {
527 let mut mapped = uniform_buf
528 .slice(..)
529 .get_mapped_range_mut()
530 .expect("uniform buffer mapped at creation");
531 for (idx, sample) in samples.iter().enumerate() {
532 let u = MotionBlurUniform {
533 origins: [union_origin[0], union_origin[1], sample.origin[0], sample.origin[1]],
534 params: [weight, 0.0, 0.0, 0.0],
535 };
536 let start = (idx as u64 * stride) as usize;
537 let end = start + uniform_size as usize;
538 mapped.slice(start..end).copy_from_slice(bytemuck::bytes_of(&u));
539 }
540 }
541 uniform_buf.unmap();
542
543 // 3. Ping-pong accumulate each sample into Rgba32Float.
544 for (idx, sample) in samples.iter().enumerate() {
545 let (src_view, dst_view) = if idx % 2 == 0 {
546 (&accum_a_view, &accum_b_view)
547 } else {
548 (&accum_b_view, &accum_a_view)
549 };
550 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
551 label: Some("motion-blur-add-bg"),
552 layout: &inner.bgl_add,
553 entries: &[
554 wgpu::BindGroupEntry {
555 binding: 0,
556 resource: wgpu::BindingResource::TextureView(src_view),
557 },
558 wgpu::BindGroupEntry {
559 binding: 1,
560 resource: wgpu::BindingResource::TextureView(&sample.view),
561 },
562 wgpu::BindGroupEntry {
563 binding: 2,
564 resource: wgpu::BindingResource::TextureView(dst_view),
565 },
566 wgpu::BindGroupEntry {
567 binding: 4,
568 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
569 buffer: &uniform_buf,
570 offset: 0,
571 size: NonZeroU64::new(uniform_size),
572 }),
573 },
574 ],
575 });
576 let dyn_offset = (idx as u32) * inner.uniform_stride;
577 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
578 label: Some("motion-blur-add"),
579 timestamp_writes: None,
580 });
581 pass.set_pipeline(&inner.pipeline_add);
582 pass.set_bind_group(0, &bg, &[dyn_offset]);
583 pass.dispatch_workgroups(wg_x, wg_y, 1);
584 }
585
586 // 4. Finalize accumulated buffer into destination format, preserving center sample metadata.
587 let center = &samples[samples.len() / 2];
588 let mut out = create_output_texture(
589 device,
590 [uw, uh],
591 union_origin,
592 center.canvas_size,
593 dst_depth,
594 target_fmt,
595 content_hash,
596 );
597 out.tex_scale = center.tex_scale;
598 out.edge_mode = center.edge_mode;
599 // Only attach `center.aux` verbatim when the union DoD matches the center sample's DoD;
600 // otherwise the caller pads/re-origins `center.aux` to `(union_origin, [uw, uh])`.
601 if center.origin == union_origin && center.size == [uw, uh] {
602 if let Some(aux) = &center.aux {
603 out.set_aux(Some(aux.clone()));
604 }
605 }
606
607 let final_accum_view = if samples.len() % 2 == 1 {
608 &accum_b_view
609 } else {
610 &accum_a_view
611 };
612 let finalize = inner.finalize_for(device, target_fmt);
613 let finalize_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
614 label: Some("motion-blur-finalize-bg"),
615 layout: &finalize.bgl,
616 entries: &[
617 wgpu::BindGroupEntry {
618 binding: 0,
619 resource: wgpu::BindingResource::TextureView(final_accum_view),
620 },
621 wgpu::BindGroupEntry {
622 binding: 3,
623 resource: wgpu::BindingResource::TextureView(&out.view),
624 },
625 ],
626 });
627 {
628 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
629 label: Some("motion-blur-finalize"),
630 timestamp_writes: None,
631 });
632 pass.set_pipeline(&finalize.pipeline);
633 pass.set_bind_group(0, &finalize_bg, &[]);
634 pass.dispatch_workgroups(wg_x, wg_y, 1);
635 }
636
637 out
638 }
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644
645 fn parse_single_node_comp(kind: &str, inputs_lua: &str) -> (Comp, Node) {
646 let src = format!(
647 r#"Composition {{
648 CurrentTime = 5,
649 RenderRange = {{ 0, 10 }},
650 GlobalRange = {{ 0, 10 }},
651 Tools = ordered() {{
652 TestNode = {kind} {{
653 Inputs = {{
654 {inputs_lua}
655 }},
656 }},
657 }},
658 }}"#
659 );
660 let comp = Comp::from_fusion_str(&src).expect("valid test comp");
661 let id = comp.find_node("TestNode").expect("TestNode present");
662 let node = comp.node(id).clone();
663 (comp, node)
664 }
665
666 #[test]
667 fn node_support_matches_fusion_tool_set() {
668 for supported in [
669 "Transform",
670 "Merge",
671 "TextPlus",
672 "Renderer3D",
673 "DVE",
674 "CornerPositioner",
675 "PerspectivePositioner",
676 "EllipseMask",
677 "RectangleMask",
678 "PolylineMask",
679 "BSplineMask",
680 "Shadow",
681 "GridWarp",
682 "Displace",
683 ] {
684 assert!(node_supports_motion_blur(supported), "{supported} should support MB");
685 }
686 for unsupported in ["Background", "ColorCorrector", "Blur", "Loader", "Saver", "Merge3D"] {
687 assert!(!node_supports_motion_blur(unsupported), "{unsupported} should not support MB");
688 }
689 }
690
691 #[test]
692 fn read_motion_blur_config_defaults_and_clamping() {
693 let expr = ExprEngine::new();
694
695 // Off by default
696 let (comp, node) = parse_single_node_comp("Transform", "");
697 assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None);
698
699 // MotionBlur = 1 uses Fusion defaults: Quality=2, ShutterAngle=180, CenterBias=0, SampleSpread=1
700 let (comp, node) = parse_single_node_comp("Transform", "MotionBlur = Input { Value = 1, },");
701 assert_eq!(
702 read_motion_blur_config(&comp, &node, 5.0, &expr),
703 Some(MotionBlurConfig {
704 quality: 2,
705 shutter_angle: 180.0,
706 center_bias: 0.0,
707 sample_spread: 1.0,
708 })
709 );
710
711 // Non-MB node kind always returns None even with MotionBlur = 1
712 let (comp, node) = parse_single_node_comp("Blur", "MotionBlur = Input { Value = 1, },");
713 assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None);
714
715 // Extreme upper clamping
716 let (comp, node) = parse_single_node_comp(
717 "Merge",
718 "MotionBlur = Input { Value = 1, },
719 Quality = Input { Value = 99, },
720 ShutterAngle = Input { Value = 1440.0, },
721 CenterBias = Input { Value = 5.0, },
722 SampleSpread = Input { Value = 25.0, },",
723 );
724 assert_eq!(
725 read_motion_blur_config(&comp, &node, 5.0, &expr),
726 Some(MotionBlurConfig {
727 quality: 16,
728 shutter_angle: 720.0,
729 center_bias: 1.0,
730 sample_spread: 10.0,
731 })
732 );
733
734 // Extreme negative CenterBias clamping
735 let (comp, node) = parse_single_node_comp(
736 "TextPlus",
737 "MotionBlur = Input { Value = 1, },
738 Quality = Input { Value = 5, },
739 CenterBias = Input { Value = -4.5, },",
740 );
741 assert_eq!(
742 read_motion_blur_config(&comp, &node, 5.0, &expr).map(|c| c.center_bias),
743 Some(-1.0)
744 );
745
746 // Degenerate disabling thresholds
747 for inputs in [
748 "MotionBlur = Input { Value = 0.49, },",
749 "MotionBlur = Input { Value = 1, }, ShutterAngle = Input { Value = 0.0, },",
750 "MotionBlur = Input { Value = 1, }, SampleSpread = Input { Value = 0.0, },",
751 "MotionBlur = Input { Value = 1, }, Quality = Input { Value = 1, },",
752 ] {
753 let (comp, node) = parse_single_node_comp("Transform", inputs);
754 assert_eq!(
755 read_motion_blur_config(&comp, &node, 5.0, &expr),
756 None,
757 "expected None for {inputs}"
758 );
759 }
760 }
761
762 #[test]
763 fn shutter_times_symmetry_bias_and_360_angle() {
764 let cfg = MotionBlurConfig {
765 quality: 5,
766 shutter_angle: 180.0,
767 center_bias: 0.0,
768 sample_spread: 1.0,
769 };
770 let ts = cfg.shutter_times(5.0);
771 assert_eq!(ts.len(), 5);
772 assert!((ts[0] - 4.75).abs() < 1e-12);
773 assert!((ts[1] - 4.875).abs() < 1e-12);
774 assert!((ts[2] - 5.0).abs() < 1e-12);
775 assert!((ts[3] - 5.125).abs() < 1e-12);
776 assert!((ts[4] - 5.25).abs() < 1e-12);
777 assert!(((ts[0] + ts[4]) * 0.5 - 5.0).abs() < 1e-12);
778 assert!(((ts[1] + ts[3]) * 0.5 - 5.0).abs() < 1e-12);
779
780 // ShutterAngle = 360 spans 1.0 full frame
781 let cfg360 = MotionBlurConfig {
782 shutter_angle: 360.0,
783 ..cfg
784 };
785 let ts360 = cfg360.shutter_times(5.0);
786 assert!((ts360[0] - 4.5).abs() < 1e-12);
787 assert!((ts360[4] - 5.5).abs() < 1e-12);
788
789 // CenterBias = +1 shifts window to [time, time + shutter_frames]
790 let cfg_lead = MotionBlurConfig {
791 center_bias: 1.0,
792 ..cfg
793 };
794 let ts_lead = cfg_lead.shutter_times(5.0);
795 assert!((ts_lead[0] - 5.0).abs() < 1e-12);
796 assert!((ts_lead[4] - 5.5).abs() < 1e-12);
797
798 // CenterBias = -1 shifts window to [time - shutter_frames, time]
799 let cfg_trail = MotionBlurConfig {
800 center_bias: -1.0,
801 ..cfg
802 };
803 let ts_trail = cfg_trail.shutter_times(5.0);
804 assert!((ts_trail[0] - 4.5).abs() < 1e-12);
805 assert!((ts_trail[4] - 5.0).abs() < 1e-12);
806
807 // Non-finite time guard
808 assert!(cfg.shutter_times(f64::NAN).is_empty());
809 assert!(cfg.shutter_times(f64::INFINITY).is_empty());
810
811 // Cache key distinguishes parameters and normalizes -0.0
812 let cfg_neg_zero = MotionBlurConfig {
813 center_bias: -0.0,
814 ..cfg
815 };
816 assert_eq!(cfg.cache_key_bits(), cfg_neg_zero.cache_key_bits());
817 assert_ne!(cfg.cache_key_bits(), cfg360.cache_key_bits());
818 }
819
820 #[cfg(not(target_arch = "wasm32"))]
821 mod gpu_tests {
822 use super::*;
823 use crate::cache::{AuxChannelTex, AuxChannels};
824 use std::sync::Arc;
825
826 fn create_webgpu_baseline_device() -> Option<(wgpu::Device, wgpu::Queue)> {
827 let instance =
828 wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
829 let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
830 // Request EMPTY features to prove zero reliance on FLOAT32_FILTERABLE or
831 // TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES (WebGPU baseline safe).
832 pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
833 required_features: wgpu::Features::empty(),
834 ..Default::default()
835 }))
836 .ok()
837 }
838
839 fn upload_rgba32f_dod(
840 device: &wgpu::Device,
841 queue: &wgpu::Queue,
842 size: [u32; 2],
843 origin: [i32; 2],
844 canvas_size: [u32; 2],
845 rgba: &[[f32; 4]],
846 hash: u64,
847 ) -> CachedTexture {
848 let tex = device.create_texture(&wgpu::TextureDescriptor {
849 label: Some("mb-test-src-f32"),
850 size: wgpu::Extent3d {
851 width: size[0],
852 height: size[1],
853 depth_or_array_layers: 1,
854 },
855 mip_level_count: 1,
856 sample_count: 1,
857 dimension: wgpu::TextureDimension::D2,
858 format: wgpu::TextureFormat::Rgba32Float,
859 usage: wgpu::TextureUsages::TEXTURE_BINDING
860 | wgpu::TextureUsages::COPY_DST
861 | wgpu::TextureUsages::COPY_SRC,
862 view_formats: &[],
863 });
864 let bytes: &[u8] = bytemuck::cast_slice(rgba);
865 queue.write_texture(
866 tex.as_image_copy(),
867 bytes,
868 wgpu::TexelCopyBufferLayout {
869 offset: 0,
870 bytes_per_row: Some(size[0] * 16),
871 rows_per_image: Some(size[1]),
872 },
873 wgpu::Extent3d {
874 width: size[0],
875 height: size[1],
876 depth_or_array_layers: 1,
877 },
878 );
879 CachedTexture::from_texture_dod_depth(
880 tex,
881 size,
882 origin,
883 canvas_size,
884 BitDepth::Float32,
885 hash,
886 )
887 }
888
889 fn readback_bytes(
890 device: &wgpu::Device,
891 queue: &wgpu::Queue,
892 tex: &CachedTexture,
893 bpp: u32,
894 ) -> Vec<u8> {
895 let [w, h] = tex.size;
896 let unpadded_bpr = w * bpp;
897 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
898 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
899 let buf = device.create_buffer(&wgpu::BufferDescriptor {
900 label: Some("mb-test-readback"),
901 size: u64::from(padded_bpr) * u64::from(h),
902 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
903 mapped_at_creation: false,
904 });
905 let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
906 label: Some("mb-test-readback-enc"),
907 });
908 enc.copy_texture_to_buffer(
909 tex.texture.as_image_copy(),
910 wgpu::TexelCopyBufferInfo {
911 buffer: &buf,
912 layout: wgpu::TexelCopyBufferLayout {
913 offset: 0,
914 bytes_per_row: Some(padded_bpr),
915 rows_per_image: Some(h),
916 },
917 },
918 wgpu::Extent3d {
919 width: w,
920 height: h,
921 depth_or_array_layers: 1,
922 },
923 );
924 queue.submit(Some(enc.finish()));
925
926 let slice = buf.slice(..);
927 let (tx, rx) = std::sync::mpsc::channel();
928 slice.map_async(wgpu::MapMode::Read, move |res| {
929 let _ = tx.send(res);
930 });
931 device
932 .poll(wgpu::PollType::Wait {
933 submission_index: None,
934 timeout: Some(std::time::Duration::from_secs(10)),
935 })
936 .expect("device poll failed");
937 rx.recv().expect("channel closed").expect("map_async failed");
938 let data = slice.get_mapped_range().expect("get_mapped_range failed");
939 let mut out = Vec::with_capacity((unpadded_bpr * h) as usize);
940 for row in 0..h as usize {
941 let start = row * padded_bpr as usize;
942 out.extend_from_slice(&data[start..start + unpadded_bpr as usize]);
943 }
944 drop(data);
945 buf.unmap();
946 out
947 }
948
949 fn f16_to_f32(bits: u16) -> f32 {
950 let sign = ((bits >> 15) as u32) << 31;
951 let exp = ((bits >> 10) & 0x1f) as u32;
952 let frac = (bits & 0x03ff) as u32;
953 if exp == 0 {
954 if frac == 0 {
955 f32::from_bits(sign)
956 } else {
957 let val = (frac as f32) * (2.0_f32).powi(-24);
958 if sign != 0 { -val } else { val }
959 }
960 } else if exp == 31 {
961 f32::from_bits(sign | 0x7f80_0000 | (frac << 13))
962 } else {
963 f32::from_bits(sign | ((exp + 112) << 23) | (frac << 13))
964 }
965 }
966
967 /// Renders a 64x64 image with a 4px wide vertical white bar at `[bar_x, bar_x + 4)`
968 /// shifted sub-pixel by `dx` using exact bilinear coverage.
969 fn render_shifted_4px_bar(w: u32, h: u32, origin: [i32; 2], bar_x: f32) -> Vec<[f32; 4]> {
970 let mut px = vec![[0.0_f32; 4]; (w * h) as usize];
971 for y in 0..h {
972 for x in 0..w {
973 let gx = (origin[0] + x as i32) as f32;
974 // Overlap of pixel interval [gx, gx+1] with bar [bar_x, bar_x+4]
975 let lo = gx.max(bar_x);
976 let hi = (gx + 1.0).min(bar_x + 4.0);
977 let cov = (hi - lo).clamp(0.0, 1.0);
978 px[(y * w + x) as usize] = [cov, cov, cov, cov];
979 }
980 }
981 px
982 }
983
984 #[test]
985 fn gpu_accumulate_samples_snow_globe_probe_dod_union_and_all_formats() {
986 let Some((device, queue)) = create_webgpu_baseline_device() else {
987 return;
988 };
989 let pipelines = MotionBlurPipelines::new(&device);
990
991 // Replicate the Snow Globe 4px bar probe:
992 // Quality=5, ShutterAngle=180, CenterBias=0, velocity=+3.84 px/frame at frame=5.0.
993 let cfg = MotionBlurConfig {
994 quality: 5,
995 shutter_angle: 180.0,
996 center_bias: 0.0,
997 sample_spread: 1.0,
998 };
999 let times = cfg.shutter_times(5.0);
1000 assert_eq!(times.len(), 5);
1001
1002 // Give each sub-frame a slightly shifted DoD origin so DoD union & origin alignment
1003 // are exercised simultaneously.
1004 let origins = [[-4, -2], [-2, 0], [0, 0], [2, 1], [4, 2]];
1005 let base_x = 30.0_f32;
1006 let vel = 3.84_f32;
1007 let mut samples: Vec<CachedTexture> = times
1008 .iter()
1009 .zip(origins.iter())
1010 .enumerate()
1011 .map(|(i, (&t, &org))| {
1012 let bar_x = base_x + ((t - 5.0) as f32) * vel;
1013 let data = render_shifted_4px_bar(64, 64, org, bar_x);
1014 upload_rgba32f_dod(&device, &queue, [64, 64], org, [64, 64], &data, i as u64 + 1)
1015 })
1016 .collect();
1017
1018 // Attach an AuxChannels Z buffer to the center sample (index 2) to verify preservation.
1019 let center_aux = Arc::new(AuxChannels {
1020 z: Some(AuxChannelTex::new(
1021 &device,
1022 [64, 64],
1023 wgpu::TextureFormat::R32Float,
1024 "mb-test-aux-z",
1025 )),
1026 ..Default::default()
1027 });
1028 samples[2].set_aux(Some(center_aux));
1029
1030 let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1031 label: Some("mb-test-all-formats"),
1032 });
1033 let out_u8 = pipelines.accumulate_samples(
1034 &device,
1035 &queue,
1036 &mut enc,
1037 &samples,
1038 BitDepth::Int8,
1039 wgpu::TextureFormat::Rgba8Unorm,
1040 101,
1041 );
1042 let out_f16 = pipelines.accumulate_samples(
1043 &device,
1044 &queue,
1045 &mut enc,
1046 &samples,
1047 BitDepth::Float16,
1048 wgpu::TextureFormat::Rgba16Float,
1049 102,
1050 );
1051 let out_f32 = pipelines.accumulate_samples(
1052 &device,
1053 &queue,
1054 &mut enc,
1055 &samples,
1056 BitDepth::Float32,
1057 wgpu::TextureFormat::Rgba32Float,
1058 103,
1059 );
1060 queue.submit(Some(enc.finish()));
1061
1062 // Union of [-4..-4+64]..=[4..4+64] in X is [-4, 68) -> width 72.
1063 // Union of [-2..-2+64]..=[2..2+64] in Y is [-2, 66) -> height 68.
1064 for (tex, fmt, depth) in [
1065 (&out_u8, wgpu::TextureFormat::Rgba8Unorm, BitDepth::Int8),
1066 (&out_f16, wgpu::TextureFormat::Rgba16Float, BitDepth::Float16),
1067 (&out_f32, wgpu::TextureFormat::Rgba32Float, BitDepth::Float32),
1068 ] {
1069 assert_eq!(tex.origin, [-4, -2]);
1070 assert_eq!(tex.size, [72, 68]);
1071 assert_eq!(tex.canvas_size, [64, 64]);
1072 assert_eq!(tex.format, fmt);
1073 assert_eq!(tex.depth, depth);
1074 // Center sample had DoD [0,0] 64x64 != union [-4,-2] 72x68, so `accumulate_samples`
1075 // must NOT attach misaligned aux verbatim (caller pads/re-origins via aux_pipelines).
1076 assert!(tex.aux.is_none());
1077 }
1078
1079 // Readback Rgba32Float at row y=32 (local row 32 - (-2) = 34) and verify Snow Globe
1080 // symmetry and exact energy conservation (sum = 4.000).
1081 let raw_f32 = readback_bytes(&device, &queue, &out_f32, 16);
1082 let floats: Vec<f32> = raw_f32
1083 .chunks_exact(4)
1084 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1085 .collect();
1086 let row_y = 34usize;
1087 let row_offset = row_y * 72;
1088 let mut row_sum = 0.0_f32;
1089 let mut profile = Vec::new();
1090 for gx in 28..=35 {
1091 let lx = (gx - (-4)) as usize;
1092 let r = floats[(row_offset + lx) * 4];
1093 profile.push(r);
1094 row_sum += r;
1095 }
1096 assert!(
1097 (row_sum - 4.0).abs() < 1e-4,
1098 "energy conservation broken: sum={row_sum}, profile={profile:?}"
1099 );
1100 // Expected profile: [0.0, 0.288, 0.712, 1.0, 1.0, 0.712, 0.288, 0.0]
1101 assert!(profile[0].abs() < 1e-5);
1102 assert!((profile[1] - 0.288).abs() < 1e-4, "p[1]={}", profile[1]);
1103 assert!((profile[2] - 0.712).abs() < 1e-4, "p[2]={}", profile[2]);
1104 assert!((profile[3] - 1.0).abs() < 1e-4);
1105 assert!((profile[4] - 1.0).abs() < 1e-4);
1106 assert!((profile[1] - profile[6]).abs() < 1e-5, "asymmetric left/right outer");
1107 assert!((profile[2] - profile[5]).abs() < 1e-5, "asymmetric left/right inner");
1108 assert!(profile[7].abs() < 1e-5);
1109
1110 // Verify Rgba16Float matches Rgba32Float closely
1111 let raw_f16 = readback_bytes(&device, &queue, &out_f16, 8);
1112 let f16_vals: Vec<f32> = raw_f16
1113 .chunks_exact(2)
1114 .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]])))
1115 .collect();
1116 for gx in 28..=35 {
1117 let lx = (gx - (-4)) as usize;
1118 let r32 = floats[(row_offset + lx) * 4];
1119 let r16 = f16_vals[(row_offset + lx) * 4];
1120 assert!((r32 - r16).abs() < 2e-3, "f16 mismatch at x={gx}: {r16} vs {r32}");
1121 }
1122
1123 // Verify Rgba8Unorm matches quantized [0, 1] profile
1124 let raw_u8 = readback_bytes(&device, &queue, &out_u8, 4);
1125 for gx in 28..=35 {
1126 let lx = (gx - (-4)) as usize;
1127 let r32 = floats[(row_offset + lx) * 4];
1128 let ru8 = f32::from(raw_u8[(row_offset + lx) * 4]) / 255.0;
1129 assert!((r32 - ru8).abs() < 0.01, "u8 mismatch at x={gx}: {ru8} vs {r32}");
1130 }
1131 }
1132
1133 #[test]
1134 fn gpu_accumulate_samples_clamps_hdr_only_for_unorm() {
1135 let Some((device, queue)) = create_webgpu_baseline_device() else {
1136 return;
1137 };
1138 let pipelines = MotionBlurPipelines::new(&device);
1139 let hdr_a = vec![[2.5_f32, -0.5, 0.5, 1.0]; 4 * 4];
1140 let hdr_b = vec![[1.5_f32, 0.5, 0.5, 1.0]; 4 * 4];
1141 let s_a = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_a, 1);
1142 let s_b = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_b, 2);
1143
1144 let mut enc = device.create_command_encoder(&Default::default());
1145 let out_u8 = pipelines.accumulate_samples(
1146 &device,
1147 &queue,
1148 &mut enc,
1149 &[s_a.clone(), s_b.clone()],
1150 BitDepth::Int8,
1151 wgpu::TextureFormat::Rgba8Unorm,
1152 201,
1153 );
1154 let out_f32 = pipelines.accumulate_samples(
1155 &device,
1156 &queue,
1157 &mut enc,
1158 &[s_a, s_b],
1159 BitDepth::Float32,
1160 wgpu::TextureFormat::Rgba32Float,
1161 202,
1162 );
1163 queue.submit(Some(enc.finish()));
1164
1165 let u8_bytes = readback_bytes(&device, &queue, &out_u8, 4);
1166 assert_eq!(u8_bytes[0], 255);
1167 assert_eq!(u8_bytes[1], 0);
1168 assert!((u8_bytes[2] as i32 - 128).abs() <= 1);
1169 assert_eq!(u8_bytes[3], 255);
1170
1171 let f32_bytes = readback_bytes(&device, &queue, &out_f32, 16);
1172 let r = f32::from_le_bytes([f32_bytes[0], f32_bytes[1], f32_bytes[2], f32_bytes[3]]);
1173 let g = f32::from_le_bytes([f32_bytes[4], f32_bytes[5], f32_bytes[6], f32_bytes[7]]);
1174 assert!((r - 2.0).abs() < 1e-5, "HDR should preserve >1.0: {r}");
1175 assert!((g - 0.0).abs() < 1e-5);
1176 }
1177 }
1178}