From f4b9a2dcea0158f75337a48bc7233162fdeef1d9 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 00:49:09 -0800 Subject: [PATCH] feat(engine): implement DepthBlur, Fog, Highlight, HotSpot, and RankFilter --- crates/engine/src/eval/depth_optical.rs | 1327 ++++++++++++++++++ crates/engine/src/eval/mod.rs | 14 + crates/engine/src/shaders/depth_optical.wgsl | 685 +++++++++ 3 files changed, 2026 insertions(+) create mode 100644 crates/engine/src/eval/depth_optical.rs create mode 100644 crates/engine/src/shaders/depth_optical.wgsl diff --git a/crates/engine/src/eval/depth_optical.rs b/crates/engine/src/eval/depth_optical.rs new file mode 100644 index 0000000000000000000000000000000000000000..a2c53b53b728293abe74d204cc2303d30dbcc2d3 --- /dev/null +++ b/crates/engine/src/eval/depth_optical.rs @@ -0,0 +1,1327 @@ +//! Wave 35B — Depth, Optical & Filter FX GPU pipelines and evaluators: +//! - `DepthBlur` (depth-driven CoC blur from `BlurImage`/`BlurChannel` or `aux.z`) +//! - `Fog` (depth-driven atmospheric fog from `aux.z` or `FogImage`/`Fog`) +//! - `Highlight` (2-pass bright-threshold extraction + directional starburst streaks) +//! - `HotSpot` (radial primary glow + secondary optical lens flare elements) +//! - `RankFilter` (GPU order-statistic Min/Median/Max/Percentile filter) +//! +//! WebGPU safety: `R32Float` depth textures are bound with `filterable: false` and read +//! exclusively via `textureLoad`; output storage textures are `WriteOnly`. + +use super::*; +use crate::cache::{AuxChannelTex, EMPTY_Z_SENTINEL}; +use std::num::NonZeroU64; + +const DEPTH_OPTICAL_WGSL: &str = include_str!("../shaders/depth_optical.wgsl"); +const UNIFORM_SLOTS_PER_CHUNK: u32 = 512; +const MAX_RANK_RADIUS: f32 = 5.0; + +#[derive(Clone, Copy)] +enum DepthOpticalOp { + DepthBlur, + Fog, + HighlightExtract, + HighlightStreaks, + HotSpot, + RankFilter, +} + +fn build_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + let mut src = DEPTH_OPTICAL_WGSL.to_owned(); + if storage_fmt != "rgba8unorm" { + src = src.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + } + if hdr_float { + src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); + } + src +} + +fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + } +} + +struct FormatPipelines { + bgl: wgpu::BindGroupLayout, + depth_blur: wgpu::ComputePipeline, + fog: wgpu::ComputePipeline, + highlight_extract: wgpu::ComputePipeline, + highlight_streaks: wgpu::ComputePipeline, + hot_spot: wgpu::ComputePipeline, + rank_filter: wgpu::ComputePipeline, +} + +pub(super) struct DepthOpticalPipelines { + sampler: wgpu::Sampler, + uniform_stride: u32, + uniform_chunks: Vec, + uniform_cursor: u32, + dummy_z: AuxChannelTex, + formats: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>, +} + +impl DepthOpticalPipelines { + pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self { + let uniform_size = std::mem::size_of::() as u32; + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + let uniform_stride = uniform_size.div_ceil(min_align) * min_align; + + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("depth-optical-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + + let dummy_z = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::R32Float, "do-dummy-z"); + queue.write_texture( + dummy_z.texture.as_image_copy(), + &EMPTY_Z_SENTINEL.to_le_bytes(), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(4), + rows_per_image: Some(1), + }, + wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + ); + + Self { + sampler, + uniform_stride, + uniform_chunks: Vec::new(), + uniform_cursor: 0, + dummy_z, + formats: HashMap::new(), + } + } + + pub(super) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + if self.uniform_chunks.len() > max_chunks { + self.uniform_chunks.truncate(max_chunks); + } + } + + fn alloc_uniform_slot( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + params: &UniformParams, + ) -> (usize, u32) { + let slot_global = self.uniform_cursor; + let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize; + let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK; + while chunk_idx >= self.uniform_chunks.len() { + let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("depth-optical-params-ring"), + size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.uniform_chunks.push(buf); + } + let offset = slot_in_chunk * self.uniform_stride; + queue.write_buffer( + &self.uniform_chunks[chunk_idx], + u64::from(offset), + bytemuck::bytes_of(params), + ); + self.uniform_cursor = slot_global + 1; + (chunk_idx, offset) + } + + fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { + if self.formats.contains_key(&(format, hdr_float)) { + return; + } + let u_size = std::mem::size_of::() as u64; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("depth-optical-bgl"), + entries: &[ + tex_entry(0, true), + tex_entry(1, true), + tex_entry(2, false), // R32Float depth: MUST be unfilterable for WebGPU/wasm32! + tex_entry(3, true), + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 6, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(u_size), + }, + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("depth-optical-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("depth-optical-wgsl"), + source: wgpu::ShaderSource::Wgsl(build_wgsl(format, hdr_float).into()), + }); + let mk = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&pl), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + self.formats.insert( + (format, hdr_float), + FormatPipelines { + bgl, + depth_blur: mk("depth_blur_op"), + fog: mk("fog_op"), + highlight_extract: mk("highlight_extract_op"), + highlight_streaks: mk("highlight_streaks_op"), + hot_spot: mk("hot_spot_op"), + rank_filter: mk("rank_filter_op"), + }, + ); + } + + #[allow(clippy::too_many_arguments)] + fn dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + op: DepthOpticalOp, + src_view: &wgpu::TextureView, + aux_img_view: &wgpu::TextureView, + z_view: Option<&wgpu::TextureView>, + mask_view: &wgpu::TextureView, + dst: &CachedTexture, + params: &UniformParams, + ) { + let format = dst.texture.format(); + let hdr_float = matches!( + format, + wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float + ); + self.ensure_format(device, format, hdr_float); + let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); + let fp = &self.formats[&(format, hdr_float)]; + let zv = z_view.unwrap_or(&self.dummy_z.view); + let u_size = NonZeroU64::new(std::mem::size_of::() as u64); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("depth-optical-bg"), + layout: &fp.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(aux_img_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(zv) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask_view) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) }, + wgpu::BindGroupEntry { + binding: 6, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_chunks[chunk_idx], + offset: 0, + size: u_size, + }), + }, + ], + }); + let pipeline = match op { + DepthOpticalOp::DepthBlur => &fp.depth_blur, + DepthOpticalOp::Fog => &fp.fog, + DepthOpticalOp::HighlightExtract => &fp.highlight_extract, + DepthOpticalOp::HighlightStreaks => &fp.highlight_streaks, + DepthOpticalOp::HotSpot => &fp.hot_spot, + DepthOpticalOp::RankFilter => &fp.rank_filter, + }; + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("depth-optical-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bg, &[offset]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } +} + +fn parse_depth_blur_channel(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { + if let Some(s) = node.static_str("BlurChannel") { + return match s { + "Red" => 0, + "Green" => 1, + "Blue" => 2, + "Alpha" => 3, + "Z" | "ZBuffer" | "Z-Buffer" => 4, + "Luminance" | "Luma" => 5, + _ => 4, + }; + } + comp.eval_number(node, "BlurChannel", time, 4.0, expr).round().clamp(0.0, 5.0) as i32 +} + +fn parse_depth_blur_filter(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { + if let Some(s) = node.static_str("Filter") { + return match s { + "Box" => 1, + "Gaussian" | "Fast Gaussian" => 2, + "Lens" | "Bokeh" => 3, + _ => 0, + }; + } + comp.eval_number(node, "Filter", time, 0.0, expr).round().clamp(0.0, 3.0) as i32 +} + +fn parse_hotspot_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { + if let Some(s) = node.static_str("ApplyMode") { + return match s { + "Screen" => 1, + "Normal" | "Over" => 2, + "Multiply" => 3, + "Lighten" | "Max" => 4, + "Overlay" => 5, + _ => 0, // Add / LinearDodge + }; + } + comp.eval_number(node, "ApplyMode", time, 0.0, expr).round().clamp(0.0, 5.0) as i32 +} + +fn parse_rank_filter_type(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 { + if let Some(s) = node.static_str("FilterType") { + return match s { + "Circle" | "Circular" | "Disc" => 1, + "Cross" | "Plus" => 2, + "Diamond" => 3, + _ => 0, // Box / Square + }; + } + comp.eval_number(node, "FilterType", time, 0.0, expr).round().clamp(0.0, 3.0) as i32 +} + +impl Engine { + pub(super) fn depth_optical_pipelines(&self) -> &RefCell { + self.depth_optical_pipelines + .get_or_init(|| RefCell::new(DepthOpticalPipelines::new(&self.device, &self.queue))) + } + + fn eval_num_alias(&self, comp: &Comp, node: &Node, primary: &str, fallback: &str, time: f64, default: f64) -> f32 { + if node.inputs.contains_key(primary) { + comp.eval_number(node, primary, time, default, &self.expr) as f32 + } else { + comp.eval_number(node, fallback, time, default, &self.expr) as f32 + } + } + + fn combined_skip(&self, comp: &Comp, node: &Node, time: f64) -> [f32; 4] { + let p_skip = self.process_skip(comp, node, time); + let c_names = ["Red", "Green", "Blue", "Alpha"]; + let mut out = p_skip; + for i in 0..4 { + if node.inputs.contains_key(c_names[i]) + && comp.eval_number(node, c_names[i], time, 1.0, &self.expr) <= 0.5 + { + out[i] = 1.0; + } + } + out + } + + /// 1. `DepthBlur`: circle-of-confusion blur driven by `BlurImage`/`BlurChannel` or `aux.z`. + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_depth_blur( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + let blur_raw = self.eval_num_alias(comp, node, "XBlurSize", "BlurSize", time, 1.0).max(0.0); + // Fusion blur size uses 720px-width reference; src.canvas_size already reflects proxy_scale. + let max_r = (blur_raw * (src.canvas_size[0] as f32 / 720.0)).min(96.0); + if (blend <= 1e-6 || max_r < 0.25) && !mbm { + return src; + } + + let src_aux = src.aux.clone(); + let src = self.crop_to_canvas(enc, src); + let blur_img = node + .connected_node("BlurImage") + .and_then(|s| comp.find_node(s)) + .map(|bid| { + let t = self.eval_node(comp, bid, time, enc, visiting, stats); + self.crop_to_canvas(enc, t) + }); + + let mut channel = parse_depth_blur_channel(comp, node, time, &self.expr); + let (depth_src_mode, z_tex_opt): (i32, Option) = if channel == 4 { + if let Some(bi) = &blur_img { + if let Some(bz) = bi.aux.as_ref().and_then(|a| a.z.clone()) { + (0, Some(bz)) + } else { + channel = 5; // BlurImage without aux.z -> use luminance + (1, None) + } + } else if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) { + (0, Some(sz)) + } else { + // No depth source available -> pass through unless MultiplyByMask is active. + if !mbm { + let mut out = src; + out.set_aux(src_aux); + return out; + } + (0, None) + } + } else if blur_img.is_some() { + (1, None) + } else { + (2, None) + }; + + let focal = comp.eval_number(node, "FocalPoint", time, 0.0, &self.expr) as f32; + let dof = comp.eval_number(node, "DepthOfField", time, 0.0, &self.expr) as f32; + let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32; + let filter_mode = parse_depth_blur_filter(comp, node, time, &self.expr); + let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.combined_skip(comp, node, time); + let taps = match (filter_mode, self.hiq) { + (1, true) => 3.0, + (1, false) => 2.0, + (_, true) => 36.0, + (_, false) => 16.0, + }; + + let mut u = UniformParams::default(); + u.p[0] = [if depth_src_mode == 0 && z_tex_opt.is_none() { 0.0 } else { max_r }, focal, dof, z_scale]; + u.p[1] = [filter_mode as f32, depth_src_mode as f32, channel as f32, clamp_edges]; + u.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32]; + u.p[3] = skip; + u.p[4] = [taps, z_tex_opt.is_some() as u8 as f32, 0.0, 0.0]; + + let bi_hash = blur_img.as_ref().map_or(0, |b| b.content_hash); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key( + node, + "DepthBlur", + src.size, + &[src.content_hash, bi_hash, mask_hash], + bytemuck::cast_slice(&u.p[..5]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let mut dst = self.alloc_tex_like(&src, src.depth, key); + dst.set_aux(src_aux); + let bv = blur_img.as_ref().map_or(&self.dummy.view, |b| &b.view); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref()); + self.depth_optical_pipelines().borrow_mut().dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::DepthBlur, + &src.view, + bv, + zv, + mv, + &dst, + &u, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + /// 2. `Fog`: depth-driven atmospheric fog from `aux.z` or `FogImage`/`Fog`. + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_fog( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let fog_opacity = comp.eval_number(node, "FogOpacity", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + if (blend <= 1e-6 || fog_opacity <= 1e-6) && !mbm { + return src; + } + + let src_aux = src.aux.clone(); + let src = self.crop_to_canvas(enc, src); + let fog_img = node + .connected_node("FogImage") + .or_else(|| node.connected_node("Fog")) + .and_then(|s| comp.find_node(s)) + .map(|fid| { + let t = self.eval_node(comp, fid, time, enc, visiting, stats); + self.crop_to_canvas(enc, t) + }); + + let (depth_mode, has_fog_color_img, z_tex_opt): (i32, bool, Option) = + if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) { + (0, fog_img.is_some(), Some(sz)) + } else if let Some(fi) = &fog_img { + if let Some(fz) = fi.aux.as_ref().and_then(|a| a.z.clone()) { + (0, false, Some(fz)) + } else { + (1, false, None) + } + } else { + (0, false, None) + }; + + let near_p = self.eval_num_alias(comp, node, "ZNearPlane", "NearPlane", time, 0.0); + let far_p = self.eval_num_alias(comp, node, "ZFarPlane", "FarPlane", time, -100.0); + let falloff = comp.eval_number(node, "Falloff", time, 1.0, &self.expr) as f32; + let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32; + let fog_r = comp.eval_number(node, "FogRed", time, 1.0, &self.expr) as f32; + let fog_g = comp.eval_number(node, "FogGreen", time, 1.0, &self.expr) as f32; + let fog_b = comp.eval_number(node, "FogBlue", time, 1.0, &self.expr) as f32; + let fog_a = comp.eval_number(node, "FogAlpha", time, 1.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.process_skip(comp, node, time); + + let mut u = UniformParams::default(); + u.p[0] = [near_p, far_p, falloff, z_scale]; + u.p[1] = [fog_r, fog_g, fog_b, fog_a]; + u.p[2] = [fog_opacity, depth_mode as f32, has_fog_color_img as u8 as f32, z_tex_opt.is_some() as u8 as f32]; + u.p[3] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32]; + u.p[4] = skip; + + let fi_hash = fog_img.as_ref().map_or(0, |f| f.content_hash); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key( + node, + "Fog", + src.size, + &[src.content_hash, fi_hash, mask_hash], + bytemuck::cast_slice(&u.p[..5]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let mut dst = self.alloc_tex_like(&src, src.depth, key); + dst.set_aux(src_aux); + let fv = fog_img.as_ref().map_or(&self.dummy.view, |f| &f.view); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref()); + self.depth_optical_pipelines().borrow_mut().dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::Fog, + &src.view, + fv, + zv, + mv, + &dst, + &u, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + /// 3. `Highlight`: threshold bright pixels (`Low`/`High`) + directional starburst streaks. + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_highlight( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + if blend <= 1e-6 && !mbm { + return src; + } + let src = self.crop_to_canvas(enc, src); + + let low = comp.eval_number(node, "Low", time, 0.75, &self.expr) as f32; + let high = comp.eval_number(node, "High", time, 1.0, &self.expr) as f32; + let num_points = comp.eval_number(node, "NumberOfPoints", time, 4.0, &self.expr).clamp(1.0, 16.0) as f32; + let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + let length_norm = comp.eval_number(node, "Length", time, 0.15, &self.expr).max(0.0) as f32; + // Length is normalized to image width; src.size[0] already scales cleanly by proxy_scale. + let length_px = (length_norm * src.size[0] as f32).min(256.0); + let falloff = self.eval_num_alias(comp, node, "Falloff", "Decay", time, 1.0); + let strength = self.eval_num_alias(comp, node, "Strength", "Gain", time, 1.0); + let tint_r = self.eval_num_alias(comp, node, "ColorRed", "RedScale", time, 1.0); + let tint_g = self.eval_num_alias(comp, node, "ColorGreen", "GreenScale", time, 1.0); + let tint_b = self.eval_num_alias(comp, node, "ColorBlue", "BlueScale", time, 1.0); + let merge_orig = comp.eval_number(node, "MergeWithOriginal", time, 1.0, &self.expr) > 0.5; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.process_skip(comp, node, time); + let steps = if self.hiq { 28.0 } else { 14.0 }; + + let mut u_ext = UniformParams::default(); + u_ext.p[0] = [low, high, strength, 0.0]; + + let mut u_str = UniformParams::default(); + u_str.p[0] = [num_points, angle_deg.to_radians(), length_px, falloff]; + u_str.p[1] = [tint_r, tint_g, tint_b, merge_orig as u8 as f32]; + u_str.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32]; + u_str.p[3] = skip; + u_str.p[4] = [steps, low, high, strength]; + + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key( + node, + "Highlight", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u_str.p[..5]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let bright = self.alloc_tex(src.size, src.depth, 0); + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + let mut pipes = self.depth_optical_pipelines().borrow_mut(); + pipes.dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::HighlightExtract, + &src.view, + &self.dummy.view, + None, + &self.dummy.view, + &bright, + &u_ext, + ); + pipes.dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::HighlightStreaks, + &src.view, + &bright.view, + None, + mv, + &dst, + &u_str, + ); + drop(pipes); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + /// 4. `HotSpot`: radial primary glow + optional secondary optical lens flare elements. + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_hot_spot( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + if blend <= 1e-6 && !mbm { + return src; + } + let src = self.crop_to_canvas(enc, src); + + let p_center = if node.inputs.contains_key("Center") { + comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr) + } else { + comp.eval_point(node, "PrimaryPosition", time, [0.5, 0.5], &self.expr) + }; + let default_sec = [1.0 - p_center[0], 1.0 - p_center[1]]; + let has_explicit_sec = node.inputs.contains_key("SecondaryCenter") + || node.inputs.contains_key("SecondaryPosition") + || node.inputs.contains_key("SecondaryStrength"); + let s_center = if node.inputs.contains_key("SecondaryCenter") { + comp.eval_point(node, "SecondaryCenter", time, default_sec, &self.expr) + } else if node.inputs.contains_key("SecondaryPosition") { + comp.eval_point(node, "SecondaryPosition", time, default_sec, &self.expr) + } else { + default_sec + }; + + let primary_size = self.eval_num_alias(comp, node, "PrimarySize", "HotSpotSize", time, 0.25); + let primary_strength = comp.eval_number(node, "PrimaryStrength", time, 1.0, &self.expr) as f32; + let primary_aspect = self.eval_num_alias(comp, node, "PrimaryAspect", "Aspect", time, 1.0); + let primary_r = self.eval_num_alias(comp, node, "PrimaryRed", "ColorRed", time, 1.0); + let primary_g = self.eval_num_alias(comp, node, "PrimaryGreen", "ColorGreen", time, 1.0); + let primary_b = self.eval_num_alias(comp, node, "PrimaryBlue", "ColorBlue", time, 1.0); + let default_sec_elems = if has_explicit_sec { 4.0 } else { 0.0 }; + let sec_elements = self + .eval_num_alias(comp, node, "SecondaryElements", "Elements", time, default_sec_elems) + .clamp(0.0, 16.0); + let sec_strength = comp.eval_number(node, "SecondaryStrength", time, 0.5, &self.expr) as f32; + let sec_size = comp.eval_number(node, "SecondarySize", time, (primary_size * 0.45) as f64, &self.expr) as f32; + let apply_mode = parse_hotspot_apply_mode(comp, node, time, &self.expr); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.process_skip(comp, node, time); + + let mut u = UniformParams::default(); + u.p[0] = [p_center[0] as f32, p_center[1] as f32, s_center[0] as f32, s_center[1] as f32]; + u.p[1] = [primary_size, primary_strength, primary_aspect, sec_elements]; + u.p[2] = [primary_r, primary_g, primary_b, apply_mode as f32]; + u.p[3] = [sec_strength, sec_size, blend, mask.is_some() as u8 as f32]; + u.p[4] = [mask_inv as u8 as f32, mbm as u8 as f32, 0.0, 0.0]; + u.p[5] = skip; + + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key( + node, + "HotSpot", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..6]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.depth_optical_pipelines().borrow_mut().dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::HotSpot, + &src.view, + &self.dummy.view, + None, + mv, + &dst, + &u, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + /// 5. `RankFilter`: GPU order-statistic filter (Min / Median / Max / Percentile). + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_rank_filter( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + let raw_size = self.eval_num_alias(comp, node, "Size", "FilterSize", time, 1.0).max(0.0); + let proxy = self.proxy_scale.max(1) as f32; + let radius = (raw_size / proxy).round().clamp(0.0, MAX_RANK_RADIUS); + let skip = self.combined_skip(comp, node, time); + let all_skipped = skip.iter().all(|&s| s > 0.5); + if (blend <= 1e-6 || radius < 0.5 || all_skipped) && !mbm { + return src; + } + + let src = self.crop_to_canvas(enc, src); + let rank = comp.eval_number(node, "Rank", time, 0.5, &self.expr).clamp(0.0, 1.0) as f32; + let ftype = parse_rank_filter_type(comp, node, time, &self.expr); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + + let mut u = UniformParams::default(); + u.p[0] = [radius, rank, ftype as f32, 0.0]; + u.p[1] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32]; + u.p[2] = skip; + + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key( + node, + "RankFilter", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..3]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.depth_optical_pipelines().borrow_mut().dispatch( + &self.device, + &self.queue, + enc, + DepthOpticalOp::RankFilter, + &src.view, + &self.dummy.view, + None, + mv, + &dst, + &u, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn px_at(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] { + let i = ((y * w + x) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + } + + fn eval_px(eng: &mut Engine, comp: &Comp, name: &str) -> (CachedTexture, Vec) { + let id = comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}")); + let (tex, stats) = eng.evaluate(comp, id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported: {:?}", stats.unsupported_nodes); + let rgba = eng.readback_rgba(&tex).expect("readback rgba"); + (tex, rgba) + } + + fn z_bg_nodes(prefix: &str, w: u32, h: u32, rgba: [f32; 4], z: f32) -> String { + format!( + r#" + {prefix}Col = Background {{ + Inputs = {{ + Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, + TopLeftRed = Input {{ Value = {}, }}, TopLeftGreen = Input {{ Value = {}, }}, + TopLeftBlue = Input {{ Value = {}, }}, TopLeftAlpha = Input {{ Value = {}, }}, + }}, + }}, + {prefix}Z = Background {{ + Inputs = {{ + Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, + TopLeftRed = Input {{ Value = {z}, }}, TopLeftAlpha = Input {{ Value = 1.0, }}, + }}, + }}, + {prefix}ZAux = Dimension.CopyAux {{ + Inputs = {{ + Mode = Input {{ Value = 1, }}, + Channel = Input {{ Value = FuID {{ "Z" }}, }}, + Input = Input {{ SourceOp = "{prefix}Z", Source = "Output", }}, + }}, + }}, + {prefix} = ChannelBoolean {{ + Inputs = {{ + ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }}, + ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }}, + EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }}, + Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }}, + Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }}, + }}, + }}, + "#, + rgba[0], rgba[1], rgba[2], rgba[3] + ) + } + + #[test] + fn depth_blur_aux_z_focal_sharp_far_and_sky_blurred() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // 64x64 sharp vertical stripe across two depth layers: + // top half (y<32 in texture = Fusion Y>0.5) has focal z=-5.0, bottom half has far z=-25.0. + let src = format!( + r#"Composition {{ + CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, + Tools = ordered() {{ + {} + {} + MTop = RectangleMask {{ + Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.75 }}, }}, Width = Input {{ Value = 1.0, }}, Height = Input {{ Value = 0.5, }}, }}, + }}, + MStripe = RectangleMask {{ + Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }}, + }}, + White = Background {{ + Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }}, + EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }}, + }}, + Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + Striped = Merge {{ + Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }}, + }}, + DepthSplit = Merge {{ + Inputs = {{ + Background = Input {{ SourceOp = "FarZ", Source = "Output", }}, + Foreground = Input {{ SourceOp = "NearZ", Source = "Output", }}, + EffectMask = Input {{ SourceOp = "MTop", Source = "Mask", }}, + PerformDepthMerge = Input {{ Value = 1, }}, + }}, + }}, + Scene = ChannelBoolean {{ + Inputs = {{ + ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }}, + ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }}, + EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }}, + Background = Input {{ SourceOp = "Striped", Source = "Output", }}, + Foreground = Input {{ SourceOp = "DepthSplit", Source = "Output", }}, + }}, + }}, + DB = DepthBlur {{ + Inputs = {{ + Input = Input {{ SourceOp = "Scene", Source = "Output", }}, + XBlurSize = Input {{ Value = 60.0, }}, + FocalPoint = Input {{ Value = -5.0, }}, + DepthOfField = Input {{ Value = 1.0, }}, + ZScale = Input {{ Value = 20.0, }}, + }}, + }}, + }}, + }}"#, + z_bg_nodes("NearZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -5.0), + z_bg_nodes("FarZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -25.0), + ); + let comp = Comp::from_fusion_str(&src).expect("parse DepthBlur aux.z comp"); + let (tex, px) = eval_px(&mut eng, &comp, "DB"); + assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "DepthBlur must preserve aux.z"); + + // Stripe occupies x in [28..36]; check 2px outside stripe edge (x=25): + // Near row (y=12) is at focal plane -> stays black (0); Far row (y=52) is out of focus -> blurred (>15)! + let near_outside = px_at(&px, 64, 25, 12)[0]; + let far_outside = px_at(&px, 64, 25, 52)[0]; + let near_inside = px_at(&px, 64, 32, 12)[0]; + let far_inside = px_at(&px, 64, 32, 52)[0]; + assert!(near_outside <= 2, "focal plane outside stripe must stay sharp black, got {near_outside}"); + assert!(near_inside >= 250, "focal plane inside stripe must stay crisp white, got {near_inside}"); + assert!(far_outside >= 15, "far depth outside stripe must receive blur bleed, got {far_outside}"); + assert!(far_inside < near_inside, "far depth inside stripe must soften ({far_inside} vs {near_inside})"); + + // Verify EMPTY_Z_SENTINEL (-1e30) in aux.z is treated as far background (full CoC blur). + let sky_src = format!( + r#"Composition {{ + CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, + Tools = ordered() {{ + {} + MStripe = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }}, }}, + Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }}, + White = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }}, + EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }}, }}, + Striped = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }}, }}, + Scene = ChannelBoolean {{ + Inputs = {{ + ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }}, + ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }}, + EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }}, + Background = Input {{ SourceOp = "Striped", Source = "Output", }}, + Foreground = Input {{ SourceOp = "SkyZ", Source = "Output", }}, + }}, + }}, + DB = DepthBlur {{ + Inputs = {{ + Input = Input {{ SourceOp = "Scene", Source = "Output", }}, + XBlurSize = Input {{ Value = 60.0, }}, + FocalPoint = Input {{ Value = -5.0, }}, + ZScale = Input {{ Value = 20.0, }}, + }}, + }}, + }}, + }}"#, + z_bg_nodes("SkyZ", 64, 64, [0.0, 0.0, 0.0, 1.0], EMPTY_Z_SENTINEL), + ); + let sky_comp = Comp::from_fusion_str(&sky_src).expect("parse DepthBlur sky comp"); + let (_, sky_px) = eval_px(&mut eng, &sky_comp, "DB"); + assert!(px_at(&sky_px, 64, 25, 32)[0] >= 15, "EMPTY_Z_SENTINEL sky must blur as far background"); + } + + #[test] + fn depth_blur_external_blur_image_and_proxy_scale() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // BlurImage has black top half (depth=0, sharp) and white bottom half (depth=1, blurred). + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + MStripe = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.125, }, Height = Input { Value = 1.0, }, }, }, + Black = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, }, + Stripe = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, + EffectMask = Input { SourceOp = "MStripe", Source = "Mask", }, }, }, + Img = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "Stripe", Source = "Output", }, }, }, + MBot = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.25 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 0.5, }, }, }, + DepthMap = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, + EffectMask = Input { SourceOp = "MBot", Source = "Mask", }, }, }, + DB = DepthBlur { + Inputs = { + Input = Input { SourceOp = "Img", Source = "Output", }, + BlurImage = Input { SourceOp = "DepthMap", Source = "Output", }, + BlurChannel = Input { Value = 5, }, + Filter = Input { Value = 1, }, + BlurSize = Input { Value = 72.0, }, + FocalPoint = Input { Value = 0.0, }, + ZScale = Input { Value = 1.0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse DepthBlur BlurImage comp"); + let (_, px) = eval_px(&mut eng, &comp, "DB"); + assert!(px_at(&px, 64, 24, 12)[0] <= 2, "top half depth=0 must stay sharp"); + assert!(px_at(&px, 64, 24, 52)[0] >= 15, "bottom half depth=1 must blur"); + + eng.proxy_scale = 2; + let (tex_p, px_p) = eval_px(&mut eng, &comp, "DB"); + assert_eq!(tex_p.size, [32, 32]); + assert!(px_at(&px_p, 32, 12, 6)[0] <= 2, "proxy top half must stay sharp"); + assert!(px_at(&px_p, 32, 12, 26)[0] >= 15, "proxy bottom half must blur"); + } + + #[test] + fn fog_aux_z_near_far_falloff_alpha_and_fog_image() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // Left=near(-2, red), Middle=mid(-16, green), Right=far(-30, blue). + let src = format!( + r#"Composition {{ + CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, + Tools = ordered() {{ + {} + {} + {} + MLeft = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.16, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }}, + MMid = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }}, + M1 = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "Far", Source = "Output", }}, Foreground = Input {{ SourceOp = "Mid", Source = "Output", }}, EffectMask = Input {{ SourceOp = "MMid", Source = "Mask", }}, PerformDepthMerge = Input {{ Value = 1, }}, }}, }}, + Scene = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "M1", Source = "Output", }}, Foreground = Input {{ SourceOp = "Near", Source = "Output", }}, EffectMask = Input {{ SourceOp = "MLeft", Source = "Mask", }}, PerformDepthMerge = Input {{ Value = 1, }}, }}, }}, + FogSolid = Fog {{ + Inputs = {{ + Input = Input {{ SourceOp = "Scene", Source = "Output", }}, + ZNearPlane = Input {{ Value = -2.0, }}, + ZFarPlane = Input {{ Value = -30.0, }}, + Falloff = Input {{ Value = 1.0, }}, + FogRed = Input {{ Value = 1.0, }}, FogGreen = Input {{ Value = 1.0, }}, FogBlue = Input {{ Value = 1.0, }}, + }}, + }}, + TintImg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }}, + TopLeftRed = Input {{ Value = 0.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }}, }}, }}, + FogTex = Fog {{ + Inputs = {{ + Input = Input {{ SourceOp = "Scene", Source = "Output", }}, + FogImage = Input {{ SourceOp = "TintImg", Source = "Output", }}, + NearPlane = Input {{ Value = -2.0, }}, + FarPlane = Input {{ Value = -30.0, }}, + }}, + }}, + EmptySky = Background {{ Inputs = {{ Width = Input {{ Value = 16, }}, Height = Input {{ Value = 16, }}, TopLeftAlpha = Input {{ Value = 0.0, }}, }}, }}, + FogSkyZeroA = Fog {{ Inputs = {{ Input = Input {{ SourceOp = "EmptySky", Source = "Output", }}, FogAlpha = Input {{ Value = 0.0, }}, }}, }}, + FogSkyFullA = Fog {{ Inputs = {{ Input = Input {{ SourceOp = "EmptySky", Source = "Output", }}, FogAlpha = Input {{ Value = 1.0, }}, FogRed = Input {{ Value = 0.5, }}, FogGreen = Input {{ Value = 0.5, }}, FogBlue = Input {{ Value = 0.5, }}, }}, }}, + }}, + }}"#, + z_bg_nodes("Near", 32, 32, [1.0, 0.0, 0.0, 1.0], -2.0), + z_bg_nodes("Mid", 32, 32, [0.0, 1.0, 0.0, 1.0], -16.0), + z_bg_nodes("Far", 32, 32, [0.0, 0.0, 1.0, 1.0], -30.0), + ); + let comp = Comp::from_fusion_str(&src).expect("parse Fog comp"); + let (tex, px) = eval_px(&mut eng, &comp, "FogSolid"); + assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Fog must preserve aux.z for chaining"); + + let near_c = px_at(&px, 32, 4, 16); + let mid_c = px_at(&px, 32, 16, 16); + let far_c = px_at(&px, 32, 28, 16); + assert!(near_c[0] >= 250 && near_c[1] <= 3 && near_c[2] <= 3, "near plane must have 0% fog, got {near_c:?}"); + assert!((mid_c[0] as i32 - 128).abs() <= 6 && mid_c[1] >= 250, "mid plane must have ~50% white fog on green, got {mid_c:?}"); + assert!(far_c[0] >= 250 && far_c[1] >= 250 && far_c[2] >= 250, "far plane must have 100% white fog, got {far_c:?}"); + + let (_, px_t) = eval_px(&mut eng, &comp, "FogTex"); + let far_t = px_at(&px_t, 32, 28, 16); + assert!(far_t[0] <= 3 && far_t[1] >= 250 && far_t[2] >= 250, "FogImage cyan must tint far fog, got {far_t:?}"); + + let (_, sky0) = eval_px(&mut eng, &comp, "FogSkyZeroA"); + assert_eq!(px_at(&sky0, 16, 8, 8)[3], 0, "FogAlpha=0 must keep empty sky transparent"); + let (_, sky1) = eval_px(&mut eng, &comp, "FogSkyFullA"); + assert!(px_at(&sky1, 16, 8, 8)[3] >= 250 && (px_at(&sky1, 16, 8, 8)[0] as i32 - 128).abs() <= 4); + } + + #[test] + fn highlight_thresholds_and_casts_directional_streaks() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, }, + MBright = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.08, }, Height = Input { Value = 0.08, }, }, }, + MDim = RectangleMask { Inputs = { Center = Input { Value = { 0.15, 0.15 }, }, Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, }, + Bright = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, + EffectMask = Input { SourceOp = "MBright", Source = "Mask", }, }, }, + Dim = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.3, }, TopLeftGreen = Input { Value = 0.3, }, TopLeftBlue = Input { Value = 0.3, }, + EffectMask = Input { SourceOp = "MDim", Source = "Mask", }, }, }, + M1 = Merge { Inputs = { Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Dim", Source = "Output", }, }, }, + Scene = Merge { Inputs = { Background = Input { SourceOp = "M1", Source = "Output", }, Foreground = Input { SourceOp = "Bright", Source = "Output", }, }, }, + HL = Highlight { + Inputs = { + Input = Input { SourceOp = "Scene", Source = "Output", }, + Low = Input { Value = 0.6, }, High = Input { Value = 0.9, }, + NumberOfPoints = Input { Value = 4, }, Angle = Input { Value = 0.0, }, + Length = Input { Value = 0.25, }, Falloff = Input { Value = 1.0, }, + ColorRed = Input { Value = 1.0, }, ColorGreen = Input { Value = 0.5, }, ColorBlue = Input { Value = 0.2, }, + MergeWithOriginal = Input { Value = 1, }, + }, + }, + HLOnly = Highlight { + Inputs = { + Input = Input { SourceOp = "Scene", Source = "Output", }, + Low = Input { Value = 0.6, }, High = Input { Value = 0.9, }, + NumberOfPoints = Input { Value = 4, }, Length = Input { Value = 0.25, }, + MergeWithOriginal = Input { Value = 0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Highlight comp"); + let (_, px) = eval_px(&mut eng, &comp, "HL"); + // Along +X ray from center (32,32): (40,32) must receive warm tinted streak (R > G > B > 0). + let ray_x = px_at(&px, 64, 40, 32); + let ray_y = px_at(&px, 64, 32, 40); + let off_diag = px_at(&px, 64, 44, 44); + assert!(ray_x[0] >= 20 && ray_x[0] > ray_x[1] && ray_x[1] > ray_x[2], "X ray must glow warm, got {ray_x:?}"); + assert!(ray_y[0] >= 20, "Y ray must glow for 4-point star, got {ray_y:?}"); + assert!(off_diag[0] <= 2, "off-ray diagonal must stay dark, got {off_diag:?}"); + + // MergeWithOriginal=0 must drop the dim patch (lum=0.3 < Low=0.6). + let (_, px_only) = eval_px(&mut eng, &comp, "HLOnly"); + let dim_px = px_at(&px_only, 64, 10, 54); + assert!(dim_px[0] <= 2 && dim_px[1] <= 2 && dim_px[2] <= 2, "dim spot below Low must not highlight, got {dim_px:?}"); + + eng.proxy_scale = 2; + let (tex_p, px_p) = eval_px(&mut eng, &comp, "HL"); + assert_eq!(tex_p.size, [32, 32]); + assert!(px_at(&px_p, 32, 20, 16)[0] >= 15, "proxy Highlight must scale streaks cleanly"); + } + + #[test] + fn hot_spot_primary_secondary_apply_mode_and_mask() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.05, }, TopLeftGreen = Input { Value = 0.05, }, TopLeftBlue = Input { Value = 0.05, }, }, }, + HS = HotSpot { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Center = Input { Value = { 0.25, 0.25 }, }, + SecondaryCenter = Input { Value = { 0.75, 0.75 }, }, + PrimarySize = Input { Value = 0.14, }, + PrimaryStrength = Input { Value = 1.0, }, + PrimaryRed = Input { Value = 1.0, }, PrimaryGreen = Input { Value = 0.5, }, PrimaryBlue = Input { Value = 0.2, }, + SecondaryElements = Input { Value = 4, }, + ApplyMode = Input { Value = FuID { "Add" }, }, + }, + }, + MLeft = RectangleMask { Inputs = { Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, }, + HSMasked = HotSpot { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Center = Input { Value = { 0.75, 0.5 }, }, + PrimarySize = Input { Value = 0.2, }, + EffectMask = Input { SourceOp = "MLeft", Source = "Mask", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse HotSpot comp"); + let (_, px) = eval_px(&mut eng, &comp, "HS"); + // Primary at Fusion (0.25, 0.25) -> texture pixel (16, 48) + let primary = px_at(&px, 64, 16, 48); + assert!(primary[0] >= 240 && primary[0] > primary[1] && primary[1] > primary[2], "primary core must be bright warm, got {primary:?}"); + + // Sample along secondary axis (0.5..0.85, 0.5..0.85) vs far off-axis corner (0.85, 0.15 -> px 54, 54). + let mut max_axis = 0u8; + for step in 32..56 { + let y = 63 - step; + let p = px_at(&px, 64, step, y); + max_axis = max_axis.max(p[0]).max(p[1]).max(p[2]); + } + let off_corner = px_at(&px, 64, 56, 56); + assert!(max_axis > off_corner[0] + 20, "secondary elements must brighten optical axis ({max_axis} vs {off_corner:?})"); + + let (_, px_m) = eval_px(&mut eng, &comp, "HSMasked"); + // Center of flare is at x=48 (outside left-half mask) -> must remain background (~13). + assert!(px_at(&px_m, 64, 48, 32)[0] <= 16, "EffectMask must block HotSpot outside mask"); + } + + #[test] + fn rank_filter_min_median_max_filter_type_channels_and_proxy() { + let Ok(mut eng) = Engine::new_headless() else { return }; + // 32x32 mid-gray (0.5) field with a 1px white impulse at center (16,16). + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + Gray = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, + TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, }, }, + DotMask = RectangleMask { Inputs = { Center = Input { Value = { 0.515625, 0.484375 }, }, Width = Input { Value = 0.03125, }, Height = Input { Value = 0.03125, }, }, }, + White = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, + TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, }, + EffectMask = Input { SourceOp = "DotMask", Source = "Mask", }, }, }, + Scene = Merge { Inputs = { Background = Input { SourceOp = "Gray", Source = "Output", }, Foreground = Input { SourceOp = "White", Source = "Output", }, }, }, + RMin = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.0, }, }, }, + RMed = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, }, + RPct = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.9375, }, }, }, + RMaxBox = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 0, }, }, }, + RMaxCir = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 1, }, }, }, + RSkipR = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, ProcessRed = Input { Value = 0, }, }, }, + RBig = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, FilterSize = Input { Value = 4, }, Rank = Input { Value = 1.0, }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse RankFilter comp"); + let (_, scene_px) = eval_px(&mut eng, &comp, "Scene"); + assert!(px_at(&scene_px, 32, 16, 16)[0] >= 250, "sanity: center impulse must be white"); + + let (_, min_px) = eval_px(&mut eng, &comp, "RMin"); + assert!((px_at(&min_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Min must erode 1px white impulse to 0.5"); + + let (_, med_px) = eval_px(&mut eng, &comp, "RMed"); + assert!((px_at(&med_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Median must remove 1px white impulse"); + + // In 3x3 (9 samples: eight 0.5 + one 1.0), Rank=0.9375 -> pos = 7.5 -> midpoint between 0.5 and 1.0 (~0.75 = 191)! + let (_, pct_px) = eval_px(&mut eng, &comp, "RPct"); + assert!((px_at(&pct_px, 32, 16, 16)[0] as i32 - 191).abs() <= 4, "Percentile rank=0.9375 must interpolate to ~191, got {:?}", px_at(&pct_px, 32, 16, 16)); + + let (_, box_px) = eval_px(&mut eng, &comp, "RMaxBox"); + assert!(px_at(&box_px, 32, 17, 17)[0] >= 250, "Max Box(r=1) must dilate impulse to diagonal corner (17,17)"); + + let (_, cir_px) = eval_px(&mut eng, &comp, "RMaxCir"); + assert!(px_at(&cir_px, 32, 17, 16)[0] >= 250, "Max Circle(r=1) must dilate impulse to cardinal neighbor"); + assert!((px_at(&cir_px, 32, 17, 17)[0] as i32 - 128).abs() <= 4, "Max Circle(r=1) must exclude diagonal corner"); + + let (_, skip_px) = eval_px(&mut eng, &comp, "RSkipR"); + let n_px = px_at(&skip_px, 32, 17, 16); + assert!((n_px[0] as i32 - 128).abs() <= 4 && n_px[1] >= 250, "ProcessRed=0 must skip R while filtering G: {n_px:?}"); + + eng.proxy_scale = 2; + let (tex_p, _) = eval_px(&mut eng, &comp, "RBig"); + assert_eq!(tex_p.size, [16, 16]); + } + + #[test] + fn uniform_ring_growth_reset_trim_and_hdr_float16() { + let Ok(mut eng) = Engine::new_headless() else { return }; + { + let mut pipes = eng.depth_optical_pipelines().borrow_mut(); + let u = UniformParams::default(); + for _ in 0..520 { + pipes.alloc_uniform_slot(&eng.device, &eng.queue, &u); + } + assert_eq!(pipes.uniform_chunks.len(), 2, "520 slots must allocate 2x512 chunks"); + pipes.reset_uniform_cursor(); + assert_eq!(pipes.uniform_cursor, 0); + pipes.trim_uniform_chunks(1); + assert_eq!(pipes.uniform_chunks.len(), 1); + } + + // Verify Float16 HDR compilation & execution across all 5 ops. + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + Bg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 3, }, + TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.2, }, }, }, + F = Fog { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, FogOpacity = Input { Value = 0.25, }, }, }, + H = Highlight { Inputs = { Input = Input { SourceOp = "F", Source = "Output", }, Low = Input { Value = 0.3, }, }, }, + S = HotSpot { Inputs = { Input = Input { SourceOp = "H", Source = "Output", }, PrimarySize = Input { Value = 0.3, }, }, }, + R = RankFilter { Inputs = { Input = Input { SourceOp = "S", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, }, + D = DepthBlur { Inputs = { Input = Input { SourceOp = "R", Source = "Output", }, BlurChannel = Input { Value = 5, }, BlurSize = Input { Value = 16.0, }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse HDR chain"); + let (tex, _) = eval_px(&mut eng, &comp, "D"); + assert_eq!(tex.depth, BitDepth::Float16); + } +} diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index a554bfe6b67713e6d451dfd6a62f8c92d3d0f468..39e02c1c428a157481fa59f71855fc38f0269d44 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -16,6 +16,7 @@ use web_time::Instant; mod io; mod alpha_keyers; mod aux_ops; +mod depth_optical; mod composite; mod transform; mod color; @@ -72,6 +73,7 @@ pub struct Engine { pipelines_f32: OnceCell>, aux_pipelines: OnceCell>, alpha_keyer_pipelines: OnceCell>, + depth_optical_pipelines: OnceCell>, motion_blur: crate::motion_blur::MotionBlurPipelines, supports_f32_filter: bool, scene3d: crate::scene3d::Scene3DRenderer, @@ -177,6 +179,7 @@ impl Engine { pipelines_f32: OnceCell::new(), aux_pipelines: OnceCell::new(), alpha_keyer_pipelines: OnceCell::new(), + depth_optical_pipelines: OnceCell::new(), motion_blur: crate::motion_blur::MotionBlurPipelines::default(), supports_f32_filter, scene3d, @@ -321,6 +324,9 @@ impl Engine { if let Some(ak) = self.alpha_keyer_pipelines.get() { ak.borrow_mut().reset_uniform_cursor(); } + if let Some(dp) = self.depth_optical_pipelines.get() { + dp.borrow_mut().reset_uniform_cursor(); + } if let Some(of) = self.optflow.get() { of.reset_uniform_cursor(); } @@ -335,6 +341,9 @@ impl Engine { if let Some(ak) = self.alpha_keyer_pipelines.get() { ak.borrow_mut().trim_uniform_chunks(2); } + if let Some(dp) = self.depth_optical_pipelines.get() { + dp.borrow_mut().trim_uniform_chunks(2); + } self.media.trim_nv12_uniform_chunks(2); } @@ -853,6 +862,11 @@ impl Engine { "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats), "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats), "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats), + "DepthBlur" => self.eval_depth_blur(comp, node, time, frame_i, enc, visiting, stats), + "Fog" => self.eval_fog(comp, node, time, frame_i, enc, visiting, stats), + "Highlight" => self.eval_highlight(comp, node, time, frame_i, enc, visiting, stats), + "HotSpot" => self.eval_hot_spot(comp, node, time, frame_i, enc, visiting, stats), + "RankFilter" => self.eval_rank_filter(comp, node, time, frame_i, enc, visiting, stats), "ErodeDilate" => { let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats); if self.multiplies_by_mask(comp, node, time) { diff --git a/crates/engine/src/shaders/depth_optical.wgsl b/crates/engine/src/shaders/depth_optical.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..2f03eef0de8040be2168ac63a9bdac5e389041e9 --- /dev/null +++ b/crates/engine/src/shaders/depth_optical.wgsl @@ -0,0 +1,685 @@ +// Wave 35B — Depth, Optical & Filter FX compute shaders (WGSL): +// 1. DepthBlur (`depth_blur_op`) +// 2. Fog (`fog_op`) +// 3. Highlight (`highlight_extract_op`, `highlight_streaks_op`) +// 4. HotSpot (`hot_spot_op`) +// 5. RankFilter (`rank_filter_op`) +// +// WebGPU safety: +// - `z_tex` (R32Float) is bound with `filterable: false` and ONLY read via `textureLoad`. +// - Output `dst_tex` uses WriteOnly storage texture (never `read_write`). +// - `HDR_FLOAT` and `texture_storage_2d` are patched per target format. + +struct Params { + p: array, 16>, +}; + +const HDR_FLOAT: bool = false; +const EMPTY_Z_THRESH: f32 = -0.5e30; +const PI: f32 = 3.14159265359; +const TAU: f32 = 6.28318530718; +const GOLDEN_ANGLE: f32 = 2.39996322973; + +@group(0) @binding(0) var src_tex: texture_2d; +@group(0) @binding(1) var aux_img_tex: texture_2d; +@group(0) @binding(2) var z_tex: texture_2d; +@group(0) @binding(3) var mask_tex: texture_2d; +@group(0) @binding(4) var samp: sampler; +@group(0) @binding(5) var dst_tex: texture_storage_2d; +@group(0) @binding(6) var params: Params; + +fn sanitize_f32(v: f32, lim: f32) -> f32 { + return select(0.0, clamp(v, -lim, lim), v >= -1e30 && v <= 1e30); +} + +fn sanitize_out(c: vec4) -> vec4 { + if (HDR_FLOAT) { + return vec4( + sanitize_f32(c.r, 65504.0), + sanitize_f32(c.g, 65504.0), + sanitize_f32(c.b, 65504.0), + clamp(sanitize_f32(c.a, 1.0), 0.0, 1.0), + ); + } + return clamp( + vec4( + sanitize_f32(c.r, 1.0), + sanitize_f32(c.g, 1.0), + sanitize_f32(c.b, 1.0), + sanitize_f32(c.a, 1.0), + ), + vec4(0.0), + vec4(1.0), + ); +} + +fn luma_709(rgb: vec3) -> f32 { + return dot(rgb, vec3(0.299, 0.587, 0.114)); +} + +fn eval_mask(uv: vec2, has_mask: f32, mask_inv: f32) -> f32 { + if (has_mask < 0.5) { + return 1.0; + } + let raw = clamp(textureSampleLevel(mask_tex, samp, uv, 0.0).a, 0.0, 1.0); + return select(raw, 1.0 - raw, mask_inv > 0.5); +} + +fn finalize_fx( + src: vec4, + fx: vec4, + uv: vec2, + blend: f32, + has_mask: f32, + mask_inv: f32, + mbm: f32, + skip: vec4, +) -> vec4 { + let m = eval_mask(uv, has_mask, mask_inv); + let eff = clamp(blend * m, 0.0, 1.0); + var out = mix(src, fx, eff); + out = select(out, src, skip > vec4(0.5)); + if (mbm > 0.5 && has_mask > 0.5) { + out = out * m; + } + return sanitize_out(out); +} + +// Read Z from unfilterable R32Float z_tex using normalized UV via integer textureLoad. +fn load_z_at_uv(uv: vec2) -> f32 { + let z_dims = vec2(textureDimensions(z_tex)); + let px = clamp(vec2(floor(uv * vec2(z_dims))), vec2(0), z_dims - vec2(1)); + return textureLoad(z_tex, px, 0).x; +} + +fn load_z_at_px(px: vec2, dst_dims: vec2) -> f32 { + let z_dims = vec2(textureDimensions(z_tex)); + if (z_dims.x == dst_dims.x && z_dims.y == dst_dims.y) { + let c = clamp(px, vec2(0), z_dims - vec2(1)); + return textureLoad(z_tex, c, 0).x; + } + let uv = (vec2(px) + 0.5) / vec2(dst_dims); + return load_z_at_uv(uv); +} + +// Sample depth value for DepthBlur: +// depth_src_mode: 0 = z_tex (aux.z), 1 = aux_img_tex (BlurImage), 2 = src_tex +// channel: 0=R, 1=G, 2=B, 3=A, 4=Z, 5=Luma +fn sample_depth_blur_z(uv: vec2, depth_src_mode: i32, channel: i32) -> f32 { + if (depth_src_mode == 0) { + return load_z_at_uv(uv); + } + let c = select( + textureSampleLevel(src_tex, samp, uv, 0.0), + textureSampleLevel(aux_img_tex, samp, uv, 0.0), + depth_src_mode == 1, + ); + switch channel { + case 0: { return c.r; } + case 1: { return c.g; } + case 2: { return c.b; } + case 3: { return c.a; } + default: { return luma_709(c.rgb); } + } +} + +fn compute_coc(z: f32, focal: f32, dof: f32, z_scale: f32, is_z_aux: bool) -> f32 { + if (is_z_aux && z <= EMPTY_Z_THRESH) { + return 1.0; + } + let dist = max(0.0, abs(z - focal) - 0.5 * max(dof, 0.0)); + return clamp(dist / max(abs(z_scale), 1e-4), 0.0, 1.0); +} + +fn sample_src_clipped(uv: vec2, clamp_edges: f32) -> vec4 { + if (clamp_edges < 0.5 && (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)) { + return vec4(0.0); + } + return textureSampleLevel(src_tex, samp, clamp(uv, vec2(0.0), vec2(1.0)), 0.0); +} + +// ----------------------------------------------------------------------------- +// 1. DepthBlur +// p[0] = (max_radius_px, focal_point, dof, z_scale) +// p[1] = (filter_mode, depth_src_mode, channel, clamp_edges) +// p[2] = (blend, has_mask, mask_inv, mbm) +// p[3] = process_skip (r, g, b, a) +// p[4] = (tap_count, 0, 0, 0) +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn depth_blur_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let fdims = vec2(dims); + let uv = (vec2(gid.xy) + 0.5) / fdims; + let src = textureSampleLevel(src_tex, samp, uv, 0.0); + + let max_r = params.p[0].x; + let focal = params.p[0].y; + let dof = params.p[0].z; + let z_scale = params.p[0].w; + let filter_mode = i32(round(params.p[1].x)); + let depth_src_mode = i32(round(params.p[1].y)); + let channel = i32(round(params.p[1].z)); + let clamp_edges = params.p[1].w; + let is_z_aux = depth_src_mode == 0; + + let z_center = sample_depth_blur_z(uv, depth_src_mode, channel); + let coc_center = compute_coc(z_center, focal, dof, z_scale, is_z_aux); + let radius = coc_center * max_r; + + var blurred = src; + if (radius >= 0.25) { + let inv_dims = 1.0 / fdims; + var accum = src; + var w_sum = 1.0; + if (filter_mode == 1) { + // Box kernel (up to 7x7 grid scaled to radius) + let steps = clamp(i32(round(params.p[4].x)), 1, 3); + let step_px = radius / f32(steps); + for (var dy = -steps; dy <= steps; dy = dy + 1) { + for (var dx = -steps; dx <= steps; dx = dx + 1) { + if (dx == 0 && dy == 0) { + continue; + } + let off_uv = vec2(f32(dx), f32(dy)) * step_px * inv_dims; + let su = uv + off_uv; + let sz = sample_depth_blur_z(clamp(su, vec2(0.0), vec2(1.0)), depth_src_mode, channel); + let scoc = compute_coc(sz, focal, dof, z_scale, is_z_aux); + // Suppress sharp foreground leaking onto blurred background while allowing + // blurred foreground to bleed softly over background. + let depth_w = select(smoothstep(0.0, max(coc_center, 0.05), scoc), 1.0, !is_z_aux || sz <= z_center + 1e-4); + let w = max(depth_w, 0.05); + accum += sample_src_clipped(su, clamp_edges) * w; + w_sum += w; + } + } + } else { + // Disc (0), Gaussian (2), or Lens Bokeh (3) via Vogel spiral + let taps = clamp(i32(round(params.p[4].x)), 8, 48); + let ftaps = f32(taps); + for (var i = 0; i < taps; i = i + 1) { + let fi = f32(i) + 0.5; + let r_norm = sqrt(fi / ftaps); + let theta = fi * GOLDEN_ANGLE; + let off_uv = vec2(cos(theta), sin(theta)) * (r_norm * radius) * inv_dims; + let su = uv + off_uv; + let sz = sample_depth_blur_z(clamp(su, vec2(0.0), vec2(1.0)), depth_src_mode, channel); + let scoc = compute_coc(sz, focal, dof, z_scale, is_z_aux); + let depth_w = select(smoothstep(0.0, max(coc_center, 0.05), scoc), 1.0, !is_z_aux || sz <= z_center + 1e-4); + var kw = 1.0; + if (filter_mode == 2) { + kw = exp(-2.5 * r_norm * r_norm); + } else if (filter_mode == 3) { + kw = 0.75 + 0.5 * r_norm * r_norm; + } + let sample_c = sample_src_clipped(su, clamp_edges); + if (filter_mode == 3) { + kw *= 1.0 + 0.5 * luma_709(max(sample_c.rgb, vec3(0.0))); + } + let w = kw * max(depth_w, 0.05); + accum += sample_c * w; + w_sum += w; + } + } + blurred = accum / max(w_sum, 1e-5); + } + + let out = finalize_fx( + src, + blurred, + uv, + params.p[2].x, + params.p[2].y, + params.p[2].z, + params.p[2].w, + params.p[3], + ); + textureStore(dst_tex, vec2(gid.xy), out); +} + +// ----------------------------------------------------------------------------- +// 2. Fog +// p[0] = (near_plane, far_plane, falloff, z_scale) +// p[1] = (fog_r, fog_g, fog_b, fog_a) +// p[2] = (fog_opacity, depth_mode, has_fog_color_img, 0) +// depth_mode: 0 = z_tex (aux.z), 1 = aux_img_tex luma (FogImage as depth) +// p[3] = (blend, has_mask, mask_inv, mbm) +// p[4] = process_skip (r, g, b, a) +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn fog_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let fdims = vec2(dims); + let uv = (vec2(gid.xy) + 0.5) / fdims; + let src = textureSampleLevel(src_tex, samp, uv, 0.0); + + let near_p = params.p[0].x; + let far_p = params.p[0].y; + let falloff = max(params.p[0].z, 1e-4); + let z_scale = params.p[0].w; + var fog_col = params.p[1]; + let fog_opacity = clamp(params.p[2].x, 0.0, 1.0); + let depth_mode = i32(round(params.p[2].y)); + let has_fog_color_img = params.p[2].z > 0.5; + + if (has_fog_color_img) { + let fi = textureSampleLevel(aux_img_tex, samp, uv, 0.0); + fog_col = vec4(fog_col.rgb * fi.rgb, fog_col.a * fi.a); + } + + var t_raw = 0.0; + let denom = far_p - near_p; + if (depth_mode == 0) { + let z_raw = load_z_at_px(vec2(gid.xy), vec2(dims)); + if (z_raw <= EMPTY_Z_THRESH) { + t_raw = 1.0; + } else { + let z_eff = z_raw * z_scale; + if (abs(denom) > 1e-6) { + t_raw = clamp((z_eff - near_p) / denom, 0.0, 1.0); + } else { + t_raw = select(0.0, 1.0, z_eff <= near_p); + } + } + } else { + let d_img = textureSampleLevel(aux_img_tex, samp, uv, 0.0); + let z_eff = luma_709(d_img.rgb) * z_scale; + if (abs(denom) > 1e-6) { + t_raw = clamp((z_eff - near_p) / denom, 0.0, 1.0); + } else { + t_raw = clamp(z_eff, 0.0, 1.0); + } + } + + let f = clamp(pow(t_raw, falloff) * fog_opacity, 0.0, 1.0); + let fog_a = clamp(fog_col.a, 0.0, 1.0); + // Premultiplied fog composite: opaque surfaces always fog cleanly, while + // transparent sky receives fog scaled by FogAlpha. + let out_rgb = src.rgb * (1.0 - f) + fog_col.rgb * (f * (src.a + (1.0 - src.a) * fog_a)); + let out_a = src.a + (1.0 - src.a) * (f * fog_a); + let fogged = vec4(out_rgb, out_a); + + let out = finalize_fx( + src, + fogged, + uv, + params.p[3].x, + params.p[3].y, + params.p[3].z, + params.p[3].w, + params.p[4], + ); + textureStore(dst_tex, vec2(gid.xy), out); +} + +// ----------------------------------------------------------------------------- +// 3a. Highlight — bright pixel extraction pass +// p[0] = (low, high, strength, 0) +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn highlight_extract_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let src = textureSampleLevel(src_tex, samp, uv, 0.0); + let low = params.p[0].x; + let high = params.p[0].y; + let strength = max(params.p[0].z, 0.0); + + let lum = luma_709(max(src.rgb, vec3(0.0))); + var w = 0.0; + if (high > low + 1e-5) { + w = clamp((lum - low) / (high - low), 0.0, 1.0); + } else { + w = select(0.0, 1.0, lum > high + 1e-5); + } + let extracted = vec4(src.rgb * (w * strength), w * src.a); + textureStore(dst_tex, vec2(gid.xy), sanitize_out(extracted)); +} + +// ----------------------------------------------------------------------------- +// 3b. Highlight — directional starburst streaks + composite pass +// src_tex = original image +// aux_img_tex = extracted bright texture from highlight_extract_op +// p[0] = (num_points, angle_rad, length_px, falloff) +// p[1] = (tint_r, tint_g, tint_b, merge_with_original) +// p[2] = (blend, has_mask, mask_inv, mbm) +// p[3] = process_skip (r, g, b, a) +// p[4] = (steps_per_ray, 0, 0, 0) +// ----------------------------------------------------------------------------- +@compute @workgroup_size(8, 8) +fn highlight_streaks_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let fdims = vec2(dims); + let inv_dims = 1.0 / fdims; + let uv = (vec2(gid.xy) + 0.5) / fdims; + let src = textureSampleLevel(src_tex, samp, uv, 0.0); + + let num_points = clamp(i32(round(params.p[0].x)), 1, 16); + let base_angle = params.p[0].y; + let length_px = max(params.p[0].z, 0.0); + let falloff = max(params.p[0].w, 0.05); + let tint = params.p[1].rgb; + let merge_orig = params.p[1].w > 0.5; + let steps = clamp(i32(round(params.p[4].x)), 4, 48); + + let center_bright = textureSampleLevel(aux_img_tex, samp, uv, 0.0); + var streak = center_bright * 0.25; + if (length_px > 0.25) { + let fsteps = f32(steps); + let ray_norm = 1.0 / max(f32(num_points) * 0.35 + 0.65, 1.0); + for (var k = 0; k < num_points; k = k + 1) { + let a = base_angle + TAU * (f32(k) / f32(num_points)); + // Y-up Fusion angle -> Y-down texture coordinate step + let dir = vec2(cos(a), -sin(a)) * inv_dims; + var ray_acc = vec4(0.0); + var ray_wsum = 0.0; + for (var s = 1; s <= steps; s = s + 1) { + let t = f32(s) / fsteps; + let su = uv + dir * (t * length_px); + let w = pow(max(1.0 - t, 0.0), falloff * 1.8); + if (su.x >= 0.0 && su.x <= 1.0 && su.y >= 0.0 && su.y <= 1.0) { + ray_acc += textureSampleLevel(aux_img_tex, samp, su, 0.0) * w; + } + ray_wsum += w; + } + streak += (ray_acc / max(ray_wsum * 0.35, 1e-4)) * ray_norm; + } + } + + let colored_streak = vec4(streak.rgb * tint, clamp(streak.a, 0.0, 1.0)); + var fx = colored_streak; + if (merge_orig) { + fx = vec4( + src.rgb + colored_streak.rgb, + clamp(src.a + colored_streak.a * (1.0 - src.a), 0.0, 1.0), + ); + } + + let out = finalize_fx( + src, + fx, + uv, + params.p[2].x, + params.p[2].y, + params.p[2].z, + params.p[2].w, + params.p[3], + ); + textureStore(dst_tex, vec2(gid.xy), out); +} + +// ----------------------------------------------------------------------------- +// 4. HotSpot — radial primary flare + secondary optical lens elements +// p[0] = (primary_cx, primary_cy, secondary_cx, secondary_cy) // Fusion Y-up [0..1] +// p[1] = (primary_size, primary_strength, primary_aspect, secondary_elements) +// p[2] = (primary_r, primary_g, primary_b, apply_mode) +// apply_mode: 0=Add, 1=Screen, 2=Normal, 3=Multiply, 4=Lighten, 5=Overlay +// p[3] = (secondary_strength, secondary_size, blend, has_mask) +// p[4] = (mask_inv, mbm, 0, 0) +// p[5] = process_skip (r, g, b, a) +// ----------------------------------------------------------------------------- +fn secondary_tint(idx: i32) -> vec3 { + let phase = f32(idx) * 2.0943951; // 120 deg hue offsets + return vec3( + 0.78 + 0.22 * cos(phase), + 0.78 + 0.22 * cos(phase + 2.0943951), + 0.78 + 0.22 * cos(phase + 4.1887902), + ); +} + +@compute @workgroup_size(8, 8) +fn hot_spot_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let fdims = vec2(dims); + let uv = (vec2(gid.xy) + 0.5) / fdims; + let src = textureSampleLevel(src_tex, samp, uv, 0.0); + + // Fusion Y-up normalized coordinates + let fpos = vec2(uv.x, 1.0 - uv.y); + let img_aspect = fdims.x / max(fdims.y, 1.0); + + let p_center = params.p[0].xy; + let s_center = params.p[0].zw; + let p_size = max(params.p[1].x, 1e-4); + let p_strength = max(params.p[1].y, 0.0); + let p_aspect = max(params.p[1].z, 0.05); + let sec_count = clamp(i32(round(params.p[1].w)), 0, 16); + let p_color = params.p[2].rgb; + let apply_mode = i32(round(params.p[2].w)); + let sec_strength = max(params.p[3].x, 0.0); + let sec_size = max(params.p[3].y, 1e-4); + + // Primary radial hot spot + let dp = fpos - p_center; + let dp_scaled = vec2(dp.x * img_aspect / p_aspect, dp.y); + let rp = length(dp_scaled) / p_size; + let primary_g = (0.72 * exp(-rp * rp * 3.2) + 0.28 * exp(-rp * 2.4)) * p_strength; + var flare_rgb = p_color * primary_g; + var flare_a = clamp(primary_g, 0.0, 1.0); + + // Secondary lens flare elements along the optical axis through Primary -> Secondary + if (sec_count > 0 && sec_strength > 1e-5 && p_strength > 1e-5) { + let axis = s_center - p_center; + let fcount = f32(sec_count); + for (var i = 0; i < sec_count; i = i + 1) { + let frac = (f32(i) + 1.0) / (fcount + 0.5); + let t = mix(0.35, 1.35, frac); + let e_pos = p_center + axis * t; + let size_mod = 0.55 + 0.75 * fract(f32(i) * 0.618034 + 0.25); + let e_rad = sec_size * size_mod; + let de = fpos - e_pos; + let de_scaled = vec2(de.x * img_aspect, de.y); + let re = length(de_scaled) / max(e_rad, 1e-4); + + // Alternate soft bokeh disc and thin lens halo ring + var elem = 0.0; + if ((i & 1) == 0) { + elem = smoothstep(1.05, 0.35, re) * (0.45 + 0.35 * smoothstep(0.4, 0.85, re)); + } else { + let ring = exp(-pow((re - 0.82) * 5.0, 2.0)); + let core = exp(-re * re * 2.5) * 0.25; + elem = ring * 0.65 + core; + } + let e_energy = elem * sec_strength * p_strength * 0.55; + let e_col = p_color * secondary_tint(i); + flare_rgb += e_col * e_energy; + flare_a = clamp(flare_a + e_energy * (1.0 - flare_a), 0.0, 1.0); + } + } + + var fx_rgb = src.rgb; + var fx_a = src.a; + switch apply_mode { + case 1: { + // Screen + let f_clamped = clamp(flare_rgb, vec3(0.0), vec3(1.0)); + fx_rgb = 1.0 - (1.0 - src.rgb) * (1.0 - f_clamped); + fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0); + } + case 2: { + // Normal / Over + fx_rgb = src.rgb * (1.0 - flare_a) + flare_rgb; + fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0); + } + case 3: { + // Multiply + fx_rgb = src.rgb * flare_rgb; + fx_a = src.a; + } + case 4: { + // Lighten / Max + fx_rgb = max(src.rgb, flare_rgb); + fx_a = max(src.a, flare_a); + } + case 5: { + // Overlay + let lo = 2.0 * src.rgb * flare_rgb; + let hi = 1.0 - 2.0 * (1.0 - src.rgb) * (1.0 - clamp(flare_rgb, vec3(0.0), vec3(1.0))); + fx_rgb = select(hi, lo, src.rgb < vec3(0.5)); + fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0); + } + default: { + // Add (optical light default) + fx_rgb = src.rgb + flare_rgb; + fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0); + } + } + + let out = finalize_fx( + src, + vec4(fx_rgb, fx_a), + uv, + params.p[3].z, + params.p[3].w, + params.p[4].x, + params.p[4].y, + params.p[5], + ); + textureStore(dst_tex, vec2(gid.xy), out); +} + +// ----------------------------------------------------------------------------- +// 5. RankFilter — exact GPU order-statistic filter (Min / Median / Max / Percentile) +// p[0] = (radius_px, rank, filter_type, 0) +// filter_type: 0=Box, 1=Circle, 2=Cross, 3=Diamond +// p[1] = (blend, has_mask, mask_inv, mbm) +// p[2] = process_skip (r, g, b, a) +// ----------------------------------------------------------------------------- +fn rank_in_footprint(dx: i32, dy: i32, r: i32, ftype: i32) -> bool { + switch ftype { + case 1: { + return f32(dx * dx + dy * dy) <= f32(r * r) + 0.25; + } + case 2: { + return dx == 0 || dy == 0; + } + case 3: { + return abs(dx) + abs(dy) <= r; + } + default: { + return true; + } + } +} + +fn select_kth(vals: ptr>, count: i32, k: i32, vmin: f32, vmax: f32) -> f32 { + if (count <= 1 || vmax - vmin <= 1e-6 || k <= 0) { + return vmin; + } + if (k >= count - 1) { + return vmax; + } + var lo = vmin; + var hi = vmax; + for (var iter = 0; iter < 20; iter = iter + 1) { + let mid = 0.5 * (lo + hi); + var le = 0; + for (var i = 0; i < count; i = i + 1) { + if ((*vals)[i] <= mid) { + le = le + 1; + } + } + if (le > k) { + hi = mid; + } else { + lo = mid; + } + } + return hi; +} + +fn eval_rank_channel( + px: vec2, + dims: vec2, + r: i32, + ftype: i32, + rank: f32, + chan: i32, +) -> f32 { + var vals: array; + var count = 0; + var vmin = 1e30; + var vmax = -1e30; + for (var dy = -r; dy <= r; dy = dy + 1) { + for (var dx = -r; dx <= r; dx = dx + 1) { + if (!rank_in_footprint(dx, dy, r, ftype)) { + continue; + } + let c = clamp(px + vec2(dx, dy), vec2(0), dims - vec2(1)); + let s = textureLoad(src_tex, c, 0); + var v = s.r; + if (chan == 1) { v = s.g; } + else if (chan == 2) { v = s.b; } + else if (chan == 3) { v = s.a; } + vals[count] = v; + vmin = min(vmin, v); + vmax = max(vmax, v); + count = count + 1; + } + } + if (count <= 0) { + return 0.0; + } + let pos = clamp(rank, 0.0, 1.0) * f32(count - 1); + let k0 = i32(floor(pos)); + let k1 = i32(ceil(pos)); + let frac = pos - f32(k0); + let v0 = select_kth(&vals, count, k0, vmin, vmax); + if (k1 == k0 || frac <= 1e-4) { + return v0; + } + let v1 = select_kth(&vals, count, k1, v0, vmax); + return mix(v0, v1, frac); +} + +@compute @workgroup_size(8, 8) +fn rank_filter_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { + return; + } + let idims = vec2(dims); + let px = vec2(gid.xy); + let uv = (vec2(gid.xy) + 0.5) / vec2(dims); + let src = textureLoad(src_tex, px, 0); + + let r = clamp(i32(round(params.p[0].x)), 0, 5); + let rank = clamp(params.p[0].y, 0.0, 1.0); + let ftype = i32(round(params.p[0].z)); + let skip = params.p[2]; + + var fx = src; + if (r > 0) { + if (skip.r < 0.5) { fx.r = eval_rank_channel(px, idims, r, ftype, rank, 0); } + if (skip.g < 0.5) { fx.g = eval_rank_channel(px, idims, r, ftype, rank, 1); } + if (skip.b < 0.5) { fx.b = eval_rank_channel(px, idims, r, ftype, rank, 2); } + if (skip.a < 0.5) { fx.a = eval_rank_channel(px, idims, r, ftype, rank, 3); } + } + + let out = finalize_fx( + src, + fx, + uv, + params.p[1].x, + params.p[1].y, + params.p[1].z, + params.p[1].w, + skip, + ); + textureStore(dst_tex, px, out); +} -- 2.54.1