authoravatarclover caruso<git@paperclover.net>2026-12-02 00:49:09-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-02 01:11:30-08:00
logf4b9a2dcea0158f75337a48bc7233162fdeef1d9
tree1155c9f3772b3118c1a408ee9dd438b304a1554a
parent693d3d781c4714f8ed85803d3a4c05f4269340c0
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(engine): implement DepthBlur, Fog, Highlight, HotSpot, and RankFilter


3 files changed, 2026 insertions(+), 0 deletions(-)

crates/engine/src/eval/depth_optical.rs created+1327
......@@ -0,0 +1,1327 @@
1//! Wave 35B — Depth, Optical & Filter FX GPU pipelines and evaluators:
2//! - `DepthBlur` (depth-driven CoC blur from `BlurImage`/`BlurChannel` or `aux.z`)
3//! - `Fog` (depth-driven atmospheric fog from `aux.z` or `FogImage`/`Fog`)
4//! - `Highlight` (2-pass bright-threshold extraction + directional starburst streaks)
5//! - `HotSpot` (radial primary glow + secondary optical lens flare elements)
6//! - `RankFilter` (GPU order-statistic Min/Median/Max/Percentile filter)
7//!
8//! WebGPU safety: `R32Float` depth textures are bound with `filterable: false` and read
9//! exclusively via `textureLoad`; output storage textures are `WriteOnly`.
10
11use super::*;
12use crate::cache::{AuxChannelTex, EMPTY_Z_SENTINEL};
13use std::num::NonZeroU64;
14
15const DEPTH_OPTICAL_WGSL: &str = include_str!("../shaders/depth_optical.wgsl");
16const UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
17const MAX_RANK_RADIUS: f32 = 5.0;
18
19#[derive(Clone, Copy)]
20enum DepthOpticalOp {
21 DepthBlur,
22 Fog,
23 HighlightExtract,
24 HighlightStreaks,
25 HotSpot,
26 RankFilter,
27}
28
29fn build_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String {
30 let storage_fmt = match format {
31 wgpu::TextureFormat::Rgba16Float => "rgba16float",
32 wgpu::TextureFormat::Rgba32Float => "rgba32float",
33 _ => "rgba8unorm",
34 };
35 let mut src = DEPTH_OPTICAL_WGSL.to_owned();
36 if storage_fmt != "rgba8unorm" {
37 src = src.replace(
38 "texture_storage_2d<rgba8unorm, write>",
39 &format!("texture_storage_2d<{storage_fmt}, write>"),
40 );
41 }
42 if hdr_float {
43 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
44 }
45 src
46}
47
48fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
49 wgpu::BindGroupLayoutEntry {
50 binding,
51 visibility: wgpu::ShaderStages::COMPUTE,
52 ty: wgpu::BindingType::Texture {
53 sample_type: wgpu::TextureSampleType::Float { filterable },
54 view_dimension: wgpu::TextureViewDimension::D2,
55 multisampled: false,
56 },
57 count: None,
58 }
59}
60
61struct FormatPipelines {
62 bgl: wgpu::BindGroupLayout,
63 depth_blur: wgpu::ComputePipeline,
64 fog: wgpu::ComputePipeline,
65 highlight_extract: wgpu::ComputePipeline,
66 highlight_streaks: wgpu::ComputePipeline,
67 hot_spot: wgpu::ComputePipeline,
68 rank_filter: wgpu::ComputePipeline,
69}
70
71pub(super) struct DepthOpticalPipelines {
72 sampler: wgpu::Sampler,
73 uniform_stride: u32,
74 uniform_chunks: Vec<wgpu::Buffer>,
75 uniform_cursor: u32,
76 dummy_z: AuxChannelTex,
77 formats: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>,
78}
79
80impl DepthOpticalPipelines {
81 pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
82 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
83 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
84 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
85
86 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
87 label: Some("depth-optical-linear"),
88 address_mode_u: wgpu::AddressMode::ClampToEdge,
89 address_mode_v: wgpu::AddressMode::ClampToEdge,
90 mag_filter: wgpu::FilterMode::Linear,
91 min_filter: wgpu::FilterMode::Linear,
92 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
93 ..Default::default()
94 });
95
96 let dummy_z = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::R32Float, "do-dummy-z");
97 queue.write_texture(
98 dummy_z.texture.as_image_copy(),
99 &EMPTY_Z_SENTINEL.to_le_bytes(),
100 wgpu::TexelCopyBufferLayout {
101 offset: 0,
102 bytes_per_row: Some(4),
103 rows_per_image: Some(1),
104 },
105 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
106 );
107
108 Self {
109 sampler,
110 uniform_stride,
111 uniform_chunks: Vec::new(),
112 uniform_cursor: 0,
113 dummy_z,
114 formats: HashMap::new(),
115 }
116 }
117
118 pub(super) fn reset_uniform_cursor(&mut self) {
119 self.uniform_cursor = 0;
120 }
121
122 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
123 self.uniform_cursor = 0;
124 if self.uniform_chunks.len() > max_chunks {
125 self.uniform_chunks.truncate(max_chunks);
126 }
127 }
128
129 fn alloc_uniform_slot(
130 &mut self,
131 device: &wgpu::Device,
132 queue: &wgpu::Queue,
133 params: &UniformParams,
134 ) -> (usize, u32) {
135 let slot_global = self.uniform_cursor;
136 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
137 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
138 while chunk_idx >= self.uniform_chunks.len() {
139 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
140 let buf = device.create_buffer(&wgpu::BufferDescriptor {
141 label: Some("depth-optical-params-ring"),
142 size,
143 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
144 mapped_at_creation: false,
145 });
146 self.uniform_chunks.push(buf);
147 }
148 let offset = slot_in_chunk * self.uniform_stride;
149 queue.write_buffer(
150 &self.uniform_chunks[chunk_idx],
151 u64::from(offset),
152 bytemuck::bytes_of(params),
153 );
154 self.uniform_cursor = slot_global + 1;
155 (chunk_idx, offset)
156 }
157
158 fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
159 if self.formats.contains_key(&(format, hdr_float)) {
160 return;
161 }
162 let u_size = std::mem::size_of::<UniformParams>() as u64;
163 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
164 label: Some("depth-optical-bgl"),
165 entries: &[
166 tex_entry(0, true),
167 tex_entry(1, true),
168 tex_entry(2, false), // R32Float depth: MUST be unfilterable for WebGPU/wasm32!
169 tex_entry(3, true),
170 wgpu::BindGroupLayoutEntry {
171 binding: 4,
172 visibility: wgpu::ShaderStages::COMPUTE,
173 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
174 count: None,
175 },
176 wgpu::BindGroupLayoutEntry {
177 binding: 5,
178 visibility: wgpu::ShaderStages::COMPUTE,
179 ty: wgpu::BindingType::StorageTexture {
180 access: wgpu::StorageTextureAccess::WriteOnly,
181 format,
182 view_dimension: wgpu::TextureViewDimension::D2,
183 },
184 count: None,
185 },
186 wgpu::BindGroupLayoutEntry {
187 binding: 6,
188 visibility: wgpu::ShaderStages::COMPUTE,
189 ty: wgpu::BindingType::Buffer {
190 ty: wgpu::BufferBindingType::Uniform,
191 has_dynamic_offset: true,
192 min_binding_size: NonZeroU64::new(u_size),
193 },
194 count: None,
195 },
196 ],
197 });
198 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
199 label: Some("depth-optical-pl"),
200 bind_group_layouts: &[Some(&bgl)],
201 immediate_size: 0,
202 });
203 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
204 label: Some("depth-optical-wgsl"),
205 source: wgpu::ShaderSource::Wgsl(build_wgsl(format, hdr_float).into()),
206 });
207 let mk = |entry: &str| {
208 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
209 label: Some(entry),
210 layout: Some(&pl),
211 module: &module,
212 entry_point: Some(entry),
213 compilation_options: Default::default(),
214 cache: None,
215 })
216 };
217 self.formats.insert(
218 (format, hdr_float),
219 FormatPipelines {
220 bgl,
221 depth_blur: mk("depth_blur_op"),
222 fog: mk("fog_op"),
223 highlight_extract: mk("highlight_extract_op"),
224 highlight_streaks: mk("highlight_streaks_op"),
225 hot_spot: mk("hot_spot_op"),
226 rank_filter: mk("rank_filter_op"),
227 },
228 );
229 }
230
231 #[allow(clippy::too_many_arguments)]
232 fn dispatch(
233 &mut self,
234 device: &wgpu::Device,
235 queue: &wgpu::Queue,
236 enc: &mut wgpu::CommandEncoder,
237 op: DepthOpticalOp,
238 src_view: &wgpu::TextureView,
239 aux_img_view: &wgpu::TextureView,
240 z_view: Option<&wgpu::TextureView>,
241 mask_view: &wgpu::TextureView,
242 dst: &CachedTexture,
243 params: &UniformParams,
244 ) {
245 let format = dst.texture.format();
246 let hdr_float = matches!(
247 format,
248 wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
249 );
250 self.ensure_format(device, format, hdr_float);
251 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
252 let fp = &self.formats[&(format, hdr_float)];
253 let zv = z_view.unwrap_or(&self.dummy_z.view);
254 let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64);
255 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
256 label: Some("depth-optical-bg"),
257 layout: &fp.bgl,
258 entries: &[
259 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_view) },
260 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(aux_img_view) },
261 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(zv) },
262 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask_view) },
263 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.sampler) },
264 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) },
265 wgpu::BindGroupEntry {
266 binding: 6,
267 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
268 buffer: &self.uniform_chunks[chunk_idx],
269 offset: 0,
270 size: u_size,
271 }),
272 },
273 ],
274 });
275 let pipeline = match op {
276 DepthOpticalOp::DepthBlur => &fp.depth_blur,
277 DepthOpticalOp::Fog => &fp.fog,
278 DepthOpticalOp::HighlightExtract => &fp.highlight_extract,
279 DepthOpticalOp::HighlightStreaks => &fp.highlight_streaks,
280 DepthOpticalOp::HotSpot => &fp.hot_spot,
281 DepthOpticalOp::RankFilter => &fp.rank_filter,
282 };
283 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
284 label: Some("depth-optical-pass"),
285 timestamp_writes: None,
286 });
287 pass.set_pipeline(pipeline);
288 pass.set_bind_group(0, &bg, &[offset]);
289 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
290 }
291}
292
293fn parse_depth_blur_channel(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
294 if let Some(s) = node.static_str("BlurChannel") {
295 return match s {
296 "Red" => 0,
297 "Green" => 1,
298 "Blue" => 2,
299 "Alpha" => 3,
300 "Z" | "ZBuffer" | "Z-Buffer" => 4,
301 "Luminance" | "Luma" => 5,
302 _ => 4,
303 };
304 }
305 comp.eval_number(node, "BlurChannel", time, 4.0, expr).round().clamp(0.0, 5.0) as i32
306}
307
308fn parse_depth_blur_filter(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
309 if let Some(s) = node.static_str("Filter") {
310 return match s {
311 "Box" => 1,
312 "Gaussian" | "Fast Gaussian" => 2,
313 "Lens" | "Bokeh" => 3,
314 _ => 0,
315 };
316 }
317 comp.eval_number(node, "Filter", time, 0.0, expr).round().clamp(0.0, 3.0) as i32
318}
319
320fn parse_hotspot_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
321 if let Some(s) = node.static_str("ApplyMode") {
322 return match s {
323 "Screen" => 1,
324 "Normal" | "Over" => 2,
325 "Multiply" => 3,
326 "Lighten" | "Max" => 4,
327 "Overlay" => 5,
328 _ => 0, // Add / LinearDodge
329 };
330 }
331 comp.eval_number(node, "ApplyMode", time, 0.0, expr).round().clamp(0.0, 5.0) as i32
332}
333
334fn parse_rank_filter_type(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> i32 {
335 if let Some(s) = node.static_str("FilterType") {
336 return match s {
337 "Circle" | "Circular" | "Disc" => 1,
338 "Cross" | "Plus" => 2,
339 "Diamond" => 3,
340 _ => 0, // Box / Square
341 };
342 }
343 comp.eval_number(node, "FilterType", time, 0.0, expr).round().clamp(0.0, 3.0) as i32
344}
345
346impl Engine {
347 pub(super) fn depth_optical_pipelines(&self) -> &RefCell<DepthOpticalPipelines> {
348 self.depth_optical_pipelines
349 .get_or_init(|| RefCell::new(DepthOpticalPipelines::new(&self.device, &self.queue)))
350 }
351
352 fn eval_num_alias(&self, comp: &Comp, node: &Node, primary: &str, fallback: &str, time: f64, default: f64) -> f32 {
353 if node.inputs.contains_key(primary) {
354 comp.eval_number(node, primary, time, default, &self.expr) as f32
355 } else {
356 comp.eval_number(node, fallback, time, default, &self.expr) as f32
357 }
358 }
359
360 fn combined_skip(&self, comp: &Comp, node: &Node, time: f64) -> [f32; 4] {
361 let p_skip = self.process_skip(comp, node, time);
362 let c_names = ["Red", "Green", "Blue", "Alpha"];
363 let mut out = p_skip;
364 for i in 0..4 {
365 if node.inputs.contains_key(c_names[i])
366 && comp.eval_number(node, c_names[i], time, 1.0, &self.expr) <= 0.5
367 {
368 out[i] = 1.0;
369 }
370 }
371 out
372 }
373
374 /// 1. `DepthBlur`: circle-of-confusion blur driven by `BlurImage`/`BlurChannel` or `aux.z`.
375 #[allow(clippy::too_many_arguments)]
376 pub(super) fn eval_depth_blur(
377 &mut self,
378 comp: &Comp,
379 node: &Node,
380 time: f64,
381 frame_i: i64,
382 enc: &mut wgpu::CommandEncoder,
383 visiting: &mut HashSet<(NodeId, i64)>,
384 stats: &mut EvalStats,
385 ) -> CachedTexture {
386 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
387 return self.dummy.clone();
388 };
389 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
390 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
391 let mbm = self.multiplies_by_mask(comp, node, time);
392 let blur_raw = self.eval_num_alias(comp, node, "XBlurSize", "BlurSize", time, 1.0).max(0.0);
393 // Fusion blur size uses 720px-width reference; src.canvas_size already reflects proxy_scale.
394 let max_r = (blur_raw * (src.canvas_size[0] as f32 / 720.0)).min(96.0);
395 if (blend <= 1e-6 || max_r < 0.25) && !mbm {
396 return src;
397 }
398
399 let src_aux = src.aux.clone();
400 let src = self.crop_to_canvas(enc, src);
401 let blur_img = node
402 .connected_node("BlurImage")
403 .and_then(|s| comp.find_node(s))
404 .map(|bid| {
405 let t = self.eval_node(comp, bid, time, enc, visiting, stats);
406 self.crop_to_canvas(enc, t)
407 });
408
409 let mut channel = parse_depth_blur_channel(comp, node, time, &self.expr);
410 let (depth_src_mode, z_tex_opt): (i32, Option<AuxChannelTex>) = if channel == 4 {
411 if let Some(bi) = &blur_img {
412 if let Some(bz) = bi.aux.as_ref().and_then(|a| a.z.clone()) {
413 (0, Some(bz))
414 } else {
415 channel = 5; // BlurImage without aux.z -> use luminance
416 (1, None)
417 }
418 } else if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) {
419 (0, Some(sz))
420 } else {
421 // No depth source available -> pass through unless MultiplyByMask is active.
422 if !mbm {
423 let mut out = src;
424 out.set_aux(src_aux);
425 return out;
426 }
427 (0, None)
428 }
429 } else if blur_img.is_some() {
430 (1, None)
431 } else {
432 (2, None)
433 };
434
435 let focal = comp.eval_number(node, "FocalPoint", time, 0.0, &self.expr) as f32;
436 let dof = comp.eval_number(node, "DepthOfField", time, 0.0, &self.expr) as f32;
437 let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32;
438 let filter_mode = parse_depth_blur_filter(comp, node, time, &self.expr);
439 let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 };
440 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
441 let skip = self.combined_skip(comp, node, time);
442 let taps = match (filter_mode, self.hiq) {
443 (1, true) => 3.0,
444 (1, false) => 2.0,
445 (_, true) => 36.0,
446 (_, false) => 16.0,
447 };
448
449 let mut u = UniformParams::default();
450 u.p[0] = [if depth_src_mode == 0 && z_tex_opt.is_none() { 0.0 } else { max_r }, focal, dof, z_scale];
451 u.p[1] = [filter_mode as f32, depth_src_mode as f32, channel as f32, clamp_edges];
452 u.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
453 u.p[3] = skip;
454 u.p[4] = [taps, z_tex_opt.is_some() as u8 as f32, 0.0, 0.0];
455
456 let bi_hash = blur_img.as_ref().map_or(0, |b| b.content_hash);
457 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
458 let key = self.make_key(
459 node,
460 "DepthBlur",
461 src.size,
462 &[src.content_hash, bi_hash, mask_hash],
463 bytemuck::cast_slice(&u.p[..5]),
464 );
465 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
466 stats.cache_hits += 1;
467 return hit;
468 }
469 stats.cache_misses += 1;
470 stats.nodes_evaluated += 1;
471
472 let mut dst = self.alloc_tex_like(&src, src.depth, key);
473 dst.set_aux(src_aux);
474 let bv = blur_img.as_ref().map_or(&self.dummy.view, |b| &b.view);
475 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
476 let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref());
477 self.depth_optical_pipelines().borrow_mut().dispatch(
478 &self.device,
479 &self.queue,
480 enc,
481 DepthOpticalOp::DepthBlur,
482 &src.view,
483 bv,
484 zv,
485 mv,
486 &dst,
487 &u,
488 );
489 self.cache.insert(key, dst.clone(), node.id, frame_i);
490 dst
491 }
492
493 /// 2. `Fog`: depth-driven atmospheric fog from `aux.z` or `FogImage`/`Fog`.
494 #[allow(clippy::too_many_arguments)]
495 pub(super) fn eval_fog(
496 &mut self,
497 comp: &Comp,
498 node: &Node,
499 time: f64,
500 frame_i: i64,
501 enc: &mut wgpu::CommandEncoder,
502 visiting: &mut HashSet<(NodeId, i64)>,
503 stats: &mut EvalStats,
504 ) -> CachedTexture {
505 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
506 return self.dummy.clone();
507 };
508 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
509 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
510 let fog_opacity = comp.eval_number(node, "FogOpacity", time, 1.0, &self.expr) as f32;
511 let mbm = self.multiplies_by_mask(comp, node, time);
512 if (blend <= 1e-6 || fog_opacity <= 1e-6) && !mbm {
513 return src;
514 }
515
516 let src_aux = src.aux.clone();
517 let src = self.crop_to_canvas(enc, src);
518 let fog_img = node
519 .connected_node("FogImage")
520 .or_else(|| node.connected_node("Fog"))
521 .and_then(|s| comp.find_node(s))
522 .map(|fid| {
523 let t = self.eval_node(comp, fid, time, enc, visiting, stats);
524 self.crop_to_canvas(enc, t)
525 });
526
527 let (depth_mode, has_fog_color_img, z_tex_opt): (i32, bool, Option<AuxChannelTex>) =
528 if let Some(sz) = src_aux.as_ref().and_then(|a| a.z.clone()) {
529 (0, fog_img.is_some(), Some(sz))
530 } else if let Some(fi) = &fog_img {
531 if let Some(fz) = fi.aux.as_ref().and_then(|a| a.z.clone()) {
532 (0, false, Some(fz))
533 } else {
534 (1, false, None)
535 }
536 } else {
537 (0, false, None)
538 };
539
540 let near_p = self.eval_num_alias(comp, node, "ZNearPlane", "NearPlane", time, 0.0);
541 let far_p = self.eval_num_alias(comp, node, "ZFarPlane", "FarPlane", time, -100.0);
542 let falloff = comp.eval_number(node, "Falloff", time, 1.0, &self.expr) as f32;
543 let z_scale = comp.eval_number(node, "ZScale", time, 1.0, &self.expr) as f32;
544 let fog_r = comp.eval_number(node, "FogRed", time, 1.0, &self.expr) as f32;
545 let fog_g = comp.eval_number(node, "FogGreen", time, 1.0, &self.expr) as f32;
546 let fog_b = comp.eval_number(node, "FogBlue", time, 1.0, &self.expr) as f32;
547 let fog_a = comp.eval_number(node, "FogAlpha", time, 1.0, &self.expr) as f32;
548 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
549 let skip = self.process_skip(comp, node, time);
550
551 let mut u = UniformParams::default();
552 u.p[0] = [near_p, far_p, falloff, z_scale];
553 u.p[1] = [fog_r, fog_g, fog_b, fog_a];
554 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];
555 u.p[3] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
556 u.p[4] = skip;
557
558 let fi_hash = fog_img.as_ref().map_or(0, |f| f.content_hash);
559 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
560 let key = self.make_key(
561 node,
562 "Fog",
563 src.size,
564 &[src.content_hash, fi_hash, mask_hash],
565 bytemuck::cast_slice(&u.p[..5]),
566 );
567 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
568 stats.cache_hits += 1;
569 return hit;
570 }
571 stats.cache_misses += 1;
572 stats.nodes_evaluated += 1;
573
574 let mut dst = self.alloc_tex_like(&src, src.depth, key);
575 dst.set_aux(src_aux);
576 let fv = fog_img.as_ref().map_or(&self.dummy.view, |f| &f.view);
577 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
578 let zv = z_tex_opt.as_ref().map(|z| z.view.as_ref());
579 self.depth_optical_pipelines().borrow_mut().dispatch(
580 &self.device,
581 &self.queue,
582 enc,
583 DepthOpticalOp::Fog,
584 &src.view,
585 fv,
586 zv,
587 mv,
588 &dst,
589 &u,
590 );
591 self.cache.insert(key, dst.clone(), node.id, frame_i);
592 dst
593 }
594
595 /// 3. `Highlight`: threshold bright pixels (`Low`/`High`) + directional starburst streaks.
596 #[allow(clippy::too_many_arguments)]
597 pub(super) fn eval_highlight(
598 &mut self,
599 comp: &Comp,
600 node: &Node,
601 time: f64,
602 frame_i: i64,
603 enc: &mut wgpu::CommandEncoder,
604 visiting: &mut HashSet<(NodeId, i64)>,
605 stats: &mut EvalStats,
606 ) -> CachedTexture {
607 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
608 return self.dummy.clone();
609 };
610 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
611 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
612 let mbm = self.multiplies_by_mask(comp, node, time);
613 if blend <= 1e-6 && !mbm {
614 return src;
615 }
616 let src = self.crop_to_canvas(enc, src);
617
618 let low = comp.eval_number(node, "Low", time, 0.75, &self.expr) as f32;
619 let high = comp.eval_number(node, "High", time, 1.0, &self.expr) as f32;
620 let num_points = comp.eval_number(node, "NumberOfPoints", time, 4.0, &self.expr).clamp(1.0, 16.0) as f32;
621 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
622 let length_norm = comp.eval_number(node, "Length", time, 0.15, &self.expr).max(0.0) as f32;
623 // Length is normalized to image width; src.size[0] already scales cleanly by proxy_scale.
624 let length_px = (length_norm * src.size[0] as f32).min(256.0);
625 let falloff = self.eval_num_alias(comp, node, "Falloff", "Decay", time, 1.0);
626 let strength = self.eval_num_alias(comp, node, "Strength", "Gain", time, 1.0);
627 let tint_r = self.eval_num_alias(comp, node, "ColorRed", "RedScale", time, 1.0);
628 let tint_g = self.eval_num_alias(comp, node, "ColorGreen", "GreenScale", time, 1.0);
629 let tint_b = self.eval_num_alias(comp, node, "ColorBlue", "BlueScale", time, 1.0);
630 let merge_orig = comp.eval_number(node, "MergeWithOriginal", time, 1.0, &self.expr) > 0.5;
631 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
632 let skip = self.process_skip(comp, node, time);
633 let steps = if self.hiq { 28.0 } else { 14.0 };
634
635 let mut u_ext = UniformParams::default();
636 u_ext.p[0] = [low, high, strength, 0.0];
637
638 let mut u_str = UniformParams::default();
639 u_str.p[0] = [num_points, angle_deg.to_radians(), length_px, falloff];
640 u_str.p[1] = [tint_r, tint_g, tint_b, merge_orig as u8 as f32];
641 u_str.p[2] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
642 u_str.p[3] = skip;
643 u_str.p[4] = [steps, low, high, strength];
644
645 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
646 let key = self.make_key(
647 node,
648 "Highlight",
649 src.size,
650 &[src.content_hash, mask_hash],
651 bytemuck::cast_slice(&u_str.p[..5]),
652 );
653 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
654 stats.cache_hits += 1;
655 return hit;
656 }
657 stats.cache_misses += 1;
658 stats.nodes_evaluated += 1;
659
660 let bright = self.alloc_tex(src.size, src.depth, 0);
661 let dst = self.alloc_tex_like(&src, src.depth, key);
662 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
663 let mut pipes = self.depth_optical_pipelines().borrow_mut();
664 pipes.dispatch(
665 &self.device,
666 &self.queue,
667 enc,
668 DepthOpticalOp::HighlightExtract,
669 &src.view,
670 &self.dummy.view,
671 None,
672 &self.dummy.view,
673 &bright,
674 &u_ext,
675 );
676 pipes.dispatch(
677 &self.device,
678 &self.queue,
679 enc,
680 DepthOpticalOp::HighlightStreaks,
681 &src.view,
682 &bright.view,
683 None,
684 mv,
685 &dst,
686 &u_str,
687 );
688 drop(pipes);
689 self.cache.insert(key, dst.clone(), node.id, frame_i);
690 dst
691 }
692
693 /// 4. `HotSpot`: radial primary glow + optional secondary optical lens flare elements.
694 #[allow(clippy::too_many_arguments)]
695 pub(super) fn eval_hot_spot(
696 &mut self,
697 comp: &Comp,
698 node: &Node,
699 time: f64,
700 frame_i: i64,
701 enc: &mut wgpu::CommandEncoder,
702 visiting: &mut HashSet<(NodeId, i64)>,
703 stats: &mut EvalStats,
704 ) -> CachedTexture {
705 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
706 return self.dummy.clone();
707 };
708 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
709 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
710 let mbm = self.multiplies_by_mask(comp, node, time);
711 if blend <= 1e-6 && !mbm {
712 return src;
713 }
714 let src = self.crop_to_canvas(enc, src);
715
716 let p_center = if node.inputs.contains_key("Center") {
717 comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr)
718 } else {
719 comp.eval_point(node, "PrimaryPosition", time, [0.5, 0.5], &self.expr)
720 };
721 let default_sec = [1.0 - p_center[0], 1.0 - p_center[1]];
722 let has_explicit_sec = node.inputs.contains_key("SecondaryCenter")
723 || node.inputs.contains_key("SecondaryPosition")
724 || node.inputs.contains_key("SecondaryStrength");
725 let s_center = if node.inputs.contains_key("SecondaryCenter") {
726 comp.eval_point(node, "SecondaryCenter", time, default_sec, &self.expr)
727 } else if node.inputs.contains_key("SecondaryPosition") {
728 comp.eval_point(node, "SecondaryPosition", time, default_sec, &self.expr)
729 } else {
730 default_sec
731 };
732
733 let primary_size = self.eval_num_alias(comp, node, "PrimarySize", "HotSpotSize", time, 0.25);
734 let primary_strength = comp.eval_number(node, "PrimaryStrength", time, 1.0, &self.expr) as f32;
735 let primary_aspect = self.eval_num_alias(comp, node, "PrimaryAspect", "Aspect", time, 1.0);
736 let primary_r = self.eval_num_alias(comp, node, "PrimaryRed", "ColorRed", time, 1.0);
737 let primary_g = self.eval_num_alias(comp, node, "PrimaryGreen", "ColorGreen", time, 1.0);
738 let primary_b = self.eval_num_alias(comp, node, "PrimaryBlue", "ColorBlue", time, 1.0);
739 let default_sec_elems = if has_explicit_sec { 4.0 } else { 0.0 };
740 let sec_elements = self
741 .eval_num_alias(comp, node, "SecondaryElements", "Elements", time, default_sec_elems)
742 .clamp(0.0, 16.0);
743 let sec_strength = comp.eval_number(node, "SecondaryStrength", time, 0.5, &self.expr) as f32;
744 let sec_size = comp.eval_number(node, "SecondarySize", time, (primary_size * 0.45) as f64, &self.expr) as f32;
745 let apply_mode = parse_hotspot_apply_mode(comp, node, time, &self.expr);
746 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
747 let skip = self.process_skip(comp, node, time);
748
749 let mut u = UniformParams::default();
750 u.p[0] = [p_center[0] as f32, p_center[1] as f32, s_center[0] as f32, s_center[1] as f32];
751 u.p[1] = [primary_size, primary_strength, primary_aspect, sec_elements];
752 u.p[2] = [primary_r, primary_g, primary_b, apply_mode as f32];
753 u.p[3] = [sec_strength, sec_size, blend, mask.is_some() as u8 as f32];
754 u.p[4] = [mask_inv as u8 as f32, mbm as u8 as f32, 0.0, 0.0];
755 u.p[5] = skip;
756
757 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
758 let key = self.make_key(
759 node,
760 "HotSpot",
761 src.size,
762 &[src.content_hash, mask_hash],
763 bytemuck::cast_slice(&u.p[..6]),
764 );
765 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
766 stats.cache_hits += 1;
767 return hit;
768 }
769 stats.cache_misses += 1;
770 stats.nodes_evaluated += 1;
771
772 let dst = self.alloc_tex_like(&src, src.depth, key);
773 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
774 self.depth_optical_pipelines().borrow_mut().dispatch(
775 &self.device,
776 &self.queue,
777 enc,
778 DepthOpticalOp::HotSpot,
779 &src.view,
780 &self.dummy.view,
781 None,
782 mv,
783 &dst,
784 &u,
785 );
786 self.cache.insert(key, dst.clone(), node.id, frame_i);
787 dst
788 }
789
790 /// 5. `RankFilter`: GPU order-statistic filter (Min / Median / Max / Percentile).
791 #[allow(clippy::too_many_arguments)]
792 pub(super) fn eval_rank_filter(
793 &mut self,
794 comp: &Comp,
795 node: &Node,
796 time: f64,
797 frame_i: i64,
798 enc: &mut wgpu::CommandEncoder,
799 visiting: &mut HashSet<(NodeId, i64)>,
800 stats: &mut EvalStats,
801 ) -> CachedTexture {
802 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
803 return self.dummy.clone();
804 };
805 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
806 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
807 let mbm = self.multiplies_by_mask(comp, node, time);
808 let raw_size = self.eval_num_alias(comp, node, "Size", "FilterSize", time, 1.0).max(0.0);
809 let proxy = self.proxy_scale.max(1) as f32;
810 let radius = (raw_size / proxy).round().clamp(0.0, MAX_RANK_RADIUS);
811 let skip = self.combined_skip(comp, node, time);
812 let all_skipped = skip.iter().all(|&s| s > 0.5);
813 if (blend <= 1e-6 || radius < 0.5 || all_skipped) && !mbm {
814 return src;
815 }
816
817 let src = self.crop_to_canvas(enc, src);
818 let rank = comp.eval_number(node, "Rank", time, 0.5, &self.expr).clamp(0.0, 1.0) as f32;
819 let ftype = parse_rank_filter_type(comp, node, time, &self.expr);
820 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
821
822 let mut u = UniformParams::default();
823 u.p[0] = [radius, rank, ftype as f32, 0.0];
824 u.p[1] = [blend, mask.is_some() as u8 as f32, mask_inv as u8 as f32, mbm as u8 as f32];
825 u.p[2] = skip;
826
827 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
828 let key = self.make_key(
829 node,
830 "RankFilter",
831 src.size,
832 &[src.content_hash, mask_hash],
833 bytemuck::cast_slice(&u.p[..3]),
834 );
835 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
836 stats.cache_hits += 1;
837 return hit;
838 }
839 stats.cache_misses += 1;
840 stats.nodes_evaluated += 1;
841
842 let dst = self.alloc_tex_like(&src, src.depth, key);
843 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
844 self.depth_optical_pipelines().borrow_mut().dispatch(
845 &self.device,
846 &self.queue,
847 enc,
848 DepthOpticalOp::RankFilter,
849 &src.view,
850 &self.dummy.view,
851 None,
852 mv,
853 &dst,
854 &u,
855 );
856 self.cache.insert(key, dst.clone(), node.id, frame_i);
857 dst
858 }
859}
860
861#[cfg(test)]
862mod tests {
863 use super::*;
864
865 fn px_at(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
866 let i = ((y * w + x) * 4) as usize;
867 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
868 }
869
870 fn eval_px(eng: &mut Engine, comp: &Comp, name: &str) -> (CachedTexture, Vec<u8>) {
871 let id = comp.find_node(name).unwrap_or_else(|| panic!("missing node {name}"));
872 let (tex, stats) = eng.evaluate(comp, id, 0.0);
873 assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported: {:?}", stats.unsupported_nodes);
874 let rgba = eng.readback_rgba(&tex).expect("readback rgba");
875 (tex, rgba)
876 }
877
878 fn z_bg_nodes(prefix: &str, w: u32, h: u32, rgba: [f32; 4], z: f32) -> String {
879 format!(
880 r#"
881 {prefix}Col = Background {{
882 Inputs = {{
883 Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }},
884 TopLeftRed = Input {{ Value = {}, }}, TopLeftGreen = Input {{ Value = {}, }},
885 TopLeftBlue = Input {{ Value = {}, }}, TopLeftAlpha = Input {{ Value = {}, }},
886 }},
887 }},
888 {prefix}Z = Background {{
889 Inputs = {{
890 Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }},
891 TopLeftRed = Input {{ Value = {z}, }}, TopLeftAlpha = Input {{ Value = 1.0, }},
892 }},
893 }},
894 {prefix}ZAux = Dimension.CopyAux {{
895 Inputs = {{
896 Mode = Input {{ Value = 1, }},
897 Channel = Input {{ Value = FuID {{ "Z" }}, }},
898 Input = Input {{ SourceOp = "{prefix}Z", Source = "Output", }},
899 }},
900 }},
901 {prefix} = ChannelBoolean {{
902 Inputs = {{
903 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
904 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
905 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
906 Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }},
907 Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }},
908 }},
909 }},
910 "#,
911 rgba[0], rgba[1], rgba[2], rgba[3]
912 )
913 }
914
915 #[test]
916 fn depth_blur_aux_z_focal_sharp_far_and_sky_blurred() {
917 let Ok(mut eng) = Engine::new_headless() else { return };
918 // 64x64 sharp vertical stripe across two depth layers:
919 // top half (y<32 in texture = Fusion Y>0.5) has focal z=-5.0, bottom half has far z=-25.0.
920 let src = format!(
921 r#"Composition {{
922 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
923 Tools = ordered() {{
924 {}
925 {}
926 MTop = RectangleMask {{
927 Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.75 }}, }}, Width = Input {{ Value = 1.0, }}, Height = Input {{ Value = 0.5, }}, }},
928 }},
929 MStripe = RectangleMask {{
930 Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }},
931 }},
932 White = Background {{
933 Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
934 TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }},
935 EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }},
936 }},
937 Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
938 Striped = Merge {{
939 Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }},
940 }},
941 DepthSplit = Merge {{
942 Inputs = {{
943 Background = Input {{ SourceOp = "FarZ", Source = "Output", }},
944 Foreground = Input {{ SourceOp = "NearZ", Source = "Output", }},
945 EffectMask = Input {{ SourceOp = "MTop", Source = "Mask", }},
946 PerformDepthMerge = Input {{ Value = 1, }},
947 }},
948 }},
949 Scene = ChannelBoolean {{
950 Inputs = {{
951 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
952 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
953 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
954 Background = Input {{ SourceOp = "Striped", Source = "Output", }},
955 Foreground = Input {{ SourceOp = "DepthSplit", Source = "Output", }},
956 }},
957 }},
958 DB = DepthBlur {{
959 Inputs = {{
960 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
961 XBlurSize = Input {{ Value = 60.0, }},
962 FocalPoint = Input {{ Value = -5.0, }},
963 DepthOfField = Input {{ Value = 1.0, }},
964 ZScale = Input {{ Value = 20.0, }},
965 }},
966 }},
967 }},
968 }}"#,
969 z_bg_nodes("NearZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -5.0),
970 z_bg_nodes("FarZ", 64, 64, [0.0, 0.0, 0.0, 1.0], -25.0),
971 );
972 let comp = Comp::from_fusion_str(&src).expect("parse DepthBlur aux.z comp");
973 let (tex, px) = eval_px(&mut eng, &comp, "DB");
974 assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "DepthBlur must preserve aux.z");
975
976 // Stripe occupies x in [28..36]; check 2px outside stripe edge (x=25):
977 // Near row (y=12) is at focal plane -> stays black (0); Far row (y=52) is out of focus -> blurred (>15)!
978 let near_outside = px_at(&px, 64, 25, 12)[0];
979 let far_outside = px_at(&px, 64, 25, 52)[0];
980 let near_inside = px_at(&px, 64, 32, 12)[0];
981 let far_inside = px_at(&px, 64, 32, 52)[0];
982 assert!(near_outside <= 2, "focal plane outside stripe must stay sharp black, got {near_outside}");
983 assert!(near_inside >= 250, "focal plane inside stripe must stay crisp white, got {near_inside}");
984 assert!(far_outside >= 15, "far depth outside stripe must receive blur bleed, got {far_outside}");
985 assert!(far_inside < near_inside, "far depth inside stripe must soften ({far_inside} vs {near_inside})");
986
987 // Verify EMPTY_Z_SENTINEL (-1e30) in aux.z is treated as far background (full CoC blur).
988 let sky_src = format!(
989 r#"Composition {{
990 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
991 Tools = ordered() {{
992 {}
993 MStripe = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.125, }}, Height = Input {{ Value = 1.0, }}, }}, }},
994 Black = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, }}, }},
995 White = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
996 TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }},
997 EffectMask = Input {{ SourceOp = "MStripe", Source = "Mask", }}, }}, }},
998 Striped = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "Black", Source = "Output", }}, Foreground = Input {{ SourceOp = "White", Source = "Output", }}, }}, }},
999 Scene = ChannelBoolean {{
1000 Inputs = {{
1001 ToRed = Input {{ Value = 5, }}, ToGreen = Input {{ Value = 6, }},
1002 ToBlue = Input {{ Value = 7, }}, ToAlpha = Input {{ Value = 8, }},
1003 EnableExtraChannels = Input {{ Value = 1, }}, ToZBuffer = Input {{ Value = 18, }},
1004 Background = Input {{ SourceOp = "Striped", Source = "Output", }},
1005 Foreground = Input {{ SourceOp = "SkyZ", Source = "Output", }},
1006 }},
1007 }},
1008 DB = DepthBlur {{
1009 Inputs = {{
1010 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1011 XBlurSize = Input {{ Value = 60.0, }},
1012 FocalPoint = Input {{ Value = -5.0, }},
1013 ZScale = Input {{ Value = 20.0, }},
1014 }},
1015 }},
1016 }},
1017 }}"#,
1018 z_bg_nodes("SkyZ", 64, 64, [0.0, 0.0, 0.0, 1.0], EMPTY_Z_SENTINEL),
1019 );
1020 let sky_comp = Comp::from_fusion_str(&sky_src).expect("parse DepthBlur sky comp");
1021 let (_, sky_px) = eval_px(&mut eng, &sky_comp, "DB");
1022 assert!(px_at(&sky_px, 64, 25, 32)[0] >= 15, "EMPTY_Z_SENTINEL sky must blur as far background");
1023 }
1024
1025 #[test]
1026 fn depth_blur_external_blur_image_and_proxy_scale() {
1027 let Ok(mut eng) = Engine::new_headless() else { return };
1028 // BlurImage has black top half (depth=0, sharp) and white bottom half (depth=1, blurred).
1029 let src = r#"Composition {
1030 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1031 Tools = ordered() {
1032 MStripe = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.125, }, Height = Input { Value = 1.0, }, }, },
1033 Black = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, },
1034 Stripe = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1035 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1036 EffectMask = Input { SourceOp = "MStripe", Source = "Mask", }, }, },
1037 Img = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "Stripe", Source = "Output", }, }, },
1038 MBot = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.25 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 0.5, }, }, },
1039 DepthMap = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1040 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1041 EffectMask = Input { SourceOp = "MBot", Source = "Mask", }, }, },
1042 DB = DepthBlur {
1043 Inputs = {
1044 Input = Input { SourceOp = "Img", Source = "Output", },
1045 BlurImage = Input { SourceOp = "DepthMap", Source = "Output", },
1046 BlurChannel = Input { Value = 5, },
1047 Filter = Input { Value = 1, },
1048 BlurSize = Input { Value = 72.0, },
1049 FocalPoint = Input { Value = 0.0, },
1050 ZScale = Input { Value = 1.0, },
1051 },
1052 },
1053 },
1054 }"#;
1055 let comp = Comp::from_fusion_str(src).expect("parse DepthBlur BlurImage comp");
1056 let (_, px) = eval_px(&mut eng, &comp, "DB");
1057 assert!(px_at(&px, 64, 24, 12)[0] <= 2, "top half depth=0 must stay sharp");
1058 assert!(px_at(&px, 64, 24, 52)[0] >= 15, "bottom half depth=1 must blur");
1059
1060 eng.proxy_scale = 2;
1061 let (tex_p, px_p) = eval_px(&mut eng, &comp, "DB");
1062 assert_eq!(tex_p.size, [32, 32]);
1063 assert!(px_at(&px_p, 32, 12, 6)[0] <= 2, "proxy top half must stay sharp");
1064 assert!(px_at(&px_p, 32, 12, 26)[0] >= 15, "proxy bottom half must blur");
1065 }
1066
1067 #[test]
1068 fn fog_aux_z_near_far_falloff_alpha_and_fog_image() {
1069 let Ok(mut eng) = Engine::new_headless() else { return };
1070 // Left=near(-2, red), Middle=mid(-16, green), Right=far(-30, blue).
1071 let src = format!(
1072 r#"Composition {{
1073 CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }},
1074 Tools = ordered() {{
1075 {}
1076 {}
1077 {}
1078 MLeft = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.16, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }},
1079 MMid = RectangleMask {{ Inputs = {{ Center = Input {{ Value = {{ 0.5, 0.5 }}, }}, Width = Input {{ Value = 0.34, }}, Height = Input {{ Value = 1.0, }}, }}, }},
1080 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, }}, }}, }},
1081 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, }}, }}, }},
1082 FogSolid = Fog {{
1083 Inputs = {{
1084 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1085 ZNearPlane = Input {{ Value = -2.0, }},
1086 ZFarPlane = Input {{ Value = -30.0, }},
1087 Falloff = Input {{ Value = 1.0, }},
1088 FogRed = Input {{ Value = 1.0, }}, FogGreen = Input {{ Value = 1.0, }}, FogBlue = Input {{ Value = 1.0, }},
1089 }},
1090 }},
1091 TintImg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }},
1092 TopLeftRed = Input {{ Value = 0.0, }}, TopLeftGreen = Input {{ Value = 1.0, }}, TopLeftBlue = Input {{ Value = 1.0, }}, }}, }},
1093 FogTex = Fog {{
1094 Inputs = {{
1095 Input = Input {{ SourceOp = "Scene", Source = "Output", }},
1096 FogImage = Input {{ SourceOp = "TintImg", Source = "Output", }},
1097 NearPlane = Input {{ Value = -2.0, }},
1098 FarPlane = Input {{ Value = -30.0, }},
1099 }},
1100 }},
1101 EmptySky = Background {{ Inputs = {{ Width = Input {{ Value = 16, }}, Height = Input {{ Value = 16, }}, TopLeftAlpha = Input {{ Value = 0.0, }}, }}, }},
1102 FogSkyZeroA = Fog {{ Inputs = {{ Input = Input {{ SourceOp = "EmptySky", Source = "Output", }}, FogAlpha = Input {{ Value = 0.0, }}, }}, }},
1103 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, }}, }}, }},
1104 }},
1105 }}"#,
1106 z_bg_nodes("Near", 32, 32, [1.0, 0.0, 0.0, 1.0], -2.0),
1107 z_bg_nodes("Mid", 32, 32, [0.0, 1.0, 0.0, 1.0], -16.0),
1108 z_bg_nodes("Far", 32, 32, [0.0, 0.0, 1.0, 1.0], -30.0),
1109 );
1110 let comp = Comp::from_fusion_str(&src).expect("parse Fog comp");
1111 let (tex, px) = eval_px(&mut eng, &comp, "FogSolid");
1112 assert!(tex.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Fog must preserve aux.z for chaining");
1113
1114 let near_c = px_at(&px, 32, 4, 16);
1115 let mid_c = px_at(&px, 32, 16, 16);
1116 let far_c = px_at(&px, 32, 28, 16);
1117 assert!(near_c[0] >= 250 && near_c[1] <= 3 && near_c[2] <= 3, "near plane must have 0% fog, got {near_c:?}");
1118 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:?}");
1119 assert!(far_c[0] >= 250 && far_c[1] >= 250 && far_c[2] >= 250, "far plane must have 100% white fog, got {far_c:?}");
1120
1121 let (_, px_t) = eval_px(&mut eng, &comp, "FogTex");
1122 let far_t = px_at(&px_t, 32, 28, 16);
1123 assert!(far_t[0] <= 3 && far_t[1] >= 250 && far_t[2] >= 250, "FogImage cyan must tint far fog, got {far_t:?}");
1124
1125 let (_, sky0) = eval_px(&mut eng, &comp, "FogSkyZeroA");
1126 assert_eq!(px_at(&sky0, 16, 8, 8)[3], 0, "FogAlpha=0 must keep empty sky transparent");
1127 let (_, sky1) = eval_px(&mut eng, &comp, "FogSkyFullA");
1128 assert!(px_at(&sky1, 16, 8, 8)[3] >= 250 && (px_at(&sky1, 16, 8, 8)[0] as i32 - 128).abs() <= 4);
1129 }
1130
1131 #[test]
1132 fn highlight_thresholds_and_casts_directional_streaks() {
1133 let Ok(mut eng) = Engine::new_headless() else { return };
1134 let src = r#"Composition {
1135 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1136 Tools = ordered() {
1137 Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, }, },
1138 MBright = RectangleMask { Inputs = { Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.08, }, Height = Input { Value = 0.08, }, }, },
1139 MDim = RectangleMask { Inputs = { Center = Input { Value = { 0.15, 0.15 }, }, Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, },
1140 Bright = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1141 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1142 EffectMask = Input { SourceOp = "MBright", Source = "Mask", }, }, },
1143 Dim = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1144 TopLeftRed = Input { Value = 0.3, }, TopLeftGreen = Input { Value = 0.3, }, TopLeftBlue = Input { Value = 0.3, },
1145 EffectMask = Input { SourceOp = "MDim", Source = "Mask", }, }, },
1146 M1 = Merge { Inputs = { Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Dim", Source = "Output", }, }, },
1147 Scene = Merge { Inputs = { Background = Input { SourceOp = "M1", Source = "Output", }, Foreground = Input { SourceOp = "Bright", Source = "Output", }, }, },
1148 HL = Highlight {
1149 Inputs = {
1150 Input = Input { SourceOp = "Scene", Source = "Output", },
1151 Low = Input { Value = 0.6, }, High = Input { Value = 0.9, },
1152 NumberOfPoints = Input { Value = 4, }, Angle = Input { Value = 0.0, },
1153 Length = Input { Value = 0.25, }, Falloff = Input { Value = 1.0, },
1154 ColorRed = Input { Value = 1.0, }, ColorGreen = Input { Value = 0.5, }, ColorBlue = Input { Value = 0.2, },
1155 MergeWithOriginal = Input { Value = 1, },
1156 },
1157 },
1158 HLOnly = Highlight {
1159 Inputs = {
1160 Input = Input { SourceOp = "Scene", Source = "Output", },
1161 Low = Input { Value = 0.6, }, High = Input { Value = 0.9, },
1162 NumberOfPoints = Input { Value = 4, }, Length = Input { Value = 0.25, },
1163 MergeWithOriginal = Input { Value = 0, },
1164 },
1165 },
1166 },
1167 }"#;
1168 let comp = Comp::from_fusion_str(src).expect("parse Highlight comp");
1169 let (_, px) = eval_px(&mut eng, &comp, "HL");
1170 // Along +X ray from center (32,32): (40,32) must receive warm tinted streak (R > G > B > 0).
1171 let ray_x = px_at(&px, 64, 40, 32);
1172 let ray_y = px_at(&px, 64, 32, 40);
1173 let off_diag = px_at(&px, 64, 44, 44);
1174 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:?}");
1175 assert!(ray_y[0] >= 20, "Y ray must glow for 4-point star, got {ray_y:?}");
1176 assert!(off_diag[0] <= 2, "off-ray diagonal must stay dark, got {off_diag:?}");
1177
1178 // MergeWithOriginal=0 must drop the dim patch (lum=0.3 < Low=0.6).
1179 let (_, px_only) = eval_px(&mut eng, &comp, "HLOnly");
1180 let dim_px = px_at(&px_only, 64, 10, 54);
1181 assert!(dim_px[0] <= 2 && dim_px[1] <= 2 && dim_px[2] <= 2, "dim spot below Low must not highlight, got {dim_px:?}");
1182
1183 eng.proxy_scale = 2;
1184 let (tex_p, px_p) = eval_px(&mut eng, &comp, "HL");
1185 assert_eq!(tex_p.size, [32, 32]);
1186 assert!(px_at(&px_p, 32, 20, 16)[0] >= 15, "proxy Highlight must scale streaks cleanly");
1187 }
1188
1189 #[test]
1190 fn hot_spot_primary_secondary_apply_mode_and_mask() {
1191 let Ok(mut eng) = Engine::new_headless() else { return };
1192 let src = r#"Composition {
1193 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1194 Tools = ordered() {
1195 Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
1196 TopLeftRed = Input { Value = 0.05, }, TopLeftGreen = Input { Value = 0.05, }, TopLeftBlue = Input { Value = 0.05, }, }, },
1197 HS = HotSpot {
1198 Inputs = {
1199 Input = Input { SourceOp = "Bg", Source = "Output", },
1200 Center = Input { Value = { 0.25, 0.25 }, },
1201 SecondaryCenter = Input { Value = { 0.75, 0.75 }, },
1202 PrimarySize = Input { Value = 0.14, },
1203 PrimaryStrength = Input { Value = 1.0, },
1204 PrimaryRed = Input { Value = 1.0, }, PrimaryGreen = Input { Value = 0.5, }, PrimaryBlue = Input { Value = 0.2, },
1205 SecondaryElements = Input { Value = 4, },
1206 ApplyMode = Input { Value = FuID { "Add" }, },
1207 },
1208 },
1209 MLeft = RectangleMask { Inputs = { Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, },
1210 HSMasked = HotSpot {
1211 Inputs = {
1212 Input = Input { SourceOp = "Bg", Source = "Output", },
1213 Center = Input { Value = { 0.75, 0.5 }, },
1214 PrimarySize = Input { Value = 0.2, },
1215 EffectMask = Input { SourceOp = "MLeft", Source = "Mask", },
1216 },
1217 },
1218 },
1219 }"#;
1220 let comp = Comp::from_fusion_str(src).expect("parse HotSpot comp");
1221 let (_, px) = eval_px(&mut eng, &comp, "HS");
1222 // Primary at Fusion (0.25, 0.25) -> texture pixel (16, 48)
1223 let primary = px_at(&px, 64, 16, 48);
1224 assert!(primary[0] >= 240 && primary[0] > primary[1] && primary[1] > primary[2], "primary core must be bright warm, got {primary:?}");
1225
1226 // Sample along secondary axis (0.5..0.85, 0.5..0.85) vs far off-axis corner (0.85, 0.15 -> px 54, 54).
1227 let mut max_axis = 0u8;
1228 for step in 32..56 {
1229 let y = 63 - step;
1230 let p = px_at(&px, 64, step, y);
1231 max_axis = max_axis.max(p[0]).max(p[1]).max(p[2]);
1232 }
1233 let off_corner = px_at(&px, 64, 56, 56);
1234 assert!(max_axis > off_corner[0] + 20, "secondary elements must brighten optical axis ({max_axis} vs {off_corner:?})");
1235
1236 let (_, px_m) = eval_px(&mut eng, &comp, "HSMasked");
1237 // Center of flare is at x=48 (outside left-half mask) -> must remain background (~13).
1238 assert!(px_at(&px_m, 64, 48, 32)[0] <= 16, "EffectMask must block HotSpot outside mask");
1239 }
1240
1241 #[test]
1242 fn rank_filter_min_median_max_filter_type_channels_and_proxy() {
1243 let Ok(mut eng) = Engine::new_headless() else { return };
1244 // 32x32 mid-gray (0.5) field with a 1px white impulse at center (16,16).
1245 let src = r#"Composition {
1246 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1247 Tools = ordered() {
1248 Gray = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
1249 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, }, },
1250 DotMask = RectangleMask { Inputs = { Center = Input { Value = { 0.515625, 0.484375 }, }, Width = Input { Value = 0.03125, }, Height = Input { Value = 0.03125, }, }, },
1251 White = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
1252 TopLeftRed = Input { Value = 1.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
1253 EffectMask = Input { SourceOp = "DotMask", Source = "Mask", }, }, },
1254 Scene = Merge { Inputs = { Background = Input { SourceOp = "Gray", Source = "Output", }, Foreground = Input { SourceOp = "White", Source = "Output", }, }, },
1255 RMin = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.0, }, }, },
1256 RMed = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, },
1257 RPct = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.9375, }, }, },
1258 RMaxBox = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 0, }, }, },
1259 RMaxCir = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, FilterType = Input { Value = 1, }, }, },
1260 RSkipR = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 1.0, }, ProcessRed = Input { Value = 0, }, }, },
1261 RBig = RankFilter { Inputs = { Input = Input { SourceOp = "Scene", Source = "Output", }, FilterSize = Input { Value = 4, }, Rank = Input { Value = 1.0, }, }, },
1262 },
1263 }"#;
1264 let comp = Comp::from_fusion_str(src).expect("parse RankFilter comp");
1265 let (_, scene_px) = eval_px(&mut eng, &comp, "Scene");
1266 assert!(px_at(&scene_px, 32, 16, 16)[0] >= 250, "sanity: center impulse must be white");
1267
1268 let (_, min_px) = eval_px(&mut eng, &comp, "RMin");
1269 assert!((px_at(&min_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Min must erode 1px white impulse to 0.5");
1270
1271 let (_, med_px) = eval_px(&mut eng, &comp, "RMed");
1272 assert!((px_at(&med_px, 32, 16, 16)[0] as i32 - 128).abs() <= 4, "Median must remove 1px white impulse");
1273
1274 // 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)!
1275 let (_, pct_px) = eval_px(&mut eng, &comp, "RPct");
1276 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));
1277
1278 let (_, box_px) = eval_px(&mut eng, &comp, "RMaxBox");
1279 assert!(px_at(&box_px, 32, 17, 17)[0] >= 250, "Max Box(r=1) must dilate impulse to diagonal corner (17,17)");
1280
1281 let (_, cir_px) = eval_px(&mut eng, &comp, "RMaxCir");
1282 assert!(px_at(&cir_px, 32, 17, 16)[0] >= 250, "Max Circle(r=1) must dilate impulse to cardinal neighbor");
1283 assert!((px_at(&cir_px, 32, 17, 17)[0] as i32 - 128).abs() <= 4, "Max Circle(r=1) must exclude diagonal corner");
1284
1285 let (_, skip_px) = eval_px(&mut eng, &comp, "RSkipR");
1286 let n_px = px_at(&skip_px, 32, 17, 16);
1287 assert!((n_px[0] as i32 - 128).abs() <= 4 && n_px[1] >= 250, "ProcessRed=0 must skip R while filtering G: {n_px:?}");
1288
1289 eng.proxy_scale = 2;
1290 let (tex_p, _) = eval_px(&mut eng, &comp, "RBig");
1291 assert_eq!(tex_p.size, [16, 16]);
1292 }
1293
1294 #[test]
1295 fn uniform_ring_growth_reset_trim_and_hdr_float16() {
1296 let Ok(mut eng) = Engine::new_headless() else { return };
1297 {
1298 let mut pipes = eng.depth_optical_pipelines().borrow_mut();
1299 let u = UniformParams::default();
1300 for _ in 0..520 {
1301 pipes.alloc_uniform_slot(&eng.device, &eng.queue, &u);
1302 }
1303 assert_eq!(pipes.uniform_chunks.len(), 2, "520 slots must allocate 2x512 chunks");
1304 pipes.reset_uniform_cursor();
1305 assert_eq!(pipes.uniform_cursor, 0);
1306 pipes.trim_uniform_chunks(1);
1307 assert_eq!(pipes.uniform_chunks.len(), 1);
1308 }
1309
1310 // Verify Float16 HDR compilation & execution across all 5 ops.
1311 let src = r#"Composition {
1312 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1313 Tools = ordered() {
1314 Bg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 3, },
1315 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.2, }, }, },
1316 F = Fog { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, FogOpacity = Input { Value = 0.25, }, }, },
1317 H = Highlight { Inputs = { Input = Input { SourceOp = "F", Source = "Output", }, Low = Input { Value = 0.3, }, }, },
1318 S = HotSpot { Inputs = { Input = Input { SourceOp = "H", Source = "Output", }, PrimarySize = Input { Value = 0.3, }, }, },
1319 R = RankFilter { Inputs = { Input = Input { SourceOp = "S", Source = "Output", }, Size = Input { Value = 1, }, Rank = Input { Value = 0.5, }, }, },
1320 D = DepthBlur { Inputs = { Input = Input { SourceOp = "R", Source = "Output", }, BlurChannel = Input { Value = 5, }, BlurSize = Input { Value = 16.0, }, }, },
1321 },
1322 }"#;
1323 let comp = Comp::from_fusion_str(src).expect("parse HDR chain");
1324 let (tex, _) = eval_px(&mut eng, &comp, "D");
1325 assert_eq!(tex.depth, BitDepth::Float16);
1326 }
1327}
crates/engine/src/eval/mod.rs+14
......@@ -16,6 +16,7 @@ use web_time::Instant;
1616mod io;
1717mod alpha_keyers;
1818mod aux_ops;
19mod depth_optical;
1920mod composite;
2021mod transform;
2122mod color;
......@@ -72,6 +73,7 @@ pub struct Engine {
7273 pipelines_f32: OnceCell<RefCell<ShaderRegistry>>,
7374 aux_pipelines: OnceCell<RefCell<aux_ops::AuxPipelines>>,
7475 alpha_keyer_pipelines: OnceCell<RefCell<alpha_keyers::AlphaKeyerPipelines>>,
76 depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>,
7577 motion_blur: crate::motion_blur::MotionBlurPipelines,
7678 supports_f32_filter: bool,
7779 scene3d: crate::scene3d::Scene3DRenderer,
......@@ -177,6 +179,7 @@ impl Engine {
177179 pipelines_f32: OnceCell::new(),
178180 aux_pipelines: OnceCell::new(),
179181 alpha_keyer_pipelines: OnceCell::new(),
182 depth_optical_pipelines: OnceCell::new(),
180183 motion_blur: crate::motion_blur::MotionBlurPipelines::default(),
181184 supports_f32_filter,
182185 scene3d,
......@@ -321,6 +324,9 @@ impl Engine {
321324 if let Some(ak) = self.alpha_keyer_pipelines.get() {
322325 ak.borrow_mut().reset_uniform_cursor();
323326 }
327 if let Some(dp) = self.depth_optical_pipelines.get() {
328 dp.borrow_mut().reset_uniform_cursor();
329 }
324330 if let Some(of) = self.optflow.get() {
325331 of.reset_uniform_cursor();
326332 }
......@@ -335,6 +341,9 @@ impl Engine {
335341 if let Some(ak) = self.alpha_keyer_pipelines.get() {
336342 ak.borrow_mut().trim_uniform_chunks(2);
337343 }
344 if let Some(dp) = self.depth_optical_pipelines.get() {
345 dp.borrow_mut().trim_uniform_chunks(2);
346 }
338347 self.media.trim_nv12_uniform_chunks(2);
339348 }
340349
......@@ -853,6 +862,11 @@ impl Engine {
853862 "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats),
854863 "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats),
855864 "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats),
865 "DepthBlur" => self.eval_depth_blur(comp, node, time, frame_i, enc, visiting, stats),
866 "Fog" => self.eval_fog(comp, node, time, frame_i, enc, visiting, stats),
867 "Highlight" => self.eval_highlight(comp, node, time, frame_i, enc, visiting, stats),
868 "HotSpot" => self.eval_hot_spot(comp, node, time, frame_i, enc, visiting, stats),
869 "RankFilter" => self.eval_rank_filter(comp, node, time, frame_i, enc, visiting, stats),
856870 "ErodeDilate" => {
857871 let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats);
858872 if self.multiplies_by_mask(comp, node, time) {
crates/engine/src/shaders/depth_optical.wgsl created+685
......@@ -0,0 +1,685 @@
1// Wave 35B — Depth, Optical & Filter FX compute shaders (WGSL):
2// 1. DepthBlur (`depth_blur_op`)
3// 2. Fog (`fog_op`)
4// 3. Highlight (`highlight_extract_op`, `highlight_streaks_op`)
5// 4. HotSpot (`hot_spot_op`)
6// 5. RankFilter (`rank_filter_op`)
7//
8// WebGPU safety:
9// - `z_tex` (R32Float) is bound with `filterable: false` and ONLY read via `textureLoad`.
10// - Output `dst_tex` uses WriteOnly storage texture (never `read_write`).
11// - `HDR_FLOAT` and `texture_storage_2d<rgba8unorm, write>` are patched per target format.
12
13struct Params {
14 p: array<vec4<f32>, 16>,
15};
16
17const HDR_FLOAT: bool = false;
18const EMPTY_Z_THRESH: f32 = -0.5e30;
19const PI: f32 = 3.14159265359;
20const TAU: f32 = 6.28318530718;
21const GOLDEN_ANGLE: f32 = 2.39996322973;
22
23@group(0) @binding(0) var src_tex: texture_2d<f32>;
24@group(0) @binding(1) var aux_img_tex: texture_2d<f32>;
25@group(0) @binding(2) var z_tex: texture_2d<f32>;
26@group(0) @binding(3) var mask_tex: texture_2d<f32>;
27@group(0) @binding(4) var samp: sampler;
28@group(0) @binding(5) var dst_tex: texture_storage_2d<rgba8unorm, write>;
29@group(0) @binding(6) var<uniform> params: Params;
30
31fn sanitize_f32(v: f32, lim: f32) -> f32 {
32 return select(0.0, clamp(v, -lim, lim), v >= -1e30 && v <= 1e30);
33}
34
35fn sanitize_out(c: vec4<f32>) -> vec4<f32> {
36 if (HDR_FLOAT) {
37 return vec4<f32>(
38 sanitize_f32(c.r, 65504.0),
39 sanitize_f32(c.g, 65504.0),
40 sanitize_f32(c.b, 65504.0),
41 clamp(sanitize_f32(c.a, 1.0), 0.0, 1.0),
42 );
43 }
44 return clamp(
45 vec4<f32>(
46 sanitize_f32(c.r, 1.0),
47 sanitize_f32(c.g, 1.0),
48 sanitize_f32(c.b, 1.0),
49 sanitize_f32(c.a, 1.0),
50 ),
51 vec4<f32>(0.0),
52 vec4<f32>(1.0),
53 );
54}
55
56fn luma_709(rgb: vec3<f32>) -> f32 {
57 return dot(rgb, vec3<f32>(0.299, 0.587, 0.114));
58}
59
60fn eval_mask(uv: vec2<f32>, has_mask: f32, mask_inv: f32) -> f32 {
61 if (has_mask < 0.5) {
62 return 1.0;
63 }
64 let raw = clamp(textureSampleLevel(mask_tex, samp, uv, 0.0).a, 0.0, 1.0);
65 return select(raw, 1.0 - raw, mask_inv > 0.5);
66}
67
68fn finalize_fx(
69 src: vec4<f32>,
70 fx: vec4<f32>,
71 uv: vec2<f32>,
72 blend: f32,
73 has_mask: f32,
74 mask_inv: f32,
75 mbm: f32,
76 skip: vec4<f32>,
77) -> vec4<f32> {
78 let m = eval_mask(uv, has_mask, mask_inv);
79 let eff = clamp(blend * m, 0.0, 1.0);
80 var out = mix(src, fx, eff);
81 out = select(out, src, skip > vec4<f32>(0.5));
82 if (mbm > 0.5 && has_mask > 0.5) {
83 out = out * m;
84 }
85 return sanitize_out(out);
86}
87
88// Read Z from unfilterable R32Float z_tex using normalized UV via integer textureLoad.
89fn load_z_at_uv(uv: vec2<f32>) -> f32 {
90 let z_dims = vec2<i32>(textureDimensions(z_tex));
91 let px = clamp(vec2<i32>(floor(uv * vec2<f32>(z_dims))), vec2<i32>(0), z_dims - vec2<i32>(1));
92 return textureLoad(z_tex, px, 0).x;
93}
94
95fn load_z_at_px(px: vec2<i32>, dst_dims: vec2<i32>) -> f32 {
96 let z_dims = vec2<i32>(textureDimensions(z_tex));
97 if (z_dims.x == dst_dims.x && z_dims.y == dst_dims.y) {
98 let c = clamp(px, vec2<i32>(0), z_dims - vec2<i32>(1));
99 return textureLoad(z_tex, c, 0).x;
100 }
101 let uv = (vec2<f32>(px) + 0.5) / vec2<f32>(dst_dims);
102 return load_z_at_uv(uv);
103}
104
105// Sample depth value for DepthBlur:
106// depth_src_mode: 0 = z_tex (aux.z), 1 = aux_img_tex (BlurImage), 2 = src_tex
107// channel: 0=R, 1=G, 2=B, 3=A, 4=Z, 5=Luma
108fn sample_depth_blur_z(uv: vec2<f32>, depth_src_mode: i32, channel: i32) -> f32 {
109 if (depth_src_mode == 0) {
110 return load_z_at_uv(uv);
111 }
112 let c = select(
113 textureSampleLevel(src_tex, samp, uv, 0.0),
114 textureSampleLevel(aux_img_tex, samp, uv, 0.0),
115 depth_src_mode == 1,
116 );
117 switch channel {
118 case 0: { return c.r; }
119 case 1: { return c.g; }
120 case 2: { return c.b; }
121 case 3: { return c.a; }
122 default: { return luma_709(c.rgb); }
123 }
124}
125
126fn compute_coc(z: f32, focal: f32, dof: f32, z_scale: f32, is_z_aux: bool) -> f32 {
127 if (is_z_aux && z <= EMPTY_Z_THRESH) {
128 return 1.0;
129 }
130 let dist = max(0.0, abs(z - focal) - 0.5 * max(dof, 0.0));
131 return clamp(dist / max(abs(z_scale), 1e-4), 0.0, 1.0);
132}
133
134fn sample_src_clipped(uv: vec2<f32>, clamp_edges: f32) -> vec4<f32> {
135 if (clamp_edges < 0.5 && (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0)) {
136 return vec4<f32>(0.0);
137 }
138 return textureSampleLevel(src_tex, samp, clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
139}
140
141// -----------------------------------------------------------------------------
142// 1. DepthBlur
143// p[0] = (max_radius_px, focal_point, dof, z_scale)
144// p[1] = (filter_mode, depth_src_mode, channel, clamp_edges)
145// p[2] = (blend, has_mask, mask_inv, mbm)
146// p[3] = process_skip (r, g, b, a)
147// p[4] = (tap_count, 0, 0, 0)
148// -----------------------------------------------------------------------------
149@compute @workgroup_size(8, 8)
150fn depth_blur_op(@builtin(global_invocation_id) gid: vec3<u32>) {
151 let dims = textureDimensions(dst_tex);
152 if (gid.x >= dims.x || gid.y >= dims.y) {
153 return;
154 }
155 let fdims = vec2<f32>(dims);
156 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
157 let src = textureSampleLevel(src_tex, samp, uv, 0.0);
158
159 let max_r = params.p[0].x;
160 let focal = params.p[0].y;
161 let dof = params.p[0].z;
162 let z_scale = params.p[0].w;
163 let filter_mode = i32(round(params.p[1].x));
164 let depth_src_mode = i32(round(params.p[1].y));
165 let channel = i32(round(params.p[1].z));
166 let clamp_edges = params.p[1].w;
167 let is_z_aux = depth_src_mode == 0;
168
169 let z_center = sample_depth_blur_z(uv, depth_src_mode, channel);
170 let coc_center = compute_coc(z_center, focal, dof, z_scale, is_z_aux);
171 let radius = coc_center * max_r;
172
173 var blurred = src;
174 if (radius >= 0.25) {
175 let inv_dims = 1.0 / fdims;
176 var accum = src;
177 var w_sum = 1.0;
178 if (filter_mode == 1) {
179 // Box kernel (up to 7x7 grid scaled to radius)
180 let steps = clamp(i32(round(params.p[4].x)), 1, 3);
181 let step_px = radius / f32(steps);
182 for (var dy = -steps; dy <= steps; dy = dy + 1) {
183 for (var dx = -steps; dx <= steps; dx = dx + 1) {
184 if (dx == 0 && dy == 0) {
185 continue;
186 }
187 let off_uv = vec2<f32>(f32(dx), f32(dy)) * step_px * inv_dims;
188 let su = uv + off_uv;
189 let sz = sample_depth_blur_z(clamp(su, vec2<f32>(0.0), vec2<f32>(1.0)), depth_src_mode, channel);
190 let scoc = compute_coc(sz, focal, dof, z_scale, is_z_aux);
191 // Suppress sharp foreground leaking onto blurred background while allowing
192 // blurred foreground to bleed softly over background.
193 let depth_w = select(smoothstep(0.0, max(coc_center, 0.05), scoc), 1.0, !is_z_aux || sz <= z_center + 1e-4);
194 let w = max(depth_w, 0.05);
195 accum += sample_src_clipped(su, clamp_edges) * w;
196 w_sum += w;
197 }
198 }
199 } else {
200 // Disc (0), Gaussian (2), or Lens Bokeh (3) via Vogel spiral
201 let taps = clamp(i32(round(params.p[4].x)), 8, 48);
202 let ftaps = f32(taps);
203 for (var i = 0; i < taps; i = i + 1) {
204 let fi = f32(i) + 0.5;
205 let r_norm = sqrt(fi / ftaps);
206 let theta = fi * GOLDEN_ANGLE;
207 let off_uv = vec2<f32>(cos(theta), sin(theta)) * (r_norm * radius) * inv_dims;
208 let su = uv + off_uv;
209 let sz = sample_depth_blur_z(clamp(su, vec2<f32>(0.0), vec2<f32>(1.0)), depth_src_mode, channel);
210 let scoc = compute_coc(sz, focal, dof, z_scale, is_z_aux);
211 let depth_w = select(smoothstep(0.0, max(coc_center, 0.05), scoc), 1.0, !is_z_aux || sz <= z_center + 1e-4);
212 var kw = 1.0;
213 if (filter_mode == 2) {
214 kw = exp(-2.5 * r_norm * r_norm);
215 } else if (filter_mode == 3) {
216 kw = 0.75 + 0.5 * r_norm * r_norm;
217 }
218 let sample_c = sample_src_clipped(su, clamp_edges);
219 if (filter_mode == 3) {
220 kw *= 1.0 + 0.5 * luma_709(max(sample_c.rgb, vec3<f32>(0.0)));
221 }
222 let w = kw * max(depth_w, 0.05);
223 accum += sample_c * w;
224 w_sum += w;
225 }
226 }
227 blurred = accum / max(w_sum, 1e-5);
228 }
229
230 let out = finalize_fx(
231 src,
232 blurred,
233 uv,
234 params.p[2].x,
235 params.p[2].y,
236 params.p[2].z,
237 params.p[2].w,
238 params.p[3],
239 );
240 textureStore(dst_tex, vec2<i32>(gid.xy), out);
241}
242
243// -----------------------------------------------------------------------------
244// 2. Fog
245// p[0] = (near_plane, far_plane, falloff, z_scale)
246// p[1] = (fog_r, fog_g, fog_b, fog_a)
247// p[2] = (fog_opacity, depth_mode, has_fog_color_img, 0)
248// depth_mode: 0 = z_tex (aux.z), 1 = aux_img_tex luma (FogImage as depth)
249// p[3] = (blend, has_mask, mask_inv, mbm)
250// p[4] = process_skip (r, g, b, a)
251// -----------------------------------------------------------------------------
252@compute @workgroup_size(8, 8)
253fn fog_op(@builtin(global_invocation_id) gid: vec3<u32>) {
254 let dims = textureDimensions(dst_tex);
255 if (gid.x >= dims.x || gid.y >= dims.y) {
256 return;
257 }
258 let fdims = vec2<f32>(dims);
259 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
260 let src = textureSampleLevel(src_tex, samp, uv, 0.0);
261
262 let near_p = params.p[0].x;
263 let far_p = params.p[0].y;
264 let falloff = max(params.p[0].z, 1e-4);
265 let z_scale = params.p[0].w;
266 var fog_col = params.p[1];
267 let fog_opacity = clamp(params.p[2].x, 0.0, 1.0);
268 let depth_mode = i32(round(params.p[2].y));
269 let has_fog_color_img = params.p[2].z > 0.5;
270
271 if (has_fog_color_img) {
272 let fi = textureSampleLevel(aux_img_tex, samp, uv, 0.0);
273 fog_col = vec4<f32>(fog_col.rgb * fi.rgb, fog_col.a * fi.a);
274 }
275
276 var t_raw = 0.0;
277 let denom = far_p - near_p;
278 if (depth_mode == 0) {
279 let z_raw = load_z_at_px(vec2<i32>(gid.xy), vec2<i32>(dims));
280 if (z_raw <= EMPTY_Z_THRESH) {
281 t_raw = 1.0;
282 } else {
283 let z_eff = z_raw * z_scale;
284 if (abs(denom) > 1e-6) {
285 t_raw = clamp((z_eff - near_p) / denom, 0.0, 1.0);
286 } else {
287 t_raw = select(0.0, 1.0, z_eff <= near_p);
288 }
289 }
290 } else {
291 let d_img = textureSampleLevel(aux_img_tex, samp, uv, 0.0);
292 let z_eff = luma_709(d_img.rgb) * z_scale;
293 if (abs(denom) > 1e-6) {
294 t_raw = clamp((z_eff - near_p) / denom, 0.0, 1.0);
295 } else {
296 t_raw = clamp(z_eff, 0.0, 1.0);
297 }
298 }
299
300 let f = clamp(pow(t_raw, falloff) * fog_opacity, 0.0, 1.0);
301 let fog_a = clamp(fog_col.a, 0.0, 1.0);
302 // Premultiplied fog composite: opaque surfaces always fog cleanly, while
303 // transparent sky receives fog scaled by FogAlpha.
304 let out_rgb = src.rgb * (1.0 - f) + fog_col.rgb * (f * (src.a + (1.0 - src.a) * fog_a));
305 let out_a = src.a + (1.0 - src.a) * (f * fog_a);
306 let fogged = vec4<f32>(out_rgb, out_a);
307
308 let out = finalize_fx(
309 src,
310 fogged,
311 uv,
312 params.p[3].x,
313 params.p[3].y,
314 params.p[3].z,
315 params.p[3].w,
316 params.p[4],
317 );
318 textureStore(dst_tex, vec2<i32>(gid.xy), out);
319}
320
321// -----------------------------------------------------------------------------
322// 3a. Highlight — bright pixel extraction pass
323// p[0] = (low, high, strength, 0)
324// -----------------------------------------------------------------------------
325@compute @workgroup_size(8, 8)
326fn highlight_extract_op(@builtin(global_invocation_id) gid: vec3<u32>) {
327 let dims = textureDimensions(dst_tex);
328 if (gid.x >= dims.x || gid.y >= dims.y) {
329 return;
330 }
331 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
332 let src = textureSampleLevel(src_tex, samp, uv, 0.0);
333 let low = params.p[0].x;
334 let high = params.p[0].y;
335 let strength = max(params.p[0].z, 0.0);
336
337 let lum = luma_709(max(src.rgb, vec3<f32>(0.0)));
338 var w = 0.0;
339 if (high > low + 1e-5) {
340 w = clamp((lum - low) / (high - low), 0.0, 1.0);
341 } else {
342 w = select(0.0, 1.0, lum > high + 1e-5);
343 }
344 let extracted = vec4<f32>(src.rgb * (w * strength), w * src.a);
345 textureStore(dst_tex, vec2<i32>(gid.xy), sanitize_out(extracted));
346}
347
348// -----------------------------------------------------------------------------
349// 3b. Highlight — directional starburst streaks + composite pass
350// src_tex = original image
351// aux_img_tex = extracted bright texture from highlight_extract_op
352// p[0] = (num_points, angle_rad, length_px, falloff)
353// p[1] = (tint_r, tint_g, tint_b, merge_with_original)
354// p[2] = (blend, has_mask, mask_inv, mbm)
355// p[3] = process_skip (r, g, b, a)
356// p[4] = (steps_per_ray, 0, 0, 0)
357// -----------------------------------------------------------------------------
358@compute @workgroup_size(8, 8)
359fn highlight_streaks_op(@builtin(global_invocation_id) gid: vec3<u32>) {
360 let dims = textureDimensions(dst_tex);
361 if (gid.x >= dims.x || gid.y >= dims.y) {
362 return;
363 }
364 let fdims = vec2<f32>(dims);
365 let inv_dims = 1.0 / fdims;
366 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
367 let src = textureSampleLevel(src_tex, samp, uv, 0.0);
368
369 let num_points = clamp(i32(round(params.p[0].x)), 1, 16);
370 let base_angle = params.p[0].y;
371 let length_px = max(params.p[0].z, 0.0);
372 let falloff = max(params.p[0].w, 0.05);
373 let tint = params.p[1].rgb;
374 let merge_orig = params.p[1].w > 0.5;
375 let steps = clamp(i32(round(params.p[4].x)), 4, 48);
376
377 let center_bright = textureSampleLevel(aux_img_tex, samp, uv, 0.0);
378 var streak = center_bright * 0.25;
379 if (length_px > 0.25) {
380 let fsteps = f32(steps);
381 let ray_norm = 1.0 / max(f32(num_points) * 0.35 + 0.65, 1.0);
382 for (var k = 0; k < num_points; k = k + 1) {
383 let a = base_angle + TAU * (f32(k) / f32(num_points));
384 // Y-up Fusion angle -> Y-down texture coordinate step
385 let dir = vec2<f32>(cos(a), -sin(a)) * inv_dims;
386 var ray_acc = vec4<f32>(0.0);
387 var ray_wsum = 0.0;
388 for (var s = 1; s <= steps; s = s + 1) {
389 let t = f32(s) / fsteps;
390 let su = uv + dir * (t * length_px);
391 let w = pow(max(1.0 - t, 0.0), falloff * 1.8);
392 if (su.x >= 0.0 && su.x <= 1.0 && su.y >= 0.0 && su.y <= 1.0) {
393 ray_acc += textureSampleLevel(aux_img_tex, samp, su, 0.0) * w;
394 }
395 ray_wsum += w;
396 }
397 streak += (ray_acc / max(ray_wsum * 0.35, 1e-4)) * ray_norm;
398 }
399 }
400
401 let colored_streak = vec4<f32>(streak.rgb * tint, clamp(streak.a, 0.0, 1.0));
402 var fx = colored_streak;
403 if (merge_orig) {
404 fx = vec4<f32>(
405 src.rgb + colored_streak.rgb,
406 clamp(src.a + colored_streak.a * (1.0 - src.a), 0.0, 1.0),
407 );
408 }
409
410 let out = finalize_fx(
411 src,
412 fx,
413 uv,
414 params.p[2].x,
415 params.p[2].y,
416 params.p[2].z,
417 params.p[2].w,
418 params.p[3],
419 );
420 textureStore(dst_tex, vec2<i32>(gid.xy), out);
421}
422
423// -----------------------------------------------------------------------------
424// 4. HotSpot — radial primary flare + secondary optical lens elements
425// p[0] = (primary_cx, primary_cy, secondary_cx, secondary_cy) // Fusion Y-up [0..1]
426// p[1] = (primary_size, primary_strength, primary_aspect, secondary_elements)
427// p[2] = (primary_r, primary_g, primary_b, apply_mode)
428// apply_mode: 0=Add, 1=Screen, 2=Normal, 3=Multiply, 4=Lighten, 5=Overlay
429// p[3] = (secondary_strength, secondary_size, blend, has_mask)
430// p[4] = (mask_inv, mbm, 0, 0)
431// p[5] = process_skip (r, g, b, a)
432// -----------------------------------------------------------------------------
433fn secondary_tint(idx: i32) -> vec3<f32> {
434 let phase = f32(idx) * 2.0943951; // 120 deg hue offsets
435 return vec3<f32>(
436 0.78 + 0.22 * cos(phase),
437 0.78 + 0.22 * cos(phase + 2.0943951),
438 0.78 + 0.22 * cos(phase + 4.1887902),
439 );
440}
441
442@compute @workgroup_size(8, 8)
443fn hot_spot_op(@builtin(global_invocation_id) gid: vec3<u32>) {
444 let dims = textureDimensions(dst_tex);
445 if (gid.x >= dims.x || gid.y >= dims.y) {
446 return;
447 }
448 let fdims = vec2<f32>(dims);
449 let uv = (vec2<f32>(gid.xy) + 0.5) / fdims;
450 let src = textureSampleLevel(src_tex, samp, uv, 0.0);
451
452 // Fusion Y-up normalized coordinates
453 let fpos = vec2<f32>(uv.x, 1.0 - uv.y);
454 let img_aspect = fdims.x / max(fdims.y, 1.0);
455
456 let p_center = params.p[0].xy;
457 let s_center = params.p[0].zw;
458 let p_size = max(params.p[1].x, 1e-4);
459 let p_strength = max(params.p[1].y, 0.0);
460 let p_aspect = max(params.p[1].z, 0.05);
461 let sec_count = clamp(i32(round(params.p[1].w)), 0, 16);
462 let p_color = params.p[2].rgb;
463 let apply_mode = i32(round(params.p[2].w));
464 let sec_strength = max(params.p[3].x, 0.0);
465 let sec_size = max(params.p[3].y, 1e-4);
466
467 // Primary radial hot spot
468 let dp = fpos - p_center;
469 let dp_scaled = vec2<f32>(dp.x * img_aspect / p_aspect, dp.y);
470 let rp = length(dp_scaled) / p_size;
471 let primary_g = (0.72 * exp(-rp * rp * 3.2) + 0.28 * exp(-rp * 2.4)) * p_strength;
472 var flare_rgb = p_color * primary_g;
473 var flare_a = clamp(primary_g, 0.0, 1.0);
474
475 // Secondary lens flare elements along the optical axis through Primary -> Secondary
476 if (sec_count > 0 && sec_strength > 1e-5 && p_strength > 1e-5) {
477 let axis = s_center - p_center;
478 let fcount = f32(sec_count);
479 for (var i = 0; i < sec_count; i = i + 1) {
480 let frac = (f32(i) + 1.0) / (fcount + 0.5);
481 let t = mix(0.35, 1.35, frac);
482 let e_pos = p_center + axis * t;
483 let size_mod = 0.55 + 0.75 * fract(f32(i) * 0.618034 + 0.25);
484 let e_rad = sec_size * size_mod;
485 let de = fpos - e_pos;
486 let de_scaled = vec2<f32>(de.x * img_aspect, de.y);
487 let re = length(de_scaled) / max(e_rad, 1e-4);
488
489 // Alternate soft bokeh disc and thin lens halo ring
490 var elem = 0.0;
491 if ((i & 1) == 0) {
492 elem = smoothstep(1.05, 0.35, re) * (0.45 + 0.35 * smoothstep(0.4, 0.85, re));
493 } else {
494 let ring = exp(-pow((re - 0.82) * 5.0, 2.0));
495 let core = exp(-re * re * 2.5) * 0.25;
496 elem = ring * 0.65 + core;
497 }
498 let e_energy = elem * sec_strength * p_strength * 0.55;
499 let e_col = p_color * secondary_tint(i);
500 flare_rgb += e_col * e_energy;
501 flare_a = clamp(flare_a + e_energy * (1.0 - flare_a), 0.0, 1.0);
502 }
503 }
504
505 var fx_rgb = src.rgb;
506 var fx_a = src.a;
507 switch apply_mode {
508 case 1: {
509 // Screen
510 let f_clamped = clamp(flare_rgb, vec3<f32>(0.0), vec3<f32>(1.0));
511 fx_rgb = 1.0 - (1.0 - src.rgb) * (1.0 - f_clamped);
512 fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0);
513 }
514 case 2: {
515 // Normal / Over
516 fx_rgb = src.rgb * (1.0 - flare_a) + flare_rgb;
517 fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0);
518 }
519 case 3: {
520 // Multiply
521 fx_rgb = src.rgb * flare_rgb;
522 fx_a = src.a;
523 }
524 case 4: {
525 // Lighten / Max
526 fx_rgb = max(src.rgb, flare_rgb);
527 fx_a = max(src.a, flare_a);
528 }
529 case 5: {
530 // Overlay
531 let lo = 2.0 * src.rgb * flare_rgb;
532 let hi = 1.0 - 2.0 * (1.0 - src.rgb) * (1.0 - clamp(flare_rgb, vec3<f32>(0.0), vec3<f32>(1.0)));
533 fx_rgb = select(hi, lo, src.rgb < vec3<f32>(0.5));
534 fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0);
535 }
536 default: {
537 // Add (optical light default)
538 fx_rgb = src.rgb + flare_rgb;
539 fx_a = clamp(src.a + flare_a * (1.0 - src.a), 0.0, 1.0);
540 }
541 }
542
543 let out = finalize_fx(
544 src,
545 vec4<f32>(fx_rgb, fx_a),
546 uv,
547 params.p[3].z,
548 params.p[3].w,
549 params.p[4].x,
550 params.p[4].y,
551 params.p[5],
552 );
553 textureStore(dst_tex, vec2<i32>(gid.xy), out);
554}
555
556// -----------------------------------------------------------------------------
557// 5. RankFilter — exact GPU order-statistic filter (Min / Median / Max / Percentile)
558// p[0] = (radius_px, rank, filter_type, 0)
559// filter_type: 0=Box, 1=Circle, 2=Cross, 3=Diamond
560// p[1] = (blend, has_mask, mask_inv, mbm)
561// p[2] = process_skip (r, g, b, a)
562// -----------------------------------------------------------------------------
563fn rank_in_footprint(dx: i32, dy: i32, r: i32, ftype: i32) -> bool {
564 switch ftype {
565 case 1: {
566 return f32(dx * dx + dy * dy) <= f32(r * r) + 0.25;
567 }
568 case 2: {
569 return dx == 0 || dy == 0;
570 }
571 case 3: {
572 return abs(dx) + abs(dy) <= r;
573 }
574 default: {
575 return true;
576 }
577 }
578}
579
580fn select_kth(vals: ptr<function, array<f32, 121>>, count: i32, k: i32, vmin: f32, vmax: f32) -> f32 {
581 if (count <= 1 || vmax - vmin <= 1e-6 || k <= 0) {
582 return vmin;
583 }
584 if (k >= count - 1) {
585 return vmax;
586 }
587 var lo = vmin;
588 var hi = vmax;
589 for (var iter = 0; iter < 20; iter = iter + 1) {
590 let mid = 0.5 * (lo + hi);
591 var le = 0;
592 for (var i = 0; i < count; i = i + 1) {
593 if ((*vals)[i] <= mid) {
594 le = le + 1;
595 }
596 }
597 if (le > k) {
598 hi = mid;
599 } else {
600 lo = mid;
601 }
602 }
603 return hi;
604}
605
606fn eval_rank_channel(
607 px: vec2<i32>,
608 dims: vec2<i32>,
609 r: i32,
610 ftype: i32,
611 rank: f32,
612 chan: i32,
613) -> f32 {
614 var vals: array<f32, 121>;
615 var count = 0;
616 var vmin = 1e30;
617 var vmax = -1e30;
618 for (var dy = -r; dy <= r; dy = dy + 1) {
619 for (var dx = -r; dx <= r; dx = dx + 1) {
620 if (!rank_in_footprint(dx, dy, r, ftype)) {
621 continue;
622 }
623 let c = clamp(px + vec2<i32>(dx, dy), vec2<i32>(0), dims - vec2<i32>(1));
624 let s = textureLoad(src_tex, c, 0);
625 var v = s.r;
626 if (chan == 1) { v = s.g; }
627 else if (chan == 2) { v = s.b; }
628 else if (chan == 3) { v = s.a; }
629 vals[count] = v;
630 vmin = min(vmin, v);
631 vmax = max(vmax, v);
632 count = count + 1;
633 }
634 }
635 if (count <= 0) {
636 return 0.0;
637 }
638 let pos = clamp(rank, 0.0, 1.0) * f32(count - 1);
639 let k0 = i32(floor(pos));
640 let k1 = i32(ceil(pos));
641 let frac = pos - f32(k0);
642 let v0 = select_kth(&vals, count, k0, vmin, vmax);
643 if (k1 == k0 || frac <= 1e-4) {
644 return v0;
645 }
646 let v1 = select_kth(&vals, count, k1, v0, vmax);
647 return mix(v0, v1, frac);
648}
649
650@compute @workgroup_size(8, 8)
651fn rank_filter_op(@builtin(global_invocation_id) gid: vec3<u32>) {
652 let dims = textureDimensions(dst_tex);
653 if (gid.x >= dims.x || gid.y >= dims.y) {
654 return;
655 }
656 let idims = vec2<i32>(dims);
657 let px = vec2<i32>(gid.xy);
658 let uv = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(dims);
659 let src = textureLoad(src_tex, px, 0);
660
661 let r = clamp(i32(round(params.p[0].x)), 0, 5);
662 let rank = clamp(params.p[0].y, 0.0, 1.0);
663 let ftype = i32(round(params.p[0].z));
664 let skip = params.p[2];
665
666 var fx = src;
667 if (r > 0) {
668 if (skip.r < 0.5) { fx.r = eval_rank_channel(px, idims, r, ftype, rank, 0); }
669 if (skip.g < 0.5) { fx.g = eval_rank_channel(px, idims, r, ftype, rank, 1); }
670 if (skip.b < 0.5) { fx.b = eval_rank_channel(px, idims, r, ftype, rank, 2); }
671 if (skip.a < 0.5) { fx.a = eval_rank_channel(px, idims, r, ftype, rank, 3); }
672 }
673
674 let out = finalize_fx(
675 src,
676 fx,
677 uv,
678 params.p[1].x,
679 params.p[1].y,
680 params.p[1].z,
681 params.p[1].w,
682 skip,
683 );
684 textureStore(dst_tex, px, out);
685}