| 1 | //! Wave 36 GPU pipelines & evaluators: |
| 2 | //! - `VectorDenoise` (motion-compensated bilateral temporal denoiser) |
| 3 | //! - `Mandel` (escape-time Mandelbrot / Julia fractal generator with smooth coloring) |
| 4 | //! - `UnsharpMask` (separable Gaussian blur + thresholded high-frequency boost) |
| 5 | //! - `Letterbox` (aspect-preserving Letterbox & Pan-and-Scan framing) |
| 6 | //! - Archive Fuses in `fx_fuses/fuses.rs`: `Fuse.Wipe`, `Fuse.Null`, |
| 7 | //! `Fuse.SetMetaData`, `Fuse.Linger`, and `Fuse.OCLRays`. |
| 8 | |
| 9 | mod fuses; |
| 10 | #[cfg(test)] |
| 11 | mod tests; |
| 12 | |
| 13 | use super::*; |
| 14 | use crate::cache::AuxChannelTex; |
| 15 | use std::num::NonZeroU64; |
| 16 | use std::sync::Arc; |
| 17 | |
| 18 | const FX_FUSES_WGSL: &str = include_str!("../shaders/fx_fuses.wgsl"); |
| 19 | const FX_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 20 | |
| 21 | fn build_fx_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 22 | let storage_fmt = match format { |
| 23 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 24 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 25 | _ => "rgba8unorm", |
| 26 | }; |
| 27 | let mut src = FX_FUSES_WGSL.to_owned(); |
| 28 | if storage_fmt != "rgba8unorm" { |
| 29 | src = src.replace( |
| 30 | "texture_storage_2d<rgba8unorm, write>", |
| 31 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 32 | ); |
| 33 | } |
| 34 | if hdr_float { |
| 35 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 36 | } |
| 37 | src |
| 38 | } |
| 39 | |
| 40 | fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry { |
| 41 | wgpu::BindGroupLayoutEntry { |
| 42 | binding, |
| 43 | visibility: wgpu::ShaderStages::COMPUTE, |
| 44 | ty: wgpu::BindingType::Texture { |
| 45 | sample_type: wgpu::TextureSampleType::Float { filterable }, |
| 46 | view_dimension: wgpu::TextureViewDimension::D2, |
| 47 | multisampled: false, |
| 48 | }, |
| 49 | count: None, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[derive(Clone, Copy)] |
| 54 | pub(self) enum FxOp { |
| 55 | VdWarp, |
| 56 | VdAccumColor, |
| 57 | VdAccumWeight, |
| 58 | VdFinalize, |
| 59 | Mandel, |
| 60 | UnsharpMask, |
| 61 | Letterbox, |
| 62 | Wipe, |
| 63 | LingerStep, |
| 64 | OclRays, |
| 65 | } |
| 66 | |
| 67 | struct FxFormatPipelines { |
| 68 | bgl: wgpu::BindGroupLayout, |
| 69 | vd_warp: wgpu::ComputePipeline, |
| 70 | vd_accum_color: wgpu::ComputePipeline, |
| 71 | vd_accum_weight: wgpu::ComputePipeline, |
| 72 | vd_finalize: wgpu::ComputePipeline, |
| 73 | mandel: wgpu::ComputePipeline, |
| 74 | unsharp_mask: wgpu::ComputePipeline, |
| 75 | letterbox: wgpu::ComputePipeline, |
| 76 | wipe: wgpu::ComputePipeline, |
| 77 | linger_step: wgpu::ComputePipeline, |
| 78 | ocl_rays: wgpu::ComputePipeline, |
| 79 | } |
| 80 | |
| 81 | impl FxFormatPipelines { |
| 82 | fn pipeline(&self, op: FxOp) -> &wgpu::ComputePipeline { |
| 83 | match op { |
| 84 | FxOp::VdWarp => &self.vd_warp, |
| 85 | FxOp::VdAccumColor => &self.vd_accum_color, |
| 86 | FxOp::VdAccumWeight => &self.vd_accum_weight, |
| 87 | FxOp::VdFinalize => &self.vd_finalize, |
| 88 | FxOp::Mandel => &self.mandel, |
| 89 | FxOp::UnsharpMask => &self.unsharp_mask, |
| 90 | FxOp::Letterbox => &self.letterbox, |
| 91 | FxOp::Wipe => &self.wipe, |
| 92 | FxOp::LingerStep => &self.linger_step, |
| 93 | FxOp::OclRays => &self.ocl_rays, |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub(super) struct FxFusesPipelines { |
| 99 | sampler: wgpu::Sampler, |
| 100 | uniform_stride: u32, |
| 101 | uniform_chunks: Vec<wgpu::Buffer>, |
| 102 | uniform_cursor: u32, |
| 103 | dummy_aux: AuxChannelTex, |
| 104 | by_format: HashMap<(wgpu::TextureFormat, bool), FxFormatPipelines>, |
| 105 | } |
| 106 | |
| 107 | impl FxFusesPipelines { |
| 108 | pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self { |
| 109 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 110 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 111 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 112 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 113 | label: Some("fx-fuses-linear"), |
| 114 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 115 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 116 | mag_filter: wgpu::FilterMode::Linear, |
| 117 | min_filter: wgpu::FilterMode::Linear, |
| 118 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, |
| 119 | ..Default::default() |
| 120 | }); |
| 121 | let dummy_aux = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::Rgba16Float, "fx-dummy-aux"); |
| 122 | queue.write_texture( |
| 123 | dummy_aux.texture.as_image_copy(), |
| 124 | &[0u8; 8], |
| 125 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) }, |
| 126 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 127 | ); |
| 128 | Self { |
| 129 | sampler, |
| 130 | uniform_stride, |
| 131 | uniform_chunks: Vec::new(), |
| 132 | uniform_cursor: 0, |
| 133 | dummy_aux, |
| 134 | by_format: HashMap::new(), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub(super) fn reset_uniform_cursor(&mut self) { |
| 139 | self.uniform_cursor = 0; |
| 140 | } |
| 141 | |
| 142 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 143 | self.uniform_cursor = 0; |
| 144 | if self.uniform_chunks.len() > max_chunks { |
| 145 | self.uniform_chunks.truncate(max_chunks); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { |
| 150 | let slot_global = self.uniform_cursor; |
| 151 | let chunk_idx = (slot_global / FX_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 152 | let slot_in_chunk = slot_global % FX_UNIFORM_SLOTS_PER_CHUNK; |
| 153 | while chunk_idx >= self.uniform_chunks.len() { |
| 154 | let size = u64::from(FX_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 155 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 156 | label: Some("fx-fuses-params-ring"), |
| 157 | size, |
| 158 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 159 | mapped_at_creation: false, |
| 160 | }); |
| 161 | self.uniform_chunks.push(buf); |
| 162 | } |
| 163 | let offset = slot_in_chunk * self.uniform_stride; |
| 164 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); |
| 165 | self.uniform_cursor = slot_global + 1; |
| 166 | (chunk_idx, offset) |
| 167 | } |
| 168 | |
| 169 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 170 | if self.by_format.contains_key(&(format, hdr_float)) { |
| 171 | return; |
| 172 | } |
| 173 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 174 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 175 | label: Some("fx-fuses-bgl"), |
| 176 | entries: &[ |
| 177 | tex_entry(0, true), |
| 178 | tex_entry(1, true), |
| 179 | tex_entry(2, true), |
| 180 | tex_entry(3, false), // aux_tex: unfilterable float safe for WebGPU/wasm32 |
| 181 | wgpu::BindGroupLayoutEntry { |
| 182 | binding: 4, |
| 183 | visibility: wgpu::ShaderStages::COMPUTE, |
| 184 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 185 | count: None, |
| 186 | }, |
| 187 | wgpu::BindGroupLayoutEntry { |
| 188 | binding: 5, |
| 189 | visibility: wgpu::ShaderStages::COMPUTE, |
| 190 | ty: wgpu::BindingType::StorageTexture { |
| 191 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 192 | format, |
| 193 | view_dimension: wgpu::TextureViewDimension::D2, |
| 194 | }, |
| 195 | count: None, |
| 196 | }, |
| 197 | wgpu::BindGroupLayoutEntry { |
| 198 | binding: 6, |
| 199 | visibility: wgpu::ShaderStages::COMPUTE, |
| 200 | ty: wgpu::BindingType::Buffer { |
| 201 | ty: wgpu::BufferBindingType::Uniform, |
| 202 | has_dynamic_offset: true, |
| 203 | min_binding_size: NonZeroU64::new(u_size), |
| 204 | }, |
| 205 | count: None, |
| 206 | }, |
| 207 | ], |
| 208 | }); |
| 209 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 210 | label: Some("fx-fuses-pl"), |
| 211 | bind_group_layouts: &[Some(&bgl)], |
| 212 | immediate_size: 0, |
| 213 | }); |
| 214 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 215 | label: Some("fx-fuses-wgsl"), |
| 216 | source: wgpu::ShaderSource::Wgsl(build_fx_wgsl(format, hdr_float).into()), |
| 217 | }); |
| 218 | let mk = |entry: &str| { |
| 219 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 220 | label: Some(entry), |
| 221 | layout: Some(&pl), |
| 222 | module: &module, |
| 223 | entry_point: Some(entry), |
| 224 | compilation_options: Default::default(), |
| 225 | cache: None, |
| 226 | }) |
| 227 | }; |
| 228 | let fp = FxFormatPipelines { |
| 229 | bgl, |
| 230 | vd_warp: mk("vd_warp_op"), |
| 231 | vd_accum_color: mk("vd_accum_color_op"), |
| 232 | vd_accum_weight: mk("vd_accum_weight_op"), |
| 233 | vd_finalize: mk("vd_finalize_op"), |
| 234 | mandel: mk("mandel_op"), |
| 235 | unsharp_mask: mk("unsharp_mask_op"), |
| 236 | letterbox: mk("letterbox_op"), |
| 237 | wipe: mk("wipe_op"), |
| 238 | linger_step: mk("linger_step_op"), |
| 239 | ocl_rays: mk("ocl_rays_op"), |
| 240 | }; |
| 241 | self.by_format.insert((format, hdr_float), fp); |
| 242 | } |
| 243 | |
| 244 | #[allow(clippy::too_many_arguments)] |
| 245 | fn dispatch( |
| 246 | &mut self, |
| 247 | device: &wgpu::Device, |
| 248 | queue: &wgpu::Queue, |
| 249 | enc: &mut wgpu::CommandEncoder, |
| 250 | op: FxOp, |
| 251 | src_a: &wgpu::TextureView, |
| 252 | src_b: &wgpu::TextureView, |
| 253 | mask: &wgpu::TextureView, |
| 254 | aux: Option<&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 aux_view = aux.unwrap_or(&self.dummy_aux.view); |
| 263 | let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64); |
| 264 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 265 | label: Some("fx-fuses-bg"), |
| 266 | layout: &fp.bgl, |
| 267 | entries: &[ |
| 268 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, |
| 269 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, |
| 270 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, |
| 271 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(aux_view) }, |
| 272 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 273 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) }, |
| 274 | wgpu::BindGroupEntry { |
| 275 | binding: 6, |
| 276 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 277 | buffer: &self.uniform_chunks[chunk_idx], |
| 278 | offset: 0, |
| 279 | size: u_size, |
| 280 | }), |
| 281 | }, |
| 282 | ], |
| 283 | }); |
| 284 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 285 | label: Some("fx-fuses-pass"), |
| 286 | timestamp_writes: None, |
| 287 | }); |
| 288 | pass.set_pipeline(fp.pipeline(op)); |
| 289 | pass.set_bind_group(0, &bg, &[offset]); |
| 290 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub(self) fn first_num(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { |
| 295 | for &k in keys { |
| 296 | if node.inputs.contains_key(k) { |
| 297 | return comp.eval_number(node, k, time, default, expr); |
| 298 | } |
| 299 | } |
| 300 | default |
| 301 | } |
| 302 | |
| 303 | pub(self) fn first_point(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: [f64; 2], expr: &ExprEngine) -> [f64; 2] { |
| 304 | for &k in keys { |
| 305 | if node.inputs.contains_key(k) { |
| 306 | return comp.eval_point(node, k, time, default, expr); |
| 307 | } |
| 308 | } |
| 309 | default |
| 310 | } |
| 311 | |
| 312 | pub(self) fn first_connected(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> { |
| 313 | ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) |
| 314 | } |
| 315 | |
| 316 | pub(self) fn first_str<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { |
| 317 | keys.iter().find_map(|k| node.static_str(k)) |
| 318 | } |
| 319 | |
| 320 | impl Engine { |
| 321 | fn fx_fuses_pipelines(&self) -> &RefCell<FxFusesPipelines> { |
| 322 | self.fx_fuses_pipelines |
| 323 | .get_or_init(|| RefCell::new(FxFusesPipelines::new(&self.device, &self.queue))) |
| 324 | } |
| 325 | |
| 326 | #[allow(clippy::too_many_arguments)] |
| 327 | pub(self) fn dispatch_fx( |
| 328 | &self, |
| 329 | enc: &mut wgpu::CommandEncoder, |
| 330 | op: FxOp, |
| 331 | src_a: &wgpu::TextureView, |
| 332 | src_b: &wgpu::TextureView, |
| 333 | mask: &wgpu::TextureView, |
| 334 | aux: Option<&wgpu::TextureView>, |
| 335 | dst: &CachedTexture, |
| 336 | params: &UniformParams, |
| 337 | ) { |
| 338 | self.fx_fuses_pipelines() |
| 339 | .borrow_mut() |
| 340 | .dispatch(&self.device, &self.queue, enc, op, src_a, src_b, mask, aux, dst, params); |
| 341 | } |
| 342 | |
| 343 | // ------------------------------------------------------------------------ |
| 344 | // 1. VectorDenoise |
| 345 | // ------------------------------------------------------------------------ |
| 346 | #[allow(clippy::too_many_arguments)] |
| 347 | pub(super) fn eval_vector_denoise( |
| 348 | &mut self, |
| 349 | comp: &Comp, |
| 350 | node: &Node, |
| 351 | time: f64, |
| 352 | frame_i: i64, |
| 353 | enc: &mut wgpu::CommandEncoder, |
| 354 | visiting: &mut HashSet<(NodeId, i64)>, |
| 355 | stats: &mut EvalStats, |
| 356 | ) -> CachedTexture { |
| 357 | let Some(src_id) = first_connected(comp, node, &["Input", "Background", "Image"]) else { |
| 358 | return self.dummy.clone(); |
| 359 | }; |
| 360 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 361 | let mbm_flag = self.multiplies_by_mask(comp, node, time); |
| 362 | let skip = self.process_skip(comp, node, time); |
| 363 | let curr = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 364 | if blend <= 1e-6 && !mbm_flag { |
| 365 | return curr; |
| 366 | } |
| 367 | |
| 368 | let radius = first_num(comp, node, &["TemporalRadius", "Radius", "Frames", "Average"], time, 1.0, &self.expr) |
| 369 | .round() |
| 370 | .clamp(0.0, 3.0) as i64; |
| 371 | if radius == 0 && !mbm_flag && skip == [0.0; 4] { |
| 372 | return curr; |
| 373 | } |
| 374 | let sigma = first_num(comp, node, &["Sigma", "Threshold", "ColorThreshold", "Tolerance"], time, 0.15, &self.expr) |
| 375 | .max(1e-3) as f32; |
| 376 | let vec_scale = first_num(comp, node, &["VectorScale", "Scale"], time, 1.0, &self.expr) as f32; |
| 377 | |
| 378 | let mut neighbors: Vec<(i64, CachedTexture)> = Vec::with_capacity((radius * 2) as usize); |
| 379 | let mut all_same = true; |
| 380 | for dt in -radius..=radius { |
| 381 | if dt == 0 { |
| 382 | continue; |
| 383 | } |
| 384 | let nbr = self.eval_node(comp, src_id, time + dt as f64, enc, visiting, stats); |
| 385 | if nbr.content_hash != curr.content_hash || curr.content_hash == 0 { |
| 386 | all_same = false; |
| 387 | } |
| 388 | neighbors.push((dt, nbr)); |
| 389 | } |
| 390 | if all_same && !mbm_flag && skip == [0.0; 4] { |
| 391 | return curr; |
| 392 | } |
| 393 | |
| 394 | let ext_vec = first_connected(comp, node, &["VectorInput", "Vectors"]).map(|vid| { |
| 395 | let t = self.eval_node(comp, vid, time, enc, visiting, stats); |
| 396 | self.crop_to_canvas(enc, t) |
| 397 | }); |
| 398 | let curr_c = self.crop_to_canvas(enc, curr.clone()); |
| 399 | let size = curr_c.size; |
| 400 | let dst_depth = self.node_depth(comp, node, time, Some(curr_c.depth)); |
| 401 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 402 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 403 | let mbm = mask.is_some() && mbm_flag; |
| 404 | |
| 405 | let fwd_vec: Option<(Arc<wgpu::TextureView>, u64)> = if let Some(ext) = ext_vec.as_ref() { |
| 406 | if let Some(av) = ext.aux.as_ref().and_then(|a| a.vector.as_ref()) { |
| 407 | Some((av.view.clone(), ext.content_hash ^ 0xF001)) |
| 408 | } else { |
| 409 | Some((ext.view.clone(), ext.content_hash ^ 0xF002)) |
| 410 | } |
| 411 | } else { |
| 412 | curr_c.aux.as_ref().and_then(|a| a.vector.as_ref()).map(|av| (av.view.clone(), curr_c.content_hash ^ 0xF003)) |
| 413 | }; |
| 414 | let bwd_vec: Option<(Arc<wgpu::TextureView>, u64)> = curr_c |
| 415 | .aux |
| 416 | .as_ref() |
| 417 | .and_then(|a| a.back_vector.as_ref()) |
| 418 | .map(|av| (av.view.clone(), curr_c.content_hash ^ 0xB003)); |
| 419 | |
| 420 | let mut hashes = Vec::with_capacity(neighbors.len() + 5); |
| 421 | hashes.push(curr_c.content_hash); |
| 422 | for (_, n) in &neighbors { |
| 423 | hashes.push(n.content_hash); |
| 424 | } |
| 425 | hashes.push(fwd_vec.as_ref().map_or(0, |v| v.1)); |
| 426 | hashes.push(bwd_vec.as_ref().map_or(0, |v| v.1)); |
| 427 | hashes.push(mask_hash); |
| 428 | hashes.push(dst_depth as u64); |
| 429 | let params_f32 = [ |
| 430 | radius as f32, |
| 431 | sigma, |
| 432 | vec_scale, |
| 433 | blend, |
| 434 | if mask_inv { 1.0 } else { 0.0 }, |
| 435 | if mbm { 1.0 } else { 0.0 }, |
| 436 | skip[0], |
| 437 | skip[1], |
| 438 | skip[2], |
| 439 | skip[3], |
| 440 | ]; |
| 441 | let key = self.make_key(node, "VectorDenoise", size, &hashes, &params_f32); |
| 442 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 443 | stats.cache_hits += 1; |
| 444 | return hit; |
| 445 | } |
| 446 | stats.cache_misses += 1; |
| 447 | stats.nodes_evaluated += 1; |
| 448 | |
| 449 | let work_depth = BitDepth::Float16; |
| 450 | let search_rad = if self.hiq { 4.0_f32 } else { 2.0_f32 }; |
| 451 | let mut w_tex = self.alloc_tex(size, work_depth, 0); |
| 452 | let mut u_init = UniformParams::default(); |
| 453 | u_init.p[0] = [sigma, 1.0, 1.0, 0.0]; |
| 454 | self.dispatch_fx(enc, FxOp::VdAccumWeight, &curr_c.view, &curr_c.view, &self.dummy.view, None, &w_tex, &u_init); |
| 455 | |
| 456 | let mut accum = curr_c.clone(); |
| 457 | for (dt, nbr) in &neighbors { |
| 458 | let nbr_c = self.crop_to_canvas(enc, nbr.clone()); |
| 459 | let warped = if nbr_c.content_hash != 0 && nbr_c.content_hash == curr_c.content_hash { |
| 460 | curr_c.clone() |
| 461 | } else { |
| 462 | let (vec_view, has_vec, scale_dt) = if *dt > 0 { |
| 463 | if let Some((v, _)) = &fwd_vec { |
| 464 | (Some(v.as_ref()), 1.0_f32, vec_scale * (*dt as f32)) |
| 465 | } else { |
| 466 | (None, 0.0_f32, 0.0) |
| 467 | } |
| 468 | } else if let Some((v, _)) = &bwd_vec { |
| 469 | (Some(v.as_ref()), 1.0_f32, vec_scale * ((-*dt) as f32)) |
| 470 | } else if let Some((v, _)) = &fwd_vec { |
| 471 | (Some(v.as_ref()), 1.0_f32, vec_scale * (*dt as f32)) |
| 472 | } else { |
| 473 | (None, 0.0_f32, 0.0) |
| 474 | }; |
| 475 | let dst_w = self.alloc_tex(size, work_depth, 0); |
| 476 | let mut uw = UniformParams::default(); |
| 477 | uw.p[0] = [has_vec, scale_dt, scale_dt, search_rad]; |
| 478 | self.dispatch_fx(enc, FxOp::VdWarp, &curr_c.view, &nbr_c.view, &self.dummy.view, vec_view, &dst_w, &uw); |
| 479 | dst_w |
| 480 | }; |
| 481 | |
| 482 | let temporal_w = (-0.25 * (*dt * *dt) as f32).exp(); |
| 483 | let mut ua = UniformParams::default(); |
| 484 | ua.p[0] = [sigma, temporal_w, 0.0, 0.0]; |
| 485 | let next_acc = self.alloc_tex(size, work_depth, 0); |
| 486 | self.dispatch_fx(enc, FxOp::VdAccumColor, &accum.view, &warped.view, &curr_c.view, Some(&w_tex.view), &next_acc, &ua); |
| 487 | let next_w = self.alloc_tex(size, work_depth, 0); |
| 488 | self.dispatch_fx(enc, FxOp::VdAccumWeight, &curr_c.view, &warped.view, &self.dummy.view, Some(&w_tex.view), &next_w, &ua); |
| 489 | accum = next_acc; |
| 490 | w_tex = next_w; |
| 491 | } |
| 492 | |
| 493 | let mut dst = self.alloc_tex(size, dst_depth, key); |
| 494 | let mut uf = UniformParams::default(); |
| 495 | uf.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }]; |
| 496 | uf.p[1] = skip; |
| 497 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 498 | self.dispatch_fx(enc, FxOp::VdFinalize, &curr_c.view, &accum.view, mv, None, &dst, &uf); |
| 499 | if curr_c.aux.is_some() && dst.size == curr_c.size && dst.origin == curr_c.origin { |
| 500 | dst.set_aux(curr_c.aux.clone()); |
| 501 | } |
| 502 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 503 | dst |
| 504 | } |
| 505 | |
| 506 | // ------------------------------------------------------------------------ |
| 507 | // 2. Mandel |
| 508 | // ------------------------------------------------------------------------ |
| 509 | #[allow(clippy::too_many_arguments)] |
| 510 | pub(super) fn eval_mandel( |
| 511 | &mut self, |
| 512 | comp: &Comp, |
| 513 | node: &Node, |
| 514 | time: f64, |
| 515 | frame_i: i64, |
| 516 | comp_dims: [u32; 2], |
| 517 | enc: &mut wgpu::CommandEncoder, |
| 518 | visiting: &mut HashSet<(NodeId, i64)>, |
| 519 | stats: &mut EvalStats, |
| 520 | ) -> CachedTexture { |
| 521 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 522 | let w = if use_ff { comp.width } else { comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 }; |
| 523 | let h = if use_ff { comp.height } else { comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 }; |
| 524 | let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; |
| 525 | let depth = self.node_depth(comp, node, time, None); |
| 526 | |
| 527 | let is_julia = match first_str(node, &["Mode", "Type", "FractalType"]) { |
| 528 | Some(s) => s.eq_ignore_ascii_case("julia"), |
| 529 | None => first_num(comp, node, &["Mode", "Type", "FractalType", "Julia"], time, 0.0, &self.expr) >= 0.5, |
| 530 | }; |
| 531 | let default_center = if is_julia { [0.0, 0.0] } else { [-0.5, 0.0] }; |
| 532 | let (cx, cy) = if node.inputs.contains_key("XPosition") || node.inputs.contains_key("YPosition") { |
| 533 | ( |
| 534 | comp.eval_number(node, "XPosition", time, default_center[0], &self.expr) as f32, |
| 535 | comp.eval_number(node, "YPosition", time, default_center[1], &self.expr) as f32, |
| 536 | ) |
| 537 | } else { |
| 538 | let c = first_point(comp, node, &["Center"], time, default_center, &self.expr); |
| 539 | (c[0] as f32, c[1] as f32) |
| 540 | }; |
| 541 | let zoom = if node.inputs.contains_key("Zoom") { |
| 542 | comp.eval_number(node, "Zoom", time, 1.0, &self.expr).max(1e-6) as f32 |
| 543 | } else if node.inputs.contains_key("Size") { |
| 544 | (1.0 / comp.eval_number(node, "Size", time, 1.0, &self.expr).max(1e-6)) as f32 |
| 545 | } else { |
| 546 | 1.0_f32 |
| 547 | }; |
| 548 | let rot_rad = (first_num(comp, node, &["Rotation", "Angle"], time, 0.0, &self.expr) as f32).to_radians(); |
| 549 | let max_iter = first_num(comp, node, &["Iterations", "MaxIterations"], time, 64.0, &self.expr).round().clamp(1.0, 1024.0) as f32; |
| 550 | let escape_lim = first_num(comp, node, &["EscapeLimit", "Bailout"], time, 4.0, &self.expr).max(4.0) as f32; |
| 551 | let escape_r2 = (escape_lim * escape_lim).max(16.0); |
| 552 | let grad_curve = first_num(comp, node, &["GradientCurve", "Curve"], time, 0.5, &self.expr).max(0.05) as f32; |
| 553 | |
| 554 | let mut jc = first_point(comp, node, &["JuliaSeed", "C", "Seed"], time, [-0.7, 0.27015], &self.expr); |
| 555 | if node.inputs.contains_key("JuliaX") || node.inputs.contains_key("CReal") { |
| 556 | jc[0] = first_num(comp, node, &["JuliaX", "CReal"], time, jc[0], &self.expr); |
| 557 | } |
| 558 | if node.inputs.contains_key("JuliaY") || node.inputs.contains_key("CImag") { |
| 559 | jc[1] = first_num(comp, node, &["JuliaY", "CImag"], time, jc[1], &self.expr); |
| 560 | } |
| 561 | |
| 562 | let any_rgb_wave = ["RedRepetitions", "GreenRepetitions", "BlueRepetitions", "RedPhase", "GreenPhase", "BluePhase"] |
| 563 | .iter() |
| 564 | .any(|k| node.inputs.contains_key(*k)); |
| 565 | let r_rep = comp.eval_number(node, "RedRepetitions", time, 1.0, &self.expr) as f32; |
| 566 | let g_rep = comp.eval_number(node, "GreenRepetitions", time, 1.0, &self.expr) as f32; |
| 567 | let b_rep = comp.eval_number(node, "BlueRepetitions", time, 1.0, &self.expr) as f32; |
| 568 | let r_ph = comp.eval_number(node, "RedPhase", time, 0.0, &self.expr) as f32; |
| 569 | let g_ph = comp.eval_number(node, "GreenPhase", time, if any_rgb_wave { 0.0 } else { 0.15 }, &self.expr) as f32; |
| 570 | let b_ph = comp.eval_number(node, "BluePhase", time, if any_rgb_wave { 0.0 } else { 0.30 }, &self.expr) as f32; |
| 571 | |
| 572 | let tint = [ |
| 573 | first_num(comp, node, &["ColorRed", "Red"], time, 1.0, &self.expr) as f32, |
| 574 | first_num(comp, node, &["ColorGreen", "Green"], time, 1.0, &self.expr) as f32, |
| 575 | first_num(comp, node, &["ColorBlue", "Blue"], time, 1.0, &self.expr) as f32, |
| 576 | first_num(comp, node, &["ColorAlpha", "Alpha"], time, 1.0, &self.expr) as f32, |
| 577 | ]; |
| 578 | let inside = [ |
| 579 | comp.eval_number(node, "InsideRed", time, 0.0, &self.expr) as f32, |
| 580 | comp.eval_number(node, "InsideGreen", time, 0.0, &self.expr) as f32, |
| 581 | comp.eval_number(node, "InsideBlue", time, 0.0, &self.expr) as f32, |
| 582 | comp.eval_number(node, "InsideAlpha", time, 1.0, &self.expr) as f32, |
| 583 | ]; |
| 584 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 585 | let grad = comp.eval_gradient(node, "Gradient", time).or_else(|| comp.eval_gradient(node, "Palette", time)); |
| 586 | let lut_data = grad.map(|g| { |
| 587 | let mut bytes = [0u8; 256 * 4]; |
| 588 | for (i, texel) in bytes.chunks_exact_mut(4).enumerate() { |
| 589 | let c = g.sample(i as f64 / 255.0); |
| 590 | for (b, v) in texel.iter_mut().zip(c) { |
| 591 | *b = (v.clamp(0.0, 1.0) * 255.0).round() as u8; |
| 592 | } |
| 593 | } |
| 594 | let mut gh = DefaultHasher::new(); |
| 595 | bytes.hash(&mut gh); |
| 596 | (bytes, gh.finish()) |
| 597 | }); |
| 598 | let grad_hash = lut_data.as_ref().map_or(0, |l| l.1); |
| 599 | |
| 600 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 601 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 602 | |
| 603 | let mut u = UniformParams::default(); |
| 604 | u.p[0] = [cx, cy, zoom, rot_rad]; |
| 605 | u.p[1] = [if is_julia { 1.0 } else { 0.0 }, max_iter, escape_r2, grad_curve]; |
| 606 | u.p[2] = [jc[0] as f32, jc[1] as f32, r_rep, g_rep]; |
| 607 | u.p[3] = [b_rep, r_ph, g_ph, b_ph]; |
| 608 | u.p[4] = [if lut_data.is_some() { 1.0 } else { 0.0 }, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; |
| 609 | u.p[5] = tint; |
| 610 | u.p[6] = inside; |
| 611 | |
| 612 | let key = self.make_key(node, "Mandel", size, &[mask_hash, grad_hash, depth as u64], bytemuck::cast_slice(&u.p[..7])); |
| 613 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 614 | stats.cache_hits += 1; |
| 615 | return hit; |
| 616 | } |
| 617 | stats.cache_misses += 1; |
| 618 | stats.nodes_evaluated += 1; |
| 619 | |
| 620 | let lut_tex = lut_data.map(|(bytes, _)| { |
| 621 | let tex = create_texture(&self.device, [256, 1], 0); |
| 622 | self.queue.write_texture( |
| 623 | tex.texture.as_image_copy(), |
| 624 | &bytes, |
| 625 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, |
| 626 | wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, |
| 627 | ); |
| 628 | tex |
| 629 | }); |
| 630 | let dst = self.alloc_tex(size, depth, key); |
| 631 | let lut_view = lut_tex.as_ref().map_or(&self.dummy.view, |t| &t.view); |
| 632 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 633 | self.dispatch_fx(enc, FxOp::Mandel, &self.dummy.view, lut_view, mv, None, &dst, &u); |
| 634 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 635 | dst |
| 636 | } |
| 637 | |
| 638 | // ------------------------------------------------------------------------ |
| 639 | // 3. UnsharpMask |
| 640 | // ------------------------------------------------------------------------ |
| 641 | #[allow(clippy::too_many_arguments)] |
| 642 | pub(super) fn eval_unsharp_mask( |
| 643 | &mut self, |
| 644 | comp: &Comp, |
| 645 | node: &Node, |
| 646 | time: f64, |
| 647 | frame_i: i64, |
| 648 | enc: &mut wgpu::CommandEncoder, |
| 649 | visiting: &mut HashSet<(NodeId, i64)>, |
| 650 | stats: &mut EvalStats, |
| 651 | ) -> CachedTexture { |
| 652 | let Some(src_id) = first_connected(comp, node, &["Input", "Background"]) else { |
| 653 | return self.dummy.clone(); |
| 654 | }; |
| 655 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 656 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 657 | let lock_xy = first_num(comp, node, &["LockXY", "LockSizeXY"], time, 1.0, &self.expr) > 0.5; |
| 658 | let x_size = first_num(comp, node, &["XSize", "Size"], time, 2.0, &self.expr).max(0.0) as f32; |
| 659 | let y_size = if lock_xy { x_size } else { first_num(comp, node, &["YSize", "Size"], time, x_size as f64, &self.expr).max(0.0) as f32 }; |
| 660 | let gain = first_num(comp, node, &["Gain", "Amount"], time, 1.0, &self.expr) as f32; |
| 661 | let threshold = first_num(comp, node, &["Threshold"], time, 0.0, &self.expr).max(0.0) as f32; |
| 662 | let mbm_flag = self.multiplies_by_mask(comp, node, time); |
| 663 | let skip = self.process_skip(comp, node, time); |
| 664 | |
| 665 | if (blend <= 1e-6 || gain.abs() <= 1e-6 || x_size.max(y_size) <= 1e-5) && !mbm_flag && skip == [0.0; 4] { |
| 666 | return src; |
| 667 | } |
| 668 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); |
| 669 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 670 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 671 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 672 | let mbm = mask.is_some() && mbm_flag; |
| 673 | |
| 674 | let scale_ref = (src.canvas_size[0] as f32 / 720.0).max(1e-4); |
| 675 | let rx = x_size * scale_ref; |
| 676 | let ry = y_size * scale_ref; |
| 677 | |
| 678 | let mut u = UniformParams::default(); |
| 679 | u.p[0] = [gain, threshold, blend, if mask.is_some() { 1.0 } else { 0.0 }]; |
| 680 | u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, rx, ry]; |
| 681 | u.p[2] = skip; |
| 682 | |
| 683 | let key = self.make_key(node, "UnsharpMask", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); |
| 684 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 685 | stats.cache_hits += 1; |
| 686 | return hit; |
| 687 | } |
| 688 | stats.cache_misses += 1; |
| 689 | stats.nodes_evaluated += 1; |
| 690 | |
| 691 | let blurred = self.blur_separable(enc, &src, rx, ry, 0.0, 1.0); |
| 692 | let mut dst = self.alloc_tex_like(&src, src.depth, key); |
| 693 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 694 | self.dispatch_fx(enc, FxOp::UnsharpMask, &src.view, &blurred.view, mv, None, &dst, &u); |
| 695 | if src.aux.is_some() && dst.size == src.size && dst.origin == src.origin { |
| 696 | dst.set_aux(src.aux.clone()); |
| 697 | } |
| 698 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 699 | dst |
| 700 | } |
| 701 | |
| 702 | // ------------------------------------------------------------------------ |
| 703 | // 4. Letterbox |
| 704 | // ------------------------------------------------------------------------ |
| 705 | #[allow(clippy::too_many_arguments)] |
| 706 | pub(super) fn eval_letterbox( |
| 707 | &mut self, |
| 708 | comp: &Comp, |
| 709 | node: &Node, |
| 710 | time: f64, |
| 711 | frame_i: i64, |
| 712 | comp_dims: [u32; 2], |
| 713 | enc: &mut wgpu::CommandEncoder, |
| 714 | visiting: &mut HashSet<(NodeId, i64)>, |
| 715 | stats: &mut EvalStats, |
| 716 | ) -> CachedTexture { |
| 717 | let Some(src_id) = first_connected(comp, node, &["Input", "Background"]) else { |
| 718 | return self.dummy.clone(); |
| 719 | }; |
| 720 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 721 | let hiq_only = comp.eval_number(node, "HiQOnly", time, 0.0, &self.expr) > 0.5; |
| 722 | if !self.hiq && hiq_only { |
| 723 | return src; |
| 724 | } |
| 725 | let src = self.crop_to_canvas(enc, src); |
| 726 | let max_dim = self.device.limits().max_texture_dimension_2d as f64; |
| 727 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 728 | let dst_size = if use_ff { |
| 729 | comp_dims |
| 730 | } else { |
| 731 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).clamp(1.0, max_dim).round() as u32; |
| 732 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).clamp(1.0, max_dim).round() as u32; |
| 733 | if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) } |
| 734 | }; |
| 735 | |
| 736 | let mode = match node.static_str("Mode") { |
| 737 | Some(s) if s.to_ascii_lowercase().contains("pan") => 1.0_f32, |
| 738 | Some(_) => 0.0_f32, |
| 739 | None => if comp.eval_number(node, "Mode", time, 0.0, &self.expr) >= 0.5 { 1.0 } else { 0.0 }, |
| 740 | }; |
| 741 | let position = first_num(comp, node, &["Position", "CenterOffset"], time, 0.0, &self.expr).clamp(-1.0, 1.0) as f32; |
| 742 | let filter = match node.static_str("FilterMethod") { |
| 743 | Some("Nearest" | "Nearest Neighbor") => 0.0_f32, |
| 744 | Some("Box" | "Linear" | "Bilinear") => 1.0_f32, |
| 745 | Some("Cubic" | "Catmull-Rom" | "CatmullRom" | "Lanczos" | "Mitchell" | "Quadratic") => 3.0_f32, |
| 746 | Some(_) => 2.0_f32, |
| 747 | None => comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) as f32, |
| 748 | }; |
| 749 | let pa_pt = comp.eval_point(node, "PixelAspect", time, [1.0, 1.0], &self.expr); |
| 750 | let pa = (pa_pt[0] / pa_pt[1].max(1e-4)).clamp(0.1, 10.0) as f32; |
| 751 | |
| 752 | let mut u = UniformParams::default(); |
| 753 | u.p[0] = [mode, position, filter, pa]; |
| 754 | let key = self.make_key(node, "Letterbox", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); |
| 755 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 756 | stats.cache_hits += 1; |
| 757 | return hit; |
| 758 | } |
| 759 | stats.cache_misses += 1; |
| 760 | stats.nodes_evaluated += 1; |
| 761 | let dst = self.alloc_tex(dst_size, src.depth, key); |
| 762 | self.dispatch_fx(enc, FxOp::Letterbox, &src.view, &self.dummy.view, &self.dummy.view, None, &dst, &u); |
| 763 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 764 | dst |
| 765 | } |
| 766 | } |