From f490606bd49320b6f40453f6edbc43fa9d4dd284 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 01:21:40 -0800 Subject: [PATCH] Wave 14A: PerspectivePositioner/Crop DoD, Displace light, SeetheRate, looping video, OutputCache accounting - PerspectivePositioner reads source DoD and emits the pullback DoD of its source domain; Crop reads DoD; DoD readers absorb upstream expansion instead of vetoing it; bbox-clip classifier unwraps routers/bypass (Composition2 f157 18.0% -> 0.3%). - Displace: LightAngle default 135 with diamond direction, LightChannel 0..5 (per-channel/R/G/B/A/Luma), unclamped light incl. alpha, negative LightPower ignored, light softened by a Gaussian of sigma = 0.3 + Spread * width / 240 (falling_2360 2.30% -> 0.39%, falling_2380 1.25% -> 0.33%). - MultiplyByMask still zeroes outside the EffectMask for identity Drip/Dent/Vortex and mapless Displace. - FastNoise: SeetheRate factor 0.1 (was 0.02), seethe summed in f64, continuous octave weights, depth in cache key, gradient LUT only in Gradient mode. - MediaCache: looping videos loop past GlobalEnd; ExtendFirst holds frame 0. - OutputCache: dedupe by Arc pointer; unshared when every strong ref is an output entry. Assisted-by: claude-sonnet-5.5 --- crates/engine/src/eval/io.rs | 88 ++++++----- crates/engine/src/eval/output_cache.rs | 61 ++++++-- crates/engine/src/eval/transform.rs | 171 +++++++++++++++++++--- crates/engine/src/eval/warps.rs | 118 ++++++++++++++- crates/engine/src/media.rs | 17 ++- crates/engine/src/shaders/archive_fx.wgsl | 15 +- crates/engine/src/shaders/keyers_gen.wgsl | 2 +- crates/engine/src/shaders/transform.wgsl | 52 ++++--- 8 files changed, 416 insertions(+), 108 deletions(-) diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index 0c73dc474e19e89c566aacca4fe2a82ab57c44bf..a2703a60d0379bd8703a260ac29e9877382fb78b 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -688,8 +688,8 @@ impl Engine { let dst_size = self.scaled_dims(x_size, y_size); let (x_off, y_off) = if keep_centered { ( - (src.size[0] as f32 - dst_size[0] as f32) * 0.5, - (src.size[1] as f32 - dst_size[1] as f32) * 0.5, + (src.canvas_size[0] as f32 - dst_size[0] as f32) * 0.5, + (src.canvas_size[1] as f32 - dst_size[1] as f32) * 0.5, ) } else { ( @@ -700,7 +700,10 @@ impl Engine { let mut u = UniformParams::default(); u.p[0] = [x_off, y_off, 1.0, 1.0]; - let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); + if src.has_dod() { + u.p[1] = [src.origin[0] as f32, src.origin[1] as f32, src.canvas_size[0] as f32, src.canvas_size[1] as f32]; + } + let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..2])); if let Some(hit) = self.cache.get(key, node.id, frame_i) { stats.cache_hits += 1; return hit; @@ -746,8 +749,8 @@ impl Engine { let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32; let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32; let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32; - let seethe = comp.eval_number(node, "Seethe", time, 0.0, &self.expr) as f32 - + (comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) as f32) * (time as f32) * 0.02; + let seethe = (comp.eval_number(node, "Seethe", time, 0.0, &self.expr) + + comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) * time * 0.1) as f32; let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32; let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); @@ -768,30 +771,7 @@ impl Engine { let noise_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as i32; let grad = if noise_type == 1 { comp.eval_gradient(node, "Gradient", time) } else { None }; - // Bake high-precision 256x1 RGBA gradient LUT so sharp thresholds (e.g. 0.95..0.96 stars) are exact! - let mut grad_bytes = [0u8; 256 * 4]; - for i in 0..256 { - let t = i as f64 / 255.0; - let c = if let Some(g) = &grad { - g.sample(t) - } else { - let tf = t as f32; - [ - c1[0] + (c2[0] - c1[0]) * tf, - c1[1] + (c2[1] - c1[1]) * tf, - c1[2] + (c2[2] - c1[2]) * tf, - c1[3] + (c2[3] - c1[3]) * tf, - ] - }; - grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8; - grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8; - grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8; - grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8; - } - let mut gh = DefaultHasher::new(); - grad_bytes.hash(&mut gh); - let grad_hash = gh.finish(); - + let dst_depth = self.node_depth(comp, node, time, None); let mut u = UniformParams::default(); u.p[0] = [x_scale, y_scale, detail, contrast]; u.p[1] = [brightness, seethe, disc, center[0] as f32]; @@ -799,23 +779,43 @@ impl Engine { u.p[3] = c1; u.p[4] = c2; - let key = self.make_key(node, "FastNoise", size, &[grad_hash], bytemuck::cast_slice(&u.p[..5])); + // Gradient mode only: 256x1 RGBA LUT so sharp thresholds (e.g. 0.95..0.96 stars) stay exact. + let lut = (noise_type == 1).then(|| { + let mut bytes = [0u8; 256 * 4]; + for (i, texel) in bytes.chunks_exact_mut(4).enumerate() { + let t = i as f64 / 255.0; + let c = grad.as_ref().map_or_else(|| std::array::from_fn(|k| c1[k] + (c2[k] - c1[k]) * t as f32), |g| g.sample(t)); + for (b, v) in texel.iter_mut().zip(c) { + *b = (v.clamp(0.0, 1.0) * 255.0).round() as u8; + } + } + let mut gh = DefaultHasher::new(); + bytes.hash(&mut gh); + (bytes, gh.finish()) + }); + let grad_hash = lut.as_ref().map_or(0, |l| l.1); + + let key = self.make_key(node, "FastNoise", size, &[grad_hash, dst_depth as u64], 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 lut_tex = create_texture(&self.device, [256, 1], 0); - self.queue.write_texture( - lut_tex.texture.as_image_copy(), - &grad_bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, - wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, - ); - let mut dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key); + let lut_tex = lut.map(|(bytes, _)| { + let tex = create_texture(&self.device, [256, 1], 0); + self.queue.write_texture( + tex.texture.as_image_copy(), + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, + ); + tex + }); + let mut dst = self.alloc_tex(size, dst_depth, key); dst.tex_scale *= tex_scale; - self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u); + let lut_view = lut_tex.as_ref().map_or(&self.dummy.view, |t| &t.view); + self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, lut_view, &self.dummy.view, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); dst } @@ -1537,6 +1537,16 @@ Composition {{ } } + #[test] + fn fast_noise_detail_weight_is_continuous_above_integers() { + let render = |detail: &str| { + render_generator("FastNoise", 64, 64, &format!("Detail = Input {{ Value = {detail}, }}, XScale = Input {{ Value = 8, }},")) + }; + let (Some(a), Some(b)) = (render("2"), render("2.00005")) else { return }; + let worst = a.iter().zip(&b).map(|(x, y)| (x[0] - y[0]).abs()).fold(0.0f32, f32::max); + assert!(worst <= 1.5 / 255.0, "Detail 2 -> 2.00005 jumped by {worst}"); + } + #[test] fn fast_noise_two_color_extrapolates_unclamped_highlights() { // High Contrast + Discontinuous pushes `val > 1.0`, so Two-Color mode must extrapolate diff --git a/crates/engine/src/eval/output_cache.rs b/crates/engine/src/eval/output_cache.rs index 0437cf32063eeba346042f365af8e4d9a8cd4d8b..255177d4982297334d6d32eb52a459c229fb8c66 100644 --- a/crates/engine/src/eval/output_cache.rs +++ b/crates/engine/src/eval/output_cache.rs @@ -1,6 +1,6 @@ //! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting. -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -44,20 +44,33 @@ impl OutputCache { } } - /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`). + /// Per distinct texture: `(bytes, entries referencing it, Arc::strong_count)`. + fn textures(&self) -> HashMap<*const wgpu::Texture, (u64, usize, usize)> { + let mut by_ptr = HashMap::new(); + for (_, tex, _) in &self.entries { + let slot = by_ptr + .entry(Arc::as_ptr(&tex.texture)) + .or_insert((tex.bytes, 0, Arc::strong_count(&tex.texture))); + slot.1 += 1; + } + by_ptr + } + + /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`), + /// counting a texture once however many entries point at it. pub(super) fn total_bytes(&self) -> u64 { - self.entries.iter().map(|(_, tex, _)| tex.bytes).sum() + self.textures().values().map(|&(bytes, _, _)| bytes).sum() } - /// GPU bytes held *exclusively* by `output_cache` (`Arc::strong_count(&tex.texture) == 1`). + /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here. /// - /// Textures still resident in `NodeCache` have `strong_count >= 2` and are already counted in - /// `NodeCache::total_vram_bytes()`, so skipping them prevents double-counting against the VRAM budget. + /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry + /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget. pub(super) fn unshared_bytes(&self) -> u64 { - self.entries - .iter() - .filter(|(_, tex, _)| Arc::strong_count(&tex.texture) == 1) - .map(|(_, tex, _)| tex.bytes) + self.textures() + .values() + .filter(|&&(_, entries, strong)| entries == strong) + .map(|&(bytes, _, _)| bytes) .sum() } @@ -173,3 +186,31 @@ impl Engine { self.sync_node_cache_budget(); } } + +#[cfg(test)] +mod tests { + use super::*; + use model::BitDepth; + + #[test] + fn duplicate_arcs_count_once_and_caller_clones_count_as_shared() { + let eng = Engine::new_headless().expect("gpu"); + let tex = eng.alloc_tex([64, 64], BitDepth::Int8, 1); + let other = eng.alloc_tex([32, 32], BitDepth::Int8, 2); + let (tex_bytes, other_bytes) = (tex.bytes, other.bytes); + let mut cache = OutputCache::new(); + let cap = u64::MAX; + cache.insert(1, tex.clone(), vec![], CacheMode::Enabled, cap); + cache.insert(2, tex.clone(), vec![], CacheMode::Enabled, cap); + cache.insert(3, other.clone(), vec![], CacheMode::Enabled, cap); + assert_eq!(cache.len(), 3); + assert_eq!(cache.total_bytes(), tex_bytes + other_bytes); + + // The test's own clones stand in for `NodeCache` entries or in-flight callers. + assert_eq!(cache.unshared_bytes(), 0); + drop(other); + assert_eq!(cache.unshared_bytes(), other_bytes); + drop(tex); + assert_eq!(cache.unshared_bytes(), tex_bytes + other_bytes); + } +} diff --git a/crates/engine/src/eval/transform.rs b/crates/engine/src/eval/transform.rs index 7be8eba6a78feec07de9c8b04dd831c37f2a873e..f6ba30027c807407995890ca7225c68962bee244 100644 --- a/crates/engine/src/eval/transform.rs +++ b/crates/engine/src/eval/transform.rs @@ -1,5 +1,21 @@ use super::*; +/// Follows bypassed nodes and routers upstream to the node that actually produces the image. +pub(super) fn unwrap_passthrough(comp: &Comp, start_id: NodeId) -> NodeId { + let mut cur = start_id; + for _ in 0..24 { + let n = comp.node(cur); + if !(n.bypassed || matches!(n.kind.as_str(), "PipeRouter" | "Fuse.Wireless")) { + break; + } + match n.connected_node(default_main_input_port(&n.kind)).and_then(|s| comp.find_node(s)) { + Some(next) => cur = next, + None => break, + } + } + cur +} + /// Returns `true` if `start_id` traces back through point/passthrough ops to a `Background` generator /// (whose Fusion RoI extends uniformly beyond the canvas boundary). fn is_background_chain(comp: &Comp, start_id: NodeId, depth: usize) -> bool { @@ -189,7 +205,9 @@ fn compute_transform_source_roi( ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32]) } -fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool { +/// A downstream DoD reader (`Transform`, `DVE`, `CornerPositioner`, `PerspectivePositioner`, `Crop`) that cannot +/// expand itself still consumes the DoD safely, so the walk stops there instead of following its output. +pub(super) fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool { let mut queue = vec![start_name]; let mut seen = HashSet::new(); let mut feeds_dod_reader = false; @@ -215,10 +233,9 @@ fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool { } queue.push(n.name.as_str()); } - "Transform" | "DVE" | "CornerPositioner" => { + "Transform" | "DVE" | "CornerPositioner" | "PerspectivePositioner" | "Crop" => { if port == "Input" { feeds_dod_reader = true; - queue.push(n.name.as_str()); } else { return false; } @@ -307,21 +324,35 @@ fn compute_transform_dst_dod( min_y = min_y.min(src.origin[1] as f32); max_y = max_y.max((src.origin[1] + src.size[1] as i32) as f32); + dod_from_px_bounds(min_x, max_x, min_y, max_y, src.canvas_size, max_dim) +} + +/// Integer DoD rectangle covering the canvas plus pixel bounds `[min, max]` (canvas pixels, y down), +/// padded for filtering, clamped to +-2048 px beyond the canvas and `max_dim` across. +pub(super) fn dod_from_px_bounds( + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, + canvas_size: [u32; 2], + max_dim: u32, +) -> ([i32; 2], [u32; 2]) { + let (cw, ch) = (canvas_size[0].max(1) as f32, canvas_size[1].max(1) as f32); let pad = 2_i32; let max_pad = 2048_i32; let mut x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 }; let mut y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 }; let mut x1 = if max_x > cw + 0.25 { - (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad) + (max_x.ceil() as i32 + pad).min(canvas_size[0] as i32 + max_pad) } else { - src.canvas_size[0] as i32 + canvas_size[0] as i32 }; let mut y1 = if max_y > ch + 0.25 { - (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad) + (max_y.ceil() as i32 + pad).min(canvas_size[1] as i32 + max_pad) } else { - src.canvas_size[1] as i32 + canvas_size[1] as i32 }; - let cap = max_dim.max(src.canvas_size[0]).max(src.canvas_size[1]) as i32; + let cap = max_dim.max(canvas_size[0]).max(canvas_size[1]) as i32; if x1 - x0 > cap { let excess = (x1 - x0) - cap; let trim_l = (0 - x0).max(0).min(excess); @@ -812,6 +843,12 @@ impl Engine { dst } + /// `MultiplyByMask` zeroes outside the EffectMask even when the effect itself is an identity. + pub(super) fn multiplies_by_mask(&self, comp: &Comp, node: &Node, time: f64) -> bool { + node.connected_node("EffectMask").is_some() + && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5 + } + pub(super) fn eval_displace( &mut self, comp: &Comp, @@ -826,28 +863,42 @@ impl Engine { return self.dummy.clone(); }; let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else { + let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s)); + if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) { return src; - }; + } let src = self.crop_to_canvas(enc, src); - let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); - let fg = self.crop_to_canvas(enc, fg); + let fg = match fg_id { + Some(id) => { + let fg = self.eval_node(comp, id, time, enc, visiting, stats); + self.crop_to_canvas(enc, fg) + } + None => self.dummy.clone(), + }; let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32; - let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32; - let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32; + // Without a map Displace is an identity warp; only MultiplyByMask still applies. + let mapped = if fg_id.is_some() { 1.0 } else { 0.0 }; + let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 }; + let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped; + let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped; let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32; let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32; let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32; let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32; - let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32; - let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32; - let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32; - let light_angle_rad = (comp.eval_number(node, "LightAngle", time, 0.0, &self.expr) as f32 - 45.0).to_radians(); - let light_channel = comp.eval_number(node, "LightChannel", time, 5.0, &self.expr) as f32; + let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped; + let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped; + let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped; + // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus. + let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr); + let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs(); + let light_dir = [ + ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32, + ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32, + ]; + let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32; let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; @@ -857,7 +908,7 @@ impl Engine { u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; - u.p[4] = [light_angle_rad, light_channel, if mbm { 1.0 } else { 0.0 }, 0.0]; + u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel]; let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); if let Some(hit) = self.cache.get(key, node.id, frame_i) { @@ -890,7 +941,7 @@ impl Engine { 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 angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; - if blend <= 1e-6 || angle_deg.abs() <= 1e-5 { + if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) { return src; } let src = self.crop_to_canvas(enc, src); @@ -1754,6 +1805,82 @@ mod tests { assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept"); } + #[test] + fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() { + // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask. + let cases = [ + ("Drip", "Amplitude = Input { Value = 0, },", false), + ("Dent", "Strength = Input { Value = 0, },", false), + ("Vortex", "Angle = Input { Value = 0, },", false), + ("Displace", "", false), + ("Drip", "Blend = Input { Value = 0, },", true), + ("Vortex", "Blend = Input { Value = 0, },", true), + ]; + if Engine::new_headless().is_err() { + return; + } + for (kind, inputs, survives) in cases { + let src = format!( + 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 = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }}, + MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, + FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs} + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let mut eng = Engine::new_headless().unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3]; + assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask"); + assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask"); + } + } + + #[test] + fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() { + // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond + // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped. + let lit = |inputs: &str| -> [u8; 4] { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, + TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, + Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs} + Input = Input {{ SourceOp = "Flat", Source = "Output", }}, + Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let mut eng = Engine::new_headless().unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (32 * 64 + 32) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + if Engine::new_headless().is_err() { + return; + } + let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}"); + // Ramp slope per tap pair is 2/63 of full scale = ~8 levels. + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8); + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8); + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128); + // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively. + near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8); + // LightChannel 4 lights every channel from alpha, which is flat. + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128); + near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128); + } + #[test] fn transform_invert_transform_shifts_the_opposite_way() { let src = |invert: u8| { diff --git a/crates/engine/src/eval/warps.rs b/crates/engine/src/eval/warps.rs index 2c53fc84141e3bd5f2a739502c8a759598c6e201..0b08b5ad756f83f64f8a7edab739d82ac4b2abb3 100644 --- a/crates/engine/src/eval/warps.rs +++ b/crates/engine/src/eval/warps.rs @@ -1,5 +1,6 @@ //! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`). +use super::transform::{dod_from_px_bounds, transform_should_expand_dod, unwrap_passthrough}; use super::*; impl Engine { @@ -20,7 +21,7 @@ impl Engine { 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 amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32; - if blend <= 1e-6 || amp.abs() <= 1e-7 { + if blend <= 1e-6 || (amp.abs() <= 1e-7 && !self.multiplies_by_mask(comp, node, time)) { return src; } let src = self.crop_to_canvas(enc, src); @@ -77,7 +78,7 @@ impl Engine { 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 strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32; - if blend <= 1e-6 || strength.abs() <= 1e-6 { + if blend <= 1e-6 || (strength.abs() <= 1e-6 && !self.multiplies_by_mask(comp, node, time)) { return src; } let src = self.crop_to_canvas(enc, src); @@ -132,14 +133,13 @@ impl Engine { if blend <= 1e-6 { return src; } - let src = self.crop_to_canvas(enc, src); let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr); let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr); let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr); let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr); let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32; let h_fwd = quad_forward_homography(bl, br, tr, tl); - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; @@ -158,7 +158,8 @@ impl Engine { // Fusion renders computed sources only inside the corner bounding box (unless an EffectMask // pulls the whole input), so Blend < 1 fades the rest toward transparent; Loader and sRender // sources are always complete. - if mask.is_none() && !matches!(comp.node(src_id).kind.as_str(), "Loader" | "MediaIn" | "sRender") { + let src_kind = comp.node(unwrap_passthrough(comp, src_id)).kind.as_str(); + if mask.is_none() && !matches!(src_kind, "Loader" | "MediaIn" | "sRender") { let xs = [bl[0], br[0], tr[0], tl[0]]; let ys = [bl[1], br[1], tr[1], tl[1]]; let (x0, x1) = xs.iter().fold((f64::MAX, f64::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v))); @@ -167,12 +168,37 @@ impl Engine { u.p[6] = [x0 as f32, y0 as f32, x1 as f32, y1 as f32]; } + // The output extends past the canvas wherever the corner mapping still lands inside the source domain. + let canvas = src.canvas_size.map(|v| v.max(1) as f64); + let src_rect = [ + src.origin[0] as f64 / canvas[0], + 1.0 - (src.origin[1] + src.size[1] as i32) as f64 / canvas[1], + (src.origin[0] + src.size[0] as i32) as f64 / canvas[0], + 1.0 - src.origin[1] as f64 / canvas[1], + ]; + let (dst_origin, dst_size) = match positioner_preimage(mapping_type, [bl, br, tr, tl], h_fwd, src_rect) { + Some(fu) if mask.is_none() && transform_should_expand_dod(comp, &node.name) => { + let px = fu.map(|[x, y]| [(x * canvas[0]) as f32, ((1.0 - y) * canvas[1]) as f32]); + let (min_x, max_x) = px.iter().fold((0.0, canvas[0] as f32), |(lo, hi), p| (f32::min(lo, p[0]), f32::max(hi, p[0]))); + let (min_y, max_y) = px.iter().fold((0.0, canvas[1] as f32), |(lo, hi), p| (f32::min(lo, p[1]), f32::max(hi, p[1]))); + let max_dim = self.device.limits().max_texture_dimension_2d.min(4096); + dod_from_px_bounds(min_x, max_x, min_y, max_y, src.canvas_size, max_dim) + } + _ => ([0, 0], src.canvas_size), + }; + if dst_origin != [0, 0] || dst_size != src.canvas_size { + u.p[7] = [dst_origin[0] as f32, dst_origin[1] as f32, src.canvas_size[0] as f32, src.canvas_size[1] as f32]; + } + if src.has_dod() { + u.p[8] = [src.origin[0] as f32, src.origin[1] as f32, src.canvas_size[0] as f32, src.canvas_size[1] as f32]; + } + let key = self.make_key( node, "PerspectivePositioner", - src.size, + dst_size, &[src.content_hash, mask_hash], - bytemuck::cast_slice(&u.p[..7]), + bytemuck::cast_slice(&u.p[..9]), ); if let Some(hit) = self.cache.get(key, node.id, frame_i) { stats.cache_hits += 1; @@ -180,7 +206,8 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex_like(&src, src.depth, key); + let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key); + dst.tex_scale = src.tex_scale; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -438,6 +465,67 @@ fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2 [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0] } +/// Output-space corners (Fusion UV) of `src_rect` (`u0, v0, u1, v1`) pulled back through the corner mapping, or +/// `None` when the mapping is degenerate or the pullback reaches infinity. +fn positioner_preimage(mapping_type: i32, quad: [[f64; 2]; 4], h: [f32; 9], src_rect: [f64; 4]) -> Option<[[f64; 2]; 4]> { + let [bl, br, tr, tl] = quad; + let [u0, v0, u1, v1] = src_rect; + let source_corners = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]]; + let mut out = [[0.0; 2]; 4]; + if mapping_type == 1 { + let [a, b, c, d, e, f, g, hh, i] = h.map(f64::from); + let inv = [ + [e * i - f * hh, c * hh - b * i, b * f - c * e], + [f * g - d * i, a * i - c * g, c * d - a * f], + [d * hh - e * g, b * g - a * hh, a * e - b * d], + ]; + let det = a * inv[0][0] + b * inv[1][0] + c * inv[2][0]; + if det.abs() < 1e-12 { + return None; + } + let mut sign = 0.0_f64; + for (o, s) in out.iter_mut().zip(source_corners) { + let row = |r: [f64; 3]| (r[0] * s[0] + r[1] * s[1] + r[2]) / det; + let w = row(inv[2]); + sign = if sign == 0.0 { w.signum() } else { sign }; + if w.abs() < 1e-9 || w.signum() != sign { + return None; + } + *o = [row(inv[0]) / w, row(inv[1]) / w]; + } + return Some(out); + } + // Bilinear: s(x, y) = bl + (br - bl) x + (tl - bl) y + (bl - br - tl + tr) x y, solved by Newton. + let ex = [br[0] - bl[0], br[1] - bl[1]]; + let ey = [tl[0] - bl[0], tl[1] - bl[1]]; + let exy = [bl[0] - br[0] - tl[0] + tr[0], bl[1] - br[1] - tl[1] + tr[1]]; + for (o, t) in out.iter_mut().zip(source_corners) { + let (mut x, mut y) = (0.5, 0.5); + let mut converged = false; + for _ in 0..64 { + let r = [0, 1].map(|k| bl[k] + ex[k] * x + ey[k] * y + exy[k] * x * y - t[k]); + let jx = [0, 1].map(|k| ex[k] + exy[k] * y); + let jy = [0, 1].map(|k| ey[k] + exy[k] * x); + let det = jx[0] * jy[1] - jy[0] * jx[1]; + if det.abs() < 1e-12 { + return None; + } + let (dx, dy) = ((r[0] * jy[1] - jy[0] * r[1]) / det, (jx[0] * r[1] - r[0] * jx[1]) / det); + x -= dx; + y -= dy; + if dx.abs() + dy.abs() < 1e-10 { + converged = true; + break; + } + } + if !converged { + return None; + } + *o = [x, y]; + } + Some(out) +} + fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize { if let Some(m) = node.static_str("Month") { let low = m.to_ascii_lowercase(); @@ -630,6 +718,20 @@ fn rasterize_grid_warp_uv_f16( #[cfg(test)] mod tests { use super::*; + + #[test] + fn positioner_preimage_of_a_zoomed_quad_spans_twice_the_frame() { + // Corners cover the middle half of the source, so the whole source lands at [-0.5, 1.5]^2. + let quad = [[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]]; + let h = quad_forward_homography(quad[0], quad[1], quad[2], quad[3]); + for mapping_type in [0, 1] { + let corners = positioner_preimage(mapping_type, quad, h, [0.0, 0.0, 1.0, 1.0]).expect("finite pullback"); + let (lo, hi) = corners.iter().flatten().fold((f64::MAX, f64::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v))); + assert!((lo + 0.5).abs() < 1e-6 && (hi - 1.5).abs() < 1e-6, "type {mapping_type}: {lo}..{hi}"); + } + let flat = [[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [0.0, 0.0]]; + assert!(positioner_preimage(0, flat, quad_forward_homography(flat[0], flat[1], flat[2], flat[3]), [0.0, 0.0, 1.0, 1.0]).is_none()); + } use crate::Engine; #[test] diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index bc057b1b6f07b8b3cc5cd2640b4f4ee70c095513..fdb124b71d760588c918434cd022a77fd059d284 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -186,7 +186,7 @@ impl MediaCache { { let min_f = clip.global_start - clip.extend_first.max(0); let max_f = clip.global_end + clip.extend_last.max(0); - if frame < min_f || frame > max_f { + if frame < min_f || (!clip.loop_clip && frame > max_f) { return None; } } @@ -202,7 +202,7 @@ impl MediaCache { }; let span = (trim_out - trim_in + 1).max(1); let rel = if clip.loop_clip { - (frame - clip.global_start).rem_euclid(span) + (frame - clip.global_start).max(0).rem_euclid(span) } else { (frame - clip.global_start).clamp(0, span - 1) }; @@ -741,11 +741,18 @@ mod tests { loop_clip: true, reverse: false, }; - // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15], rel = -1 -> rem_euclid(6) = 5. + // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0. let (_, local_idx, _, _) = cache .load_clip(&clip, 9, false, [None; 4]) - .expect("loop_clip negative rel inside ExtendFirst should resolve"); - assert_eq!(local_idx, 5); + .expect("loop_clip inside ExtendFirst should resolve"); + assert_eq!(local_idx, 0); + // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4. + let (_, local_idx, _, _) = cache + .load_clip(&clip, 20, false, [None; 4]) + .expect("loop_clip past GlobalEnd should keep looping"); + assert_eq!(local_idx, 4); + let once = ClipSpec { loop_clip: false, ..clip }; + assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none()); } assert!( cache.video_decoder_count() <= MAX_VIDEO_DECODERS, diff --git a/crates/engine/src/shaders/archive_fx.wgsl b/crates/engine/src/shaders/archive_fx.wgsl index 2cefc02cb2ef58d6ff6777b573d97e7074da3efd..1c3516abf9af96e3cf3f4d5ba03e9063052b52a8 100644 --- a/crates/engine/src/shaders/archive_fx.wgsl +++ b/crates/engine/src/shaders/archive_fx.wgsl @@ -123,13 +123,20 @@ fn dent_op(@builtin(global_invocation_id) gid: vec3) { // p[4] = (h22, mapping_type: 0=Linear / 1=Perspective, blend, has_mask) // p[5] = (mask_invert, multiply_by_mask, clip_orig_to_roi, 0) // p[6] = (roi_x0, roi_y0, roi_x1, roi_y1) corner bounding box in Fusion UV +// p[7] = (dod_origin_x, dod_origin_y, canvas_w, canvas_h) when the output extends past the canvas +// p[8] = same for src_a when it carries a DoD @compute @workgroup_size(8, 8) fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3) { let dims = textureDimensions(dst_tex); if (gid.x >= dims.x || gid.y >= dims.y) { return; } - let fu = pix_to_fu(gid.xy, dims); + let has_dod = u.p[7].z > 0.5; + let canvas = select(vec2(dims), u.p[7].zw, has_dod); + let canvas_px = vec2(gid.xy) + select(vec2(0), vec2(u.p[7].xy), has_dod); + let fu = vec2((f32(canvas_px.x) + 0.5) / canvas.x, 1.0 - (f32(canvas_px.y) + 0.5) / canvas.y); let in_roi = all(fu >= u.p[6].xy) && all(fu <= u.p[6].zw); - let orig = select(textureLoad(src_a, vec2(gid.xy), 0), vec4(0.0), u.p[5].z > 0.5 && !in_roi); + let src_px = canvas_px - select(vec2(0), vec2(u.p[8].xy), u.p[8].z > 0.5); + let in_src = all(src_px >= vec2(0)) && all(src_px < vec2(textureDimensions(src_a))); + let orig = select(vec4(0.0), textureLoad(src_a, src_px, 0), in_src && !(u.p[5].z > 0.5 && !in_roi)); var s_fu: vec2; var valid = true; @@ -154,8 +161,8 @@ fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3) { } var warped = vec4(0.0); - if (valid && s_fu.x >= 0.0 && s_fu.x <= 1.0 && s_fu.y >= 0.0 && s_fu.y <= 1.0) { - warped = sample_edges(src_a, s_fu, 0); + if (valid) { + warped = sample_dod_edges(src_a, s_fu, 0, u.p[8]); } store_dst(vec2(gid.xy), mask_mix(orig, warped, read_mask(gid.xy, dims, u.p[4].w, u.p[5].x), u.p[4].z, u.p[5].y > 0.5)); diff --git a/crates/engine/src/shaders/keyers_gen.wgsl b/crates/engine/src/shaders/keyers_gen.wgsl index 7c7ea3274cedfdba2f26b6451c9aed65f5d27d9a..d9fd14f0805196749eadaaf28483d2b6615f6dc9 100644 --- a/crates/engine/src/shaders/keyers_gen.wgsl +++ b/crates/engine/src/shaders/keyers_gen.wgsl @@ -127,7 +127,7 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { var amp = 1.0; var freq = 1.0; for (var i = 0; i < octaves; i = i + 1) { - let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4); + let weight = amp * clamp(detail - f32(i), 0.0, 1.0); let off = OCTAVE_OFFSET * f32(i); let n = simplex3d(vec3(p * freq + off, seethe * freq + off)); sum = sum + weight * select(n, 2.0 * abs(n), disc); diff --git a/crates/engine/src/shaders/transform.wgsl b/crates/engine/src/shaders/transform.wgsl index 7f1eb4ef9c1a0d24999afd85261d16837fd2f188..b7f4700ea6854170b97aa949cd7f81eb29171ade 100644 --- a/crates/engine/src/shaders/transform.wgsl +++ b/crates/engine/src/shaders/transform.wgsl @@ -76,7 +76,7 @@ fn mask_mix(orig: vec4, warped: vec4, raw_mask: f32, blend: f32, mbm: // p[1] = (y_off, ref_strength, blend, has_mask) // p[2] = (mask_invert, spread, light_power, offset) // p[3] = (center.x, center.y, x_channel, y_channel) -// p[4] = (light_angle, light_channel, multiply_by_mask, 0) +// p[4] = (light_dir_px.x, light_dir_px.y (down), multiply_by_mask, light_channel: 0 = per channel, 1..5 = R G B A Luma) // ============================================================================ fn pick_channel(c: vec4, ch: i32) -> f32 { switch ch { @@ -133,22 +133,32 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3) { warped = sample_edges(src_a, fu + base_disp, 2); } - if (abs(light_power) > 1e-4) { - let light_angle = u.p[4].x; - let light_ch = i32(u.p[4].y + 0.5); - // Fusion Displace radial LightPower adds directional slope lighting from Foreground - // along LightAngle (default 0 deg -> diagonal (+1, +1) in UV y-down, per-channel RGB by default). - let dir_uv = vec2(cos(light_angle), -sin(light_angle)) * 1.41421356 / fdims; - let s_pos = textureSampleLevel(src_b, samp_lin, clamp(uv + dir_uv, vec2(0.0), vec2(1.0)), 0.0); - let s_neg = textureSampleLevel(src_b, samp_lin, clamp(uv - dir_uv, vec2(0.0), vec2(1.0)), 0.0); - var delta_rgb: vec3; - if (light_ch >= 0 && light_ch <= 4) { - let d = pick_channel(s_pos, light_ch) - pick_channel(s_neg, light_ch); - delta_rgb = vec3(d, d, d); - } else { - delta_rgb = s_pos.rgb - s_neg.rgb; + if (light_power > 1e-4) { + // Slope lighting: the Foreground gradient along the light direction (one-pixel taps at the + // undisplaced position), softened by a Gaussian whose width grows with Spread, added + // unclamped to every channel including alpha. + let light_ch = i32(u.p[4].w + 0.5); + let sigma = select(0.0, 0.3 + spread * fdims.x / 240.0, spread > 1e-4); + let radius = i32(min(ceil(3.0 * sigma), 24.0)); + let inv_two_var = 0.5 / max(sigma * sigma, 1e-6); + var delta = vec4(0.0); + var wsum = 0.0; + for (var dy = -radius; dy <= radius; dy = dy + 1) { + for (var dx = -radius; dx <= radius; dx = dx + 1) { + let w = exp(-f32(dx * dx + dy * dy) * inv_two_var); + let at = uv + vec2(f32(dx), f32(dy)) / fdims; + let s_pos = textureSampleLevel(src_b, samp_lin, clamp(at + u.p[4].xy / fdims, vec2(0.0), vec2(1.0)), 0.0); + let s_neg = textureSampleLevel(src_b, samp_lin, clamp(at - u.p[4].xy / fdims, vec2(0.0), vec2(1.0)), 0.0); + var d = s_pos - s_neg; + if (light_ch >= 1 && light_ch <= 5) { + d = vec4(pick_channel(s_pos, light_ch - 1) - pick_channel(s_neg, light_ch - 1)); + } + delta = delta + d * w; + wsum = wsum + w; + } } - warped = vec4(max(warped.rgb + delta_rgb * light_power, vec3(0.0)), warped.a); + delta = delta / wsum; + warped = warped + delta * light_power; } } @@ -157,6 +167,7 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3) { // ============================================================================ // 14. Crop / Scale / Copy // p[0] = (x_off_norm, y_off_norm, x_scale, y_scale) +// p[1] = (dod_origin_x, dod_origin_y, canvas_w, canvas_h) when src_a carries a DoD // ============================================================================ @compute @workgroup_size(8, 8) fn crop_op(@builtin(global_invocation_id) gid: vec3) { @@ -164,13 +175,16 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3) { if (gid.x >= dims.x || gid.y >= dims.y) { return; } let src_dims = vec2(textureDimensions(src_a)); let dst_dims = vec2(dims); + let has_dod = u.p[1].z > 0.5; + let canvas = select(src_dims, u.p[1].zw, has_dod); + let origin = select(vec2(0.0), u.p[1].xy, has_dod); let x_off = u.p[0].x; let y_off = u.p[0].y; - // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from bottom-left (x_off, y_off) + // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from the canvas bottom-left (x_off, y_off) let dst_y_up = dst_dims.y - 1.0 - f32(gid.y); - let src_x = f32(gid.x) + x_off; + let src_x = f32(gid.x) + x_off - origin.x; let src_y_up = dst_y_up + y_off; - let src_y = src_dims.y - 1.0 - src_y_up; + let src_y = canvas.y - 1.0 - src_y_up - origin.y; if (src_x < 0.0 || src_x >= src_dims.x || src_y < 0.0 || src_y >= src_dims.y) { textureStore(dst_tex, vec2(gid.xy), vec4(0.0)); return; -- 2.54.1