| 1 | //! Wave 62 GPU pipelines & evaluators — Fusion Warp, Filter, Film, Mask & Classic Built-ins: |
| 2 | //! 1. `Distort` — Map-driven UV distortion / lens-style radial distortion |
| 3 | //! 2. `CreateBumpMap` — Tangent-space Sobel 3x3 / 5x5 normal/bump map |
| 4 | //! 3. `CreateReliefMap` — Relief / Cone / RelaxedCone height+normal map & shaded emboss |
| 5 | //! 4. `CustomFilter` — User-defined 3x3 / 5x5 / 7x7 convolution kernel |
| 6 | //! 5. `CineonLog` — Kodak Cineon 10-bit Log<->Lin & camera log curves |
| 7 | //! 6. `LightTrim` — Printer-lights / log-trim / stops exposure grading |
| 8 | //! 7. `MultiPoly` — Multi-shape composite polygon & B-spline mask container |
| 9 | //! 8. `RangesMask` — Luminance / channel range mask (`ColorRanges` or `Low`/`High`) |
| 10 | //! 9. `TeapotMask` — Procedural Utah teapot silhouette mask |
| 11 | //! 10. `TV` — Classic CRT scanlines, sync jitter, noise, roll bar |
| 12 | //! 11. `AutoDomain` — Tight non-zero bounding box (DoD) computation preserving aux & HDR |
| 13 | //! 12. `Fuse.FrameAverage` — Temporal frame-averaging blur/denoise with cycle protection |
| 14 | //! |
| 15 | //! WebGPU safety: all texture inputs use `TextureSampleType::Float { filterable: false }` |
| 16 | //! (read exclusively via `textureLoad`), outputs are `WriteOnly` storage textures patched via |
| 17 | //! [`patch_storage_format`], and uniform slots grow in 512-slot chunks reset via |
| 18 | //! `Engine::reset_uniform_cursors()`. |
| 19 | |
| 20 | mod film; |
| 21 | mod masks_fx; |
| 22 | #[cfg(test)] |
| 23 | mod tests; |
| 24 | mod util; |
| 25 | mod warp_filter; |
| 26 | |
| 27 | use super::*; |
| 28 | use std::num::NonZeroU64; |
| 29 | |
| 30 | const SURFACE_FX_WGSL: &str = include_str!("../shaders/surface_fx.wgsl"); |
| 31 | const SFX_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 32 | |
| 33 | fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 34 | let storage_fmt = match format { |
| 35 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 36 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 37 | _ => "rgba8unorm", |
| 38 | }; |
| 39 | let mut src = SURFACE_FX_WGSL.to_owned(); |
| 40 | if storage_fmt != "rgba8unorm" { |
| 41 | src = src.replace( |
| 42 | "texture_storage_2d<rgba8unorm, write>", |
| 43 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 44 | ); |
| 45 | } |
| 46 | if hdr_float { |
| 47 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 48 | } |
| 49 | src |
| 50 | } |
| 51 | |
| 52 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { |
| 53 | wgpu::BindGroupLayoutEntry { |
| 54 | binding, |
| 55 | visibility: wgpu::ShaderStages::COMPUTE, |
| 56 | ty: wgpu::BindingType::Texture { |
| 57 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 58 | view_dimension: wgpu::TextureViewDimension::D2, |
| 59 | multisampled: false, |
| 60 | }, |
| 61 | count: None, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 66 | pub(self) enum SurfaceFxOp { |
| 67 | Distort, |
| 68 | CreateBumpMap, |
| 69 | CreateReliefMap, |
| 70 | CustomFilter, |
| 71 | CineonLog, |
| 72 | LightTrim, |
| 73 | RangesMask, |
| 74 | Tv, |
| 75 | #[cfg_attr(target_arch = "wasm32", allow(dead_code))] |
| 76 | AutoDomainReduce1, |
| 77 | AutoDomainReduce2, |
| 78 | FrameAvgAccum, |
| 79 | FrameAvgFinish, |
| 80 | } |
| 81 | |
| 82 | struct SurfaceFxFormatPipelines { |
| 83 | bgl: wgpu::BindGroupLayout, |
| 84 | distort: wgpu::ComputePipeline, |
| 85 | create_bump_map: wgpu::ComputePipeline, |
| 86 | create_relief_map: wgpu::ComputePipeline, |
| 87 | custom_filter: wgpu::ComputePipeline, |
| 88 | cineon_log: wgpu::ComputePipeline, |
| 89 | light_trim: wgpu::ComputePipeline, |
| 90 | ranges_mask: wgpu::ComputePipeline, |
| 91 | tv: wgpu::ComputePipeline, |
| 92 | auto_domain_reduce1: wgpu::ComputePipeline, |
| 93 | auto_domain_reduce2: wgpu::ComputePipeline, |
| 94 | frame_avg_accum: wgpu::ComputePipeline, |
| 95 | frame_avg_finish: wgpu::ComputePipeline, |
| 96 | } |
| 97 | |
| 98 | impl SurfaceFxFormatPipelines { |
| 99 | fn pipeline(&self, op: SurfaceFxOp) -> &wgpu::ComputePipeline { |
| 100 | match op { |
| 101 | SurfaceFxOp::Distort => &self.distort, |
| 102 | SurfaceFxOp::CreateBumpMap => &self.create_bump_map, |
| 103 | SurfaceFxOp::CreateReliefMap => &self.create_relief_map, |
| 104 | SurfaceFxOp::CustomFilter => &self.custom_filter, |
| 105 | SurfaceFxOp::CineonLog => &self.cineon_log, |
| 106 | SurfaceFxOp::LightTrim => &self.light_trim, |
| 107 | SurfaceFxOp::RangesMask => &self.ranges_mask, |
| 108 | SurfaceFxOp::Tv => &self.tv, |
| 109 | SurfaceFxOp::AutoDomainReduce1 => &self.auto_domain_reduce1, |
| 110 | SurfaceFxOp::AutoDomainReduce2 => &self.auto_domain_reduce2, |
| 111 | SurfaceFxOp::FrameAvgAccum => &self.frame_avg_accum, |
| 112 | SurfaceFxOp::FrameAvgFinish => &self.frame_avg_finish, |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | pub(crate) struct SurfaceFxPipelines { |
| 118 | uniform_stride: u32, |
| 119 | uniform_chunks: Vec<wgpu::Buffer>, |
| 120 | uniform_cursor: u32, |
| 121 | by_format: HashMap<(wgpu::TextureFormat, bool), SurfaceFxFormatPipelines>, |
| 122 | } |
| 123 | |
| 124 | impl SurfaceFxPipelines { |
| 125 | pub(super) fn new(device: &wgpu::Device) -> Self { |
| 126 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 127 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 128 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 129 | Self { |
| 130 | uniform_stride, |
| 131 | uniform_chunks: Vec::new(), |
| 132 | uniform_cursor: 0, |
| 133 | by_format: HashMap::new(), |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | pub(super) fn reset_uniform_cursor(&mut self) { |
| 138 | self.uniform_cursor = 0; |
| 139 | } |
| 140 | |
| 141 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 142 | self.uniform_cursor = 0; |
| 143 | if self.uniform_chunks.len() > max_chunks { |
| 144 | self.uniform_chunks.truncate(max_chunks); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | fn alloc_uniform_slot( |
| 149 | &mut self, |
| 150 | device: &wgpu::Device, |
| 151 | queue: &wgpu::Queue, |
| 152 | params: &UniformParams, |
| 153 | ) -> (usize, u32) { |
| 154 | let slot_global = self.uniform_cursor; |
| 155 | let chunk_idx = (slot_global / SFX_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 156 | let slot_in_chunk = slot_global % SFX_UNIFORM_SLOTS_PER_CHUNK; |
| 157 | while chunk_idx >= self.uniform_chunks.len() { |
| 158 | let size = u64::from(SFX_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 159 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 160 | label: Some("surface-fx-params-ring"), |
| 161 | size, |
| 162 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 163 | mapped_at_creation: false, |
| 164 | }); |
| 165 | self.uniform_chunks.push(buf); |
| 166 | } |
| 167 | let offset = slot_in_chunk * self.uniform_stride; |
| 168 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); |
| 169 | self.uniform_cursor = slot_global + 1; |
| 170 | (chunk_idx, offset) |
| 171 | } |
| 172 | |
| 173 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 174 | if self.by_format.contains_key(&(format, hdr_float)) { |
| 175 | return; |
| 176 | } |
| 177 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 178 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 179 | label: Some("surface-fx-bgl"), |
| 180 | entries: &[ |
| 181 | unfilterable_tex_entry(0), |
| 182 | unfilterable_tex_entry(1), |
| 183 | unfilterable_tex_entry(2), |
| 184 | wgpu::BindGroupLayoutEntry { |
| 185 | binding: 3, |
| 186 | visibility: wgpu::ShaderStages::COMPUTE, |
| 187 | ty: wgpu::BindingType::StorageTexture { |
| 188 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 189 | format, |
| 190 | view_dimension: wgpu::TextureViewDimension::D2, |
| 191 | }, |
| 192 | count: None, |
| 193 | }, |
| 194 | wgpu::BindGroupLayoutEntry { |
| 195 | binding: 4, |
| 196 | visibility: wgpu::ShaderStages::COMPUTE, |
| 197 | ty: wgpu::BindingType::Buffer { |
| 198 | ty: wgpu::BufferBindingType::Uniform, |
| 199 | has_dynamic_offset: true, |
| 200 | min_binding_size: NonZeroU64::new(u_size), |
| 201 | }, |
| 202 | count: None, |
| 203 | }, |
| 204 | ], |
| 205 | }); |
| 206 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 207 | label: Some("surface-fx-pl"), |
| 208 | bind_group_layouts: &[Some(&bgl)], |
| 209 | immediate_size: 0, |
| 210 | }); |
| 211 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 212 | label: Some("surface-fx-wgsl"), |
| 213 | source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()), |
| 214 | }); |
| 215 | let mk = |entry: &str| { |
| 216 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 217 | label: Some(entry), |
| 218 | layout: Some(&pl), |
| 219 | module: &module, |
| 220 | entry_point: Some(entry), |
| 221 | compilation_options: Default::default(), |
| 222 | cache: None, |
| 223 | }) |
| 224 | }; |
| 225 | self.by_format.insert( |
| 226 | (format, hdr_float), |
| 227 | SurfaceFxFormatPipelines { |
| 228 | bgl, |
| 229 | distort: mk("distort_op"), |
| 230 | create_bump_map: mk("create_bump_map_op"), |
| 231 | create_relief_map: mk("create_relief_map_op"), |
| 232 | custom_filter: mk("custom_filter_op"), |
| 233 | cineon_log: mk("cineon_log_op"), |
| 234 | light_trim: mk("light_trim_op"), |
| 235 | ranges_mask: mk("ranges_mask_op"), |
| 236 | tv: mk("tv_op"), |
| 237 | auto_domain_reduce1: mk("auto_domain_reduce1_op"), |
| 238 | auto_domain_reduce2: mk("auto_domain_reduce2_op"), |
| 239 | frame_avg_accum: mk("frame_avg_accum_op"), |
| 240 | frame_avg_finish: mk("frame_avg_finish_op"), |
| 241 | }, |
| 242 | ); |
| 243 | } |
| 244 | |
| 245 | #[allow(clippy::too_many_arguments)] |
| 246 | fn dispatch( |
| 247 | &mut self, |
| 248 | device: &wgpu::Device, |
| 249 | queue: &wgpu::Queue, |
| 250 | enc: &mut wgpu::CommandEncoder, |
| 251 | op: SurfaceFxOp, |
| 252 | src_a: &wgpu::TextureView, |
| 253 | src_b: &wgpu::TextureView, |
| 254 | mask: &wgpu::TextureView, |
| 255 | dst: &CachedTexture, |
| 256 | params: &UniformParams, |
| 257 | ) { |
| 258 | let hdr_float = dst.depth.is_float(); |
| 259 | self.ensure_format(device, dst.format, hdr_float); |
| 260 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 261 | let fp = &self.by_format[&(dst.format, hdr_float)]; |
| 262 | let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64); |
| 263 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 264 | label: Some("surface-fx-bg"), |
| 265 | layout: &fp.bgl, |
| 266 | entries: &[ |
| 267 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, |
| 268 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, |
| 269 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, |
| 270 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&dst.view) }, |
| 271 | wgpu::BindGroupEntry { |
| 272 | binding: 4, |
| 273 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 274 | buffer: &self.uniform_chunks[chunk_idx], |
| 275 | offset: 0, |
| 276 | size: u_size, |
| 277 | }), |
| 278 | }, |
| 279 | ], |
| 280 | }); |
| 281 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 282 | label: Some("surface-fx-pass"), |
| 283 | timestamp_writes: None, |
| 284 | }); |
| 285 | pass.set_pipeline(fp.pipeline(op)); |
| 286 | pass.set_bind_group(0, &bg, &[offset]); |
| 287 | if op == SurfaceFxOp::AutoDomainReduce2 { |
| 288 | pass.dispatch_workgroups(1, 1, 1); |
| 289 | } else { |
| 290 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | pub(self) fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { |
| 296 | keys.iter() |
| 297 | .find(|&&k| node.inputs.contains_key(k)) |
| 298 | .map_or(default, |&k| comp.eval_number(node, k, time, default, expr)) |
| 299 | } |
| 300 | |
| 301 | pub(self) fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> { |
| 302 | ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) |
| 303 | } |
| 304 | |
| 305 | pub(self) fn str_any<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { |
| 306 | keys.iter().find_map(|k| node.static_str(k)) |
| 307 | } |
| 308 | |
| 309 | pub(self) fn b2f(v: bool) -> f32 { |
| 310 | if v { 1.0 } else { 0.0 } |
| 311 | } |
| 312 | |
| 313 | pub(self) fn source_channel_id(s: Option<&str>, fallback: f64) -> f32 { |
| 314 | match s { |
| 315 | Some(v) if v.eq_ignore_ascii_case("luminance") || v.eq_ignore_ascii_case("luma") => 0.0, |
| 316 | Some(v) if v.eq_ignore_ascii_case("average") || v.eq_ignore_ascii_case("avg") => 1.0, |
| 317 | Some(v) if v.eq_ignore_ascii_case("max") || v.eq_ignore_ascii_case("maximum") => 2.0, |
| 318 | Some(v) if v.eq_ignore_ascii_case("min") || v.eq_ignore_ascii_case("minimum") => 3.0, |
| 319 | Some(v) if v.eq_ignore_ascii_case("red") => 4.0, |
| 320 | Some(v) if v.eq_ignore_ascii_case("green") => 5.0, |
| 321 | Some(v) if v.eq_ignore_ascii_case("blue") => 6.0, |
| 322 | Some(v) if v.eq_ignore_ascii_case("alpha") => 7.0, |
| 323 | _ => fallback.round().clamp(0.0, 7.0) as f32, |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | pub(self) fn resolve_texture_depth(comp: &Comp, node: &Node, time: f64, fallback: BitDepth, expr: &ExprEngine) -> BitDepth { |
| 328 | if let Some(s) = node.static_str("TextureDepth") { |
| 329 | return match s { |
| 330 | "int8" => BitDepth::Int8, |
| 331 | "int16" => BitDepth::Int16, |
| 332 | "float16" => BitDepth::Float16, |
| 333 | "float32" => BitDepth::Float32, |
| 334 | _ => fallback, |
| 335 | }; |
| 336 | } |
| 337 | let d = comp.eval_number(node, "TextureDepth", time, 0.0, expr).round() as i32; |
| 338 | BitDepth::from_fusion_depth(d).unwrap_or(fallback) |
| 339 | } |
| 340 | |
| 341 | impl Engine { |
| 342 | fn surface_fx_pipelines(&self) -> &RefCell<SurfaceFxPipelines> { |
| 343 | self.surface_fx |
| 344 | .get_or_init(|| RefCell::new(SurfaceFxPipelines::new(&self.device))) |
| 345 | } |
| 346 | |
| 347 | #[allow(clippy::too_many_arguments)] |
| 348 | pub(self) fn dispatch_sfx( |
| 349 | &self, |
| 350 | enc: &mut wgpu::CommandEncoder, |
| 351 | op: SurfaceFxOp, |
| 352 | src_a: &wgpu::TextureView, |
| 353 | src_b: &wgpu::TextureView, |
| 354 | mask: &wgpu::TextureView, |
| 355 | dst: &CachedTexture, |
| 356 | params: &UniformParams, |
| 357 | ) { |
| 358 | self.surface_fx_pipelines() |
| 359 | .borrow_mut() |
| 360 | .dispatch(&self.device, &self.queue, enc, op, src_a, src_b, mask, dst, params); |
| 361 | } |
| 362 | |
| 363 | #[allow(clippy::too_many_arguments)] |
| 364 | pub(self) fn run_sfx_filter( |
| 365 | &mut self, |
| 366 | node: &Node, |
| 367 | op_tag: &'static str, |
| 368 | op: SurfaceFxOp, |
| 369 | src_a: &CachedTexture, |
| 370 | src_b: &wgpu::TextureView, |
| 371 | src_b_hash: u64, |
| 372 | mask: Option<&CachedTexture>, |
| 373 | dst_depth: BitDepth, |
| 374 | u: &UniformParams, |
| 375 | u_vecs: usize, |
| 376 | frame_i: i64, |
| 377 | enc: &mut wgpu::CommandEncoder, |
| 378 | stats: &mut EvalStats, |
| 379 | ) -> CachedTexture { |
| 380 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 381 | let key = self.make_key( |
| 382 | node, |
| 383 | op_tag, |
| 384 | src_a.size, |
| 385 | &[src_a.content_hash, src_b_hash, mask_hash, dst_depth as u64], |
| 386 | bytemuck::cast_slice(&u.p[..u_vecs]), |
| 387 | ); |
| 388 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 389 | stats.cache_hits += 1; |
| 390 | return hit; |
| 391 | } |
| 392 | stats.cache_misses += 1; |
| 393 | stats.nodes_evaluated += 1; |
| 394 | let mut dst = self.alloc_tex(src_a.size, dst_depth, key); |
| 395 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 396 | self.dispatch_sfx(enc, op, &src_a.view, src_b, mv, &dst, u); |
| 397 | dst.set_aux(src_a.aux.clone()); |
| 398 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 399 | dst |
| 400 | } |
| 401 | } |