| ... | @@ -0,0 +1,1172 @@ |
| 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 | |
| 8 | use crate::cache::CachedTexture; |
| 9 | use bytemuck::{Pod, Zeroable}; |
| 10 | use model::{BitDepth, Comp, ExprEngine, Node}; |
| 11 | use std::collections::hash_map::DefaultHasher; |
| 12 | use std::hash::{Hash, Hasher}; |
| 13 | use std::num::NonZeroU64; |
| 14 | use std::sync::OnceLock; |
| 15 | |
| 16 | const MOTION_BLUR_WGSL: &str = include_str!("shaders/motion_blur.wgsl"); |
| 17 | const WORKGROUP_SIZE: u32 = 8; |
| 18 | |
| 19 | /// Returns `true` for Fusion tool kinds that support node-level temporal motion blur. |
| 20 | pub 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)] |
| 42 | pub struct MotionBlurConfig { |
| 43 | pub quality: u32, |
| 44 | pub shutter_angle: f64, |
| 45 | pub center_bias: f64, |
| 46 | pub sample_spread: f64, |
| 47 | } |
| 48 | |
| 49 | fn canonical_f64_bits(v: f64) -> u64 { |
| 50 | if v == 0.0 { 0.0_f64.to_bits() } else { v.to_bits() } |
| 51 | } |
| 52 | |
| 53 | impl 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`. |
| 101 | pub 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)] |
| 152 | struct MotionBlurUniform { |
| 153 | origins: [i32; 4], |
| 154 | params: [f32; 4], |
| 155 | } |
| 156 | |
| 157 | struct FinalizePipeline { |
| 158 | bgl: wgpu::BindGroupLayout, |
| 159 | pipeline: wgpu::ComputePipeline, |
| 160 | } |
| 161 | |
| 162 | impl 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 | |
| 225 | struct 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 | |
| 236 | impl 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)] |
| 350 | pub struct MotionBlurPipelines { |
| 351 | inner: OnceLock<MotionBlurInner>, |
| 352 | } |
| 353 | |
| 354 | fn 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 | |
| 387 | fn 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 | |
| 406 | fn 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 | |
| 447 | impl 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 | if let Some(aux) = &center.aux { |
| 600 | out.set_aux(Some(aux.clone())); |
| 601 | } |
| 602 | |
| 603 | let final_accum_view = if samples.len() % 2 == 1 { |
| 604 | &accum_b_view |
| 605 | } else { |
| 606 | &accum_a_view |
| 607 | }; |
| 608 | let finalize = inner.finalize_for(device, target_fmt); |
| 609 | let finalize_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 610 | label: Some("motion-blur-finalize-bg"), |
| 611 | layout: &finalize.bgl, |
| 612 | entries: &[ |
| 613 | wgpu::BindGroupEntry { |
| 614 | binding: 0, |
| 615 | resource: wgpu::BindingResource::TextureView(final_accum_view), |
| 616 | }, |
| 617 | wgpu::BindGroupEntry { |
| 618 | binding: 3, |
| 619 | resource: wgpu::BindingResource::TextureView(&out.view), |
| 620 | }, |
| 621 | ], |
| 622 | }); |
| 623 | { |
| 624 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 625 | label: Some("motion-blur-finalize"), |
| 626 | timestamp_writes: None, |
| 627 | }); |
| 628 | pass.set_pipeline(&finalize.pipeline); |
| 629 | pass.set_bind_group(0, &finalize_bg, &[]); |
| 630 | pass.dispatch_workgroups(wg_x, wg_y, 1); |
| 631 | } |
| 632 | |
| 633 | out |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[cfg(test)] |
| 638 | mod tests { |
| 639 | use super::*; |
| 640 | |
| 641 | fn parse_single_node_comp(kind: &str, inputs_lua: &str) -> (Comp, Node) { |
| 642 | let src = format!( |
| 643 | r#"Composition {{ |
| 644 | CurrentTime = 5, |
| 645 | RenderRange = {{ 0, 10 }}, |
| 646 | GlobalRange = {{ 0, 10 }}, |
| 647 | Tools = ordered() {{ |
| 648 | TestNode = {kind} {{ |
| 649 | Inputs = {{ |
| 650 | {inputs_lua} |
| 651 | }}, |
| 652 | }}, |
| 653 | }}, |
| 654 | }}"# |
| 655 | ); |
| 656 | let comp = Comp::from_fusion_str(&src).expect("valid test comp"); |
| 657 | let id = comp.find_node("TestNode").expect("TestNode present"); |
| 658 | let node = comp.node(id).clone(); |
| 659 | (comp, node) |
| 660 | } |
| 661 | |
| 662 | #[test] |
| 663 | fn node_support_matches_fusion_tool_set() { |
| 664 | for supported in [ |
| 665 | "Transform", |
| 666 | "Merge", |
| 667 | "TextPlus", |
| 668 | "Renderer3D", |
| 669 | "DVE", |
| 670 | "CornerPositioner", |
| 671 | "PerspectivePositioner", |
| 672 | "EllipseMask", |
| 673 | "RectangleMask", |
| 674 | "PolylineMask", |
| 675 | "BSplineMask", |
| 676 | "Shadow", |
| 677 | "GridWarp", |
| 678 | "Displace", |
| 679 | ] { |
| 680 | assert!(node_supports_motion_blur(supported), "{supported} should support MB"); |
| 681 | } |
| 682 | for unsupported in ["Background", "ColorCorrector", "Blur", "Loader", "Saver", "Merge3D"] { |
| 683 | assert!(!node_supports_motion_blur(unsupported), "{unsupported} should not support MB"); |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | #[test] |
| 688 | fn read_motion_blur_config_defaults_and_clamping() { |
| 689 | let expr = ExprEngine::new(); |
| 690 | |
| 691 | // Off by default |
| 692 | let (comp, node) = parse_single_node_comp("Transform", ""); |
| 693 | assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None); |
| 694 | |
| 695 | // MotionBlur = 1 uses Fusion defaults: Quality=2, ShutterAngle=180, CenterBias=0, SampleSpread=1 |
| 696 | let (comp, node) = parse_single_node_comp("Transform", "MotionBlur = Input { Value = 1, },"); |
| 697 | assert_eq!( |
| 698 | read_motion_blur_config(&comp, &node, 5.0, &expr), |
| 699 | Some(MotionBlurConfig { |
| 700 | quality: 2, |
| 701 | shutter_angle: 180.0, |
| 702 | center_bias: 0.0, |
| 703 | sample_spread: 1.0, |
| 704 | }) |
| 705 | ); |
| 706 | |
| 707 | // Non-MB node kind always returns None even with MotionBlur = 1 |
| 708 | let (comp, node) = parse_single_node_comp("Blur", "MotionBlur = Input { Value = 1, },"); |
| 709 | assert_eq!(read_motion_blur_config(&comp, &node, 5.0, &expr), None); |
| 710 | |
| 711 | // Extreme upper clamping |
| 712 | let (comp, node) = parse_single_node_comp( |
| 713 | "Merge", |
| 714 | "MotionBlur = Input { Value = 1, }, |
| 715 | Quality = Input { Value = 99, }, |
| 716 | ShutterAngle = Input { Value = 1440.0, }, |
| 717 | CenterBias = Input { Value = 5.0, }, |
| 718 | SampleSpread = Input { Value = 25.0, },", |
| 719 | ); |
| 720 | assert_eq!( |
| 721 | read_motion_blur_config(&comp, &node, 5.0, &expr), |
| 722 | Some(MotionBlurConfig { |
| 723 | quality: 16, |
| 724 | shutter_angle: 720.0, |
| 725 | center_bias: 1.0, |
| 726 | sample_spread: 10.0, |
| 727 | }) |
| 728 | ); |
| 729 | |
| 730 | // Extreme negative CenterBias clamping |
| 731 | let (comp, node) = parse_single_node_comp( |
| 732 | "TextPlus", |
| 733 | "MotionBlur = Input { Value = 1, }, |
| 734 | Quality = Input { Value = 5, }, |
| 735 | CenterBias = Input { Value = -4.5, },", |
| 736 | ); |
| 737 | assert_eq!( |
| 738 | read_motion_blur_config(&comp, &node, 5.0, &expr).map(|c| c.center_bias), |
| 739 | Some(-1.0) |
| 740 | ); |
| 741 | |
| 742 | // Degenerate disabling thresholds |
| 743 | for inputs in [ |
| 744 | "MotionBlur = Input { Value = 0.49, },", |
| 745 | "MotionBlur = Input { Value = 1, }, ShutterAngle = Input { Value = 0.0, },", |
| 746 | "MotionBlur = Input { Value = 1, }, SampleSpread = Input { Value = 0.0, },", |
| 747 | "MotionBlur = Input { Value = 1, }, Quality = Input { Value = 1, },", |
| 748 | ] { |
| 749 | let (comp, node) = parse_single_node_comp("Transform", inputs); |
| 750 | assert_eq!( |
| 751 | read_motion_blur_config(&comp, &node, 5.0, &expr), |
| 752 | None, |
| 753 | "expected None for {inputs}" |
| 754 | ); |
| 755 | } |
| 756 | } |
| 757 | |
| 758 | #[test] |
| 759 | fn shutter_times_symmetry_bias_and_360_angle() { |
| 760 | let cfg = MotionBlurConfig { |
| 761 | quality: 5, |
| 762 | shutter_angle: 180.0, |
| 763 | center_bias: 0.0, |
| 764 | sample_spread: 1.0, |
| 765 | }; |
| 766 | let ts = cfg.shutter_times(5.0); |
| 767 | assert_eq!(ts.len(), 5); |
| 768 | assert!((ts[0] - 4.75).abs() < 1e-12); |
| 769 | assert!((ts[1] - 4.875).abs() < 1e-12); |
| 770 | assert!((ts[2] - 5.0).abs() < 1e-12); |
| 771 | assert!((ts[3] - 5.125).abs() < 1e-12); |
| 772 | assert!((ts[4] - 5.25).abs() < 1e-12); |
| 773 | assert!(((ts[0] + ts[4]) * 0.5 - 5.0).abs() < 1e-12); |
| 774 | assert!(((ts[1] + ts[3]) * 0.5 - 5.0).abs() < 1e-12); |
| 775 | |
| 776 | // ShutterAngle = 360 spans 1.0 full frame |
| 777 | let cfg360 = MotionBlurConfig { |
| 778 | shutter_angle: 360.0, |
| 779 | ..cfg |
| 780 | }; |
| 781 | let ts360 = cfg360.shutter_times(5.0); |
| 782 | assert!((ts360[0] - 4.5).abs() < 1e-12); |
| 783 | assert!((ts360[4] - 5.5).abs() < 1e-12); |
| 784 | |
| 785 | // CenterBias = +1 shifts window to [time, time + shutter_frames] |
| 786 | let cfg_lead = MotionBlurConfig { |
| 787 | center_bias: 1.0, |
| 788 | ..cfg |
| 789 | }; |
| 790 | let ts_lead = cfg_lead.shutter_times(5.0); |
| 791 | assert!((ts_lead[0] - 5.0).abs() < 1e-12); |
| 792 | assert!((ts_lead[4] - 5.5).abs() < 1e-12); |
| 793 | |
| 794 | // CenterBias = -1 shifts window to [time - shutter_frames, time] |
| 795 | let cfg_trail = MotionBlurConfig { |
| 796 | center_bias: -1.0, |
| 797 | ..cfg |
| 798 | }; |
| 799 | let ts_trail = cfg_trail.shutter_times(5.0); |
| 800 | assert!((ts_trail[0] - 4.5).abs() < 1e-12); |
| 801 | assert!((ts_trail[4] - 5.0).abs() < 1e-12); |
| 802 | |
| 803 | // Non-finite time guard |
| 804 | assert!(cfg.shutter_times(f64::NAN).is_empty()); |
| 805 | assert!(cfg.shutter_times(f64::INFINITY).is_empty()); |
| 806 | |
| 807 | // Cache key distinguishes parameters and normalizes -0.0 |
| 808 | let cfg_neg_zero = MotionBlurConfig { |
| 809 | center_bias: -0.0, |
| 810 | ..cfg |
| 811 | }; |
| 812 | assert_eq!(cfg.cache_key_bits(), cfg_neg_zero.cache_key_bits()); |
| 813 | assert_ne!(cfg.cache_key_bits(), cfg360.cache_key_bits()); |
| 814 | } |
| 815 | |
| 816 | #[cfg(not(target_arch = "wasm32"))] |
| 817 | mod gpu_tests { |
| 818 | use super::*; |
| 819 | use crate::cache::{AuxChannelTex, AuxChannels}; |
| 820 | use std::sync::Arc; |
| 821 | |
| 822 | fn create_webgpu_baseline_device() -> Option<(wgpu::Device, wgpu::Queue)> { |
| 823 | let instance = |
| 824 | wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 825 | let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; |
| 826 | // Request EMPTY features to prove zero reliance on FLOAT32_FILTERABLE or |
| 827 | // TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES (WebGPU baseline safe). |
| 828 | pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { |
| 829 | required_features: wgpu::Features::empty(), |
| 830 | ..Default::default() |
| 831 | })) |
| 832 | .ok() |
| 833 | } |
| 834 | |
| 835 | fn upload_rgba32f_dod( |
| 836 | device: &wgpu::Device, |
| 837 | queue: &wgpu::Queue, |
| 838 | size: [u32; 2], |
| 839 | origin: [i32; 2], |
| 840 | canvas_size: [u32; 2], |
| 841 | rgba: &[[f32; 4]], |
| 842 | hash: u64, |
| 843 | ) -> CachedTexture { |
| 844 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 845 | label: Some("mb-test-src-f32"), |
| 846 | size: wgpu::Extent3d { |
| 847 | width: size[0], |
| 848 | height: size[1], |
| 849 | depth_or_array_layers: 1, |
| 850 | }, |
| 851 | mip_level_count: 1, |
| 852 | sample_count: 1, |
| 853 | dimension: wgpu::TextureDimension::D2, |
| 854 | format: wgpu::TextureFormat::Rgba32Float, |
| 855 | usage: wgpu::TextureUsages::TEXTURE_BINDING |
| 856 | | wgpu::TextureUsages::COPY_DST |
| 857 | | wgpu::TextureUsages::COPY_SRC, |
| 858 | view_formats: &[], |
| 859 | }); |
| 860 | let bytes: &[u8] = bytemuck::cast_slice(rgba); |
| 861 | queue.write_texture( |
| 862 | tex.as_image_copy(), |
| 863 | bytes, |
| 864 | wgpu::TexelCopyBufferLayout { |
| 865 | offset: 0, |
| 866 | bytes_per_row: Some(size[0] * 16), |
| 867 | rows_per_image: Some(size[1]), |
| 868 | }, |
| 869 | wgpu::Extent3d { |
| 870 | width: size[0], |
| 871 | height: size[1], |
| 872 | depth_or_array_layers: 1, |
| 873 | }, |
| 874 | ); |
| 875 | CachedTexture::from_texture_dod_depth( |
| 876 | tex, |
| 877 | size, |
| 878 | origin, |
| 879 | canvas_size, |
| 880 | BitDepth::Float32, |
| 881 | hash, |
| 882 | ) |
| 883 | } |
| 884 | |
| 885 | fn readback_bytes( |
| 886 | device: &wgpu::Device, |
| 887 | queue: &wgpu::Queue, |
| 888 | tex: &CachedTexture, |
| 889 | bpp: u32, |
| 890 | ) -> Vec<u8> { |
| 891 | let [w, h] = tex.size; |
| 892 | let unpadded_bpr = w * bpp; |
| 893 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 894 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 895 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 896 | label: Some("mb-test-readback"), |
| 897 | size: u64::from(padded_bpr) * u64::from(h), |
| 898 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 899 | mapped_at_creation: false, |
| 900 | }); |
| 901 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 902 | label: Some("mb-test-readback-enc"), |
| 903 | }); |
| 904 | enc.copy_texture_to_buffer( |
| 905 | tex.texture.as_image_copy(), |
| 906 | wgpu::TexelCopyBufferInfo { |
| 907 | buffer: &buf, |
| 908 | layout: wgpu::TexelCopyBufferLayout { |
| 909 | offset: 0, |
| 910 | bytes_per_row: Some(padded_bpr), |
| 911 | rows_per_image: Some(h), |
| 912 | }, |
| 913 | }, |
| 914 | wgpu::Extent3d { |
| 915 | width: w, |
| 916 | height: h, |
| 917 | depth_or_array_layers: 1, |
| 918 | }, |
| 919 | ); |
| 920 | queue.submit(Some(enc.finish())); |
| 921 | |
| 922 | let slice = buf.slice(..); |
| 923 | let (tx, rx) = std::sync::mpsc::channel(); |
| 924 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 925 | let _ = tx.send(res); |
| 926 | }); |
| 927 | device |
| 928 | .poll(wgpu::PollType::Wait { |
| 929 | submission_index: None, |
| 930 | timeout: Some(std::time::Duration::from_secs(10)), |
| 931 | }) |
| 932 | .expect("device poll failed"); |
| 933 | rx.recv().expect("channel closed").expect("map_async failed"); |
| 934 | let data = slice.get_mapped_range().expect("get_mapped_range failed"); |
| 935 | let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); |
| 936 | for row in 0..h as usize { |
| 937 | let start = row * padded_bpr as usize; |
| 938 | out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); |
| 939 | } |
| 940 | drop(data); |
| 941 | buf.unmap(); |
| 942 | out |
| 943 | } |
| 944 | |
| 945 | fn f16_to_f32(bits: u16) -> f32 { |
| 946 | let sign = ((bits >> 15) as u32) << 31; |
| 947 | let exp = ((bits >> 10) & 0x1f) as u32; |
| 948 | let frac = (bits & 0x03ff) as u32; |
| 949 | if exp == 0 { |
| 950 | if frac == 0 { |
| 951 | f32::from_bits(sign) |
| 952 | } else { |
| 953 | let val = (frac as f32) * (2.0_f32).powi(-24); |
| 954 | if sign != 0 { -val } else { val } |
| 955 | } |
| 956 | } else if exp == 31 { |
| 957 | f32::from_bits(sign | 0x7f80_0000 | (frac << 13)) |
| 958 | } else { |
| 959 | f32::from_bits(sign | ((exp + 112) << 23) | (frac << 13)) |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | /// Renders a 64x64 image with a 4px wide vertical white bar at `[bar_x, bar_x + 4)` |
| 964 | /// shifted sub-pixel by `dx` using exact bilinear coverage. |
| 965 | fn render_shifted_4px_bar(w: u32, h: u32, origin: [i32; 2], bar_x: f32) -> Vec<[f32; 4]> { |
| 966 | let mut px = vec![[0.0_f32; 4]; (w * h) as usize]; |
| 967 | for y in 0..h { |
| 968 | for x in 0..w { |
| 969 | let gx = (origin[0] + x as i32) as f32; |
| 970 | // Overlap of pixel interval [gx, gx+1] with bar [bar_x, bar_x+4] |
| 971 | let lo = gx.max(bar_x); |
| 972 | let hi = (gx + 1.0).min(bar_x + 4.0); |
| 973 | let cov = (hi - lo).clamp(0.0, 1.0); |
| 974 | px[(y * w + x) as usize] = [cov, cov, cov, cov]; |
| 975 | } |
| 976 | } |
| 977 | px |
| 978 | } |
| 979 | |
| 980 | #[test] |
| 981 | fn gpu_accumulate_samples_snow_globe_probe_dod_union_and_all_formats() { |
| 982 | let Some((device, queue)) = create_webgpu_baseline_device() else { |
| 983 | return; |
| 984 | }; |
| 985 | let pipelines = MotionBlurPipelines::new(&device); |
| 986 | |
| 987 | // Replicate the Snow Globe 4px bar probe: |
| 988 | // Quality=5, ShutterAngle=180, CenterBias=0, velocity=+3.84 px/frame at frame=5.0. |
| 989 | let cfg = MotionBlurConfig { |
| 990 | quality: 5, |
| 991 | shutter_angle: 180.0, |
| 992 | center_bias: 0.0, |
| 993 | sample_spread: 1.0, |
| 994 | }; |
| 995 | let times = cfg.shutter_times(5.0); |
| 996 | assert_eq!(times.len(), 5); |
| 997 | |
| 998 | // Give each sub-frame a slightly shifted DoD origin so DoD union & origin alignment |
| 999 | // are exercised simultaneously. |
| 1000 | let origins = [[-4, -2], [-2, 0], [0, 0], [2, 1], [4, 2]]; |
| 1001 | let base_x = 30.0_f32; |
| 1002 | let vel = 3.84_f32; |
| 1003 | let mut samples: Vec<CachedTexture> = times |
| 1004 | .iter() |
| 1005 | .zip(origins.iter()) |
| 1006 | .enumerate() |
| 1007 | .map(|(i, (&t, &org))| { |
| 1008 | let bar_x = base_x + ((t - 5.0) as f32) * vel; |
| 1009 | let data = render_shifted_4px_bar(64, 64, org, bar_x); |
| 1010 | upload_rgba32f_dod(&device, &queue, [64, 64], org, [64, 64], &data, i as u64 + 1) |
| 1011 | }) |
| 1012 | .collect(); |
| 1013 | |
| 1014 | // Attach an AuxChannels Z buffer to the center sample (index 2) to verify preservation. |
| 1015 | let center_aux = Arc::new(AuxChannels { |
| 1016 | z: Some(AuxChannelTex::new( |
| 1017 | &device, |
| 1018 | [64, 64], |
| 1019 | wgpu::TextureFormat::R32Float, |
| 1020 | "mb-test-aux-z", |
| 1021 | )), |
| 1022 | ..Default::default() |
| 1023 | }); |
| 1024 | samples[2].set_aux(Some(center_aux)); |
| 1025 | |
| 1026 | let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 1027 | label: Some("mb-test-all-formats"), |
| 1028 | }); |
| 1029 | let out_u8 = pipelines.accumulate_samples( |
| 1030 | &device, |
| 1031 | &queue, |
| 1032 | &mut enc, |
| 1033 | &samples, |
| 1034 | BitDepth::Int8, |
| 1035 | wgpu::TextureFormat::Rgba8Unorm, |
| 1036 | 101, |
| 1037 | ); |
| 1038 | let out_f16 = pipelines.accumulate_samples( |
| 1039 | &device, |
| 1040 | &queue, |
| 1041 | &mut enc, |
| 1042 | &samples, |
| 1043 | BitDepth::Float16, |
| 1044 | wgpu::TextureFormat::Rgba16Float, |
| 1045 | 102, |
| 1046 | ); |
| 1047 | let out_f32 = pipelines.accumulate_samples( |
| 1048 | &device, |
| 1049 | &queue, |
| 1050 | &mut enc, |
| 1051 | &samples, |
| 1052 | BitDepth::Float32, |
| 1053 | wgpu::TextureFormat::Rgba32Float, |
| 1054 | 103, |
| 1055 | ); |
| 1056 | queue.submit(Some(enc.finish())); |
| 1057 | |
| 1058 | // Union of [-4..-4+64]..=[4..4+64] in X is [-4, 68) -> width 72. |
| 1059 | // Union of [-2..-2+64]..=[2..2+64] in Y is [-2, 66) -> height 68. |
| 1060 | for (tex, fmt, depth) in [ |
| 1061 | (&out_u8, wgpu::TextureFormat::Rgba8Unorm, BitDepth::Int8), |
| 1062 | (&out_f16, wgpu::TextureFormat::Rgba16Float, BitDepth::Float16), |
| 1063 | (&out_f32, wgpu::TextureFormat::Rgba32Float, BitDepth::Float32), |
| 1064 | ] { |
| 1065 | assert_eq!(tex.origin, [-4, -2]); |
| 1066 | assert_eq!(tex.size, [72, 68]); |
| 1067 | assert_eq!(tex.canvas_size, [64, 64]); |
| 1068 | assert_eq!(tex.format, fmt); |
| 1069 | assert_eq!(tex.depth, depth); |
| 1070 | assert!(tex.aux.as_ref().is_some_and(|a| a.z.is_some())); |
| 1071 | } |
| 1072 | |
| 1073 | // Readback Rgba32Float at row y=32 (local row 32 - (-2) = 34) and verify Snow Globe |
| 1074 | // symmetry and exact energy conservation (sum = 4.000). |
| 1075 | let raw_f32 = readback_bytes(&device, &queue, &out_f32, 16); |
| 1076 | let floats: Vec<f32> = raw_f32 |
| 1077 | .chunks_exact(4) |
| 1078 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 1079 | .collect(); |
| 1080 | let row_y = 34usize; |
| 1081 | let row_offset = row_y * 72; |
| 1082 | let mut row_sum = 0.0_f32; |
| 1083 | let mut profile = Vec::new(); |
| 1084 | for gx in 28..=35 { |
| 1085 | let lx = (gx - (-4)) as usize; |
| 1086 | let r = floats[(row_offset + lx) * 4]; |
| 1087 | profile.push(r); |
| 1088 | row_sum += r; |
| 1089 | } |
| 1090 | assert!( |
| 1091 | (row_sum - 4.0).abs() < 1e-4, |
| 1092 | "energy conservation broken: sum={row_sum}, profile={profile:?}" |
| 1093 | ); |
| 1094 | // Expected profile: [0.0, 0.288, 0.712, 1.0, 1.0, 0.712, 0.288, 0.0] |
| 1095 | assert!(profile[0].abs() < 1e-5); |
| 1096 | assert!((profile[1] - 0.288).abs() < 1e-4, "p[1]={}", profile[1]); |
| 1097 | assert!((profile[2] - 0.712).abs() < 1e-4, "p[2]={}", profile[2]); |
| 1098 | assert!((profile[3] - 1.0).abs() < 1e-4); |
| 1099 | assert!((profile[4] - 1.0).abs() < 1e-4); |
| 1100 | assert!((profile[1] - profile[6]).abs() < 1e-5, "asymmetric left/right outer"); |
| 1101 | assert!((profile[2] - profile[5]).abs() < 1e-5, "asymmetric left/right inner"); |
| 1102 | assert!(profile[7].abs() < 1e-5); |
| 1103 | |
| 1104 | // Verify Rgba16Float matches Rgba32Float closely |
| 1105 | let raw_f16 = readback_bytes(&device, &queue, &out_f16, 8); |
| 1106 | let f16_vals: Vec<f32> = raw_f16 |
| 1107 | .chunks_exact(2) |
| 1108 | .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))) |
| 1109 | .collect(); |
| 1110 | for gx in 28..=35 { |
| 1111 | let lx = (gx - (-4)) as usize; |
| 1112 | let r32 = floats[(row_offset + lx) * 4]; |
| 1113 | let r16 = f16_vals[(row_offset + lx) * 4]; |
| 1114 | assert!((r32 - r16).abs() < 2e-3, "f16 mismatch at x={gx}: {r16} vs {r32}"); |
| 1115 | } |
| 1116 | |
| 1117 | // Verify Rgba8Unorm matches quantized [0, 1] profile |
| 1118 | let raw_u8 = readback_bytes(&device, &queue, &out_u8, 4); |
| 1119 | for gx in 28..=35 { |
| 1120 | let lx = (gx - (-4)) as usize; |
| 1121 | let r32 = floats[(row_offset + lx) * 4]; |
| 1122 | let ru8 = f32::from(raw_u8[(row_offset + lx) * 4]) / 255.0; |
| 1123 | assert!((r32 - ru8).abs() < 0.01, "u8 mismatch at x={gx}: {ru8} vs {r32}"); |
| 1124 | } |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn gpu_accumulate_samples_clamps_hdr_only_for_unorm() { |
| 1129 | let Some((device, queue)) = create_webgpu_baseline_device() else { |
| 1130 | return; |
| 1131 | }; |
| 1132 | let pipelines = MotionBlurPipelines::new(&device); |
| 1133 | let hdr_a = vec![[2.5_f32, -0.5, 0.5, 1.0]; 4 * 4]; |
| 1134 | let hdr_b = vec![[1.5_f32, 0.5, 0.5, 1.0]; 4 * 4]; |
| 1135 | let s_a = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_a, 1); |
| 1136 | let s_b = upload_rgba32f_dod(&device, &queue, [4, 4], [0, 0], [4, 4], &hdr_b, 2); |
| 1137 | |
| 1138 | let mut enc = device.create_command_encoder(&Default::default()); |
| 1139 | let out_u8 = pipelines.accumulate_samples( |
| 1140 | &device, |
| 1141 | &queue, |
| 1142 | &mut enc, |
| 1143 | &[s_a.clone(), s_b.clone()], |
| 1144 | BitDepth::Int8, |
| 1145 | wgpu::TextureFormat::Rgba8Unorm, |
| 1146 | 201, |
| 1147 | ); |
| 1148 | let out_f32 = pipelines.accumulate_samples( |
| 1149 | &device, |
| 1150 | &queue, |
| 1151 | &mut enc, |
| 1152 | &[s_a, s_b], |
| 1153 | BitDepth::Float32, |
| 1154 | wgpu::TextureFormat::Rgba32Float, |
| 1155 | 202, |
| 1156 | ); |
| 1157 | queue.submit(Some(enc.finish())); |
| 1158 | |
| 1159 | let u8_bytes = readback_bytes(&device, &queue, &out_u8, 4); |
| 1160 | assert_eq!(u8_bytes[0], 255); |
| 1161 | assert_eq!(u8_bytes[1], 0); |
| 1162 | assert!((u8_bytes[2] as i32 - 128).abs() <= 1); |
| 1163 | assert_eq!(u8_bytes[3], 255); |
| 1164 | |
| 1165 | let f32_bytes = readback_bytes(&device, &queue, &out_f32, 16); |
| 1166 | let r = f32::from_le_bytes([f32_bytes[0], f32_bytes[1], f32_bytes[2], f32_bytes[3]]); |
| 1167 | let g = f32::from_le_bytes([f32_bytes[4], f32_bytes[5], f32_bytes[6], f32_bytes[7]]); |
| 1168 | assert!((r - 2.0).abs() < 1e-5, "HDR should preserve >1.0: {r}"); |
| 1169 | assert!((g - 0.0).abs() < 1e-5); |
| 1170 | } |
| 1171 | } |
| 1172 | } |