1//! Auxiliary channel GPU pipelines and evaluators:
2//! - `Merge.PerformDepthMerge` (Z-aware depth compositing)
3//! - `Dimension.CopyAux` (Mode 0 Aux->Color with Remap, Mode 1 Color->Aux, `KillAuxChannels`)
4//! - `ChannelBoolean.ToZBuffer` (`EnableExtraChannels` extra-channel Z copy/ops)
5//! - `Dimension.OpticalFlow` (forward/backward dense flow into `aux.vector` / `aux.back_vector`)
6//! - `VectorMotionBlur` GPU dispatch helper
7//!
8//! WebGPU safety: `R32Float` textures are ONLY bound with `TextureSampleType::Float { filterable: false }`
9//! (read via `textureLoad`) and written via `texture_storage_2d<r32float, write>`.
10
11use super::*;
12use crate::cache::{AuxChannelTex, AuxChannels, EMPTY_Z_SENTINEL};
13use std::num::NonZeroU64;
14use std::sync::Arc;
15
16const AUX_OPS_WGSL: &str = include_str!("../shaders/aux_ops.wgsl");
17const AUX_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
18
19fn wgsl_section(tag: &str) -> &'static str {
20 let marker = format!("// @SECTION:{tag}");
21 let start = AUX_OPS_WGSL
22 .find(&marker)
23 .unwrap_or_else(|| panic!("missing WGSL section {tag}"))
24 + marker.len();
25 let rest = &AUX_OPS_WGSL[start..];
26 let end = rest.find("// @SECTION:").unwrap_or(rest.len());
27 &rest[..end]
28}
29
30fn build_aux_wgsl(section: &str, rgba_format: Option<wgpu::TextureFormat>, hdr_float: bool) -> String {
31 let common = wgsl_section("COMMON");
32 let body = wgsl_section(section);
33 let mut src = String::with_capacity(common.len() + body.len() + 2);
34 src.push_str(common);
35 src.push('\n');
36 src.push_str(body);
37 if let Some(fmt) = rgba_format {
38 let storage_fmt = match fmt {
39 wgpu::TextureFormat::Rgba16Float => "rgba16float",
40 wgpu::TextureFormat::Rgba32Float => "rgba32float",
41 _ => "rgba8unorm",
42 };
43 if storage_fmt != "rgba8unorm" {
44 src = src.replace(
45 "texture_storage_2d<rgba8unorm, write>",
46 &format!("texture_storage_2d<{storage_fmt}, write>"),
47 );
48 }
49 if hdr_float {
50 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
51 }
52 }
53 src
54}
55
56fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
57 wgpu::BindGroupLayoutEntry {
58 binding,
59 visibility: wgpu::ShaderStages::COMPUTE,
60 ty: wgpu::BindingType::Texture {
61 sample_type: wgpu::TextureSampleType::Float { filterable },
62 view_dimension: wgpu::TextureViewDimension::D2,
63 multisampled: false,
64 },
65 count: None,
66 }
67}
68
69fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
70 wgpu::BindGroupLayoutEntry {
71 binding,
72 visibility: wgpu::ShaderStages::COMPUTE,
73 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
74 count: None,
75 }
76}
77
78fn storage_entry(binding: u32, format: wgpu::TextureFormat) -> wgpu::BindGroupLayoutEntry {
79 wgpu::BindGroupLayoutEntry {
80 binding,
81 visibility: wgpu::ShaderStages::COMPUTE,
82 ty: wgpu::BindingType::StorageTexture {
83 access: wgpu::StorageTextureAccess::WriteOnly,
84 format,
85 view_dimension: wgpu::TextureViewDimension::D2,
86 },
87 count: None,
88 }
89}
90
91fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry {
92 wgpu::BindGroupLayoutEntry {
93 binding,
94 visibility: wgpu::ShaderStages::COMPUTE,
95 ty: wgpu::BindingType::Buffer {
96 ty: wgpu::BufferBindingType::Uniform,
97 has_dynamic_offset: true,
98 min_binding_size: NonZeroU64::new(size),
99 },
100 count: None,
101 }
102}
103
104struct FormatPipelines {
105 bgl: wgpu::BindGroupLayout,
106 pipeline: wgpu::ComputePipeline,
107}
108
109struct RgbaOpsPipelines {
110 bgl: wgpu::BindGroupLayout,
111 copy_aux_to_color: wgpu::ComputePipeline,
112 vector_motion_blur: wgpu::ComputePipeline,
113}
114
115pub(super) struct AuxPipelines {
116 sampler: wgpu::Sampler,
117 uniform_stride: u32,
118 uniform_chunks: Vec<wgpu::Buffer>,
119 uniform_cursor: u32,
120 pub(super) dummy_z: AuxChannelTex,
121 pub(super) dummy_f16: AuxChannelTex,
122 depth_merge: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>,
123 rgba_ops: HashMap<(wgpu::TextureFormat, bool), RgbaOpsPipelines>,
124 r32f_bgl: wgpu::BindGroupLayout,
125 copy_color_to_aux_z: wgpu::ComputePipeline,
126 cb_to_zbuffer: wgpu::ComputePipeline,
127 crop_r32f: wgpu::ComputePipeline,
128 f16_bgl: wgpu::BindGroupLayout,
129 copy_color_to_aux_f16: wgpu::ComputePipeline,
130 crop_f16: wgpu::ComputePipeline,
131 optflow_features: wgpu::ComputePipeline,
132 optflow_coarse: wgpu::ComputePipeline,
133 optflow_refine: wgpu::ComputePipeline,
134}
135
136impl AuxPipelines {
137 pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
138 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
139 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
140 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
141 let u_size_u64 = u64::from(uniform_size);
142
143 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
144 label: Some("aux-linear"),
145 address_mode_u: wgpu::AddressMode::ClampToEdge,
146 address_mode_v: wgpu::AddressMode::ClampToEdge,
147 mag_filter: wgpu::FilterMode::Linear,
148 min_filter: wgpu::FilterMode::Linear,
149 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
150 ..Default::default()
151 });
152
153 let dummy_z = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::R32Float, "aux-dummy-z");
154 queue.write_texture(
155 dummy_z.texture.as_image_copy(),
156 &EMPTY_Z_SENTINEL.to_le_bytes(),
157 wgpu::TexelCopyBufferLayout {
158 offset: 0,
159 bytes_per_row: Some(4),
160 rows_per_image: Some(1),
161 },
162 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
163 );
164
165 let dummy_f16 = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::Rgba16Float, "aux-dummy-f16");
166 queue.write_texture(
167 dummy_f16.texture.as_image_copy(),
168 &[0u8; 8],
169 wgpu::TexelCopyBufferLayout {
170 offset: 0,
171 bytes_per_row: Some(8),
172 rows_per_image: Some(1),
173 },
174 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
175 );
176
177 // R32Float output pipelines (all texture reads unfilterable except mask_tex)
178 let r32f_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
179 label: Some("aux-r32f-bgl"),
180 entries: &[
181 tex_entry(0, false),
182 tex_entry(1, false),
183 tex_entry(2, false),
184 tex_entry(3, false),
185 tex_entry(4, true),
186 sampler_entry(5),
187 storage_entry(6, wgpu::TextureFormat::R32Float),
188 uniform_entry(7, u_size_u64),
189 ],
190 });
191 let r32f_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
192 label: Some("aux-r32f-pl"),
193 bind_group_layouts: &[Some(&r32f_bgl)],
194 immediate_size: 0,
195 });
196 let r32f_mod = device.create_shader_module(wgpu::ShaderModuleDescriptor {
197 label: Some("aux-r32f-wgsl"),
198 source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("R32F_OPS", None, false).into()),
199 });
200 let mk_pipe = |module: &wgpu::ShaderModule, pl: &wgpu::PipelineLayout, entry: &str| {
201 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
202 label: Some(entry),
203 layout: Some(pl),
204 module,
205 entry_point: Some(entry),
206 compilation_options: Default::default(),
207 cache: None,
208 })
209 };
210 let copy_color_to_aux_z = mk_pipe(&r32f_mod, &r32f_pl, "copy_color_to_aux_z_op");
211 let cb_to_zbuffer = mk_pipe(&r32f_mod, &r32f_pl, "cb_to_zbuffer_op");
212 let crop_r32f = mk_pipe(&r32f_mod, &r32f_pl, "crop_r32f_op");
213
214 // Rgba16Float output pipelines (CopyAux Normal/Vector/BackVector + OpticalFlow)
215 let f16_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
216 label: Some("aux-f16-bgl"),
217 entries: &[
218 tex_entry(0, true),
219 tex_entry(1, true),
220 tex_entry(2, true),
221 sampler_entry(3),
222 storage_entry(4, wgpu::TextureFormat::Rgba16Float),
223 uniform_entry(5, u_size_u64),
224 ],
225 });
226 let f16_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
227 label: Some("aux-f16-pl"),
228 bind_group_layouts: &[Some(&f16_bgl)],
229 immediate_size: 0,
230 });
231 let f16_mod = device.create_shader_module(wgpu::ShaderModuleDescriptor {
232 label: Some("aux-f16-wgsl"),
233 source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("F16_OPS", None, false).into()),
234 });
235 let copy_color_to_aux_f16 = mk_pipe(&f16_mod, &f16_pl, "copy_color_to_aux_f16_op");
236 let crop_f16 = mk_pipe(&f16_mod, &f16_pl, "crop_f16_op");
237 let optflow_features = mk_pipe(&f16_mod, &f16_pl, "optflow_features_op");
238 let optflow_coarse = mk_pipe(&f16_mod, &f16_pl, "optflow_coarse_op");
239 let optflow_refine = mk_pipe(&f16_mod, &f16_pl, "optflow_refine_op");
240
241 Self {
242 sampler,
243 uniform_stride,
244 uniform_chunks: Vec::new(),
245 uniform_cursor: 0,
246 dummy_z,
247 dummy_f16,
248 depth_merge: HashMap::new(),
249 rgba_ops: HashMap::new(),
250 r32f_bgl,
251 copy_color_to_aux_z,
252 cb_to_zbuffer,
253 crop_r32f,
254 f16_bgl,
255 copy_color_to_aux_f16,
256 crop_f16,
257 optflow_features,
258 optflow_coarse,
259 optflow_refine,
260 }
261 }
262
263 pub(super) fn reset_uniform_cursor(&mut self) {
264 self.uniform_cursor = 0;
265 }
266
267 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
268 self.uniform_cursor = 0;
269 if self.uniform_chunks.len() > max_chunks {
270 self.uniform_chunks.truncate(max_chunks);
271 }
272 }
273
274 fn alloc_uniform_slot(
275 &mut self,
276 device: &wgpu::Device,
277 queue: &wgpu::Queue,
278 params: &UniformParams,
279 ) -> (usize, u32) {
280 let slot_global = self.uniform_cursor;
281 let chunk_idx = (slot_global / AUX_UNIFORM_SLOTS_PER_CHUNK) as usize;
282 let slot_in_chunk = slot_global % AUX_UNIFORM_SLOTS_PER_CHUNK;
283 while chunk_idx >= self.uniform_chunks.len() {
284 let size = u64::from(AUX_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
285 let buf = device.create_buffer(&wgpu::BufferDescriptor {
286 label: Some("aux-params-ring"),
287 size,
288 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
289 mapped_at_creation: false,
290 });
291 self.uniform_chunks.push(buf);
292 }
293 let offset = slot_in_chunk * self.uniform_stride;
294 queue.write_buffer(
295 &self.uniform_chunks[chunk_idx],
296 u64::from(offset),
297 bytemuck::bytes_of(params),
298 );
299 self.uniform_cursor = slot_global + 1;
300 (chunk_idx, offset)
301 }
302
303 fn ensure_depth_merge(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
304 if self.depth_merge.contains_key(&(format, hdr_float)) {
305 return;
306 }
307 let u_size = std::mem::size_of::<UniformParams>() as u64;
308 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
309 label: Some("aux-depth-merge-bgl"),
310 entries: &[
311 tex_entry(0, false),
312 tex_entry(1, true),
313 tex_entry(2, false),
314 tex_entry(3, false),
315 tex_entry(4, true),
316 sampler_entry(5),
317 storage_entry(6, format),
318 storage_entry(7, wgpu::TextureFormat::R32Float),
319 uniform_entry(8, u_size),
320 ],
321 });
322 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
323 label: Some("aux-depth-merge-pl"),
324 bind_group_layouts: &[Some(&bgl)],
325 immediate_size: 0,
326 });
327 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
328 label: Some("aux-depth-merge-wgsl"),
329 source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("DEPTH_MERGE", Some(format), hdr_float).into()),
330 });
331 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
332 label: Some("depth_merge_op"),
333 layout: Some(&pl),
334 module: &module,
335 entry_point: Some("depth_merge_op"),
336 compilation_options: Default::default(),
337 cache: None,
338 });
339 self.depth_merge.insert((format, hdr_float), FormatPipelines { bgl, pipeline });
340 }
341
342 fn ensure_rgba_ops(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
343 if self.rgba_ops.contains_key(&(format, hdr_float)) {
344 return;
345 }
346 let u_size = std::mem::size_of::<UniformParams>() as u64;
347 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
348 label: Some("aux-rgba-ops-bgl"),
349 entries: &[
350 tex_entry(0, true),
351 tex_entry(1, false),
352 tex_entry(2, true),
353 sampler_entry(3),
354 storage_entry(4, format),
355 uniform_entry(5, u_size),
356 ],
357 });
358 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
359 label: Some("aux-rgba-ops-pl"),
360 bind_group_layouts: &[Some(&bgl)],
361 immediate_size: 0,
362 });
363 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
364 label: Some("aux-rgba-ops-wgsl"),
365 source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("RGBA_OPS", Some(format), hdr_float).into()),
366 });
367 let copy_aux_to_color = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
368 label: Some("copy_aux_to_color_op"),
369 layout: Some(&pl),
370 module: &module,
371 entry_point: Some("copy_aux_to_color_op"),
372 compilation_options: Default::default(),
373 cache: None,
374 });
375 let vector_motion_blur = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
376 label: Some("vector_motion_blur_op"),
377 layout: Some(&pl),
378 module: &module,
379 entry_point: Some("vector_motion_blur_op"),
380 compilation_options: Default::default(),
381 cache: None,
382 });
383 self.rgba_ops.insert(
384 (format, hdr_float),
385 RgbaOpsPipelines {
386 bgl,
387 copy_aux_to_color,
388 vector_motion_blur,
389 },
390 );
391 }
392
393 #[allow(clippy::too_many_arguments)]
394 fn dispatch_depth_merge(
395 &mut self,
396 device: &wgpu::Device,
397 queue: &wgpu::Queue,
398 enc: &mut wgpu::CommandEncoder,
399 bg_rgba: &wgpu::TextureView,
400 fg_rgba: &wgpu::TextureView,
401 bg_z: Option<&wgpu::TextureView>,
402 fg_z: Option<&wgpu::TextureView>,
403 mask: &wgpu::TextureView,
404 dst_rgba: &CachedTexture,
405 dst_z: &AuxChannelTex,
406 params: &UniformParams,
407 ) {
408 let hdr_float = dst_rgba.depth.is_float();
409 self.ensure_depth_merge(device, dst_rgba.format, hdr_float);
410 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
411 let entry = &self.depth_merge[&(dst_rgba.format, hdr_float)];
412 let bg_z_view = bg_z.unwrap_or(&self.dummy_z.view);
413 let fg_z_view = fg_z.unwrap_or(&self.dummy_z.view);
414 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
415 label: Some("aux-depth-merge-bg"),
416 layout: &entry.bgl,
417 entries: &[
418 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(bg_rgba) },
419 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fg_rgba) },
420 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(bg_z_view) },
421 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(fg_z_view) },
422 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) },
423 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::Sampler(&self.sampler) },
424 wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&dst_rgba.view) },
425 wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&dst_z.view) },
426 wgpu::BindGroupEntry {
427 binding: 8,
428 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
429 buffer: &self.uniform_chunks[chunk_idx],
430 offset: 0,
431 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
432 }),
433 },
434 ],
435 });
436 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
437 label: Some("depth-merge"),
438 timestamp_writes: None,
439 });
440 pass.set_pipeline(&entry.pipeline);
441 pass.set_bind_group(0, &bg, &[offset]);
442 pass.dispatch_workgroups(dst_rgba.size[0].div_ceil(8), dst_rgba.size[1].div_ceil(8), 1);
443 }
444
445 #[allow(clippy::too_many_arguments)]
446 fn dispatch_rgba_op(
447 &mut self,
448 device: &wgpu::Device,
449 queue: &wgpu::Queue,
450 enc: &mut wgpu::CommandEncoder,
451 is_vmb: bool,
452 src_rgba: &wgpu::TextureView,
453 aux_tex: &wgpu::TextureView,
454 mask: &wgpu::TextureView,
455 dst_rgba: &CachedTexture,
456 params: &UniformParams,
457 ) {
458 let hdr_float = dst_rgba.depth.is_float();
459 self.ensure_rgba_ops(device, dst_rgba.format, hdr_float);
460 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
461 let entry = &self.rgba_ops[&(dst_rgba.format, hdr_float)];
462 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
463 label: Some(if is_vmb { "vmb-bg" } else { "copy-aux-bg" }),
464 layout: &entry.bgl,
465 entries: &[
466 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_rgba) },
467 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(aux_tex) },
468 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
469 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
470 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst_rgba.view) },
471 wgpu::BindGroupEntry {
472 binding: 5,
473 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
474 buffer: &self.uniform_chunks[chunk_idx],
475 offset: 0,
476 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
477 }),
478 },
479 ],
480 });
481 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
482 label: Some(if is_vmb { "vector-motion-blur" } else { "copy-aux-to-color" }),
483 timestamp_writes: None,
484 });
485 pass.set_pipeline(if is_vmb { &entry.vector_motion_blur } else { &entry.copy_aux_to_color });
486 pass.set_bind_group(0, &bg, &[offset]);
487 pass.dispatch_workgroups(dst_rgba.size[0].div_ceil(8), dst_rgba.size[1].div_ceil(8), 1);
488 }
489
490 #[allow(clippy::too_many_arguments)]
491 fn dispatch_r32f_op(
492 &mut self,
493 device: &wgpu::Device,
494 queue: &wgpu::Queue,
495 enc: &mut wgpu::CommandEncoder,
496 which: u8, // 0 = copy_color_to_aux_z, 1 = cb_to_zbuffer, 2 = crop_r32f
497 bg_rgba: &wgpu::TextureView,
498 fg_rgba: &wgpu::TextureView,
499 bg_z: Option<&wgpu::TextureView>,
500 fg_z: Option<&wgpu::TextureView>,
501 mask: &wgpu::TextureView,
502 dst_z: &AuxChannelTex,
503 params: &UniformParams,
504 ) {
505 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
506 let bg_z_view = bg_z.unwrap_or(&self.dummy_z.view);
507 let fg_z_view = fg_z.unwrap_or(&self.dummy_z.view);
508 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
509 label: Some("aux-r32f-bg"),
510 layout: &self.r32f_bgl,
511 entries: &[
512 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(bg_rgba) },
513 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fg_rgba) },
514 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(bg_z_view) },
515 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(fg_z_view) },
516 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) },
517 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::Sampler(&self.sampler) },
518 wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&dst_z.view) },
519 wgpu::BindGroupEntry {
520 binding: 7,
521 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
522 buffer: &self.uniform_chunks[chunk_idx],
523 offset: 0,
524 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
525 }),
526 },
527 ],
528 });
529 let pipe = match which {
530 0 => &self.copy_color_to_aux_z,
531 1 => &self.cb_to_zbuffer,
532 _ => &self.crop_r32f,
533 };
534 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
535 label: Some("aux-r32f"),
536 timestamp_writes: None,
537 });
538 pass.set_pipeline(pipe);
539 pass.set_bind_group(0, &bg, &[offset]);
540 pass.dispatch_workgroups(dst_z.size[0].div_ceil(8), dst_z.size[1].div_ceil(8), 1);
541 }
542
543 #[allow(clippy::too_many_arguments)]
544 fn dispatch_f16_op(
545 &mut self,
546 device: &wgpu::Device,
547 queue: &wgpu::Queue,
548 enc: &mut wgpu::CommandEncoder,
549 which: u8, // 0=copy_color_to_aux_f16, 1=crop_f16, 2=optflow_features, 3=optflow_coarse, 4=optflow_refine
550 tex_a: &wgpu::TextureView,
551 tex_b: Option<&wgpu::TextureView>,
552 tex_c: Option<&wgpu::TextureView>,
553 dst_f16: &AuxChannelTex,
554 params: &UniformParams,
555 ) {
556 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
557 let vb = tex_b.unwrap_or(&self.dummy_f16.view);
558 let vc = tex_c.unwrap_or(&self.dummy_f16.view);
559 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
560 label: Some("aux-f16-bg"),
561 layout: &self.f16_bgl,
562 entries: &[
563 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(tex_a) },
564 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(vb) },
565 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(vc) },
566 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
567 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst_f16.view) },
568 wgpu::BindGroupEntry {
569 binding: 5,
570 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
571 buffer: &self.uniform_chunks[chunk_idx],
572 offset: 0,
573 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
574 }),
575 },
576 ],
577 });
578 let pipe = match which {
579 0 => &self.copy_color_to_aux_f16,
580 1 => &self.crop_f16,
581 2 => &self.optflow_features,
582 3 => &self.optflow_coarse,
583 _ => &self.optflow_refine,
584 };
585 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
586 label: Some("aux-f16"),
587 timestamp_writes: None,
588 });
589 pass.set_pipeline(pipe);
590 pass.set_bind_group(0, &bg, &[offset]);
591 pass.dispatch_workgroups(dst_f16.size[0].div_ceil(8), dst_f16.size[1].div_ceil(8), 1);
592 }
593}
594
595#[derive(Clone, Copy, Debug, PartialEq, Eq)]
596enum CopyAuxChannel {
597 Z,
598 Normal,
599 Vector,
600 BackVector,
601 Color,
602}
603
604impl CopyAuxChannel {
605 fn from_str(s: &str) -> Self {
606 match s {
607 "Normal" | "Normals" => Self::Normal,
608 "Vector" | "Vectors" => Self::Vector,
609 "BackVector" | "Back Vector" | "BackVectors" => Self::BackVector,
610 "Color" => Self::Color,
611 _ => Self::Z,
612 }
613 }
614
615 fn remap_prefix(self) -> &'static str {
616 match self {
617 Self::Z => "Z",
618 Self::Normal => "Normal",
619 Self::Vector => "Vector",
620 Self::BackVector => "BackVector",
621 Self::Color => "Color",
622 }
623 }
624
625 fn shader_kind(self) -> f32 {
626 match self {
627 Self::Z => 0.0,
628 Self::Normal => 1.0,
629 Self::Vector | Self::BackVector => 2.0,
630 Self::Color => 3.0,
631 }
632 }
633}
634
635/// Returns `true` iff any active node in `comp` consumes optical-flow motion vectors
636/// (`VectorMotionBlur`, or `Dimension.CopyAux` reading `Vector`/`BackVector`).
637pub(super) fn comp_uses_optical_flow_vectors(comp: &Comp) -> bool {
638 comp.nodes.iter().any(|n| {
639 if n.bypassed {
640 return false;
641 }
642 if n.kind == "VectorMotionBlur" {
643 return true;
644 }
645 if n.kind == "Dimension.CopyAux" {
646 let ch = CopyAuxChannel::from_str(n.static_str("Channel").unwrap_or("Z"));
647 if matches!(ch, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) {
648 return true;
649 }
650 }
651 false
652 })
653}
654
655impl Engine {
656 pub(super) fn aux_pipelines(&self) -> &RefCell<AuxPipelines> {
657 self.aux_pipelines
658 .get_or_init(|| RefCell::new(AuxPipelines::new(&self.device, &self.queue)))
659 }
660
661 /// Dispatches depth-aware `Merge` (`PerformDepthMerge = 0` or `1`) when at least one of
662 /// `bg` or `fg` carries `aux.z`. Attaches `out.aux.z` whenever `bg` carried `aux.z`.
663 #[allow(clippy::too_many_arguments)]
664 pub(super) fn dispatch_depth_merge(
665 &self,
666 enc: &mut wgpu::CommandEncoder,
667 bg: &CachedTexture,
668 fg: &CachedTexture,
669 mask_view: &wgpu::TextureView,
670 dst: &mut CachedTexture,
671 params: &UniformParams,
672 ) {
673 let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref());
674 let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref());
675 let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "merge-z");
676 self.aux_pipelines().borrow_mut().dispatch_depth_merge(
677 &self.device,
678 &self.queue,
679 enc,
680 &bg.view,
681 &fg.view,
682 bg_z.map(|t| t.view.as_ref()),
683 fg_z.map(|t| t.view.as_ref()),
684 mask_view,
685 dst,
686 &dst_z,
687 params,
688 );
689 let same_dod = dst.size == bg.size && dst.origin == bg.origin;
690 if bg_z.is_some() {
691 let mut out_aux = if same_dod {
692 bg.aux_cloned()
693 } else {
694 AuxChannels::default()
695 };
696 out_aux.z = Some(dst_z);
697 dst.set_aux(Some(Arc::new(out_aux)));
698 } else if bg.aux.is_some() && same_dod {
699 // Preserve any non-Z aux channels on BG, keeping Z = None matching Snow Globe!
700 dst.set_aux(bg.aux.clone());
701 }
702 }
703
704 /// Re-origins and resizes `src.aux` channels from `(src.origin, src.size)` to
705 /// `(dst.origin, dst.size)`, padding out-of-bounds Z with `EMPTY_Z_SENTINEL` and
706 /// out-of-bounds `Rgba16Float` channels with `0.0`.
707 pub(super) fn reorigin_aux(
708 &self,
709 enc: &mut wgpu::CommandEncoder,
710 src: &CachedTexture,
711 dst: &mut CachedTexture,
712 ) {
713 let Some(src_aux) = src.aux.as_ref() else {
714 return;
715 };
716 if src.origin == dst.origin && src.size == dst.size {
717 dst.set_aux(Some(src_aux.clone()));
718 return;
719 }
720 let mut out_aux = AuxChannels::default();
721 let mut u = UniformParams::default();
722 u.p[0] = [
723 (src.origin[0] - dst.origin[0]) as f32,
724 (src.origin[1] - dst.origin[1]) as f32,
725 dst.size[0] as f32,
726 dst.size[1] as f32,
727 ];
728 let mut ap = self.aux_pipelines().borrow_mut();
729 if let Some(z) = src_aux.z.as_ref() {
730 let cropped_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "crop-z");
731 ap.dispatch_r32f_op(
732 &self.device,
733 &self.queue,
734 enc,
735 2,
736 &self.dummy.view,
737 &self.dummy.view,
738 Some(&z.view),
739 None,
740 &self.dummy.view,
741 &cropped_z,
742 &u,
743 );
744 out_aux.z = Some(cropped_z);
745 }
746 let mut crop_f16 = |ap: &mut AuxPipelines, tex: &AuxChannelTex, label: &str| {
747 let cropped = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::Rgba16Float, label);
748 ap.dispatch_f16_op(
749 &self.device,
750 &self.queue,
751 enc,
752 1,
753 &tex.view,
754 None,
755 None,
756 &cropped,
757 &u,
758 );
759 cropped
760 };
761 if let Some(n) = src_aux.normal.as_ref() {
762 out_aux.normal = Some(crop_f16(&mut ap, n, "crop-normal"));
763 }
764 if let Some(v) = src_aux.vector.as_ref() {
765 out_aux.vector = Some(crop_f16(&mut ap, v, "crop-vector"));
766 }
767 if let Some(bv) = src_aux.back_vector.as_ref() {
768 out_aux.back_vector = Some(crop_f16(&mut ap, bv, "crop-back-vector"));
769 }
770 dst.set_aux(Some(Arc::new(out_aux)));
771 }
772
773 /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`.
774 pub(super) fn crop_aux_to_canvas(
775 &self,
776 enc: &mut wgpu::CommandEncoder,
777 src: &CachedTexture,
778 dst: &mut CachedTexture,
779 ) {
780 self.reorigin_aux(enc, src, dst);
781 }
782
783 /// Evaluates `Dimension.CopyAux` (Mode 0: Aux -> Color with Remap; Mode 1: Color -> Aux).
784 #[allow(clippy::too_many_arguments)]
785 pub(super) fn eval_copy_aux(
786 &mut self,
787 comp: &Comp,
788 node: &Node,
789 time: f64,
790 frame_i: i64,
791 enc: &mut wgpu::CommandEncoder,
792 visiting: &mut HashSet<(NodeId, i64)>,
793 stats: &mut EvalStats,
794 ) -> CachedTexture {
795 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
796 return self.dummy.clone();
797 };
798 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
799 let mode = comp.eval_number(node, "Mode", time, 0.0, &self.expr).round() as i32;
800 let channel = CopyAuxChannel::from_str(node.static_str("Channel").unwrap_or("Z"));
801 let kill_aux = comp.eval_number(node, "KillAuxChannels", time, 0.0, &self.expr) >= 0.5;
802 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
803 let mbm = self.multiplies_by_mask(comp, node, time);
804 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
805
806 // Early passthrough when blend == 0 (or channel == Color)
807 if (blend <= 1e-6 && !(mbm && has_mask)) || channel == CopyAuxChannel::Color {
808 if kill_aux && src.aux.is_some() {
809 let key = self.make_key(node, "CopyAuxKill", src.size, &[src.content_hash], &[1.0]);
810 let mut out = src.clone();
811 out.content_hash = key;
812 out.set_aux(None);
813 return out;
814 }
815 return src;
816 }
817
818 if mode == 1 {
819 // Mode 1: Color To Aux (passes RGBA through and writes selected aux channel)
820 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
821 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
822 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
823 let key = self.make_key(
824 node,
825 "CopyAuxColorToAux",
826 src.size,
827 &[src.content_hash, mask_hash],
828 &[
829 channel.shader_kind(),
830 if kill_aux { 1.0 } else { 0.0 },
831 blend,
832 if mask_inv { 1.0 } else { 0.0 },
833 ],
834 );
835 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
836 stats.cache_hits += 1;
837 return hit;
838 }
839 stats.cache_misses += 1;
840 stats.nodes_evaluated += 1;
841
842 let mut out = src.clone();
843 out.content_hash = key;
844 let mut out_aux = if kill_aux {
845 AuxChannels::default()
846 } else {
847 src.aux_cloned()
848 };
849 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
850 let has_m_f = if mask.is_some() { 1.0 } else { 0.0 };
851 let inv_f = if mask_inv { 1.0 } else { 0.0 };
852
853 match channel {
854 CopyAuxChannel::Z => {
855 let dst_z = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::R32Float, "copy-aux-z");
856 let existing_z = out_aux.z.as_ref();
857 let mut u = UniformParams::default();
858 u.p[0] = [blend, has_m_f, inv_f, if existing_z.is_some() { 1.0 } else { 0.0 }];
859 self.aux_pipelines().borrow_mut().dispatch_r32f_op(
860 &self.device,
861 &self.queue,
862 enc,
863 0,
864 &src.view,
865 &self.dummy.view,
866 existing_z.map(|t| t.view.as_ref()),
867 None,
868 mv,
869 &dst_z,
870 &u,
871 );
872 out_aux.z = Some(dst_z);
873 }
874 CopyAuxChannel::Normal | CopyAuxChannel::Vector | CopyAuxChannel::BackVector => {
875 let label = match channel {
876 CopyAuxChannel::Normal => "copy-aux-normal",
877 CopyAuxChannel::Vector => "copy-aux-vector",
878 _ => "copy-aux-back-vector",
879 };
880 let dst_f16 = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::Rgba16Float, label);
881 let existing = match channel {
882 CopyAuxChannel::Normal => out_aux.normal.as_ref(),
883 CopyAuxChannel::Vector => out_aux.vector.as_ref(),
884 _ => out_aux.back_vector.as_ref(),
885 };
886 let mut u = UniformParams::default();
887 u.p[0] = [channel.shader_kind(), blend, has_m_f, inv_f];
888 u.p[1] = [if existing.is_some() { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
889 self.aux_pipelines().borrow_mut().dispatch_f16_op(
890 &self.device,
891 &self.queue,
892 enc,
893 0,
894 &src.view,
895 existing.map(|t| t.view.as_ref()),
896 Some(mv),
897 &dst_f16,
898 &u,
899 );
900 match channel {
901 CopyAuxChannel::Normal => out_aux.normal = Some(dst_f16),
902 CopyAuxChannel::Vector => out_aux.vector = Some(dst_f16),
903 _ => out_aux.back_vector = Some(dst_f16),
904 }
905 }
906 CopyAuxChannel::Color => {}
907 }
908 out.set_aux(Some(Arc::new(out_aux)));
909 self.cache.insert(key, out.clone(), node.id, frame_i);
910 return out;
911 }
912
913 // Mode 0: Aux To Color
914 let src_has_sel = src.aux.as_ref().is_some_and(|a| match channel {
915 CopyAuxChannel::Z => a.z.is_some(),
916 CopyAuxChannel::Normal => a.normal.is_some(),
917 CopyAuxChannel::Vector => a.vector.is_some(),
918 CopyAuxChannel::BackVector => a.back_vector.is_some(),
919 CopyAuxChannel::Color => false,
920 });
921 if !src_has_sel {
922 if kill_aux && src.aux.is_some() {
923 let key = self.make_key(node, "CopyAuxKillMissing", src.size, &[src.content_hash], &[1.0]);
924 let mut out = src.clone();
925 out.content_hash = key;
926 out.set_aux(None);
927 return out;
928 }
929 return src;
930 }
931
932 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
933 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
934 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
935
936 let pfx = channel.remap_prefix();
937 let remap_en = comp.eval_number(node, &format!("{pfx}.Remap.Enable"), time, 0.0, &self.expr) >= 0.5;
938 let fmin = comp.eval_number(node, &format!("{pfx}.Remap.From.Min"), time, 0.0, &self.expr);
939 let fmax = comp.eval_number(node, &format!("{pfx}.Remap.From.Max"), time, 1.0, &self.expr);
940 let tmin = comp.eval_number(node, &format!("{pfx}.Remap.To.Min"), time, 0.0, &self.expr);
941 let tmax = comp.eval_number(node, &format!("{pfx}.Remap.To.Max"), time, 1.0, &self.expr);
942 let inv_base = comp.eval_number(node, &format!("{pfx}.Remap.To.Invert"), time, 0.0, &self.expr);
943
944 let (fmin_x, fmax_x, fmin_y, fmax_y, tmin_x, tmax_x, tmin_y, tmax_y, inv_x, inv_y) =
945 if matches!(channel, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) {
946 (
947 comp.eval_number(node, &format!("{pfx}.Remap.From.MinX"), time, fmin, &self.expr) as f32,
948 comp.eval_number(node, &format!("{pfx}.Remap.From.MaxX"), time, fmax, &self.expr) as f32,
949 comp.eval_number(node, &format!("{pfx}.Remap.From.MinY"), time, fmin, &self.expr) as f32,
950 comp.eval_number(node, &format!("{pfx}.Remap.From.MaxY"), time, fmax, &self.expr) as f32,
951 comp.eval_number(node, &format!("{pfx}.Remap.To.MinX"), time, tmin, &self.expr) as f32,
952 comp.eval_number(node, &format!("{pfx}.Remap.To.MaxX"), time, tmax, &self.expr) as f32,
953 comp.eval_number(node, &format!("{pfx}.Remap.To.MinY"), time, tmin, &self.expr) as f32,
954 comp.eval_number(node, &format!("{pfx}.Remap.To.MaxY"), time, tmax, &self.expr) as f32,
955 comp.eval_number(node, &format!("{pfx}.Remap.To.InvertX"), time, inv_base, &self.expr) as f32,
956 comp.eval_number(node, &format!("{pfx}.Remap.To.InvertY"), time, inv_base, &self.expr) as f32,
957 )
958 } else {
959 (
960 fmin as f32,
961 fmax as f32,
962 fmin as f32,
963 fmax as f32,
964 tmin as f32,
965 tmax as f32,
966 tmin as f32,
967 tmax as f32,
968 inv_base as f32,
969 inv_base as f32,
970 )
971 };
972
973 let dst_depth = self.node_depth(comp, node, time, Some(src.depth));
974 let mut u = UniformParams::default();
975 u.p[0] = [
976 channel.shader_kind(),
977 if remap_en { 1.0 } else { 0.0 },
978 if inv_x >= 0.5 { 1.0 } else { 0.0 },
979 if inv_y >= 0.5 { 1.0 } else { 0.0 },
980 ];
981 u.p[1] = [fmin_x, fmax_x, tmin_x, tmax_x];
982 u.p[2] = [fmin_y, fmax_y, tmin_y, tmax_y];
983 u.p[3] = [
984 blend,
985 if mask.is_some() { 1.0 } else { 0.0 },
986 if mask_inv { 1.0 } else { 0.0 },
987 if mbm { 1.0 } else { 0.0 },
988 ];
989
990 let key = self.make_key(
991 node,
992 "CopyAuxToColor",
993 src.size,
994 &[src.content_hash, mask_hash, dst_depth as u64, kill_aux as u64],
995 bytemuck::cast_slice(&u.p[..4]),
996 );
997 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
998 stats.cache_hits += 1;
999 return hit;
1000 }
1001 stats.cache_misses += 1;
1002 stats.nodes_evaluated += 1;
1003
1004 let aux_view = {
1005 let a = src.aux.as_ref().expect("checked src_has_sel");
1006 match channel {
1007 CopyAuxChannel::Z => a.z.as_ref().expect("z").view.clone(),
1008 CopyAuxChannel::Normal => a.normal.as_ref().expect("normal").view.clone(),
1009 CopyAuxChannel::Vector => a.vector.as_ref().expect("vector").view.clone(),
1010 CopyAuxChannel::BackVector => a.back_vector.as_ref().expect("back_vector").view.clone(),
1011 CopyAuxChannel::Color => unreachable!(),
1012 }
1013 };
1014 let mut dst = self.alloc_tex_like(&src, dst_depth, key);
1015 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1016 self.aux_pipelines().borrow_mut().dispatch_rgba_op(
1017 &self.device,
1018 &self.queue,
1019 enc,
1020 false,
1021 &src.view,
1022 &aux_view,
1023 mv,
1024 &dst,
1025 &u,
1026 );
1027 if !kill_aux {
1028 dst.set_aux(src.aux.clone());
1029 }
1030 self.cache.insert(key, dst.clone(), node.id, frame_i);
1031 dst
1032 }
1033
1034 /// Computes `ChannelBoolean`'s `ToZBuffer` extra channel and attaches it to `dst.aux.z`.
1035 #[allow(clippy::too_many_arguments)]
1036 pub(super) fn apply_channel_boolean_z(
1037 &self,
1038 enc: &mut wgpu::CommandEncoder,
1039 bg: &CachedTexture,
1040 fg: &CachedTexture,
1041 mask: Option<&CachedTexture>,
1042 mask_inv: bool,
1043 op: i32,
1044 to_z: i32,
1045 blend: f32,
1046 expand_canvas: bool,
1047 dst: &mut CachedTexture,
1048 ) {
1049 let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref());
1050 let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref());
1051
1052 // If copying FG Z when FG has no Z, or BG Z when BG has no Z, preserve bg.aux without fabricating Z.
1053 if to_z == 18 && fg_z.is_none() {
1054 if bg.aux.is_some() && dst.size == bg.size {
1055 dst.set_aux(bg.aux.clone());
1056 }
1057 return;
1058 }
1059 if to_z == 19 && bg_z.is_none() {
1060 if bg.aux.is_some() && dst.size == bg.size {
1061 dst.set_aux(bg.aux.clone());
1062 }
1063 return;
1064 }
1065
1066 // Zero-copy fast path: Op=Copy, ToZBuffer=18 (FG Z), full blend, unmasked, matching extents.
1067 if op == 0
1068 && to_z == 18
1069 && blend >= 0.9999
1070 && mask.is_none()
1071 && !expand_canvas
1072 && !bg.has_dod()
1073 && !fg.has_dod()
1074 && let Some(fz) = fg_z
1075 && fz.size == dst.size
1076 {
1077 let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() };
1078 out_aux.z = Some(fz.clone());
1079 dst.set_aux(Some(Arc::new(out_aux)));
1080 return;
1081 }
1082
1083 let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "cb-zbuffer");
1084 let mut u = UniformParams::default();
1085 u.p[0] = [op as f32, to_z as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }];
1086 u.p[1] = [
1087 if mask_inv { 1.0 } else { 0.0 },
1088 if bg_z.is_some() { 1.0 } else { 0.0 },
1089 if fg_z.is_some() { 1.0 } else { 0.0 },
1090 if expand_canvas { 1.0 } else { 0.0 },
1091 ];
1092 if fg.has_dod() {
1093 u.p[2] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32];
1094 }
1095 if bg.has_dod() {
1096 u.p[3] = [bg.origin[0] as f32, bg.origin[1] as f32, bg.canvas_size[0] as f32, bg.canvas_size[1] as f32];
1097 }
1098 let mv = mask.map_or(&self.dummy.view, |m| &m.view);
1099 self.aux_pipelines().borrow_mut().dispatch_r32f_op(
1100 &self.device,
1101 &self.queue,
1102 enc,
1103 1,
1104 &bg.view,
1105 &fg.view,
1106 bg_z.map(|t| t.view.as_ref()),
1107 fg_z.map(|t| t.view.as_ref()),
1108 mv,
1109 &dst_z,
1110 &u,
1111 );
1112 let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() };
1113 out_aux.z = Some(dst_z);
1114 dst.set_aux(Some(Arc::new(out_aux)));
1115 }
1116
1117 /// Dispatches `VectorMotionBlur` compute pass using `vec_view` (either `src.aux.vector`
1118 /// or an external `VectorInput` texture).
1119 #[allow(clippy::too_many_arguments)]
1120 pub(super) fn dispatch_vector_motion_blur(
1121 &self,
1122 enc: &mut wgpu::CommandEncoder,
1123 src: &CachedTexture,
1124 vec_view: &wgpu::TextureView,
1125 mask_view: &wgpu::TextureView,
1126 dst: &CachedTexture,
1127 params: &UniformParams,
1128 ) {
1129 self.aux_pipelines().borrow_mut().dispatch_rgba_op(
1130 &self.device,
1131 &self.queue,
1132 enc,
1133 true,
1134 &src.view,
1135 vec_view,
1136 mask_view,
1137 dst,
1138 params,
1139 );
1140 }
1141
1142 /// Computes a dense motion vector texture (`Rgba16Float`, Fusion pixel units `+X` right, `+Y` up)
1143 /// from `frame_src` to `frame_dst`.
1144 fn compute_optflow_vector_tex(
1145 &self,
1146 enc: &mut wgpu::CommandEncoder,
1147 frame_src: &CachedTexture,
1148 frame_dst: &CachedTexture,
1149 label: &str,
1150 ) -> AuxChannelTex {
1151 let size = frame_src.size;
1152 let out = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, label);
1153 let mut ap = self.aux_pipelines().borrow_mut();
1154
1155 // Identical static frames -> zero flow in a single trivial fill.
1156 if frame_src.content_hash != 0 && frame_src.content_hash == frame_dst.content_hash {
1157 let mut u = UniformParams::default();
1158 u.p[0] = [3.0, 1.0, 0.0, 0.0]; // kind 3 = ZeroFill
1159 ap.dispatch_f16_op(&self.device, &self.queue, enc, 0, &frame_src.view, None, None, &out, &u);
1160 return out;
1161 }
1162
1163 let coarse_size = [size[0].div_ceil(4).max(1), size[1].div_ceil(4).max(1)];
1164 let feat_a = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fa");
1165 let feat_b = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fb");
1166 let feat_ac = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fac");
1167 let feat_bc = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fbc");
1168 let flow_c = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fc");
1169
1170 let u0 = UniformParams::default();
1171 ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_a, &u0);
1172 ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_b, &u0);
1173 ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_ac, &u0);
1174 ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_bc, &u0);
1175 ap.dispatch_f16_op(&self.device, &self.queue, enc, 3, &feat_ac.view, Some(&feat_bc.view), None, &flow_c, &u0);
1176
1177 let mut ur = UniformParams::default();
1178 ur.p[0] = [
1179 size[0] as f32 / coarse_size[0] as f32,
1180 size[1] as f32 / coarse_size[1] as f32,
1181 1.0, // convert texture +Y-down to Fusion +Y-up
1182 0.0,
1183 ];
1184 ap.dispatch_f16_op(
1185 &self.device,
1186 &self.queue,
1187 enc,
1188 4,
1189 &feat_a.view,
1190 Some(&feat_b.view),
1191 Some(&flow_c.view),
1192 &out,
1193 &ur,
1194 );
1195 out
1196 }
1197
1198 /// Evaluates `Dimension.OpticalFlow` / `OpticalFlow`: passes RGBA through unchanged,
1199 /// and attaches forward (`t -> t+1`) + backward (`t -> t-1`) motion vectors as
1200 /// `aux.vector` / `aux.back_vector` ONLY when a downstream consumer uses motion vectors.
1201 #[allow(clippy::too_many_arguments)]
1202 pub(super) fn eval_optical_flow(
1203 &mut self,
1204 comp: &Comp,
1205 node: &Node,
1206 time: f64,
1207 frame_i: i64,
1208 enc: &mut wgpu::CommandEncoder,
1209 visiting: &mut HashSet<(NodeId, i64)>,
1210 stats: &mut EvalStats,
1211 ) -> CachedTexture {
1212 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1213 return self.dummy.clone();
1214 };
1215 let curr = self.eval_node(comp, src_id, time, enc, visiting, stats);
1216 if !time.is_finite() || !comp_uses_optical_flow_vectors(comp) {
1217 return curr;
1218 }
1219 let next = self.eval_node(comp, src_id, time + 1.0, enc, visiting, stats);
1220 let prev = self.eval_node(comp, src_id, time - 1.0, enc, visiting, stats);
1221 let curr_c = self.crop_to_canvas(enc, curr.clone());
1222 let next_c = self.crop_to_canvas(enc, next);
1223 let prev_c = self.crop_to_canvas(enc, prev);
1224
1225 let key = self.make_key(
1226 node,
1227 "OpticalFlowAux",
1228 curr_c.size,
1229 &[curr_c.content_hash, next_c.content_hash, prev_c.content_hash],
1230 &[],
1231 );
1232 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1233 stats.cache_hits += 1;
1234 return hit;
1235 }
1236 stats.cache_misses += 1;
1237 stats.nodes_evaluated += 1;
1238
1239 let fwd = self.compute_optflow_vector_tex(enc, &curr_c, &next_c, "optflow-fwd-vec");
1240 let bwd = self.compute_optflow_vector_tex(enc, &curr_c, &prev_c, "optflow-bwd-vec");
1241
1242 let mut out = curr_c;
1243 out.content_hash = key;
1244 let mut aux = out.aux_cloned();
1245 aux.vector = Some(fwd);
1246 aux.back_vector = Some(bwd);
1247 out.set_aux(Some(Arc::new(aux)));
1248 self.cache.insert(key, out.clone(), node.id, frame_i);
1249 out
1250 }
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255 use super::*;
1256
1257 fn readback_r32f(eng: &Engine, tex: &AuxChannelTex) -> Vec<f32> {
1258 let [w, h] = tex.size;
1259 assert_eq!(tex.format, wgpu::TextureFormat::R32Float);
1260 let unpadded_bpr = w * 4;
1261 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1262 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
1263 let buf = eng.device.create_buffer(&wgpu::BufferDescriptor {
1264 label: Some("readback-r32f"),
1265 size: u64::from(padded_bpr) * u64::from(h),
1266 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1267 mapped_at_creation: false,
1268 });
1269 let mut enc = eng.device.create_command_encoder(&Default::default());
1270 enc.copy_texture_to_buffer(
1271 tex.texture.as_image_copy(),
1272 wgpu::TexelCopyBufferInfo {
1273 buffer: &buf,
1274 layout: wgpu::TexelCopyBufferLayout {
1275 offset: 0,
1276 bytes_per_row: Some(padded_bpr),
1277 rows_per_image: Some(h),
1278 },
1279 },
1280 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
1281 );
1282 eng.queue.submit(Some(enc.finish()));
1283 let slice = buf.slice(..);
1284 let (tx, rx) = std::sync::mpsc::channel();
1285 slice.map_async(wgpu::MapMode::Read, move |res| {
1286 let _ = tx.send(res);
1287 });
1288 eng.device
1289 .poll(wgpu::PollType::Wait {
1290 submission_index: None,
1291 timeout: Some(std::time::Duration::from_secs(10)),
1292 })
1293 .unwrap();
1294 rx.recv().unwrap().unwrap();
1295 let data = slice.get_mapped_range().unwrap();
1296 let mut out = Vec::with_capacity((w * h) as usize);
1297 for y in 0..h as usize {
1298 let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize];
1299 for ch in row.chunks_exact(4) {
1300 out.push(f32::from_le_bytes([ch[0], ch[1], ch[2], ch[3]]));
1301 }
1302 }
1303 drop(data);
1304 buf.unmap();
1305 out
1306 }
1307
1308 fn f16_to_f32(bits: u16) -> f32 {
1309 let sign = ((bits & 0x8000) as u32) << 16;
1310 let exp = (bits >> 10) & 0x1F;
1311 let frac = (bits & 0x03FF) as u32;
1312 if exp == 0 {
1313 if frac == 0 {
1314 f32::from_bits(sign)
1315 } else {
1316 let mut f = frac;
1317 let mut e = -14i32;
1318 while (f & 0x0400) == 0 {
1319 f <<= 1;
1320 e -= 1;
1321 }
1322 let f_norm = f & 0x03FF;
1323 let e_f32 = ((e + 127) as u32) << 23;
1324 f32::from_bits(sign | e_f32 | (f_norm << 13))
1325 }
1326 } else if exp == 0x1F {
1327 f32::from_bits(sign | 0x7F80_0000 | (frac << 13))
1328 } else {
1329 let e_f32 = ((exp as u32) + 112) << 23;
1330 f32::from_bits(sign | e_f32 | (frac << 13))
1331 }
1332 }
1333
1334 fn readback_rgba16f(eng: &Engine, tex: &AuxChannelTex) -> Vec<[f32; 4]> {
1335 let [w, h] = tex.size;
1336 assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float);
1337 let unpadded_bpr = w * 8;
1338 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1339 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
1340 let buf = eng.device.create_buffer(&wgpu::BufferDescriptor {
1341 label: Some("readback-aux-f16"),
1342 size: u64::from(padded_bpr) * u64::from(h),
1343 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1344 mapped_at_creation: false,
1345 });
1346 let mut enc = eng.device.create_command_encoder(&Default::default());
1347 enc.copy_texture_to_buffer(
1348 tex.texture.as_image_copy(),
1349 wgpu::TexelCopyBufferInfo {
1350 buffer: &buf,
1351 layout: wgpu::TexelCopyBufferLayout {
1352 offset: 0,
1353 bytes_per_row: Some(padded_bpr),
1354 rows_per_image: Some(h),
1355 },
1356 },
1357 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
1358 );
1359 eng.queue.submit(Some(enc.finish()));
1360 let slice = buf.slice(..);
1361 let (tx, rx) = std::sync::mpsc::channel();
1362 slice.map_async(wgpu::MapMode::Read, move |res| {
1363 let _ = tx.send(res);
1364 });
1365 eng.device
1366 .poll(wgpu::PollType::Wait {
1367 submission_index: None,
1368 timeout: Some(std::time::Duration::from_secs(10)),
1369 })
1370 .unwrap();
1371 rx.recv().unwrap().unwrap();
1372 let data = slice.get_mapped_range().unwrap();
1373 let mut out = Vec::with_capacity((w * h) as usize);
1374 for y in 0..h as usize {
1375 let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize];
1376 for ch in row.chunks_exact(8) {
1377 out.push([
1378 f16_to_f32(u16::from_le_bytes([ch[0], ch[1]])),
1379 f16_to_f32(u16::from_le_bytes([ch[2], ch[3]])),
1380 f16_to_f32(u16::from_le_bytes([ch[4], ch[5]])),
1381 f16_to_f32(u16::from_le_bytes([ch[6], ch[7]])),
1382 ]);
1383 }
1384 }
1385 drop(data);
1386 buf.unmap();
1387 out
1388 }
1389
1390 fn px_center(px: &[u8], w: u32, h: u32) -> [u8; 4] {
1391 let i = (((h / 2) * w + (w / 2)) * 4) as usize;
1392 [px[i], px[i + 1], px[i + 2], px[i + 3]]
1393 }
1394
1395 /// Helper snippet building a 16x16 float32 image with RGBA `(r,g,b,a)` and `aux.z = z_val`
1396 /// via `CopyAux` Mode 1 + `ChannelBoolean` `ToZBuffer = 18`.
1397 fn z_layer_nodes(prefix: &str, rgba: [f32; 4], z_val: f32) -> String {
1398 format!(
1399 r#"
1400 {prefix}Col = Background {{
1401 Inputs = {{
1402 Width = Input {{ Value = 16, }},
1403 Height = Input {{ Value = 16, }},
1404 Depth = Input {{ Value = 4, }},
1405 TopLeftRed = Input {{ Value = {r}, }},
1406 TopLeftGreen = Input {{ Value = {g}, }},
1407 TopLeftBlue = Input {{ Value = {b}, }},
1408 TopLeftAlpha = Input {{ Value = {a}, }},
1409 }},
1410 }},
1411 {prefix}ZSrc = Background {{
1412 Inputs = {{
1413 Width = Input {{ Value = 16, }},
1414 Height = Input {{ Value = 16, }},
1415 Depth = Input {{ Value = 4, }},
1416 TopLeftRed = Input {{ Value = {z}, }},
1417 TopLeftAlpha = Input {{ Value = 1.0, }},
1418 }},
1419 }},
1420 {prefix}ZAux = Dimension.CopyAux {{
1421 Inputs = {{
1422 Mode = Input {{ Value = 1, }},
1423 Channel = Input {{ Value = FuID {{ "Z" }}, }},
1424 Input = Input {{ SourceOp = "{prefix}ZSrc", Source = "Output", }},
1425 }},
1426 }},
1427 {prefix} = ChannelBoolean {{
1428 Inputs = {{
1429 ToRed = Input {{ Value = 5, }},
1430 ToGreen = Input {{ Value = 6, }},
1431 ToBlue = Input {{ Value = 7, }},
1432 ToAlpha = Input {{ Value = 8, }},
1433 EnableExtraChannels = Input {{ Value = 1, }},
1434 ToZBuffer = Input {{ Value = 18, }},
1435 Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }},
1436 Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }},
1437 }},
1438 }},"#,
1439 r = rgba[0],
1440 g = rgba[1],
1441 b = rgba[2],
1442 a = rgba[3],
1443 z = z_val,
1444 )
1445 }
1446
1447 #[test]
1448 fn merge_perform_depth_merge_all_snow_globe_cases() {
1449 let Ok(mut eng) = Engine::new_headless() else { return };
1450 let src = format!(
1451 r#"Composition {{
1452 CurrentTime = 0,
1453 RenderRange = {{ 0, 1 }},
1454 GlobalRange = {{ 0, 1 }},
1455 Tools = ordered() {{
1456 {}
1457 {}
1458 {}
1459 {}
1460 Plain2DRed = Background {{
1461 Inputs = {{
1462 Width = Input {{ Value = 16, }},
1463 Height = Input {{ Value = 16, }},
1464 Depth = Input {{ Value = 4, }},
1465 TopLeftRed = Input {{ Value = 1.0, }},
1466 TopLeftGreen = Input {{ Value = 0.0, }},
1467 TopLeftBlue = Input {{ Value = 0.0, }},
1468 TopLeftAlpha = Input {{ Value = 1.0, }},
1469 }},
1470 }},
1471 Plain2DGreen = Background {{
1472 Inputs = {{
1473 Width = Input {{ Value = 16, }},
1474 Height = Input {{ Value = 16, }},
1475 Depth = Input {{ Value = 4, }},
1476 TopLeftRed = Input {{ Value = 0.0, }},
1477 TopLeftGreen = Input {{ Value = 1.0, }},
1478 TopLeftBlue = Input {{ Value = 0.0, }},
1479 TopLeftAlpha = Input {{ Value = 1.0, }},
1480 }},
1481 }},
1482 -- 1. Opaque FG near (-2) over BG far (-5): FG wins, Z = -2
1483 M1_FgNear = Merge {{
1484 Inputs = {{
1485 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
1486 Foreground = Input {{ SourceOp = "FgNear", Source = "Output", }},
1487 PerformDepthMerge = Input {{ Value = 1, }},
1488 }},
1489 }},
1490 -- 2. Opaque FG far (-5) over BG near (-2): BG wins completely, Z = -2
1491 M2_FgFar = Merge {{
1492 Inputs = {{
1493 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
1494 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
1495 PerformDepthMerge = Input {{ Value = 1, }},
1496 }},
1497 }},
1498 -- 3. Semi-transparent FG near (-2, a=0.5) over opaque BG far (-5): FG blends over BG, Z = -2
1499 M3_SemiFgNear = Merge {{
1500 Inputs = {{
1501 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
1502 Foreground = Input {{ SourceOp = "SemiNear", Source = "Output", }},
1503 PerformDepthMerge = Input {{ Value = 1, }},
1504 }},
1505 }},
1506 -- 4. Opaque FG far (-5) over semi-transparent BG near (-2, a=0.5): BG blends OVER FG, Z = -2
1507 M4_FgFarOverSemiBgNear = Merge {{
1508 Inputs = {{
1509 Background = Input {{ SourceOp = "SemiNear", Source = "Output", }},
1510 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
1511 PerformDepthMerge = Input {{ Value = 1, }},
1512 }},
1513 }},
1514 -- 5. 2D FG (no Z, implicit 0.0) over Z BG (-5): FG wins, output Z = 0.0!
1515 M5_2dFgOverZBg = Merge {{
1516 Inputs = {{
1517 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
1518 Foreground = Input {{ SourceOp = "Plain2DGreen", Source = "Output", }},
1519 PerformDepthMerge = Input {{ Value = 1, }},
1520 }},
1521 }},
1522 -- 6. Z FG (-5) over 2D BG (no Z, implicit 0.0): BG wins (0.0 > -5.0), output Z = None!
1523 M6_ZFgOver2dBg = Merge {{
1524 Inputs = {{
1525 Background = Input {{ SourceOp = "Plain2DRed", Source = "Output", }},
1526 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
1527 PerformDepthMerge = Input {{ Value = 1, }},
1528 }},
1529 }},
1530 -- 7. PerformDepthMerge = 0: FG far (-5) composited OVER BG near (-2) normally, Z = -5!
1531 M7_NoDepthMerge = Merge {{
1532 Inputs = {{
1533 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
1534 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
1535 PerformDepthMerge = Input {{ Value = 0, }},
1536 }},
1537 }},
1538 -- 8. ForegroundZOffset shifts FG far (-5) by +4 -> -1 (> BG -2), so FG wins!
1539 M8_ZOffset = Merge {{
1540 Inputs = {{
1541 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
1542 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
1543 PerformDepthMerge = Input {{ Value = 1, }},
1544 ForegroundZOffset = Input {{ Value = 4.0, }},
1545 }},
1546 }},
1547 }},
1548 }}"#,
1549 // BgFar: opaque blue (0, 0, 1, 1) at Z = -5.0
1550 z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0),
1551 // FgNear: opaque red (1, 0, 0, 1) at Z = -2.0
1552 z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0),
1553 // SemiNear: semi-transparent premultiplied green (0, 0.5, 0, 0.5) at Z = -2.0
1554 z_layer_nodes("SemiNear", [0.0, 0.5, 0.0, 0.5], -2.0),
1555 // Unused helper just for variety
1556 z_layer_nodes("UnusedExtra", [0.2, 0.3, 0.4, 1.0], -8.0),
1557 );
1558
1559 let comp = Comp::from_fusion_str(&src).expect("parse depth merge comp");
1560 let mut eval_one = |name: &str| -> ([u8; 4], Option<f32>) {
1561 let id = comp.find_node(name).unwrap();
1562 let (tex, stats) = eng.evaluate(&comp, id, 0.0);
1563 assert!(stats.unsupported_nodes.is_empty(), "{name}: {:?}", stats.unsupported_nodes);
1564 let px = eng.readback_rgba(&tex).unwrap();
1565 let c = px_center(&px, tex.size[0], tex.size[1]);
1566 let z = tex.aux.as_ref().and_then(|a| a.z.as_ref()).map(|zt| {
1567 let zs = readback_r32f(&eng, zt);
1568 zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize]
1569 });
1570 (c, z)
1571 };
1572
1573 // 1. Opaque FG near (red, -2) over BG far (blue, -5) -> red, Z = -2
1574 let (c1, z1) = eval_one("M1_FgNear");
1575 assert_eq!(c1, [255, 0, 0, 255], "M1_FgNear color");
1576 assert!((z1.unwrap() - (-2.0)).abs() < 1e-3, "M1_FgNear z={z1:?}");
1577
1578 // 2. Opaque FG far (blue, -5) over BG near (red, -2) -> red (BG wins!), Z = -2
1579 let (c2, z2) = eval_one("M2_FgFar");
1580 assert_eq!(c2, [255, 0, 0, 255], "M2_FgFar color (BG must occlude far FG)");
1581 assert!((z2.unwrap() - (-2.0)).abs() < 1e-3, "M2_FgFar z={z2:?}");
1582
1583 // 3. Semi-transparent FG near (0, 0.5, 0, 0.5 @ -2) over opaque BG far (0, 0, 1, 1 @ -5)
1584 // -> (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2
1585 let (c3, z3) = eval_one("M3_SemiFgNear");
1586 assert_eq!(c3[0], 0);
1587 assert!((c3[1] as i32 - 128).abs() <= 2, "M3 G={c3:?}");
1588 assert!((c3[2] as i32 - 128).abs() <= 2, "M3 B={c3:?}");
1589 assert_eq!(c3[3], 255);
1590 assert!((z3.unwrap() - (-2.0)).abs() < 1e-3, "M3 z={z3:?}");
1591
1592 // 4. Opaque FG far (0, 0, 1, 1 @ -5) over semi-transparent BG near (0, 0.5, 0, 0.5 @ -2)
1593 // -> BG over FG = (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2!
1594 let (c4, z4) = eval_one("M4_FgFarOverSemiBgNear");
1595 assert_eq!(c4[0], 0);
1596 assert!((c4[1] as i32 - 128).abs() <= 2, "M4 G={c4:?}");
1597 assert!((c4[2] as i32 - 128).abs() <= 2, "M4 B={c4:?}");
1598 assert_eq!(c4[3], 255);
1599 assert!((z4.unwrap() - (-2.0)).abs() < 1e-3, "M4 z={z4:?}");
1600
1601 // 5. 2D FG (green, no Z -> implicit 0.0) over Z BG (blue, -5) -> green, Z = 0.0!
1602 let (c5, z5) = eval_one("M5_2dFgOverZBg");
1603 assert_eq!(c5, [0, 255, 0, 255], "M5 2D FG must beat -5 BG");
1604 assert!((z5.unwrap() - 0.0).abs() < 1e-3, "M5 z={z5:?}");
1605
1606 // 6. Z FG (blue, -5) over 2D BG (red, no Z -> implicit 0.0) -> red (BG wins!), Z = None!
1607 let (c6, z6) = eval_one("M6_ZFgOver2dBg");
1608 assert_eq!(c6, [255, 0, 0, 255], "M6 2D BG at 0.0 must occlude -5 FG");
1609 assert!(z6.is_none(), "M6 output Z must be None when BG had no Z, got {z6:?}");
1610
1611 // 7. PerformDepthMerge = 0: FG far (blue, -5) wins over BG near (red, -2), Z = -5!
1612 let (c7, z7) = eval_one("M7_NoDepthMerge");
1613 assert_eq!(c7, [0, 0, 255, 255], "M7 PerformDepthMerge=0 must composite FG over BG");
1614 assert!((z7.unwrap() - (-5.0)).abs() < 1e-3, "M7 z={z7:?}");
1615
1616 // 8. ForegroundZOffset = +4.0 shifts FG (-5 + 4 = -1 > -2) in front of BG -> blue, Z = -1!
1617 let (c8, z8) = eval_one("M8_ZOffset");
1618 assert_eq!(c8, [0, 0, 255, 255], "M8 ZOffset must bring FG in front of BG");
1619 assert!((z8.unwrap() - (-1.0)).abs() < 1e-3, "M8 z={z8:?}");
1620 }
1621
1622 #[test]
1623 fn copy_aux_modes_remap_channels_and_kill_aux() {
1624 let Ok(mut eng) = Engine::new_headless() else { return };
1625 let src = r#"Composition {
1626 CurrentTime = 0,
1627 RenderRange = { 0, 1 },
1628 GlobalRange = { 0, 1 },
1629 Tools = ordered() {
1630 ZData = Background {
1631 Inputs = {
1632 Width = Input { Value = 16, },
1633 Height = Input { Value = 16, },
1634 Depth = Input { Value = 4, },
1635 TopLeftRed = Input { Value = -5.0, },
1636 TopLeftGreen = Input { Value = 0.25, },
1637 TopLeftBlue = Input { Value = 0.75, },
1638 TopLeftAlpha = Input { Value = 1.0, },
1639 },
1640 },
1641 -- Mode 1: Color -> Z (preserves RGBA + sets aux.z = -5.0)
1642 WriteZ = Dimension.CopyAux {
1643 Inputs = {
1644 Mode = Input { Value = 1, },
1645 Channel = Input { Value = FuID { "Z" }, },
1646 Input = Input { SourceOp = "ZData", Source = "Output", },
1647 },
1648 },
1649 -- Mode 0: Z -> Color with Remap -10..0 -> 0..1 (-5.0 -> 0.5 -> ~128)
1650 ReadZRemap = Dimension.CopyAux {
1651 Inputs = {
1652 Mode = Input { Value = 0, },
1653 Channel = Input { Value = FuID { "Z" }, },
1654 ["Z.Remap.Enable"] = Input { Value = 1, },
1655 ["Z.Remap.From.Min"] = Input { Value = -10.0, },
1656 ["Z.Remap.From.Max"] = Input { Value = 0.0, },
1657 ["Z.Remap.To.Min"] = Input { Value = 0.0, },
1658 ["Z.Remap.To.Max"] = Input { Value = 1.0, },
1659 Input = Input { SourceOp = "WriteZ", Source = "Output", },
1660 },
1661 },
1662 -- Mode 0: Z -> Color with Remap + Invert + KillAuxChannels = 1
1663 ReadZInvertKill = Dimension.CopyAux {
1664 Inputs = {
1665 Mode = Input { Value = 0, },
1666 Channel = Input { Value = FuID { "Z" }, },
1667 KillAuxChannels = Input { Value = 1, },
1668 ["Z.Remap.Enable"] = Input { Value = 1, },
1669 ["Z.Remap.From.Min"] = Input { Value = -10.0, },
1670 ["Z.Remap.From.Max"] = Input { Value = 0.0, },
1671 ["Z.Remap.To.Min"] = Input { Value = 0.0, },
1672 ["Z.Remap.To.Max"] = Input { Value = 1.0, },
1673 ["Z.Remap.To.Invert"] = Input { Value = 1, },
1674 Input = Input { SourceOp = "WriteZ", Source = "Output", },
1675 },
1676 },
1677 -- Mode 1 -> Mode 0 for Normal
1678 NormSrc = Background {
1679 Inputs = {
1680 Width = Input { Value = 16, },
1681 Height = Input { Value = 16, },
1682 Depth = Input { Value = 4, },
1683 TopLeftRed = Input { Value = 0.2, },
1684 TopLeftGreen = Input { Value = 0.6, },
1685 TopLeftBlue = Input { Value = 0.8, },
1686 TopLeftAlpha = Input { Value = 1.0, },
1687 },
1688 },
1689 WriteNorm = Dimension.CopyAux {
1690 Inputs = {
1691 Mode = Input { Value = 1, },
1692 Channel = Input { Value = FuID { "Normal" }, },
1693 Input = Input { SourceOp = "NormSrc", Source = "Output", },
1694 },
1695 },
1696 ReadNorm = Dimension.CopyAux {
1697 Inputs = {
1698 Mode = Input { Value = 0, },
1699 Channel = Input { Value = FuID { "Normal" }, },
1700 Input = Input { SourceOp = "WriteNorm", Source = "Output", },
1701 },
1702 },
1703 -- Mode 1 -> Mode 0 for Vector with MinX/MaxX/MinY/MaxY remap
1704 VecSrc = Background {
1705 Inputs = {
1706 Width = Input { Value = 16, },
1707 Height = Input { Value = 16, },
1708 Depth = Input { Value = 4, },
1709 TopLeftRed = Input { Value = 4.0, },
1710 TopLeftGreen = Input { Value = -2.0, },
1711 TopLeftBlue = Input { Value = 0.9, },
1712 TopLeftAlpha = Input { Value = 1.0, },
1713 },
1714 },
1715 WriteVec = Dimension.CopyAux {
1716 Inputs = {
1717 Mode = Input { Value = 1, },
1718 Channel = Input { Value = FuID { "Vector" }, },
1719 Input = Input { SourceOp = "VecSrc", Source = "Output", },
1720 },
1721 },
1722 ReadVec = Dimension.CopyAux {
1723 Inputs = {
1724 Mode = Input { Value = 0, },
1725 Channel = Input { Value = FuID { "Vector" }, },
1726 ["Vector.Remap.Enable"] = Input { Value = 1, },
1727 ["Vector.Remap.From.MinX"] = Input { Value = 0.0, },
1728 ["Vector.Remap.From.MaxX"] = Input { Value = 8.0, },
1729 ["Vector.Remap.From.MinY"] = Input { Value = -4.0, },
1730 ["Vector.Remap.From.MaxY"] = Input { Value = 4.0, },
1731 ["Vector.Remap.To.Min"] = Input { Value = 0.0, },
1732 ["Vector.Remap.To.Max"] = Input { Value = 1.0, },
1733 Input = Input { SourceOp = "WriteVec", Source = "Output", },
1734 },
1735 },
1736 },
1737 }"#;
1738 let comp = Comp::from_fusion_str(src).expect("parse CopyAux comp");
1739
1740 // Mode 1: WriteZ preserves RGBA (G=0.25~64, B=0.75~191) AND sets aux.z = -5.0
1741 let (wz, _) = eng.evaluate(&comp, comp.find_node("WriteZ").unwrap(), 0.0);
1742 let wz_px = px_center(&eng.readback_rgba(&wz).unwrap(), wz.size[0], wz.size[1]);
1743 assert!((wz_px[1] as i32 - 64).abs() <= 2 && (wz_px[2] as i32 - 191).abs() <= 2, "WriteZ RGBA={wz_px:?}");
1744 let wz_z = readback_r32f(&eng, wz.aux.as_ref().unwrap().z.as_ref().unwrap());
1745 assert!((wz_z[8 * 16 + 8] - (-5.0)).abs() < 1e-3, "WriteZ aux.z={}", wz_z[8 * 16 + 8]);
1746
1747 // Mode 0: ReadZRemap maps -5 in [-10..0] -> 0.5 (~128) and preserves aux.z
1748 let (rz, _) = eng.evaluate(&comp, comp.find_node("ReadZRemap").unwrap(), 0.0);
1749 let rz_px = px_center(&eng.readback_rgba(&rz).unwrap(), rz.size[0], rz.size[1]);
1750 assert!((rz_px[0] as i32 - 128).abs() <= 2 && rz_px[0] == rz_px[1] && rz_px[1] == rz_px[2] && rz_px[3] == 255, "ReadZRemap={rz_px:?}");
1751 assert!(rz.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Mode 0 preserves aux when KillAuxChannels=0");
1752
1753 // Mode 0 + KillAuxChannels = 1 clears aux!
1754 let (rzk, _) = eng.evaluate(&comp, comp.find_node("ReadZInvertKill").unwrap(), 0.0);
1755 assert!(rzk.aux.is_none(), "KillAuxChannels=1 must clear aux");
1756
1757 // Normal roundtrip: (0.2, 0.6, 0.8) -> ~(51, 153, 204, 255)
1758 let (rn, _) = eng.evaluate(&comp, comp.find_node("ReadNorm").unwrap(), 0.0);
1759 let rn_px = px_center(&eng.readback_rgba(&rn).unwrap(), rn.size[0], rn.size[1]);
1760 assert!((rn_px[0] as i32 - 51).abs() <= 2 && (rn_px[1] as i32 - 153).abs() <= 2 && (rn_px[2] as i32 - 204).abs() <= 2 && rn_px[3] == 255, "ReadNorm={rn_px:?}");
1761
1762 // Vector remap: vx=4 in [0..8] -> 0.5 (~128), vy=-2 in [-4..4] -> 0.25 (~64), b=0, a=1
1763 let (rv, _) = eng.evaluate(&comp, comp.find_node("ReadVec").unwrap(), 0.0);
1764 let rv_px = px_center(&eng.readback_rgba(&rv).unwrap(), rv.size[0], rv.size[1]);
1765 assert!((rv_px[0] as i32 - 128).abs() <= 2 && (rv_px[1] as i32 - 64).abs() <= 2 && rv_px[2] == 0 && rv_px[3] == 255, "ReadVec={rv_px:?}");
1766 }
1767
1768 #[test]
1769 fn channel_boolean_to_zbuffer_and_color_op_aux_propagation() {
1770 let Ok(mut eng) = Engine::new_headless() else { return };
1771 let src = format!(
1772 r#"Composition {{
1773 CurrentTime = 0,
1774 RenderRange = {{ 0, 1 }},
1775 GlobalRange = {{ 0, 1 }},
1776 Tools = ordered() {{
1777 {}
1778 PlainBg = Background {{
1779 Inputs = {{
1780 Width = Input {{ Value = 16, }},
1781 Height = Input {{ Value = 16, }},
1782 Depth = Input {{ Value = 3, }},
1783 TopLeftRed = Input {{ Value = 0.3, }},
1784 TopLeftGreen = Input {{ Value = 0.6, }},
1785 TopLeftBlue = Input {{ Value = 0.9, }},
1786 TopLeftAlpha = Input {{ Value = 1.0, }},
1787 }},
1788 }},
1789 -- Copy FG's aux.z (-3.5) onto PlainBg while keeping PlainBg's RGBA
1790 CbCopyZ = ChannelBoolean {{
1791 Inputs = {{
1792 ToRed = Input {{ Value = 5, }},
1793 ToGreen = Input {{ Value = 6, }},
1794 ToBlue = Input {{ Value = 7, }},
1795 ToAlpha = Input {{ Value = 8, }},
1796 EnableExtraChannels = Input {{ Value = 1, }},
1797 ToZBuffer = Input {{ Value = 18, }},
1798 Background = Input {{ SourceOp = "PlainBg", Source = "Output", }},
1799 Foreground = Input {{ SourceOp = "ZLayer", Source = "Output", }},
1800 }},
1801 }},
1802 -- Chain every single-input color/depth op to verify aux.z propagation!
1803 N_CC = ColorCorrector {{ Inputs = {{ MasterRGBGain = Input {{ Value = 1.1, }}, Input = Input {{ SourceOp = "CbCopyZ", Source = "Output", }}, }}, }},
1804 N_BC = BrightnessContrast {{ Inputs = {{ Gain = Input {{ Value = 0.95, }}, Input = Input {{ SourceOp = "N_CC", Source = "Output", }}, }}, }},
1805 N_CG = ColorGain {{ Inputs = {{ GainRed = Input {{ Value = 1.05, }}, Input = Input {{ SourceOp = "N_BC", Source = "Output", }}, }}, }},
1806 N_GC = GamutConvert {{ Inputs = {{ SourceSpace = Input {{ Value = FuID {{ "sRGB" }}, }}, OutputSpace = Input {{ Value = FuID {{ "NoChange" }}, }}, Input = Input {{ SourceOp = "N_CG", Source = "Output", }}, }}, }},
1807 N_CD = ChangeDepth {{ Inputs = {{ Depth = Input {{ Value = 4, }}, Input = Input {{ SourceOp = "N_GC", Source = "Output", }}, }}, }},
1808 N_INV = InvertColor {{ Inputs = {{ Input = Input {{ SourceOp = "N_CD", Source = "Output", }}, }}, }},
1809 N_CRV = ColorCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_INV", Source = "Output", }}, }}, }},
1810 N_HUE = HueCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_CRV", Source = "Output", }}, }}, }},
1811 -- ChannelBoolean ToZBuffer = 0 (FG R -> Z) and 16 (White -> 1.0)
1812 CbFgRToZ = ChannelBoolean {{
1813 Inputs = {{
1814 ToRed = Input {{ Value = 5, }},
1815 ToGreen = Input {{ Value = 6, }},
1816 ToBlue = Input {{ Value = 7, }},
1817 ToAlpha = Input {{ Value = 8, }},
1818 EnableExtraChannels = Input {{ Value = 1, }},
1819 ToZBuffer = Input {{ Value = 0, }},
1820 Background = Input {{ SourceOp = "PlainBg", Source = "Output", }},
1821 Foreground = Input {{ SourceOp = "PlainBg", Source = "Output", }},
1822 }},
1823 }},
1824 CbWhiteZ = ChannelBoolean {{
1825 Inputs = {{
1826 ToRed = Input {{ Value = 4, }},
1827 ToGreen = Input {{ Value = 4, }},
1828 ToBlue = Input {{ Value = 4, }},
1829 ToAlpha = Input {{ Value = 4, }},
1830 EnableExtraChannels = Input {{ Value = 1, }},
1831 ToZBuffer = Input {{ Value = 16, }},
1832 Background = Input {{ SourceOp = "PlainBg", Source = "Output", }},
1833 }},
1834 }},
1835 }},
1836 }}"#,
1837 z_layer_nodes("ZLayer", [1.0, 0.0, 0.0, 1.0], -3.5),
1838 );
1839 let comp = Comp::from_fusion_str(&src).expect("parse CB + propagation comp");
1840
1841 // Verify CbCopyZ kept PlainBg RGBA (0.3, 0.6, 0.9) and got aux.z = -3.5
1842 let (cb_tex, _) = eng.evaluate(&comp, comp.find_node("CbCopyZ").unwrap(), 0.0);
1843 let cb_px = px_center(&eng.readback_rgba(&cb_tex).unwrap(), 16, 16);
1844 assert!((cb_px[0] as i32 - 77).abs() <= 2 && (cb_px[2] as i32 - 230).abs() <= 2, "CbCopyZ RGBA={cb_px:?}");
1845 let cb_z = readback_r32f(&eng, cb_tex.aux.as_ref().unwrap().z.as_ref().unwrap());
1846 assert!((cb_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3);
1847
1848 // Verify aux.z survived all 8 color/depth ops!
1849 let (end_tex, _) = eng.evaluate(&comp, comp.find_node("N_HUE").unwrap(), 0.0);
1850 let end_z = readback_r32f(&eng, end_tex.aux.as_ref().expect("aux survived 8 color ops").z.as_ref().unwrap());
1851 assert!((end_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3, "aux.z after 8 ops = {}", end_z[8 * 16 + 8]);
1852
1853 // Verify ToZBuffer = 0 (FG R = 0.3) and ToZBuffer = 16 (White = 1.0)
1854 let (r_tex, _) = eng.evaluate(&comp, comp.find_node("CbFgRToZ").unwrap(), 0.0);
1855 let r_z = readback_r32f(&eng, r_tex.aux.as_ref().unwrap().z.as_ref().unwrap());
1856 assert!((r_z[8 * 16 + 8] - 0.3).abs() < 0.01, "ToZBuffer=0 got {}", r_z[8 * 16 + 8]);
1857
1858 let (w_tex, _) = eng.evaluate(&comp, comp.find_node("CbWhiteZ").unwrap(), 0.0);
1859 let w_z = readback_r32f(&eng, w_tex.aux.as_ref().unwrap().z.as_ref().unwrap());
1860 assert!((w_z[8 * 16 + 8] - 1.0).abs() < 1e-3, "ToZBuffer=16 got {}", w_z[8 * 16 + 8]);
1861 }
1862
1863 #[test]
1864 fn vector_motion_blur_consumes_aux_vector_and_optical_flow() {
1865 let Ok(mut eng) = Engine::new_headless() else { return };
1866 // 1. Sharp vertical white bar on black with synthetic aux.vector = (16.0, 0.0)
1867 // -> VectorMotionBlur smears horizontally into adjacent columns!
1868 let src = r#"Composition {
1869 CurrentTime = 0,
1870 RenderRange = { 0, 5 },
1871 GlobalRange = { 0, 5 },
1872 Tools = ordered() {
1873 Black = Background {
1874 Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1.0, }, },
1875 },
1876 BarMask = RectangleMask {
1877 Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.0625, }, Height = Input { Value = 0.75, }, },
1878 },
1879 WhiteBar = Background {
1880 Inputs = {
1881 Width = Input { Value = 64, },
1882 Height = Input { Value = 64, },
1883 TopLeftRed = Input { Value = 1.0, },
1884 TopLeftGreen = Input { Value = 1.0, },
1885 TopLeftBlue = Input { Value = 1.0, },
1886 TopLeftAlpha = Input { Value = 1.0, },
1887 EffectMask = Input { SourceOp = "BarMask", Source = "Mask", },
1888 },
1889 },
1890 Scene = Merge {
1891 Inputs = {
1892 Background = Input { SourceOp = "Black", Source = "Output", },
1893 Foreground = Input { SourceOp = "WhiteBar", Source = "Output", },
1894 },
1895 },
1896 -- Put vx=20.0, vy=0.0 into aux.vector via CopyAux Mode 1
1897 VecVal = Background {
1898 Inputs = {
1899 Width = Input { Value = 64, },
1900 Height = Input { Value = 64, },
1901 Depth = Input { Value = 4, },
1902 TopLeftRed = Input { Value = 20.0, },
1903 TopLeftGreen = Input { Value = 0.0, },
1904 TopLeftAlpha = Input { Value = 1.0, },
1905 },
1906 },
1907 VecAux = Dimension.CopyAux {
1908 Inputs = {
1909 Mode = Input { Value = 1, },
1910 Channel = Input { Value = FuID { "Vector" }, },
1911 Input = Input { SourceOp = "VecVal", Source = "Output", },
1912 },
1913 },
1914 -- Copy Scene RGBA onto VecAux (ChannelBoolean preserves BG's aux.vector when ToZBuffer=4)
1915 SceneWithAuxVec = ChannelBoolean {
1916 Inputs = {
1917 Background = Input { SourceOp = "VecAux", Source = "Output", },
1918 Foreground = Input { SourceOp = "Scene", Source = "Output", },
1919 ToRed = Input { Value = 0, },
1920 ToGreen = Input { Value = 1, },
1921 ToBlue = Input { Value = 2, },
1922 ToAlpha = Input { Value = 3, },
1923 },
1924 },
1925 VMB = VectorMotionBlur {
1926 Inputs = {
1927 Input = Input { SourceOp = "SceneWithAuxVec", Source = "Output", },
1928 Scale = Input { Value = 1.0, },
1929 },
1930 },
1931 -- 2. Animated moving textured rectangle -> Dimension.OpticalFlow -> VectorMotionBlur
1932 MoveMask = RectangleMask {
1933 Inputs = {
1934 MaskWidth = Input { Value = 64, },
1935 MaskHeight = Input { Value = 64, },
1936 Width = Input { Value = 0.35, },
1937 Height = Input { Value = 0.35, },
1938 Center = Input { Value = { 0.5, 0.5 }, },
1939 },
1940 },
1941 MoveRect = Background {
1942 Inputs = {
1943 Width = Input { Value = 64, },
1944 Height = Input { Value = 64, },
1945 Type = Input { Value = FuID { "Horizontal" }, },
1946 TopLeftRed = Input { Value = 0.1, },
1947 TopLeftGreen = Input { Value = 0.9, },
1948 TopLeftBlue = Input { Value = 0.2, },
1949 TopLeftAlpha = Input { Value = 1.0, },
1950 TopRightRed = Input { Value = 1.0, },
1951 TopRightGreen = Input { Value = 0.1, },
1952 TopRightBlue = Input { Value = 0.8, },
1953 TopRightAlpha = Input { Value = 1.0, },
1954 EffectMask = Input { SourceOp = "MoveMask", Source = "Mask", },
1955 },
1956 },
1957 MoveXf = Merge {
1958 Inputs = {
1959 Background = Input { SourceOp = "Black", Source = "Output", },
1960 Foreground = Input { SourceOp = "MoveRect", Source = "Output", },
1961 Center = Input {
1962 Value = { 0.5, 0.5 },
1963 Expression = "Point(0.4 + time * 0.1, 0.5)",
1964 },
1965 },
1966 },
1967 OF = Dimension.OpticalFlow {
1968 Inputs = { Input = Input { SourceOp = "MoveXf", Source = "Output", }, },
1969 },
1970 OF_VMB = VectorMotionBlur {
1971 Inputs = { Input = Input { SourceOp = "OF", Source = "Output", }, },
1972 },
1973 },
1974 }"#;
1975 let comp = Comp::from_fusion_str(src).expect("parse VMB comp");
1976
1977 // Before blur: pixel at (x=38, y=32) is black (bar spans [30..34]).
1978 let (sc_tex, _) = eng.evaluate(&comp, comp.find_node("SceneWithAuxVec").unwrap(), 0.0);
1979 assert!(sc_tex.aux.as_ref().and_then(|a| a.vector.as_ref()).is_some(), "aux.vector must survive ChannelBoolean");
1980 let sc_px = eng.readback_rgba(&sc_tex).unwrap();
1981 assert_eq!(sc_px[(32 * 64 + 38) * 4], 0, "unblurred pixel at x=38 must be black");
1982
1983 // After VectorMotionBlur consuming aux.vector (vx=20px -> +-10px):
1984 // x=38 (6px right of bar center) smears bright, while y=4 (above bar) stays black!
1985 let (vmb_tex, stats) = eng.evaluate(&comp, comp.find_node("VMB").unwrap(), 0.0);
1986 assert!(stats.unsupported_nodes.is_empty(), "{:?}", stats.unsupported_nodes);
1987 let vmb_px = eng.readback_rgba(&vmb_tex).unwrap();
1988 let smeared = vmb_px[(32 * 64 + 38) * 4];
1989 assert!(smeared > 20, "VectorMotionBlur should smear white bar horizontally to x=38, got {smeared}");
1990 assert_eq!(vmb_px[(4 * 64 + 32) * 4], 0, "horizontal vector should not blur vertically into y=4");
1991
1992 // OpticalFlow attaches both aux.vector and aux.back_vector when VectorMotionBlur is in comp
1993 let (of_tex, _) = eng.evaluate(&comp, comp.find_node("OF").unwrap(), 1.0);
1994 let of_aux = of_tex.aux.as_ref().expect("OpticalFlow must attach aux vectors when VMB exists");
1995 let fwd = readback_rgba16f(&eng, of_aux.vector.as_ref().expect("aux.vector"));
1996 let bwd = readback_rgba16f(&eng, of_aux.back_vector.as_ref().expect("aux.back_vector"));
1997 let c_fwd = fwd[32 * 64 + 32];
1998 let c_bwd = bwd[32 * 64 + 32];
1999 // Box moves +0.1 * 64 = +6.4 px/frame right -> fwd.x > 0, bwd.x < 0!
2000 assert!(c_fwd[0] > 2.0, "expected positive forward flow x, got {c_fwd:?}");
2001 assert!(c_bwd[0] < -2.0, "expected negative backward flow x, got {c_bwd:?}");
2002 }
2003
2004 #[test]
2005 fn depth_merge_transparent_fg_preserves_bg_z_and_non_over_modes_apply_when_bg_closer() {
2006 let Ok(mut eng) = Engine::new_headless() else { return };
2007 let src = format!(
2008 r#"Composition {{
2009 CurrentTime = 0,
2010 RenderRange = {{ 0, 1 }},
2011 GlobalRange = {{ 0, 1 }},
2012 Tools = ordered() {{
2013 {}
2014 {}
2015 {}
2016 Transparent2D = Background {{
2017 Inputs = {{
2018 Width = Input {{ Value = 16, }},
2019 Height = Input {{ Value = 16, }},
2020 TopLeftRed = Input {{ Value = 0.0, }},
2021 TopLeftGreen = Input {{ Value = 0.0, }},
2022 TopLeftBlue = Input {{ Value = 0.0, }},
2023 TopLeftAlpha = Input {{ Value = 0.0, }},
2024 }},
2025 }},
2026 -- Transparent 2D FG (no Z -> implicit 0.0) over BG with Z = -5.0 must keep bg_z = -5.0!
2027 M_Trans2D = Merge {{
2028 Inputs = {{
2029 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
2030 Foreground = Input {{ SourceOp = "Transparent2D", Source = "Output", }},
2031 PerformDepthMerge = Input {{ Value = 1, }},
2032 }},
2033 }},
2034 -- Transparent 3D FG (alpha=0, Z = -2.0) over BG with Z = -5.0 must also keep bg_z = -5.0!
2035 M_Trans3D = Merge {{
2036 Inputs = {{
2037 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
2038 Foreground = Input {{ SourceOp = "TransNear", Source = "Output", }},
2039 PerformDepthMerge = Input {{ Value = 1, }},
2040 }},
2041 }},
2042 -- fg_z (-5) < bg_z (-2) with ApplyMode = Screen: Screen(blue, red) -> magenta!
2043 M_Screen = Merge {{
2044 Inputs = {{
2045 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2046 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2047 PerformDepthMerge = Input {{ Value = 1, }},
2048 ApplyMode = Input {{ Value = FuID {{ "Screen" }}, }},
2049 }},
2050 }},
2051 -- fg_z (-5) < bg_z (-2) with ApplyMode = Multiply: Multiply(blue, red) -> black!
2052 M_Multiply = Merge {{
2053 Inputs = {{
2054 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2055 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2056 PerformDepthMerge = Input {{ Value = 1, }},
2057 ApplyMode = Input {{ Value = FuID {{ "Multiply" }}, }},
2058 }},
2059 }},
2060 -- fg_z (-5) < bg_z (-2) with Operator = Under: swaps BG behind FG -> blue!
2061 M_Under = Merge {{
2062 Inputs = {{
2063 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2064 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2065 PerformDepthMerge = Input {{ Value = 1, }},
2066 Operator = Input {{ Value = FuID {{ "Under" }}, }},
2067 }},
2068 }},
2069 -- fg_z (-5) < bg_z (-2) with Operator = Held Out: bg * (1 - fg.a) -> transparent!
2070 M_HeldOut = Merge {{
2071 Inputs = {{
2072 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2073 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2074 PerformDepthMerge = Input {{ Value = 1, }},
2075 Operator = Input {{ Value = FuID {{ "Held Out" }}, }},
2076 }},
2077 }},
2078 }},
2079 }}"#,
2080 z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0),
2081 z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0),
2082 z_layer_nodes("TransNear", [0.0, 0.0, 0.0, 0.0], -2.0),
2083 );
2084 let comp = Comp::from_fusion_str(&src).expect("parse depth merge regression comp");
2085 let mut eval_one = |name: &str| -> ([u8; 4], f32) {
2086 let id = comp.find_node(name).unwrap();
2087 let (tex, _) = eng.evaluate(&comp, id, 0.0);
2088 let px = eng.readback_rgba(&tex).unwrap();
2089 let c = px_center(&px, tex.size[0], tex.size[1]);
2090 let zt = tex.aux.as_ref().unwrap().z.as_ref().unwrap();
2091 let zs = readback_r32f(&eng, zt);
2092 (c, zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize])
2093 };
2094
2095 let (c_t2d, z_t2d) = eval_one("M_Trans2D");
2096 assert_eq!(c_t2d, [0, 0, 255, 255]);
2097 assert!((z_t2d - (-5.0)).abs() < 1e-3, "transparent 2D FG must preserve bg_z=-5.0, got {z_t2d}");
2098
2099 let (c_t3d, z_t3d) = eval_one("M_Trans3D");
2100 assert_eq!(c_t3d, [0, 0, 255, 255]);
2101 assert!((z_t3d - (-5.0)).abs() < 1e-3, "transparent 3D FG must preserve bg_z=-5.0, got {z_t3d}");
2102
2103 let (c_scr, z_scr) = eval_one("M_Screen");
2104 assert_eq!(c_scr, [255, 0, 255, 255], "Screen when fg_z < bg_z must blend red+blue -> magenta");
2105 assert!((z_scr - (-2.0)).abs() < 1e-3);
2106
2107 let (c_mul, z_mul) = eval_one("M_Multiply");
2108 assert_eq!(c_mul, [0, 0, 0, 255], "Multiply when fg_z < bg_z must yield black");
2109 assert!((z_mul - (-2.0)).abs() < 1e-3);
2110
2111 let (c_und, z_und) = eval_one("M_Under");
2112 assert_eq!(c_und, [0, 0, 255, 255], "Under when fg_z < bg_z must put BG behind FG -> blue");
2113 assert!((z_und - (-2.0)).abs() < 1e-3);
2114
2115 let (c_ho, z_ho) = eval_one("M_HeldOut");
2116 assert_eq!(c_ho, [0, 0, 0, 0], "Held Out when fg_z < bg_z with opaque FG must yield transparent");
2117 assert!((z_ho - (-2.0)).abs() < 1e-3);
2118 }
2119
2120 #[test]
2121 fn copy_aux_mode0_sanitizes_nan_and_inf_pixels() {
2122 let Ok(eng) = Engine::new_headless() else { return };
2123 let z_tex = AuxChannelTex::new(&eng.device, [4, 1], wgpu::TextureFormat::R32Float, "nan-z");
2124 let z_vals: [f32; 4] = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -5.0];
2125 eng.queue.write_texture(
2126 z_tex.texture.as_image_copy(),
2127 bytemuck::cast_slice(&z_vals),
2128 wgpu::TexelCopyBufferLayout {
2129 offset: 0,
2130 bytes_per_row: Some(16),
2131 rows_per_image: Some(1),
2132 },
2133 wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 1 },
2134 );
2135 let src = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2136 let dst_remap = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2137 let dst_raw = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2138
2139 let mut u_remap = UniformParams::default();
2140 u_remap.p[0] = [0.0, 1.0, 0.0, 0.0]; // kind=Z, remap_en=1
2141 u_remap.p[1] = [-10.0, 0.0, 0.0, 1.0]; // -10..0 -> 0..1 (so 0.0 -> 1.0, -5.0 -> 0.5)
2142 u_remap.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1
2143
2144 let mut u_raw = UniformParams::default();
2145 u_raw.p[0] = [0.0, 0.0, 0.0, 0.0]; // kind=Z, remap_en=0
2146 u_raw.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1
2147
2148 let mut enc = eng.device.create_command_encoder(&Default::default());
2149 eng.aux_pipelines().borrow_mut().dispatch_rgba_op(
2150 &eng.device,
2151 &eng.queue,
2152 &mut enc,
2153 false,
2154 &src.view,
2155 &z_tex.view,
2156 &eng.dummy.view,
2157 &dst_remap,
2158 &u_remap,
2159 );
2160 eng.aux_pipelines().borrow_mut().dispatch_rgba_op(
2161 &eng.device,
2162 &eng.queue,
2163 &mut enc,
2164 false,
2165 &src.view,
2166 &z_tex.view,
2167 &eng.dummy.view,
2168 &dst_raw,
2169 &u_raw,
2170 );
2171 eng.queue.submit(Some(enc.finish()));
2172 eng.reset_uniform_cursors();
2173
2174 let remapped = eng.readback_rgba_f32(&dst_remap).expect("readback remapped");
2175 for i in 0..3 {
2176 let v = remapped[i * 4];
2177 assert!(v.is_finite(), "pixel {i} remapped must be finite, got {v}");
2178 assert!((v - 1.0).abs() < 1e-4, "sanitized 0.0 remapped in [-10..0]->[0..1] should be 1.0, got {v}");
2179 }
2180 assert!((remapped[12] - 0.5).abs() < 1e-4, "valid -5.0 remapped should be 0.5, got {}", remapped[12]);
2181
2182 let raw = eng.readback_rgba_f32(&dst_raw).expect("readback raw");
2183 for i in 0..3 {
2184 assert!(raw[i * 4].is_finite() && raw[i * 4] == 0.0, "pixel {i} raw NaN/Inf must sanitize to 0.0, got {}", raw[i * 4]);
2185 }
2186 assert!((raw[12] - (-5.0)).abs() < 1e-4, "valid -5.0 raw should stay -5.0, got {}", raw[12]);
2187 }
2188
2189 #[test]
2190 fn motion_blur_expanded_union_dod_pads_aux_z_with_empty_sentinel() {
2191 let Ok(mut eng) = Engine::new_headless() else { return };
2192 // BgZ and FgZ are both 16x16; MBMerge animates Center.x across 0.25..0.75 with MotionBlur=1,
2193 // Quality=3, ShutterAngle=360 so:
2194 // t=0.5 -> Center.x = 0.375 -> DoD expands left ([-2, 0], 18x16)
2195 // t=1.0 -> Center.x = 0.500 -> center DoD is ([ 0, 0], 16x16) with Z = -1.0
2196 // t=1.5 -> Center.x = 0.625 -> DoD expands right ([ 0, 0], 18x16)
2197 // Union DoD = ([-2, 0], 20x16); center's 16x16 aux.z must be padded to 20x16 with
2198 // EMPTY_Z_SENTINEL in the 2px OOB margins on left and right.
2199 let src = format!(
2200 r#"Composition {{
2201 CurrentTime = 1,
2202 RenderRange = {{ 0, 2 }},
2203 GlobalRange = {{ 0, 2 }},
2204 Tools = ordered() {{
2205 {}
2206 {}
2207 MBMerge = Merge {{
2208 Inputs = {{
2209 Background = Input {{ SourceOp = "BgZ", Source = "Output", }},
2210 Foreground = Input {{ SourceOp = "FgZ", Source = "Output", }},
2211 PerformDepthMerge = Input {{ Value = 1, }},
2212 MotionBlur = Input {{ Value = 1, }},
2213 Quality = Input {{ Value = 3, }},
2214 ShutterAngle = Input {{ Value = 360.0, }},
2215 Center = Input {{
2216 Value = {{ 0.5, 0.5 }},
2217 Expression = "Point(0.25 + time * 0.25, 0.5)",
2218 }},
2219 }},
2220 }},
2221 -- Downstream zoomed-out Transform ensures Merge does not clip its expanded DoD to canvas!
2222 ZoomOut = Transform {{
2223 Inputs = {{
2224 Input = Input {{ SourceOp = "MBMerge", Source = "Output", }},
2225 Size = Input {{ Value = 0.5, }},
2226 }},
2227 }},
2228 }},
2229 }}"#,
2230 z_layer_nodes("BgZ", [0.0, 0.0, 1.0, 1.0], -5.0),
2231 z_layer_nodes("FgZ", [1.0, 0.0, 0.0, 1.0], -1.0),
2232 );
2233 let comp = Comp::from_fusion_str(&src).expect("parse MB DoD aux comp");
2234 let id = comp.find_node("MBMerge").unwrap();
2235
2236 let mut visiting = eng.prepare_frame_scratch(&comp);
2237 let mut stats = EvalStats::default();
2238 let mut enc = eng.device.create_command_encoder(&Default::default());
2239 let out = eng.eval_node(&comp, id, 1.0, &mut enc, &mut visiting, &mut stats);
2240 eng.queue.submit(Some(enc.finish()));
2241 eng.reset_uniform_cursors();
2242 eng.finish_frame_scratch(visiting);
2243
2244 assert!(out.size[0] > 16 && out.origin[0] < 0, "expected expanded union DoD, got origin={:?} size={:?}", out.origin, out.size);
2245 let aux_z = out
2246 .aux
2247 .as_ref()
2248 .expect("MotionBlur output must carry padded aux")
2249 .z
2250 .as_ref()
2251 .expect("MotionBlur output must carry padded aux.z");
2252 assert_eq!(aux_z.size, out.size, "padded aux.z size must match out.size");
2253
2254 let zs = readback_r32f(&eng, aux_z);
2255 let w = out.size[0] as usize;
2256 let row = (out.size[1] / 2) as usize;
2257 let left_oob = zs[row * w];
2258 let right_oob = zs[row * w + (w - 1)];
2259 let center_z = zs[row * w + (w / 2)];
2260 assert_eq!(left_oob, EMPTY_Z_SENTINEL, "left OOB Z must be EMPTY_Z_SENTINEL, got {left_oob}");
2261 assert_eq!(right_oob, EMPTY_Z_SENTINEL, "right OOB Z must be EMPTY_Z_SENTINEL, got {right_oob}");
2262 assert!((center_z - (-1.0)).abs() < 1e-3, "center Z must preserve -1.0, got {center_z}");
2263 }
2264}