authoravatarclover caruso<git@paperclover.net>2026-12-01 01:21:40-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 02:52:53-08:00
logf490606bd49320b6f40453f6edbc43fa9d4dd284
treeae4a7634534ca9412f65791104eb8657906b289f
parent0529b1dbabeac2c671a6d7a085041221c61b42b9
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

8 files changed, 416 insertions(+), 108 deletions(-)

crates/engine/src/eval/io.rs+49-39
...@@ -688,8 +688,8 @@ impl Engine {...@@ -688,8 +688,8 @@ impl Engine {
688 let dst_size = self.scaled_dims(x_size, y_size);688 let dst_size = self.scaled_dims(x_size, y_size);
689 let (x_off, y_off) = if keep_centered {689 let (x_off, y_off) = if keep_centered {
690 (690 (
691 (src.size[0] as f32 - dst_size[0] as f32) * 0.5,691 (src.canvas_size[0] as f32 - dst_size[0] as f32) * 0.5,
692 (src.size[1] as f32 - dst_size[1] as f32) * 0.5,692 (src.canvas_size[1] as f32 - dst_size[1] as f32) * 0.5,
693 )693 )
694 } else {694 } else {
695 (695 (
...@@ -700,7 +700,10 @@ impl Engine {...@@ -700,7 +700,10 @@ impl Engine {
700700
701 let mut u = UniformParams::default();701 let mut u = UniformParams::default();
702 u.p[0] = [x_off, y_off, 1.0, 1.0];702 u.p[0] = [x_off, y_off, 1.0, 1.0];
703 let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1]));703 if src.has_dod() {
704 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];
705 }
706 let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..2]));
704 if let Some(hit) = self.cache.get(key, node.id, frame_i) {707 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
705 stats.cache_hits += 1;708 stats.cache_hits += 1;
706 return hit;709 return hit;
...@@ -746,8 +749,8 @@ impl Engine {...@@ -746,8 +749,8 @@ impl Engine {
746 let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32;749 let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32;
747 let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32;750 let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32;
748 let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32;751 let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32;
749 let seethe = comp.eval_number(node, "Seethe", time, 0.0, &self.expr) as f32752 let seethe = (comp.eval_number(node, "Seethe", time, 0.0, &self.expr)
750 + (comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) as f32) * (time as f32) * 0.02;753 + comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) * time * 0.1) as f32;
751 let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32;754 let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32;
752 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);755 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
753 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();756 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
...@@ -768,30 +771,7 @@ impl Engine {...@@ -768,30 +771,7 @@ impl Engine {
768 let noise_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as i32;771 let noise_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as i32;
769 let grad = if noise_type == 1 { comp.eval_gradient(node, "Gradient", time) } else { None };772 let grad = if noise_type == 1 { comp.eval_gradient(node, "Gradient", time) } else { None };
770773
771 // Bake high-precision 256x1 RGBA gradient LUT so sharp thresholds (e.g. 0.95..0.96 stars) are exact!774 let dst_depth = self.node_depth(comp, node, time, None);
772 let mut grad_bytes = [0u8; 256 * 4];
773 for i in 0..256 {
774 let t = i as f64 / 255.0;
775 let c = if let Some(g) = &grad {
776 g.sample(t)
777 } else {
778 let tf = t as f32;
779 [
780 c1[0] + (c2[0] - c1[0]) * tf,
781 c1[1] + (c2[1] - c1[1]) * tf,
782 c1[2] + (c2[2] - c1[2]) * tf,
783 c1[3] + (c2[3] - c1[3]) * tf,
784 ]
785 };
786 grad_bytes[i * 4] = (c[0].clamp(0.0, 1.0) * 255.0).round() as u8;
787 grad_bytes[i * 4 + 1] = (c[1].clamp(0.0, 1.0) * 255.0).round() as u8;
788 grad_bytes[i * 4 + 2] = (c[2].clamp(0.0, 1.0) * 255.0).round() as u8;
789 grad_bytes[i * 4 + 3] = (c[3].clamp(0.0, 1.0) * 255.0).round() as u8;
790 }
791 let mut gh = DefaultHasher::new();
792 grad_bytes.hash(&mut gh);
793 let grad_hash = gh.finish();
794
795 let mut u = UniformParams::default();775 let mut u = UniformParams::default();
796 u.p[0] = [x_scale, y_scale, detail, contrast];776 u.p[0] = [x_scale, y_scale, detail, contrast];
797 u.p[1] = [brightness, seethe, disc, center[0] as f32];777 u.p[1] = [brightness, seethe, disc, center[0] as f32];
...@@ -799,23 +779,43 @@ impl Engine {...@@ -799,23 +779,43 @@ impl Engine {
799 u.p[3] = c1;779 u.p[3] = c1;
800 u.p[4] = c2;780 u.p[4] = c2;
801781
802 let key = self.make_key(node, "FastNoise", size, &[grad_hash], bytemuck::cast_slice(&u.p[..5]));782 // Gradient mode only: 256x1 RGBA LUT so sharp thresholds (e.g. 0.95..0.96 stars) stay exact.
783 let lut = (noise_type == 1).then(|| {
784 let mut bytes = [0u8; 256 * 4];
785 for (i, texel) in bytes.chunks_exact_mut(4).enumerate() {
786 let t = i as f64 / 255.0;
787 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));
788 for (b, v) in texel.iter_mut().zip(c) {
789 *b = (v.clamp(0.0, 1.0) * 255.0).round() as u8;
790 }
791 }
792 let mut gh = DefaultHasher::new();
793 bytes.hash(&mut gh);
794 (bytes, gh.finish())
795 });
796 let grad_hash = lut.as_ref().map_or(0, |l| l.1);
797
798 let key = self.make_key(node, "FastNoise", size, &[grad_hash, dst_depth as u64], bytemuck::cast_slice(&u.p[..5]));
803 if let Some(hit) = self.cache.get(key, node.id, frame_i) {799 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
804 stats.cache_hits += 1;800 stats.cache_hits += 1;
805 return hit;801 return hit;
806 }802 }
807 stats.cache_misses += 1;803 stats.cache_misses += 1;
808 stats.nodes_evaluated += 1;804 stats.nodes_evaluated += 1;
809 let lut_tex = create_texture(&self.device, [256, 1], 0);805 let lut_tex = lut.map(|(bytes, _)| {
810 self.queue.write_texture(806 let tex = create_texture(&self.device, [256, 1], 0);
811 lut_tex.texture.as_image_copy(),807 self.queue.write_texture(
812 &grad_bytes,808 tex.texture.as_image_copy(),
813 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },809 &bytes,
814 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },810 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
815 );811 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
816 let mut dst = self.alloc_tex(size, self.node_depth(comp, node, time, None), key);812 );
813 tex
814 });
815 let mut dst = self.alloc_tex(size, dst_depth, key);
817 dst.tex_scale *= tex_scale;816 dst.tex_scale *= tex_scale;
818 self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, &lut_tex.view, &self.dummy.view, &dst, &u);817 let lut_view = lut_tex.as_ref().map_or(&self.dummy.view, |t| &t.view);
818 self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, lut_view, &self.dummy.view, &dst, &u);
819 self.cache.insert(key, dst.clone(), node.id, frame_i);819 self.cache.insert(key, dst.clone(), node.id, frame_i);
820 dst820 dst
821 }821 }
...@@ -1537,6 +1537,16 @@ Composition {{...@@ -1537,6 +1537,16 @@ Composition {{
1537 }1537 }
1538 }1538 }
15391539
1540 #[test]
1541 fn fast_noise_detail_weight_is_continuous_above_integers() {
1542 let render = |detail: &str| {
1543 render_generator("FastNoise", 64, 64, &format!("Detail = Input {{ Value = {detail}, }}, XScale = Input {{ Value = 8, }},"))
1544 };
1545 let (Some(a), Some(b)) = (render("2"), render("2.00005")) else { return };
1546 let worst = a.iter().zip(&b).map(|(x, y)| (x[0] - y[0]).abs()).fold(0.0f32, f32::max);
1547 assert!(worst <= 1.5 / 255.0, "Detail 2 -> 2.00005 jumped by {worst}");
1548 }
1549
1540 #[test]1550 #[test]
1541 fn fast_noise_two_color_extrapolates_unclamped_highlights() {1551 fn fast_noise_two_color_extrapolates_unclamped_highlights() {
1542 // High Contrast + Discontinuous pushes `val > 1.0`, so Two-Color mode must extrapolate1552 // High Contrast + Discontinuous pushes `val > 1.0`, so Two-Color mode must extrapolate
crates/engine/src/eval/output_cache.rs+51-10
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1//! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting.1//! Bounded LRU cache for recent final evaluation outputs and VRAM budget accounting.
22
3use std::collections::VecDeque;3use std::collections::{HashMap, VecDeque};
4use std::collections::hash_map::DefaultHasher;4use std::collections::hash_map::DefaultHasher;
5use std::hash::{Hash, Hasher};5use std::hash::{Hash, Hasher};
6use std::sync::Arc;6use std::sync::Arc;
...@@ -44,20 +44,33 @@ impl OutputCache {...@@ -44,20 +44,33 @@ impl OutputCache {
44 }44 }
45 }45 }
4646
47 /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`).47 /// Per distinct texture: `(bytes, entries referencing it, Arc::strong_count)`.
48 fn textures(&self) -> HashMap<*const wgpu::Texture, (u64, usize, usize)> {
49 let mut by_ptr = HashMap::new();
50 for (_, tex, _) in &self.entries {
51 let slot = by_ptr
52 .entry(Arc::as_ptr(&tex.texture))
53 .or_insert((tex.bytes, 0, Arc::strong_count(&tex.texture)));
54 slot.1 += 1;
55 }
56 by_ptr
57 }
58
59 /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`),
60 /// counting a texture once however many entries point at it.
48 pub(super) fn total_bytes(&self) -> u64 {61 pub(super) fn total_bytes(&self) -> u64 {
49 self.entries.iter().map(|(_, tex, _)| tex.bytes).sum()62 self.textures().values().map(|&(bytes, _, _)| bytes).sum()
50 }63 }
5164
52 /// GPU bytes held *exclusively* by `output_cache` (`Arc::strong_count(&tex.texture) == 1`).65 /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here.
53 ///66 ///
54 /// Textures still resident in `NodeCache` have `strong_count >= 2` and are already counted in67 /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry
55 /// `NodeCache::total_vram_bytes()`, so skipping them prevents double-counting against the VRAM budget.68 /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget.
56 pub(super) fn unshared_bytes(&self) -> u64 {69 pub(super) fn unshared_bytes(&self) -> u64 {
57 self.entries70 self.textures()
58 .iter()71 .values()
59 .filter(|(_, tex, _)| Arc::strong_count(&tex.texture) == 1)72 .filter(|&&(_, entries, strong)| entries == strong)
60 .map(|(_, tex, _)| tex.bytes)73 .map(|&(bytes, _, _)| bytes)
61 .sum()74 .sum()
62 }75 }
6376
...@@ -173,3 +186,31 @@ impl Engine {...@@ -173,3 +186,31 @@ impl Engine {
173 self.sync_node_cache_budget();186 self.sync_node_cache_budget();
174 }187 }
175}188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use model::BitDepth;
194
195 #[test]
196 fn duplicate_arcs_count_once_and_caller_clones_count_as_shared() {
197 let eng = Engine::new_headless().expect("gpu");
198 let tex = eng.alloc_tex([64, 64], BitDepth::Int8, 1);
199 let other = eng.alloc_tex([32, 32], BitDepth::Int8, 2);
200 let (tex_bytes, other_bytes) = (tex.bytes, other.bytes);
201 let mut cache = OutputCache::new();
202 let cap = u64::MAX;
203 cache.insert(1, tex.clone(), vec![], CacheMode::Enabled, cap);
204 cache.insert(2, tex.clone(), vec![], CacheMode::Enabled, cap);
205 cache.insert(3, other.clone(), vec![], CacheMode::Enabled, cap);
206 assert_eq!(cache.len(), 3);
207 assert_eq!(cache.total_bytes(), tex_bytes + other_bytes);
208
209 // The test's own clones stand in for `NodeCache` entries or in-flight callers.
210 assert_eq!(cache.unshared_bytes(), 0);
211 drop(other);
212 assert_eq!(cache.unshared_bytes(), other_bytes);
213 drop(tex);
214 assert_eq!(cache.unshared_bytes(), tex_bytes + other_bytes);
215 }
216}
crates/engine/src/eval/transform.rs+149-22
...@@ -1,5 +1,21 @@...@@ -1,5 +1,21 @@
1use super::*;1use super::*;
22
3/// Follows bypassed nodes and routers upstream to the node that actually produces the image.
4pub(super) fn unwrap_passthrough(comp: &Comp, start_id: NodeId) -> NodeId {
5 let mut cur = start_id;
6 for _ in 0..24 {
7 let n = comp.node(cur);
8 if !(n.bypassed || matches!(n.kind.as_str(), "PipeRouter" | "Fuse.Wireless")) {
9 break;
10 }
11 match n.connected_node(default_main_input_port(&n.kind)).and_then(|s| comp.find_node(s)) {
12 Some(next) => cur = next,
13 None => break,
14 }
15 }
16 cur
17}
18
3/// Returns `true` if `start_id` traces back through point/passthrough ops to a `Background` generator19/// Returns `true` if `start_id` traces back through point/passthrough ops to a `Background` generator
4/// (whose Fusion RoI extends uniformly beyond the canvas boundary).20/// (whose Fusion RoI extends uniformly beyond the canvas boundary).
5fn is_background_chain(comp: &Comp, start_id: NodeId, depth: usize) -> bool {21fn is_background_chain(comp: &Comp, start_id: NodeId, depth: usize) -> bool {
...@@ -189,7 +205,9 @@ fn compute_transform_source_roi(...@@ -189,7 +205,9 @@ fn compute_transform_source_roi(
189 ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32])205 ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32])
190}206}
191207
192fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool {208/// A downstream DoD reader (`Transform`, `DVE`, `CornerPositioner`, `PerspectivePositioner`, `Crop`) that cannot
209/// expand itself still consumes the DoD safely, so the walk stops there instead of following its output.
210pub(super) fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool {
193 let mut queue = vec![start_name];211 let mut queue = vec![start_name];
194 let mut seen = HashSet::new();212 let mut seen = HashSet::new();
195 let mut feeds_dod_reader = false;213 let mut feeds_dod_reader = false;
...@@ -215,10 +233,9 @@ fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool {...@@ -215,10 +233,9 @@ fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool {
215 }233 }
216 queue.push(n.name.as_str());234 queue.push(n.name.as_str());
217 }235 }
218 "Transform" | "DVE" | "CornerPositioner" => {236 "Transform" | "DVE" | "CornerPositioner" | "PerspectivePositioner" | "Crop" => {
219 if port == "Input" {237 if port == "Input" {
220 feeds_dod_reader = true;238 feeds_dod_reader = true;
221 queue.push(n.name.as_str());
222 } else {239 } else {
223 return false;240 return false;
224 }241 }
...@@ -307,21 +324,35 @@ fn compute_transform_dst_dod(...@@ -307,21 +324,35 @@ fn compute_transform_dst_dod(
307 min_y = min_y.min(src.origin[1] as f32);324 min_y = min_y.min(src.origin[1] as f32);
308 max_y = max_y.max((src.origin[1] + src.size[1] as i32) as f32);325 max_y = max_y.max((src.origin[1] + src.size[1] as i32) as f32);
309326
327 dod_from_px_bounds(min_x, max_x, min_y, max_y, src.canvas_size, max_dim)
328}
329
330/// Integer DoD rectangle covering the canvas plus pixel bounds `[min, max]` (canvas pixels, y down),
331/// padded for filtering, clamped to +-2048 px beyond the canvas and `max_dim` across.
332pub(super) fn dod_from_px_bounds(
333 min_x: f32,
334 max_x: f32,
335 min_y: f32,
336 max_y: f32,
337 canvas_size: [u32; 2],
338 max_dim: u32,
339) -> ([i32; 2], [u32; 2]) {
340 let (cw, ch) = (canvas_size[0].max(1) as f32, canvas_size[1].max(1) as f32);
310 let pad = 2_i32;341 let pad = 2_i32;
311 let max_pad = 2048_i32;342 let max_pad = 2048_i32;
312 let mut x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 };343 let mut x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 };
313 let mut y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 };344 let mut y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 };
314 let mut x1 = if max_x > cw + 0.25 {345 let mut x1 = if max_x > cw + 0.25 {
315 (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad)346 (max_x.ceil() as i32 + pad).min(canvas_size[0] as i32 + max_pad)
316 } else {347 } else {
317 src.canvas_size[0] as i32348 canvas_size[0] as i32
318 };349 };
319 let mut y1 = if max_y > ch + 0.25 {350 let mut y1 = if max_y > ch + 0.25 {
320 (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad)351 (max_y.ceil() as i32 + pad).min(canvas_size[1] as i32 + max_pad)
321 } else {352 } else {
322 src.canvas_size[1] as i32353 canvas_size[1] as i32
323 };354 };
324 let cap = max_dim.max(src.canvas_size[0]).max(src.canvas_size[1]) as i32;355 let cap = max_dim.max(canvas_size[0]).max(canvas_size[1]) as i32;
325 if x1 - x0 > cap {356 if x1 - x0 > cap {
326 let excess = (x1 - x0) - cap;357 let excess = (x1 - x0) - cap;
327 let trim_l = (0 - x0).max(0).min(excess);358 let trim_l = (0 - x0).max(0).min(excess);
...@@ -812,6 +843,12 @@ impl Engine {...@@ -812,6 +843,12 @@ impl Engine {
812 dst843 dst
813 }844 }
814845
846 /// `MultiplyByMask` zeroes outside the EffectMask even when the effect itself is an identity.
847 pub(super) fn multiplies_by_mask(&self, comp: &Comp, node: &Node, time: f64) -> bool {
848 node.connected_node("EffectMask").is_some()
849 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5
850 }
851
815 pub(super) fn eval_displace(852 pub(super) fn eval_displace(
816 &mut self,853 &mut self,
817 comp: &Comp,854 comp: &Comp,
...@@ -826,28 +863,42 @@ impl Engine {...@@ -826,28 +863,42 @@ impl Engine {
826 return self.dummy.clone();863 return self.dummy.clone();
827 };864 };
828 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);865 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
829 let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else {866 let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s));
867 if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) {
830 return src;868 return src;
831 };869 }
832 let src = self.crop_to_canvas(enc, src);870 let src = self.crop_to_canvas(enc, src);
833 let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats);871 let fg = match fg_id {
834 let fg = self.crop_to_canvas(enc, fg);872 Some(id) => {
873 let fg = self.eval_node(comp, id, time, enc, visiting, stats);
874 self.crop_to_canvas(enc, fg)
875 }
876 None => self.dummy.clone(),
877 };
835 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);878 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
836 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);879 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
837 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;880 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
838881
839 let kind = comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32;882 // Without a map Displace is an identity warp; only MultiplyByMask still applies.
840 let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32;883 let mapped = if fg_id.is_some() { 1.0 } else { 0.0 };
841 let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32;884 let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 };
885 let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped;
886 let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped;
842 let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32;887 let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32;
843 let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32;888 let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32;
844 let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32;889 let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32;
845 let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32;890 let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32;
846 let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32;891 let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped;
847 let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32;892 let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped;
848 let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr) as f32;893 let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped;
849 let light_angle_rad = (comp.eval_number(node, "LightAngle", time, 0.0, &self.expr) as f32 - 45.0).to_radians();894 // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus.
850 let light_channel = comp.eval_number(node, "LightChannel", time, 5.0, &self.expr) as f32;895 let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr);
896 let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs();
897 let light_dir = [
898 ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32,
899 ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32,
900 ];
901 let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32;
851 let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32;902 let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32;
852 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);903 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
853 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;904 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
...@@ -857,7 +908,7 @@ impl Engine {...@@ -857,7 +908,7 @@ impl Engine {
857 u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }];908 u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }];
858 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset];909 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset];
859 u.p[3] = [center[0] as f32, center[1] as f32, xch, ych];910 u.p[3] = [center[0] as f32, center[1] as f32, xch, ych];
860 u.p[4] = [light_angle_rad, light_channel, if mbm { 1.0 } else { 0.0 }, 0.0];911 u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel];
861912
862 let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));913 let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
863 if let Some(hit) = self.cache.get(key, node.id, frame_i) {914 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
...@@ -890,7 +941,7 @@ impl Engine {...@@ -890,7 +941,7 @@ impl Engine {
890 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);941 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
891 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;942 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
892 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;943 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
893 if blend <= 1e-6 || angle_deg.abs() <= 1e-5 {944 if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) {
894 return src;945 return src;
895 }946 }
896 let src = self.crop_to_canvas(enc, src);947 let src = self.crop_to_canvas(enc, src);
...@@ -1754,6 +1805,82 @@ mod tests {...@@ -1754,6 +1805,82 @@ mod tests {
1754 assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept");1805 assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept");
1755 }1806 }
17561807
1808 #[test]
1809 fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() {
1810 // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask.
1811 let cases = [
1812 ("Drip", "Amplitude = Input { Value = 0, },", false),
1813 ("Dent", "Strength = Input { Value = 0, },", false),
1814 ("Vortex", "Angle = Input { Value = 0, },", false),
1815 ("Displace", "", false),
1816 ("Drip", "Blend = Input { Value = 0, },", true),
1817 ("Vortex", "Blend = Input { Value = 0, },", true),
1818 ];
1819 if Engine::new_headless().is_err() {
1820 return;
1821 }
1822 for (kind, inputs, survives) in cases {
1823 let src = format!(
1824 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
1825 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
1826 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
1827 Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }},
1828 MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
1829 FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs}
1830 Input = Input {{ SourceOp = "BG", Source = "Output", }},
1831 EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }},
1832 }} }}"#
1833 );
1834 let comp = Comp::from_fusion_str(&src).unwrap();
1835 let mut eng = Engine::new_headless().unwrap();
1836 let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0);
1837 let rgba = eng.readback_rgba(&tex).unwrap();
1838 let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3];
1839 assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask");
1840 assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask");
1841 }
1842 }
1843
1844 #[test]
1845 fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() {
1846 // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond
1847 // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped.
1848 let lit = |inputs: &str| -> [u8; 4] {
1849 let src = format!(
1850 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
1851 Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
1852 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
1853 TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
1854 TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
1855 Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
1856 TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
1857 D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs}
1858 Input = Input {{ SourceOp = "Flat", Source = "Output", }},
1859 Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }},
1860 }} }}"#
1861 );
1862 let comp = Comp::from_fusion_str(&src).unwrap();
1863 let mut eng = Engine::new_headless().unwrap();
1864 let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0);
1865 let rgba = eng.readback_rgba(&tex).unwrap();
1866 let i = (32 * 64 + 32) * 4;
1867 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1868 };
1869 if Engine::new_headless().is_err() {
1870 return;
1871 }
1872 let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}");
1873 // Ramp slope per tap pair is 2/63 of full scale = ~8 levels.
1874 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8);
1875 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8);
1876 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128);
1877 // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively.
1878 near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8);
1879 // LightChannel 4 lights every channel from alpha, which is flat.
1880 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128);
1881 near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128);
1882 }
1883
1757 #[test]1884 #[test]
1758 fn transform_invert_transform_shifts_the_opposite_way() {1885 fn transform_invert_transform_shifts_the_opposite_way() {
1759 let src = |invert: u8| {1886 let src = |invert: u8| {
crates/engine/src/eval/warps.rs+110-8
...@@ -1,5 +1,6 @@...@@ -1,5 +1,6 @@
1//! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`).1//! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`).
22
3use super::transform::{dod_from_px_bounds, transform_should_expand_dod, unwrap_passthrough};
3use super::*;4use super::*;
45
5impl Engine {6impl Engine {
...@@ -20,7 +21,7 @@ impl Engine {...@@ -20,7 +21,7 @@ impl Engine {
20 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);21 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
21 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;22 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
22 let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32;23 let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32;
23 if blend <= 1e-6 || amp.abs() <= 1e-7 {24 if blend <= 1e-6 || (amp.abs() <= 1e-7 && !self.multiplies_by_mask(comp, node, time)) {
24 return src;25 return src;
25 }26 }
26 let src = self.crop_to_canvas(enc, src);27 let src = self.crop_to_canvas(enc, src);
...@@ -77,7 +78,7 @@ impl Engine {...@@ -77,7 +78,7 @@ impl Engine {
77 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);78 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
78 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;79 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
79 let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32;80 let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32;
80 if blend <= 1e-6 || strength.abs() <= 1e-6 {81 if blend <= 1e-6 || (strength.abs() <= 1e-6 && !self.multiplies_by_mask(comp, node, time)) {
81 return src;82 return src;
82 }83 }
83 let src = self.crop_to_canvas(enc, src);84 let src = self.crop_to_canvas(enc, src);
...@@ -132,14 +133,13 @@ impl Engine {...@@ -132,14 +133,13 @@ impl Engine {
132 if blend <= 1e-6 {133 if blend <= 1e-6 {
133 return src;134 return src;
134 }135 }
135 let src = self.crop_to_canvas(enc, src);
136 let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr);136 let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr);
137 let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr);137 let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr);
138 let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr);138 let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr);
139 let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr);139 let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr);
140 let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32;140 let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32;
141 let h_fwd = quad_forward_homography(bl, br, tr, tl);141 let h_fwd = quad_forward_homography(bl, br, tr, tl);
142 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);142 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
143 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);143 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
144 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;144 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
145145
...@@ -158,7 +158,8 @@ impl Engine {...@@ -158,7 +158,8 @@ impl Engine {
158 // Fusion renders computed sources only inside the corner bounding box (unless an EffectMask158 // Fusion renders computed sources only inside the corner bounding box (unless an EffectMask
159 // pulls the whole input), so Blend < 1 fades the rest toward transparent; Loader and sRender159 // pulls the whole input), so Blend < 1 fades the rest toward transparent; Loader and sRender
160 // sources are always complete.160 // sources are always complete.
161 if mask.is_none() && !matches!(comp.node(src_id).kind.as_str(), "Loader" | "MediaIn" | "sRender") {161 let src_kind = comp.node(unwrap_passthrough(comp, src_id)).kind.as_str();
162 if mask.is_none() && !matches!(src_kind, "Loader" | "MediaIn" | "sRender") {
162 let xs = [bl[0], br[0], tr[0], tl[0]];163 let xs = [bl[0], br[0], tr[0], tl[0]];
163 let ys = [bl[1], br[1], tr[1], tl[1]];164 let ys = [bl[1], br[1], tr[1], tl[1]];
164 let (x0, x1) = xs.iter().fold((f64::MAX, f64::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));165 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 {...@@ -167,12 +168,37 @@ impl Engine {
167 u.p[6] = [x0 as f32, y0 as f32, x1 as f32, y1 as f32];168 u.p[6] = [x0 as f32, y0 as f32, x1 as f32, y1 as f32];
168 }169 }
169170
171 // The output extends past the canvas wherever the corner mapping still lands inside the source domain.
172 let canvas = src.canvas_size.map(|v| v.max(1) as f64);
173 let src_rect = [
174 src.origin[0] as f64 / canvas[0],
175 1.0 - (src.origin[1] + src.size[1] as i32) as f64 / canvas[1],
176 (src.origin[0] + src.size[0] as i32) as f64 / canvas[0],
177 1.0 - src.origin[1] as f64 / canvas[1],
178 ];
179 let (dst_origin, dst_size) = match positioner_preimage(mapping_type, [bl, br, tr, tl], h_fwd, src_rect) {
180 Some(fu) if mask.is_none() && transform_should_expand_dod(comp, &node.name) => {
181 let px = fu.map(|[x, y]| [(x * canvas[0]) as f32, ((1.0 - y) * canvas[1]) as f32]);
182 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])));
183 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])));
184 let max_dim = self.device.limits().max_texture_dimension_2d.min(4096);
185 dod_from_px_bounds(min_x, max_x, min_y, max_y, src.canvas_size, max_dim)
186 }
187 _ => ([0, 0], src.canvas_size),
188 };
189 if dst_origin != [0, 0] || dst_size != src.canvas_size {
190 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];
191 }
192 if src.has_dod() {
193 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];
194 }
195
170 let key = self.make_key(196 let key = self.make_key(
171 node,197 node,
172 "PerspectivePositioner",198 "PerspectivePositioner",
173 src.size,199 dst_size,
174 &[src.content_hash, mask_hash],200 &[src.content_hash, mask_hash],
175 bytemuck::cast_slice(&u.p[..7]),201 bytemuck::cast_slice(&u.p[..9]),
176 );202 );
177 if let Some(hit) = self.cache.get(key, node.id, frame_i) {203 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
178 stats.cache_hits += 1;204 stats.cache_hits += 1;
...@@ -180,7 +206,8 @@ impl Engine {...@@ -180,7 +206,8 @@ impl Engine {
180 }206 }
181 stats.cache_misses += 1;207 stats.cache_misses += 1;
182 stats.nodes_evaluated += 1;208 stats.nodes_evaluated += 1;
183 let dst = self.alloc_tex_like(&src, src.depth, key);209 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key);
210 dst.tex_scale = src.tex_scale;
184 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);211 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
185 self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u);212 self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u);
186 self.cache.insert(key, dst.clone(), node.id, frame_i);213 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...@@ -438,6 +465,67 @@ fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2
438 [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]465 [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]
439}466}
440467
468/// Output-space corners (Fusion UV) of `src_rect` (`u0, v0, u1, v1`) pulled back through the corner mapping, or
469/// `None` when the mapping is degenerate or the pullback reaches infinity.
470fn positioner_preimage(mapping_type: i32, quad: [[f64; 2]; 4], h: [f32; 9], src_rect: [f64; 4]) -> Option<[[f64; 2]; 4]> {
471 let [bl, br, tr, tl] = quad;
472 let [u0, v0, u1, v1] = src_rect;
473 let source_corners = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
474 let mut out = [[0.0; 2]; 4];
475 if mapping_type == 1 {
476 let [a, b, c, d, e, f, g, hh, i] = h.map(f64::from);
477 let inv = [
478 [e * i - f * hh, c * hh - b * i, b * f - c * e],
479 [f * g - d * i, a * i - c * g, c * d - a * f],
480 [d * hh - e * g, b * g - a * hh, a * e - b * d],
481 ];
482 let det = a * inv[0][0] + b * inv[1][0] + c * inv[2][0];
483 if det.abs() < 1e-12 {
484 return None;
485 }
486 let mut sign = 0.0_f64;
487 for (o, s) in out.iter_mut().zip(source_corners) {
488 let row = |r: [f64; 3]| (r[0] * s[0] + r[1] * s[1] + r[2]) / det;
489 let w = row(inv[2]);
490 sign = if sign == 0.0 { w.signum() } else { sign };
491 if w.abs() < 1e-9 || w.signum() != sign {
492 return None;
493 }
494 *o = [row(inv[0]) / w, row(inv[1]) / w];
495 }
496 return Some(out);
497 }
498 // Bilinear: s(x, y) = bl + (br - bl) x + (tl - bl) y + (bl - br - tl + tr) x y, solved by Newton.
499 let ex = [br[0] - bl[0], br[1] - bl[1]];
500 let ey = [tl[0] - bl[0], tl[1] - bl[1]];
501 let exy = [bl[0] - br[0] - tl[0] + tr[0], bl[1] - br[1] - tl[1] + tr[1]];
502 for (o, t) in out.iter_mut().zip(source_corners) {
503 let (mut x, mut y) = (0.5, 0.5);
504 let mut converged = false;
505 for _ in 0..64 {
506 let r = [0, 1].map(|k| bl[k] + ex[k] * x + ey[k] * y + exy[k] * x * y - t[k]);
507 let jx = [0, 1].map(|k| ex[k] + exy[k] * y);
508 let jy = [0, 1].map(|k| ey[k] + exy[k] * x);
509 let det = jx[0] * jy[1] - jy[0] * jx[1];
510 if det.abs() < 1e-12 {
511 return None;
512 }
513 let (dx, dy) = ((r[0] * jy[1] - jy[0] * r[1]) / det, (jx[0] * r[1] - r[0] * jx[1]) / det);
514 x -= dx;
515 y -= dy;
516 if dx.abs() + dy.abs() < 1e-10 {
517 converged = true;
518 break;
519 }
520 }
521 if !converged {
522 return None;
523 }
524 *o = [x, y];
525 }
526 Some(out)
527}
528
441fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize {529fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize {
442 if let Some(m) = node.static_str("Month") {530 if let Some(m) = node.static_str("Month") {
443 let low = m.to_ascii_lowercase();531 let low = m.to_ascii_lowercase();
...@@ -630,6 +718,20 @@ fn rasterize_grid_warp_uv_f16(...@@ -630,6 +718,20 @@ fn rasterize_grid_warp_uv_f16(
630#[cfg(test)]718#[cfg(test)]
631mod tests {719mod tests {
632 use super::*;720 use super::*;
721
722 #[test]
723 fn positioner_preimage_of_a_zoomed_quad_spans_twice_the_frame() {
724 // Corners cover the middle half of the source, so the whole source lands at [-0.5, 1.5]^2.
725 let quad = [[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]];
726 let h = quad_forward_homography(quad[0], quad[1], quad[2], quad[3]);
727 for mapping_type in [0, 1] {
728 let corners = positioner_preimage(mapping_type, quad, h, [0.0, 0.0, 1.0, 1.0]).expect("finite pullback");
729 let (lo, hi) = corners.iter().flatten().fold((f64::MAX, f64::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));
730 assert!((lo + 0.5).abs() < 1e-6 && (hi - 1.5).abs() < 1e-6, "type {mapping_type}: {lo}..{hi}");
731 }
732 let flat = [[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [0.0, 0.0]];
733 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());
734 }
633 use crate::Engine;735 use crate::Engine;
634736
635 #[test]737 #[test]
crates/engine/src/media.rs+12-5
...@@ -186,7 +186,7 @@ impl MediaCache {...@@ -186,7 +186,7 @@ impl MediaCache {
186 {186 {
187 let min_f = clip.global_start - clip.extend_first.max(0);187 let min_f = clip.global_start - clip.extend_first.max(0);
188 let max_f = clip.global_end + clip.extend_last.max(0);188 let max_f = clip.global_end + clip.extend_last.max(0);
189 if frame < min_f || frame > max_f {189 if frame < min_f || (!clip.loop_clip && frame > max_f) {
190 return None;190 return None;
191 }191 }
192 }192 }
...@@ -202,7 +202,7 @@ impl MediaCache {...@@ -202,7 +202,7 @@ impl MediaCache {
202 };202 };
203 let span = (trim_out - trim_in + 1).max(1);203 let span = (trim_out - trim_in + 1).max(1);
204 let rel = if clip.loop_clip {204 let rel = if clip.loop_clip {
205 (frame - clip.global_start).rem_euclid(span)205 (frame - clip.global_start).max(0).rem_euclid(span)
206 } else {206 } else {
207 (frame - clip.global_start).clamp(0, span - 1)207 (frame - clip.global_start).clamp(0, span - 1)
208 };208 };
...@@ -741,11 +741,18 @@ mod tests {...@@ -741,11 +741,18 @@ mod tests {
741 loop_clip: true,741 loop_clip: true,
742 reverse: false,742 reverse: false,
743 };743 };
744 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15], rel = -1 -> rem_euclid(6) = 5.744 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0.
745 let (_, local_idx, _, _) = cache745 let (_, local_idx, _, _) = cache
746 .load_clip(&clip, 9, false, [None; 4])746 .load_clip(&clip, 9, false, [None; 4])
747 .expect("loop_clip negative rel inside ExtendFirst should resolve");747 .expect("loop_clip inside ExtendFirst should resolve");
748 assert_eq!(local_idx, 5);748 assert_eq!(local_idx, 0);
749 // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4.
750 let (_, local_idx, _, _) = cache
751 .load_clip(&clip, 20, false, [None; 4])
752 .expect("loop_clip past GlobalEnd should keep looping");
753 assert_eq!(local_idx, 4);
754 let once = ClipSpec { loop_clip: false, ..clip };
755 assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none());
749 }756 }
750 assert!(757 assert!(
751 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,758 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,
crates/engine/src/shaders/archive_fx.wgsl+11-4
...@@ -123,13 +123,20 @@ fn dent_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -123,13 +123,20 @@ fn dent_op(@builtin(global_invocation_id) gid: vec3<u32>) {
123// p[4] = (h22, mapping_type: 0=Linear / 1=Perspective, blend, has_mask)123// p[4] = (h22, mapping_type: 0=Linear / 1=Perspective, blend, has_mask)
124// p[5] = (mask_invert, multiply_by_mask, clip_orig_to_roi, 0)124// p[5] = (mask_invert, multiply_by_mask, clip_orig_to_roi, 0)
125// p[6] = (roi_x0, roi_y0, roi_x1, roi_y1) corner bounding box in Fusion UV125// p[6] = (roi_x0, roi_y0, roi_x1, roi_y1) corner bounding box in Fusion UV
126// p[7] = (dod_origin_x, dod_origin_y, canvas_w, canvas_h) when the output extends past the canvas
127// p[8] = same for src_a when it carries a DoD
126@compute @workgroup_size(8, 8)128@compute @workgroup_size(8, 8)
127fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3<u32>) {129fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3<u32>) {
128 let dims = textureDimensions(dst_tex);130 let dims = textureDimensions(dst_tex);
129 if (gid.x >= dims.x || gid.y >= dims.y) { return; }131 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
130 let fu = pix_to_fu(gid.xy, dims);132 let has_dod = u.p[7].z > 0.5;
133 let canvas = select(vec2<f32>(dims), u.p[7].zw, has_dod);
134 let canvas_px = vec2<i32>(gid.xy) + select(vec2<i32>(0), vec2<i32>(u.p[7].xy), has_dod);
135 let fu = vec2<f32>((f32(canvas_px.x) + 0.5) / canvas.x, 1.0 - (f32(canvas_px.y) + 0.5) / canvas.y);
131 let in_roi = all(fu >= u.p[6].xy) && all(fu <= u.p[6].zw);136 let in_roi = all(fu >= u.p[6].xy) && all(fu <= u.p[6].zw);
132 let orig = select(textureLoad(src_a, vec2<i32>(gid.xy), 0), vec4<f32>(0.0), u.p[5].z > 0.5 && !in_roi);137 let src_px = canvas_px - select(vec2<i32>(0), vec2<i32>(u.p[8].xy), u.p[8].z > 0.5);
138 let in_src = all(src_px >= vec2<i32>(0)) && all(src_px < vec2<i32>(textureDimensions(src_a)));
139 let orig = select(vec4<f32>(0.0), textureLoad(src_a, src_px, 0), in_src && !(u.p[5].z > 0.5 && !in_roi));
133140
134 var s_fu: vec2<f32>;141 var s_fu: vec2<f32>;
135 var valid = true;142 var valid = true;
...@@ -154,8 +161,8 @@ fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -154,8 +161,8 @@ fn perspective_pos_op(@builtin(global_invocation_id) gid: vec3<u32>) {
154 }161 }
155162
156 var warped = vec4<f32>(0.0);163 var warped = vec4<f32>(0.0);
157 if (valid && s_fu.x >= 0.0 && s_fu.x <= 1.0 && s_fu.y >= 0.0 && s_fu.y <= 1.0) {164 if (valid) {
158 warped = sample_edges(src_a, s_fu, 0);165 warped = sample_dod_edges(src_a, s_fu, 0, u.p[8]);
159 }166 }
160167
161 store_dst(vec2<i32>(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));168 store_dst(vec2<i32>(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));
crates/engine/src/shaders/keyers_gen.wgsl+1-1
...@@ -127,7 +127,7 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -127,7 +127,7 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
127 var amp = 1.0;127 var amp = 1.0;
128 var freq = 1.0;128 var freq = 1.0;
129 for (var i = 0; i < octaves; i = i + 1) {129 for (var i = 0; i < octaves; i = i + 1) {
130 let weight = select(amp, amp * fract(detail), i == octaves - 1 && fract(detail) > 1e-4);130 let weight = amp * clamp(detail - f32(i), 0.0, 1.0);
131 let off = OCTAVE_OFFSET * f32(i);131 let off = OCTAVE_OFFSET * f32(i);
132 let n = simplex3d(vec3<f32>(p * freq + off, seethe * freq + off));132 let n = simplex3d(vec3<f32>(p * freq + off, seethe * freq + off));
133 sum = sum + weight * select(n, 2.0 * abs(n), disc);133 sum = sum + weight * select(n, 2.0 * abs(n), disc);
crates/engine/src/shaders/transform.wgsl+33-19
...@@ -76,7 +76,7 @@ fn mask_mix(orig: vec4<f32>, warped: vec4<f32>, raw_mask: f32, blend: f32, mbm:...@@ -76,7 +76,7 @@ fn mask_mix(orig: vec4<f32>, warped: vec4<f32>, raw_mask: f32, blend: f32, mbm:
76// p[1] = (y_off, ref_strength, blend, has_mask)76// p[1] = (y_off, ref_strength, blend, has_mask)
77// p[2] = (mask_invert, spread, light_power, offset)77// p[2] = (mask_invert, spread, light_power, offset)
78// p[3] = (center.x, center.y, x_channel, y_channel)78// p[3] = (center.x, center.y, x_channel, y_channel)
79// p[4] = (light_angle, light_channel, multiply_by_mask, 0)79// 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)
80// ============================================================================80// ============================================================================
81fn pick_channel(c: vec4<f32>, ch: i32) -> f32 {81fn pick_channel(c: vec4<f32>, ch: i32) -> f32 {
82 switch ch {82 switch ch {
...@@ -133,22 +133,32 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -133,22 +133,32 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
133 warped = sample_edges(src_a, fu + base_disp, 2);133 warped = sample_edges(src_a, fu + base_disp, 2);
134 }134 }
135135
136 if (abs(light_power) > 1e-4) {136 if (light_power > 1e-4) {
137 let light_angle = u.p[4].x;137 // Slope lighting: the Foreground gradient along the light direction (one-pixel taps at the
138 let light_ch = i32(u.p[4].y + 0.5);138 // undisplaced position), softened by a Gaussian whose width grows with Spread, added
139 // Fusion Displace radial LightPower adds directional slope lighting from Foreground139 // unclamped to every channel including alpha.
140 // along LightAngle (default 0 deg -> diagonal (+1, +1) in UV y-down, per-channel RGB by default).140 let light_ch = i32(u.p[4].w + 0.5);
141 let dir_uv = vec2<f32>(cos(light_angle), -sin(light_angle)) * 1.41421356 / fdims;141 let sigma = select(0.0, 0.3 + spread * fdims.x / 240.0, spread > 1e-4);
142 let s_pos = textureSampleLevel(src_b, samp_lin, clamp(uv + dir_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);142 let radius = i32(min(ceil(3.0 * sigma), 24.0));
143 let s_neg = textureSampleLevel(src_b, samp_lin, clamp(uv - dir_uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);143 let inv_two_var = 0.5 / max(sigma * sigma, 1e-6);
144 var delta_rgb: vec3<f32>;144 var delta = vec4<f32>(0.0);
145 if (light_ch >= 0 && light_ch <= 4) {145 var wsum = 0.0;
146 let d = pick_channel(s_pos, light_ch) - pick_channel(s_neg, light_ch);146 for (var dy = -radius; dy <= radius; dy = dy + 1) {
147 delta_rgb = vec3<f32>(d, d, d);147 for (var dx = -radius; dx <= radius; dx = dx + 1) {
148 } else {148 let w = exp(-f32(dx * dx + dy * dy) * inv_two_var);
149 delta_rgb = s_pos.rgb - s_neg.rgb;149 let at = uv + vec2<f32>(f32(dx), f32(dy)) / fdims;
150 let s_pos = textureSampleLevel(src_b, samp_lin, clamp(at + u.p[4].xy / fdims, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
151 let s_neg = textureSampleLevel(src_b, samp_lin, clamp(at - u.p[4].xy / fdims, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
152 var d = s_pos - s_neg;
153 if (light_ch >= 1 && light_ch <= 5) {
154 d = vec4<f32>(pick_channel(s_pos, light_ch - 1) - pick_channel(s_neg, light_ch - 1));
155 }
156 delta = delta + d * w;
157 wsum = wsum + w;
158 }
150 }159 }
151 warped = vec4<f32>(max(warped.rgb + delta_rgb * light_power, vec3<f32>(0.0)), warped.a);160 delta = delta / wsum;
161 warped = warped + delta * light_power;
152 }162 }
153 }163 }
154164
...@@ -157,6 +167,7 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -157,6 +167,7 @@ fn displace_op(@builtin(global_invocation_id) gid: vec3<u32>) {
157// ============================================================================167// ============================================================================
158// 14. Crop / Scale / Copy168// 14. Crop / Scale / Copy
159// p[0] = (x_off_norm, y_off_norm, x_scale, y_scale)169// p[0] = (x_off_norm, y_off_norm, x_scale, y_scale)
170// p[1] = (dod_origin_x, dod_origin_y, canvas_w, canvas_h) when src_a carries a DoD
160// ============================================================================171// ============================================================================
161@compute @workgroup_size(8, 8)172@compute @workgroup_size(8, 8)
162fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {173fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {
...@@ -164,13 +175,16 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -164,13 +175,16 @@ fn crop_op(@builtin(global_invocation_id) gid: vec3<u32>) {
164 if (gid.x >= dims.x || gid.y >= dims.y) { return; }175 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
165 let src_dims = vec2<f32>(textureDimensions(src_a));176 let src_dims = vec2<f32>(textureDimensions(src_a));
166 let dst_dims = vec2<f32>(dims);177 let dst_dims = vec2<f32>(dims);
178 let has_dod = u.p[1].z > 0.5;
179 let canvas = select(src_dims, u.p[1].zw, has_dod);
180 let origin = select(vec2<f32>(0.0), u.p[1].xy, has_dod);
167 let x_off = u.p[0].x;181 let x_off = u.p[0].x;
168 let y_off = u.p[0].y;182 let y_off = u.p[0].y;
169 // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from bottom-left (x_off, y_off)183 // In Fusion, Crop (XOffset, YOffset, XSize, YSize) extracts pixels from the canvas bottom-left (x_off, y_off)
170 let dst_y_up = dst_dims.y - 1.0 - f32(gid.y);184 let dst_y_up = dst_dims.y - 1.0 - f32(gid.y);
171 let src_x = f32(gid.x) + x_off;185 let src_x = f32(gid.x) + x_off - origin.x;
172 let src_y_up = dst_y_up + y_off;186 let src_y_up = dst_y_up + y_off;
173 let src_y = src_dims.y - 1.0 - src_y_up;187 let src_y = canvas.y - 1.0 - src_y_up - origin.y;
174 if (src_x < 0.0 || src_x >= src_dims.x || src_y < 0.0 || src_y >= src_dims.y) {188 if (src_x < 0.0 || src_x >= src_dims.x || src_y < 0.0 || src_y >= src_dims.y) {
175 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(0.0));189 textureStore(dst_tex, vec2<i32>(gid.xy), vec4<f32>(0.0));
176 return;190 return;