1//! Position, Deep Pixel & Optical Flow built-ins:
2//! - Position: `VolumeFog`, `VolumeMask`, `ZtoWorldPos`
3//! - Deep Pixel: `SSAO`, `Shader`, `Texture`
4//! - Optical Flow: `Dimension.RepairFrame`, `Dimension.SmoothMotion`, `Dimension.Tween`,
5//! `PropagateDepth`, `VectorTransform`, `VectorWarp`
6//!
7//! WebGPU safety: every texture input is `filterable: false` (read via `textureLoad`) and the single
8//! output is a `WriteOnly` storage texture whose format token is patched per target (RGBA8/16F/32F or
9//! the `R32Float` / `Rgba16Float` aux channels). Uniform slots grow in 512-slot chunks reset via
10//! `Engine::reset_uniform_cursors()`.
11
12mod deep_pixel;
13mod flow;
14mod position;
15#[cfg(test)]
16mod tests;
17
18use super::*;
19use crate::cache::{AuxChannelTex, AuxChannels};
20use std::num::NonZeroU64;
21use std::sync::Arc;
22
23const DEEP_FLOW_WGSL: &str = include_str!("../shaders/deep_flow.wgsl");
24const DF_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
25const INPUT_PORTS: [&str; 3] = ["Input", "Image", "Background"];
26const EDGES: [&str; 4] = ["Black", "Duplicate", "Wrap", "Mirror"];
27
28fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String {
29 let storage_fmt = match format {
30 wgpu::TextureFormat::Rgba16Float => "rgba16float",
31 wgpu::TextureFormat::Rgba32Float => "rgba32float",
32 wgpu::TextureFormat::R32Float => "r32float",
33 _ => "rgba8unorm",
34 };
35 let mut src = DEEP_FLOW_WGSL.to_owned();
36 if storage_fmt != "rgba8unorm" {
37 src = src.replace(
38 "texture_storage_2d<rgba8unorm, write>",
39 &format!("texture_storage_2d<{storage_fmt}, write>"),
40 );
41 }
42 if hdr_float {
43 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
44 }
45 src
46}
47
48fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
49 wgpu::BindGroupLayoutEntry {
50 binding,
51 visibility: wgpu::ShaderStages::COMPUTE,
52 ty: wgpu::BindingType::Texture {
53 sample_type: wgpu::TextureSampleType::Float { filterable: false },
54 view_dimension: wgpu::TextureViewDimension::D2,
55 multisampled: false,
56 },
57 count: None,
58 }
59}
60
61#[derive(Clone, Copy)]
62enum DeepFlowOp {
63 Mix,
64 VolumeFog,
65 VolumeMask,
66 ZToWorld,
67 Ssao,
68 Relight,
69 Texture,
70 VectorWarp,
71 VectorTransform,
72 VecAccum,
73 DepthWarp,
74 DepthRefine,
75}
76
77impl DeepFlowOp {
78 fn entry(self) -> &'static str {
79 match self {
80 Self::Mix => "mix_op",
81 Self::VolumeFog => "volume_fog_op",
82 Self::VolumeMask => "volume_mask_op",
83 Self::ZToWorld => "z_to_world_op",
84 Self::Ssao => "ssao_op",
85 Self::Relight => "relight_op",
86 Self::Texture => "texture_op",
87 Self::VectorWarp => "vector_warp_op",
88 Self::VectorTransform => "vector_transform_op",
89 Self::VecAccum => "vec_accum_op",
90 Self::DepthWarp => "depth_warp_op",
91 Self::DepthRefine => "depth_refine_op",
92 }
93 }
94}
95
96/// Output storage target of one dispatch: an RGBA node texture or an aux channel texture.
97struct Dst<'a> {
98 view: &'a wgpu::TextureView,
99 size: [u32; 2],
100 format: wgpu::TextureFormat,
101 hdr_float: bool,
102}
103
104impl<'a> Dst<'a> {
105 fn color(t: &'a CachedTexture) -> Self {
106 Self { view: &t.view, size: t.size, format: t.format, hdr_float: t.depth.is_float() }
107 }
108
109 fn aux(t: &'a AuxChannelTex) -> Self {
110 Self { view: &t.view, size: t.size, format: t.format, hdr_float: true }
111 }
112}
113
114struct FormatPipelines {
115 bgl: wgpu::BindGroupLayout,
116 layout: wgpu::PipelineLayout,
117 module: wgpu::ShaderModule,
118 ops: HashMap<&'static str, wgpu::ComputePipeline>,
119}
120
121impl FormatPipelines {
122 fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self {
123 let tex = unfilterable_tex_entry;
124 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
125 label: Some("deep-flow-bgl"),
126 entries: &[
127 tex(0),
128 tex(1),
129 tex(2),
130 tex(3),
131 tex(4),
132 wgpu::BindGroupLayoutEntry {
133 binding: 5,
134 visibility: wgpu::ShaderStages::COMPUTE,
135 ty: wgpu::BindingType::StorageTexture {
136 access: wgpu::StorageTextureAccess::WriteOnly,
137 format,
138 view_dimension: wgpu::TextureViewDimension::D2,
139 },
140 count: None,
141 },
142 wgpu::BindGroupLayoutEntry {
143 binding: 6,
144 visibility: wgpu::ShaderStages::COMPUTE,
145 ty: wgpu::BindingType::Buffer {
146 ty: wgpu::BufferBindingType::Uniform,
147 has_dynamic_offset: true,
148 min_binding_size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
149 },
150 count: None,
151 },
152 ],
153 });
154 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
155 label: Some("deep-flow-pl"),
156 bind_group_layouts: &[Some(&bgl)],
157 immediate_size: 0,
158 });
159 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
160 label: Some("deep-flow-wgsl"),
161 source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()),
162 });
163 Self { bgl, layout, module, ops: HashMap::new() }
164 }
165
166 fn ensure(&mut self, device: &wgpu::Device, op: DeepFlowOp) {
167 let entry = op.entry();
168 if self.ops.contains_key(entry) {
169 return;
170 }
171 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
172 label: Some(entry),
173 layout: Some(&self.layout),
174 module: &self.module,
175 entry_point: Some(entry),
176 compilation_options: Default::default(),
177 cache: None,
178 });
179 self.ops.insert(entry, pipeline);
180 }
181}
182
183pub(crate) struct DeepFlowPipelines {
184 uniform_stride: u32,
185 uniform_chunks: Vec<wgpu::Buffer>,
186 uniform_cursor: u32,
187 by_format: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>,
188}
189
190impl DeepFlowPipelines {
191 pub(super) fn new(device: &wgpu::Device) -> Self {
192 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
193 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
194 Self {
195 uniform_stride: uniform_size.div_ceil(min_align) * min_align,
196 uniform_chunks: Vec::new(),
197 uniform_cursor: 0,
198 by_format: HashMap::new(),
199 }
200 }
201
202 pub(super) fn reset_uniform_cursor(&mut self) {
203 self.uniform_cursor = 0;
204 }
205
206 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
207 self.uniform_cursor = 0;
208 self.uniform_chunks.truncate(max_chunks);
209 }
210
211 fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) {
212 let slot_global = self.uniform_cursor;
213 let chunk_idx = (slot_global / DF_UNIFORM_SLOTS_PER_CHUNK) as usize;
214 let slot_in_chunk = slot_global % DF_UNIFORM_SLOTS_PER_CHUNK;
215 while chunk_idx >= self.uniform_chunks.len() {
216 self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor {
217 label: Some("deep-flow-params-ring"),
218 size: u64::from(DF_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride),
219 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
220 mapped_at_creation: false,
221 }));
222 }
223 let offset = slot_in_chunk * self.uniform_stride;
224 queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params));
225 self.uniform_cursor = slot_global + 1;
226 (chunk_idx, offset)
227 }
228
229 #[allow(clippy::too_many_arguments)]
230 fn dispatch(
231 &mut self,
232 device: &wgpu::Device,
233 queue: &wgpu::Queue,
234 enc: &mut wgpu::CommandEncoder,
235 op: DeepFlowOp,
236 srcs: [&wgpu::TextureView; 4],
237 mask: &wgpu::TextureView,
238 dst: &Dst,
239 params: &UniformParams,
240 ) {
241 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
242 let fp = self
243 .by_format
244 .entry((dst.format, dst.hdr_float))
245 .or_insert_with(|| FormatPipelines::new(device, dst.format, dst.hdr_float));
246 fp.ensure(device, op);
247 let fp: &FormatPipelines = fp;
248 let [a, b, c, d] = srcs;
249 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
250 label: Some("deep-flow-bg"),
251 layout: &fp.bgl,
252 entries: &[
253 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(a) },
254 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(b) },
255 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(c) },
256 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(d) },
257 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) },
258 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(dst.view) },
259 wgpu::BindGroupEntry {
260 binding: 6,
261 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
262 buffer: &self.uniform_chunks[chunk_idx],
263 offset: 0,
264 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
265 }),
266 },
267 ],
268 });
269 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
270 label: Some("deep-flow-pass"),
271 timestamp_writes: None,
272 });
273 pass.set_pipeline(&fp.ops[op.entry()]);
274 pass.set_bind_group(0, &bg, &[offset]);
275 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
276 }
277}
278
279fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 {
280 keys.iter()
281 .find(|&&k| node.inputs.contains_key(k))
282 .map_or(default, |&k| comp.eval_number(node, k, time, default, expr))
283}
284
285fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> {
286 ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s)))
287}
288
289fn b2f(v: bool) -> f32 {
290 if v { 1.0 } else { 0.0 }
291}
292
293/// Enum input given as a `FuID` string (case/space/underscore-insensitive match against `names`) or a numeric index.
294fn enum_idx(comp: &Comp, node: &Node, key: &str, names: &[&str], time: f64, default: usize, expr: &ExprEngine) -> usize {
295 let norm = |s: &str| s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
296 if let Some(s) = node.static_str(key) {
297 let s = norm(s);
298 return names.iter().position(|n| norm(n) == s).unwrap_or(default);
299 }
300 (comp.eval_number(node, key, time, default as f64, expr).round().max(0.0) as usize).min(names.len() - 1)
301}
302
303/// Blend / `EffectMask` / `MultiplyByMask` / `Process*` tail shared by every deep-flow kernel
304/// (uniform slots `p[14]` and `p[15]`).
305struct Fin {
306 blend: f32,
307 mbm: bool,
308 mask: Option<CachedTexture>,
309 invert: bool,
310 skip: [f32; 4],
311}
312
313impl Fin {
314 fn pack(&self, u: &mut UniformParams) {
315 u.p[14] = self.skip;
316 u.p[15] = [self.blend, b2f(self.mask.is_some()), b2f(self.invert), b2f(self.mask.is_some() && self.mbm)];
317 }
318
319 fn mask_hash(&self) -> u64 {
320 self.mask.as_ref().map_or(0, |m| m.content_hash)
321 }
322
323 /// True when the pass would return its effect unchanged.
324 fn is_identity(&self) -> bool {
325 self.blend >= 1.0 - 1e-6 && self.mask.is_none() && self.skip == [0.0; 4]
326 }
327}
328
329/// One standard cached RGBA pass over up to four source textures.
330struct DfPass<'a> {
331 tag: &'static str,
332 op: DeepFlowOp,
333 srcs: [Option<&'a wgpu::TextureView>; 4],
334 /// Content hashes of every source that influences the result.
335 hashes: &'a [u64],
336 size: [u32; 2],
337 depth: BitDepth,
338}
339
340impl Engine {
341 fn deep_flow_pipelines(&self) -> &RefCell<DeepFlowPipelines> {
342 self.deep_flow.get_or_init(|| RefCell::new(DeepFlowPipelines::new(&self.device)))
343 }
344
345 #[allow(clippy::too_many_arguments)]
346 fn dispatch_df(
347 &self,
348 enc: &mut wgpu::CommandEncoder,
349 op: DeepFlowOp,
350 srcs: [Option<&wgpu::TextureView>; 4],
351 mask: Option<&CachedTexture>,
352 dst: &Dst,
353 params: &UniformParams,
354 ) {
355 let d = &*self.dummy.view;
356 let [a, b, c, e] = srcs.map(|s| s.unwrap_or(d));
357 self.deep_flow_pipelines().borrow_mut().dispatch(
358 &self.device,
359 &self.queue,
360 enc,
361 op,
362 [a, b, c, e],
363 mask.map_or(d, |m| &m.view),
364 dst,
365 params,
366 );
367 }
368
369 /// `Blend` and whether `MultiplyByMask` forces evaluation even at `Blend = 0`.
370 fn df_blend(&self, comp: &Comp, node: &Node, time: f64) -> (f32, bool) {
371 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
372 (blend.clamp(0.0, 1.0), self.multiplies_by_mask(comp, node, time))
373 }
374
375 #[allow(clippy::too_many_arguments)]
376 fn df_fin(
377 &mut self,
378 comp: &Comp,
379 node: &Node,
380 time: f64,
381 blend: (f32, bool),
382 size: [u32; 2],
383 enc: &mut wgpu::CommandEncoder,
384 visiting: &mut HashSet<(NodeId, i64)>,
385 stats: &mut EvalStats,
386 ) -> Fin {
387 let (mask, invert) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
388 Fin { blend: blend.0, mbm: blend.1, mask, invert, skip: self.process_skip(comp, node, time) }
389 }
390
391 /// First connected image among `ports`, evaluated at `time` and cropped to the canvas.
392 #[allow(clippy::too_many_arguments)]
393 fn df_input(
394 &mut self,
395 comp: &Comp,
396 node: &Node,
397 ports: &[&str],
398 time: f64,
399 enc: &mut wgpu::CommandEncoder,
400 visiting: &mut HashSet<(NodeId, i64)>,
401 stats: &mut EvalStats,
402 ) -> Option<CachedTexture> {
403 let id = conn_any(comp, node, ports)?;
404 let tex = self.eval_node(comp, id, time, enc, visiting, stats);
405 Some(self.crop_to_canvas(enc, tex))
406 }
407
408 /// Cache lookup that records a hit, or a miss followed by an evaluation.
409 fn df_hit(&mut self, key: u64, node: &Node, frame_i: i64, stats: &mut EvalStats) -> Option<CachedTexture> {
410 let hit = self.cache.get(key, node.id, frame_i);
411 if hit.is_some() {
412 stats.cache_hits += 1;
413 } else {
414 stats.cache_misses += 1;
415 stats.nodes_evaluated += 1;
416 }
417 hit
418 }
419
420 /// Cached RGBA pass writing a new node texture (`aux` is attached to the result).
421 #[allow(clippy::too_many_arguments)]
422 fn df_run(
423 &mut self,
424 node: &Node,
425 frame_i: i64,
426 pass: DfPass,
427 fin: &Fin,
428 params: &UniformParams,
429 aux: Option<Arc<AuxChannels>>,
430 enc: &mut wgpu::CommandEncoder,
431 stats: &mut EvalStats,
432 ) -> CachedTexture {
433 let mut u = *params;
434 fin.pack(&mut u);
435 let mut upstream = pass.hashes.to_vec();
436 upstream.extend([fin.mask_hash(), pass.depth as u64]);
437 let key = self.make_key(node, pass.tag, pass.size, &upstream, bytemuck::cast_slice(&u.p));
438 if let Some(hit) = self.df_hit(key, node, frame_i, stats) {
439 return hit;
440 }
441 let mut dst = self.alloc_tex(pass.size, pass.depth, key);
442 self.dispatch_df(enc, pass.op, pass.srcs, fin.mask.as_ref(), &Dst::color(&dst), &u);
443 dst.set_aux(aux);
444 self.cache.insert(key, dst.clone(), node.id, frame_i);
445 dst
446 }
447
448 /// Uncached pass writing a fresh aux channel texture of `format`.
449 #[allow(clippy::too_many_arguments)]
450 fn df_aux_pass(
451 &self,
452 enc: &mut wgpu::CommandEncoder,
453 op: DeepFlowOp,
454 srcs: [Option<&wgpu::TextureView>; 4],
455 fin: &Fin,
456 params: &UniformParams,
457 size: [u32; 2],
458 format: wgpu::TextureFormat,
459 ) -> AuxChannelTex {
460 let mut u = *params;
461 fin.pack(&mut u);
462 u.p[14] = [0.0; 4]; // aux channels are data, not colour: `Process*` never applies
463 let out = AuxChannelTex::new(&self.device, size, format, "deep-flow-aux");
464 self.dispatch_df(enc, op, srcs, fin.mask.as_ref(), &Dst::aux(&out), &u);
465 out
466 }
467
468 /// Re-keys a texture that shares `src`'s pixels but carries new aux channels.
469 fn df_with_aux(&mut self, node: &Node, frame_i: i64, key: u64, mut out: CachedTexture, aux: AuxChannels) -> CachedTexture {
470 out.content_hash = key;
471 out.set_aux(Some(Arc::new(aux)));
472 self.cache.insert(key, out.clone(), node.id, frame_i);
473 out
474 }
475}