diff --git a/compatibility.md b/compatibility.md index dceced3e97f9ea7a29a675e376296f353dae0390..ea571eb8299c696fb28acb1ade44e6ca51c80a37 100644 --- a/compatibility.md +++ b/compatibility.md @@ -2,18 +2,18 @@ # Fusion 21.1 Compatibility -Fission currently supports **127** tool types across 2D/3D compositing, all with high accuracy. This document tracks the progress on parity with Blackmagic Fusion Studio. The main metric, **accuracy**, is the inverse of the image's [mean absolute error](https://en.wikipedia.org/wiki/Mean_absolute_error), meaning `100%` accuracy means the pixels are all identical. For details, see [`scripts/fuzz_node.py`](scripts/fuzz_node.py). +Fission currently supports **132** tool types across 2D/3D compositing, all with high accuracy. This document tracks the progress on parity with Blackmagic Fusion Studio. The main metric, **accuracy**, is the inverse of the image's [mean absolute error](https://en.wikipedia.org/wiki/Mean_absolute_error), meaning `100%` accuracy means the pixels are all identical. For details, see [`scripts/fuzz_node.py`](scripts/fuzz_node.py). ## Summary | Metric | Value | | --- | --- | -| **Supported Tools** | **127** | +| **Supported Tools** | **132** | | **Modifiers & Animation** | **8** | | **Accuracy across [paper clover](https://paperclover.net)'s compositions** | **99.5%** | | **Supported Tool Accuracy** | **99.7%** | -| **Supported Tools with 100% Accuracy** | **49** | -| **Coverage of Fusion's Built-in Tools** | **28.3%** | +| **Supported Tools with 100% Accuracy** | **51** | +| **Coverage of Fusion's Built-in Tools** | **29.1%** | | **Coverage of All Fuses on Reactor** | **0.6%** | ## Generators @@ -105,6 +105,7 @@ Fission currently supports **127** tool types across 2D/3D compositing, all with | `BetterResize` | 99.9% | — | | `Crop` | ✅ 100.0% | — | | `SetDomain` | 99.9% | — | +| `Dimension.PlanarTransform` | ✅ 100.0% | Applies projective 3×3 `ToRef` homography splines (`Invert`, `Blend`, `EffectMask`). | ## Masks @@ -190,7 +191,9 @@ Each 3D tool's accuracy is measured by rendering it inside a lit `Merge3D` + `Ca | `Fuse.SwitchElse` | ✅ 100.0% | — | | `PipeRouter` | ✅ 100.0% | — | | `Fuse.Wireless` | ✅ 100.0% | — | -| `Tracker` | ✅ 100.0% | Live optical tracking not implemented; evaluates baked `TrackerModifier` paths. | +| `Tracker` | ✅ 100.0% | Evaluates baked `TrackerModifier` paths; live NCC point & planar homography API in `engine::tracker`. | +| `SurfaceTracker` | 99.5%–99.9% | GPU 2D triangle-mesh warp (`FuTriMesh` + `WarpableCanvas`); live NCC & homography API in `engine::tracker`. | +| `Dimension.PlanarTracker` | ✅ 100.0% | Evaluates `Track` / `CornerPin` / `Steady` / `Stabilize` modes from baked `Matrix` tracks. | | `MacroOperator` | ✅ 100.0% | Internal subgraph is read-only in interactive Flow. | | `GroupOperator` | ✅ 100.0% | Internal subgraph is read-only in interactive Flow. | | `Custom` | 98.2% | — | @@ -216,9 +219,7 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w | Tool Class | Issue | Notes | | --- | --- | --- | -| `SurfaceTracker` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | `MagicMask` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | -| `PlanarTracker` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | --- diff --git a/crates/app/src/add_tool.rs b/crates/app/src/add_tool.rs index ad07305fa0d9af2858016ff72b3c3b9e860d146a..0d37ebaa6b91d642084031f603e99130e57e7ca5 100644 --- a/crates/app/src/add_tool.rs +++ b/crates/app/src/add_tool.rs @@ -186,6 +186,9 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ ToolEntry { kind: "ChangeDepth", display: "Change Depth", aliases: "cd bit depth float", category: ToolCategory::Utility, is_generator: false }, ToolEntry { kind: "SetDomain", display: "Set Domain", aliases: "dod roi", category: ToolCategory::Utility, is_generator: false }, ToolEntry { kind: "Tracker", display: "Tracker", aliases: "tr matchmove", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "SurfaceTracker", display: "Surface Tracker", aliases: "st mesh warp surface matchmove", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Dimension.PlanarTracker", display: "Planar Tracker", aliases: "pt planar track cornerpin steady stabilize", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Dimension.PlanarTransform", display: "Planar Transform", aliases: "pxf planar homography warp matchmove", category: ToolCategory::TransformWarp, is_generator: false }, ToolEntry { kind: "Note", display: "Sticky Note", aliases: "comment note", category: ToolCategory::Utility, is_generator: true }, ToolEntry { kind: "Underlay", display: "Underlay", aliases: "backdrop group", category: ToolCategory::Utility, is_generator: true }, ToolEntry { kind: "Custom", display: "Custom Tool", aliases: "ct shader expression", category: ToolCategory::Utility, is_generator: false }, diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 8180dc5f905bc7995116e60f392b7bb342ea8871..d47aa98023f1d06e7511ebe5391aa8c5d3686918 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -73,6 +73,7 @@ pub struct Engine { supports_f32_filter: bool, scene3d: crate::scene3d::Scene3DRenderer, optflow: std::sync::OnceLock, + tracker: std::sync::OnceLock, particles: crate::particles::ParticleCache, custom_shaders: crate::custom_shader::CustomShaderCache, sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, @@ -176,6 +177,7 @@ impl Engine { supports_f32_filter, scene3d, optflow: std::sync::OnceLock::new(), + tracker: std::sync::OnceLock::new(), particles: crate::particles::ParticleCache::default(), custom_shaders: crate::custom_shader::CustomShaderCache::new(), sprite_cache: HashMap::new(), @@ -826,7 +828,49 @@ impl Engine { "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats), "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats), "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats), - "ErodeDilate" => self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats), + "ErodeDilate" => { + let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats); + if self.multiplies_by_mask(comp, node, time) { + let (mask, mask_inv) = self.eval_mask_input_sized( + comp, + node, + time, + Some(out.canvas_size), + enc, + visiting, + stats, + ); + if let Some(m) = mask { + let out_c = self.crop_to_canvas(enc, out); + let key = self.make_key( + node, + "ErodeDilateMBM", + out_c.size, + &[out_c.content_hash, m.content_hash], + &[if mask_inv { 1.0 } else { 0.0 }], + ); + out = if let Some(hit) = self.cache.get(key, node.id, frame_i) { + hit + } else { + let dst = self.alloc_tex(out_c.size, out_c.depth, key); + let mut u = UniformParams::default(); + u.p[0][0] = if mask_inv { 1.0 } else { 0.0 }; + self.dispatch_op( + enc, + ShaderOp::MaskApply, + &out_c.view, + &self.dummy.view, + &m.view, + &dst, + &u, + ); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + }; + } + } + out + } "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats), "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "DaySky" => self.eval_day_sky(comp, node, time, frame_i, comp_dims, enc, visiting, stats), @@ -877,6 +921,13 @@ impl Engine { | "pBounce" => self.dummy.clone(), "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), + "Dimension.PlanarTransform" | "PlanarTransform" => { + self.eval_planar_transform(comp, node, time, frame_i, enc, visiting, stats) + } + "Dimension.PlanarTracker" | "PlanarTracker" => { + self.eval_planar_tracker(comp, node, time, frame_i, enc, visiting, stats) + } "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), other => { // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, @@ -1041,6 +1092,482 @@ impl Engine { self.eval_node(comp, src_id, remapped, enc, visiting, stats) } + fn parse_surface_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { + let mode_str = node + .static_str("OverlayCompositeMode") + .or_else(|| node.static_str("CompositeMode")) + .or_else(|| node.static_str("ApplyMode")); + if let Some(s) = mode_str { + return match s { + "Screen" => 1.0, + "Multiply" => 2.0, + "Overlay" => 3.0, + "SoftLight" | "Soft Light" => 4.0, + "HardLight" | "Hard Light" => 5.0, + "ColorDodge" | "Color Dodge" => 6.0, + "Darken" => 7.0, + "Lighten" => 8.0, + "Difference" => 9.0, + "Exclusion" => 10.0, + "Add" | "LinearDodge" | "Linear Dodge" => 11.0, + _ => 0.0, + }; + } + let n = comp + .eval_number(node, "OverlayCompositeMode", time, 0.0, expr) + .round() as i32; + match n { + 1 => 1.0, + 2 => 2.0, + 3 => 3.0, + 4 => 4.0, + 5 => 5.0, + _ => 0.0, + } + } + + #[allow(clippy::too_many_arguments)] + fn eval_surface_tracker( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(bg_id) = node + .connected_node("Input") + .or_else(|| node.connected_node("Background")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); + + let stage = comp + .eval_number(node, "ProcessStage", time, 2.0, &self.expr) + .round() as i32; + if stage < 2 { + return bg; + } + + let Some(overlay_id) = node + .connected_node("Overlay") + .or_else(|| node.connected_node("Foreground")) + .and_then(|s| comp.find_node(s)) + else { + return bg; + }; + + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let opacity = comp.eval_number(node, "OverlayOpacity", time, 1.0, &self.expr) as f32; + let eff_blend = (blend * opacity).clamp(0.0, 1.0); + if eff_blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { + return bg; + } + + let explicit_ref = node + .inputs + .contains_key("ReferenceFrame") + .then(|| comp.eval_number(node, "ReferenceFrame", time, 0.0, &self.expr)); + let Some((ref_mesh, cur_mesh, ref_frame)) = + crate::tracker::eval_surface_mesh(comp, node, time, explicit_ref) + else { + return bg; + }; + + let overlay_time = match node.static_str("OverlaySource") { + Some("OverlayFrameRef" | "OverlayFrameReference") => ref_frame, + Some("OverlayFrameCurrent" | "OverlayFrameFirst") => time, + _ => time, + }; + let overlay = self.eval_node(comp, overlay_id, overlay_time, enc, visiting, stats); + let bg = self.crop_to_canvas(enc, bg); + let overlay = self.crop_to_canvas(enc, overlay); + + let placement = comp + .eval_number(node, "OverlayPlacement", time, 1.0, &self.expr) + .round() as i32; + let corners = if placement == 0 { + crate::tracker::extract_warpable_canvas_corners(node) + .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + } else { + crate::tracker::extract_warpable_canvas_corners(node) + .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + }; + let h_inv = crate::tracker::quad_to_unit_homography( + corners[0], + corners[1], + corners[2], + corners[3], + ); + + let photo_strength = if node.inputs.contains_key("LightingWeight") { + comp.eval_number(node, "LightingWeight", time, 0.0, &self.expr) as f32 + } else if node.inputs.contains_key("MatchLighting") { + comp.eval_number(node, "MatchLighting", time, 0.0, &self.expr) as f32 + } else { + 0.0 + } + .clamp(0.0, 1.0); + + let apply_mode = Self::parse_surface_apply_mode(comp, node, time, &self.expr); + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(bg.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 dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(overlay.depth))); + + let ref_hash = ref_mesh.content_hash(); + let cur_hash = cur_mesh.content_hash(); + let params_f32: [f32; 14] = [ + h_inv[0] as f32, + h_inv[1] as f32, + h_inv[2] as f32, + h_inv[3] as f32, + h_inv[4] as f32, + h_inv[5] as f32, + h_inv[6] as f32, + h_inv[7] as f32, + h_inv[8] as f32, + eff_blend, + apply_mode, + photo_strength, + if mask_inv { 1.0 } else { 0.0 }, + if mbm { 1.0 } else { 0.0 }, + ]; + let key = self.make_key( + node, + "SurfaceTracker", + bg.size, + &[bg.content_hash, overlay.content_hash, mask_hash, ref_hash, cur_hash], + ¶ms_f32, + ); + 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; + + // WebGPU safety: render mesh exclusively into Rgba8Unorm or Rgba16Float (never Rgba32Float). + let render_depth = match self.effective_depth(dst_depth) { + BitDepth::Int8 => BitDepth::Int8, + _ => BitDepth::Float16, + }; + let warped = self.alloc_tex(bg.size, render_depth, key ^ 0x57A1_7EAC); + let tracker = self + .tracker + .get_or_init(|| crate::tracker::TrackerPipelines::new(&self.device)); + tracker.render_surface_mesh( + &self.device, + enc, + &overlay.view, + &warped.view, + warped.format, + &ref_mesh, + &cur_mesh, + h_inv, + photo_strength, + ); + + let dst = self.alloc_tex(bg.size, dst_depth, key); + let mut u = UniformParams::default(); + u.p[0] = [0.5, 0.5, 1.0, 0.0]; + u.p[1] = [eff_blend, 1.0, apply_mode, 0.0]; + u.p[2] = [0.0, 0.0, 0.0, 0.0]; + u.p[3] = [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + bg.size[0] as f32, + bg.size[1] as f32, + ]; + u.p[6] = [0.0, 1.0, 0.0, 0.0]; + u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + fn dispatch_planar_homography( + &mut self, + comp: &Comp, + node: &Node, + tag: &str, + src: &CachedTexture, + dst_size: [u32; 2], + dst_depth: BitDepth, + h_inv: [f64; 9], + blend: f32, + mask: Option<&CachedTexture>, + mask_inv: bool, + mbm: bool, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let mask_hash = mask.map_or(0, |m| m.content_hash); + let mut u = UniformParams::default(); + u.p[0] = [h_inv[0] as f32, h_inv[1] as f32, h_inv[2] as f32, h_inv[3] as f32]; + u.p[1] = [h_inv[4] as f32, h_inv[5] as f32, h_inv[6] as f32, h_inv[7] as f32]; + u.p[2] = [ + h_inv[8] as f32, + blend, + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + ]; + u.p[3][1] = if mbm { 1.0 } else { 0.0 }; + if src.size != dst_size { + u.p[4] = [0.0, 0.0, dst_size[0] as f32, dst_size[1] as f32]; + } + u.p[5] = self.process_skip(comp, node, time); + let key = self.make_key( + node, + tag, + dst_size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..6]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex(dst_size, dst_depth, key); + let mv = mask.map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + fn eval_planar_transform( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node + .connected_node("Input") + .or_else(|| node.connected_node("Background")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { + return src; + } + let Some(track) = crate::tracker::eval_planar_track(comp, node, "Track", time) else { + return src; + }; + let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) >= 0.5; + let h_inv = if invert { + crate::tracker::mat3_invert(&track.to_ref_3x3).unwrap_or(track.to_ref_3x3) + } else { + track.to_ref_3x3 + }; + let src = self.crop_to_canvas(enc, src); + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mbm = mask.is_some() + && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); + self.dispatch_planar_homography( + comp, + node, + "PlanarTransform", + &src, + src.size, + dst_depth, + h_inv, + blend, + mask.as_ref(), + mask_inv, + mbm, + time, + frame_i, + enc, + stats, + ) + } + + #[allow(clippy::too_many_arguments)] + fn eval_planar_tracker( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(bg_id) = node + .connected_node("Background") + .or_else(|| node.connected_node("Input")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); + + // OperationMode: "Track"/0 = passthrough, "CornerPin"/1, "Steady"/2, "Stabilize"/3. + let op_mode = match node.static_str("OperationMode") { + Some("CornerPin") => 1, + Some("Steady") => 2, + Some("Stabilize") => 3, + Some(_) => 0, + None => comp + .eval_number(node, "OperationMode", time, 0.0, &self.expr) + .round() as i32, + }; + if op_mode == 0 { + return bg; + } + + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { + return bg; + } + + if op_mode == 2 || op_mode == 3 { + // Steady (2) warps Background by inv(ToRef) to lock the plane to RefTime. + // Stabilize (3) uses StableTrack if valid, falling back to inv(Track.ToRef). + let mat = if op_mode == 3 { + crate::tracker::eval_planar_track(comp, node, "StableTrack", time) + .or_else(|| crate::tracker::eval_planar_track(comp, node, "Track", time)) + } else { + crate::tracker::eval_planar_track(comp, node, "Track", time) + }; + let Some(track) = mat else { + return bg; + }; + let Some(h_inv) = crate::tracker::mat3_invert(&track.to_ref_3x3) else { + return bg; + }; + let bg = self.crop_to_canvas(enc, bg); + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); + let mbm = mask.is_some() + && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + let dst_depth = self.node_depth(comp, node, time, Some(bg.depth)); + let tag = if op_mode == 3 { "PlanarStabilize" } else { "PlanarSteady" }; + return self.dispatch_planar_homography( + comp, + node, + tag, + &bg, + bg.size, + dst_depth, + h_inv, + blend, + mask.as_ref(), + mask_inv, + mbm, + time, + frame_i, + enc, + stats, + ); + } + + // CornerPin (1): warp CornerPin1 / Foreground via CornerPin quad + ToRef over Background. + let Some(fg_id) = node + .connected_node("CornerPin1") + .or_else(|| node.connected_node("Foreground")) + .or_else(|| node.connected_node("CornerPin")) + .and_then(|s| comp.find_node(s)) + else { + return bg; + }; + let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); + let bg = self.crop_to_canvas(enc, bg); + let fg = self.crop_to_canvas(enc, fg); + + let read_corner = |primary: &str, alt: &str, default: [f64; 2]| -> [f64; 2] { + if node.inputs.contains_key(primary) { + comp.eval_point(node, primary, time, default, &self.expr) + } else { + comp.eval_point(node, alt, time, default, &self.expr) + } + }; + let bl = read_corner("CornerPinBottomLeft", "BottomLeft", [0.0, 0.0]); + let br = read_corner("CornerPinBottomRight", "BottomRight", [1.0, 0.0]); + let tr = read_corner("CornerPinTopRight", "TopRight", [1.0, 1.0]); + let tl = read_corner("CornerPinTopLeft", "TopLeft", [0.0, 1.0]); + let h_pin_inv = crate::tracker::quad_to_unit_homography(tl, tr, br, bl); + let h_to_ref = crate::tracker::eval_planar_track(comp, node, "Track", time) + .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |m| m.to_ref_3x3); + let h_combined = crate::tracker::mat3_mul(&h_pin_inv, &h_to_ref); + + let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(fg.depth))); + let warped_fg = self.dispatch_planar_homography( + comp, + node, + "PlanarCornerPinWarp", + &fg, + bg.size, + dst_depth, + h_combined, + 1.0, + None, + false, + false, + time, + frame_i, + enc, + stats, + ); + + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(bg.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 key = self.make_key( + node, + "PlanarCornerPinComp", + bg.size, + &[bg.content_hash, warped_fg.content_hash, mask_hash], + &[blend, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }], + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + let dst = self.alloc_tex(bg.size, dst_depth, key); + let mut u = UniformParams::default(); + u.p[0] = [0.5, 0.5, 1.0, 0.0]; + u.p[1] = [blend, 1.0, 0.0, 0.0]; + u.p[2] = [0.0, 0.0, 0.0, 0.0]; + u.p[3] = [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + bg.size[0] as f32, + bg.size[1] as f32, + ]; + u.p[6] = [0.0, 1.0, 0.0, 0.0]; + u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped_fg.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { let mut h = DefaultHasher::new(); self.cache.gpu_salt.hash(&mut h); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bae634197ad45b431c0fa886b186eba037cc4856..7817775a7e62a60b957431fd838597d8b25ee896 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -14,6 +14,7 @@ pub mod profile; pub mod ram_cache; pub mod scene3d; pub mod text_engine; +pub mod tracker; #[cfg(not(target_arch = "wasm32"))] pub use audio::{AudioPlayer, AudioTrack}; diff --git a/crates/engine/src/shaders/tracker_mesh.wgsl b/crates/engine/src/shaders/tracker_mesh.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..880e30b2e618701e43a25603854e1d33b8799c22 --- /dev/null +++ b/crates/engine/src/shaders/tracker_mesh.wgsl @@ -0,0 +1,72 @@ +// WebGPU-safe 2D triangle mesh warp renderer for Fusion `SurfaceTracker`. +// +// Vertex positions are supplied in Fusion normalized Y-up [0..1] coordinates: +// - `cur_pos`: tracked mesh vertex position at the evaluated frame +// - `ref_pos`: reference mesh vertex position at `ReferenceFrame` +// - `photo_weight`: per-vertex photometric weight ratio (`cur_pw / ref_pw`) +// +// The fragment shader projects `ref_pos` through the inverse `WarpableCanvas` +// 3x3 projective homography `H_inv` into Overlay normalized Y-up [0..1] space, +// converts to top-down texture UV, and bilinearly samples `overlay_tex`. + +struct MeshWarpUniform { + // Row-major 3x3 inverse homography mapping ref_pos (Fusion Y-up) -> Overlay (Fusion Y-up): + // h0 = (h00, h01, h02, h10) + // h1 = (h11, h12, h20, h21) + // h2 = (h22, photo_strength, 0.0, 0.0) + h0: vec4, + h1: vec4, + h2: vec4, + extra: vec4, +}; + +@group(0) @binding(0) var overlay_tex: texture_2d; +@group(0) @binding(1) var lin_samp: sampler; +@group(0) @binding(2) var u: MeshWarpUniform; + +struct VsIn { + @location(0) cur_pos: vec2, + @location(1) ref_pos: vec2, + @location(2) photo_weight: f32, +}; + +struct VsOut { + @builtin(position) pos: vec4, + @location(0) ref_pos: vec2, + @location(1) photo_weight: f32, +}; + +@vertex +fn vs_mesh(in: VsIn) -> VsOut { + var out: VsOut; + // Fusion Y-up [0..1] maps directly to WebGPU NDC [-1..1] (where +1 is top, -1 is bottom). + let ndc = vec2(in.cur_pos.x * 2.0 - 1.0, in.cur_pos.y * 2.0 - 1.0); + out.pos = vec4(ndc, 0.0, 1.0); + out.ref_pos = in.ref_pos; + out.photo_weight = in.photo_weight; + return out; +} + +@fragment +fn fs_mesh(in: VsOut) -> @location(0) vec4 { + let rx = in.ref_pos.x; + let ry = in.ref_pos.y; + let sx = u.h0.x * rx + u.h0.y * ry + u.h0.z; + let sy = u.h0.w * rx + u.h1.x * ry + u.h1.y; + let sw = u.h1.z * rx + u.h1.w * ry + u.h2.x; + if (abs(sw) < 1e-6) { + discard; + } + let fu_uv = vec2(sx / sw, sy / sw); + if (fu_uv.x < 0.0 || fu_uv.x > 1.0 || fu_uv.y < 0.0 || fu_uv.y > 1.0) { + discard; + } + let tex_uv = vec2(fu_uv.x, 1.0 - fu_uv.y); + var col = textureSampleLevel(overlay_tex, lin_samp, tex_uv, 0.0); + let photo_strength = clamp(u.h2.y, 0.0, 1.0); + if (photo_strength > 0.0) { + let pw = mix(1.0, max(in.photo_weight, 0.0), photo_strength); + col = vec4(col.rgb * pw, col.a); + } + return col; +} diff --git a/crates/engine/src/tracker.rs b/crates/engine/src/tracker.rs new file mode 100644 index 0000000000000000000000000000000000000000..d33f3da82ffc1a1d1cb7ebf2091939d048b6474e --- /dev/null +++ b/crates/engine/src/tracker.rs @@ -0,0 +1,1431 @@ +//! `SurfaceTracker` 2D triangle-mesh warp, `Dimension.PlanarTracker` / +//! `Dimension.PlanarTransform` projective track evaluation, and live point/planar +//! tracking helpers (`track_point_ncc`, `estimate_planar_homography`). + +use bytemuck::{Pod, Zeroable}; +use model::{Comp, LuaKey, LuaTable, LuaValue, Node, ParamValue}; +use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::Mutex; +use wgpu::util::DeviceExt; + +const TRACKER_MESH_WGSL: &str = include_str!("shaders/tracker_mesh.wgsl"); + +// ============================================================================ +// 1. Raw Fusion Lua table parsing (`FuTriMesh`, `WarpableCanvas`, `Matrix`) +// ============================================================================ + +/// Parsed Fusion `FuTriMesh` keyframe payload from `SurfaceTracker.MeshCustom`. +#[derive(Clone, Debug, PartialEq)] +pub struct FuTriMesh { + /// Vertex positions in Fusion normalized `[0..1]` Y-up space. + pub vertices: Vec<[f32; 2]>, + /// 0-based triangle vertex indices (always a multiple of 3, bounds-checked). + pub faces: Vec, + /// Per-vertex photometric lighting weights (optional; defaults to `1.0` when absent). + pub photo_weights: Vec, +} + +impl FuTriMesh { + /// Parses a `FuTriMesh { Vertices = {...}, Faces = {...}, PhotoWeights = {...} }` table. + pub fn from_lua_table(tbl: &LuaTable) -> Option { + let verts_tbl = tbl.get_table("Vertices")?; + let raw_v: Vec = verts_tbl + .positional_values() + .filter_map(LuaValue::as_f64) + .collect(); + let n_verts = raw_v.len() / 2; + if n_verts < 3 { + return None; + } + let mut vertices = Vec::with_capacity(n_verts); + for i in 0..n_verts { + let x = raw_v[i * 2]; + let y = raw_v[i * 2 + 1]; + if !x.is_finite() || !y.is_finite() { + return None; + } + vertices.push([x as f32, y as f32]); + } + + let faces_tbl = tbl.get_table("Faces")?; + let raw_f: Vec = faces_tbl + .positional_values() + .filter_map(LuaValue::as_f64) + .map(|v| v.round() as i64) + .collect(); + let n_tris = raw_f.len() / 3; + let mut faces = Vec::with_capacity(n_tris * 3); + let max_v = n_verts as i64; + for t in 0..n_tris { + let i0 = raw_f[t * 3]; + let i1 = raw_f[t * 3 + 1]; + let i2 = raw_f[t * 3 + 2]; + if i0 >= 0 && i0 < max_v && i1 >= 0 && i1 < max_v && i2 >= 0 && i2 < max_v { + faces.push(i0 as u32); + faces.push(i1 as u32); + faces.push(i2 as u32); + } + } + if faces.is_empty() { + return None; + } + + let photo_weights = tbl + .get_table("PhotoWeights") + .map(|pw| { + pw.positional_values() + .filter_map(LuaValue::as_f64) + .map(|v| if v.is_finite() { v as f32 } else { 1.0 }) + .collect::>() + }) + .unwrap_or_default(); + + Some(Self { + vertices, + faces, + photo_weights, + }) + } + + /// Linearly interpolates vertex positions and photometric weights between two matching-topology meshes. + pub fn lerp(&self, other: &Self, frac: f64) -> Self { + if self.vertices.len() != other.vertices.len() { + return if frac < 0.5 { self.clone() } else { other.clone() }; + } + let t = frac.clamp(0.0, 1.0) as f32; + let vertices = self + .vertices + .iter() + .zip(other.vertices.iter()) + .map(|(a, b)| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]) + .collect(); + let photo_weights = if self.photo_weights.len() == self.vertices.len() + && other.photo_weights.len() == other.vertices.len() + { + self.photo_weights + .iter() + .zip(other.photo_weights.iter()) + .map(|(&a, &b)| a + (b - a) * t) + .collect() + } else if !self.photo_weights.is_empty() { + self.photo_weights.clone() + } else { + other.photo_weights.clone() + }; + Self { + vertices, + faces: self.faces.clone(), + photo_weights, + } + } + + pub fn content_hash(&self) -> u64 { + let mut h = DefaultHasher::new(); + self.vertices.len().hash(&mut h); + for v in &self.vertices { + v[0].to_bits().hash(&mut h); + v[1].to_bits().hash(&mut h); + } + self.faces.hash(&mut h); + for &w in &self.photo_weights { + w.to_bits().hash(&mut h); + } + h.finish() + } +} + +/// Parsed Fusion `Matrix { RefTime, RefSize, RefAspect, ToRef }` payload from +/// `Dimension.PlanarTracker` / `Dimension.PlanarTransform` track splines. +#[derive(Clone, Debug, PartialEq)] +pub struct PlanarMatrix { + pub ref_time: f64, + pub ref_size: Option<[f64; 2]>, + pub ref_aspect: Option<[f64; 2]>, + pub is_bogus: bool, + /// Row-major 3x3 column-vector projective homography `H_to_ref` mapping + /// current-frame normalized Fusion `[x, y, 1]^T` -> reference-frame `[u, v, w]^T`. + pub to_ref_3x3: [f64; 9], +} + +impl PlanarMatrix { + pub fn from_lua_table(tbl: &LuaTable) -> Option { + let is_bogus = tbl.get_bool("IsBogus").unwrap_or(false); + let ref_time = tbl.get_f64("RefTime").unwrap_or(0.0); + let ref_size = tbl.get_table("RefSize").and_then(extract_vec2); + let ref_aspect = tbl.get_table("RefAspect").and_then(extract_vec2); + let to_ref_tbl = tbl.get_table("ToRef")?; + let m = extract_matrix16(to_ref_tbl)?; + // Fusion stores `ToRef` as a 4x4 row-vector matrix: + // [x, y, 0, 1] * M = [m0*x + m4*y + m12, m1*x + m5*y + m13, ..., m3*x + m7*y + m15] + // Converting to column-vector form `H * [x, y, 1]^T` takes rows (0, 1, 3) & cols (0, 1, 3) transposed. + let to_ref_3x3 = [ + m[0], m[4], m[12], + m[1], m[5], m[13], + m[3], m[7], m[15], + ]; + if to_ref_3x3.iter().any(|v| !v.is_finite()) { + return None; + } + Some(Self { + ref_time, + ref_size, + ref_aspect, + is_bogus, + to_ref_3x3, + }) + } + + pub fn lerp(&self, other: &Self, frac: f64) -> Self { + let t = frac.clamp(0.0, 1.0); + let a = normalize_h(&self.to_ref_3x3); + let b = normalize_h(&other.to_ref_3x3); + let mut h = [0.0f64; 9]; + for i in 0..9 { + h[i] = a[i] + (b[i] - a[i]) * t; + } + Self { + ref_time: self.ref_time, + ref_size: self.ref_size.or(other.ref_size), + ref_aspect: self.ref_aspect.or(other.ref_aspect), + is_bogus: self.is_bogus && other.is_bogus, + to_ref_3x3: h, + } + } +} + +fn extract_vec2(tbl: &LuaTable) -> Option<[f64; 2]> { + let mut it = tbl.positional_values().filter_map(LuaValue::as_f64); + let x = it.next()?; + let y = it.next()?; + if x.is_finite() && y.is_finite() { + Some([x, y]) + } else { + None + } +} + +/// Extracts 16 finite floats from a Lua matrix table, handling both Fusion's `[0] = m0, m1, ..., m15` +/// 0-based layout and standard 1-based `{ m0, m1, ..., m15 }` positional tables. +fn extract_matrix16(tbl: &LuaTable) -> Option<[f64; 16]> { + let mut vals = [0.0f64; 16]; + if tbl.get_index(0).is_some() { + for (i, slot) in vals.iter_mut().enumerate() { + let v = tbl.get_index(i as i64)?.as_f64()?; + if !v.is_finite() { + return None; + } + *slot = v; + } + return Some(vals); + } + let pos: Vec = tbl.positional_values().filter_map(LuaValue::as_f64).collect(); + if pos.len() >= 16 && pos[..16].iter().all(|v| v.is_finite()) { + vals.copy_from_slice(&pos[..16]); + return Some(vals); + } + None +} + +/// Recursively locates a named tool/spline inside `Tools` (including nested Macro/Group `Tools`). +fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> { + if let Some(t) = tools.get_table(target) { + return Some(t); + } + tools + .entries + .iter() + .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) + .find_map(|inner| find_raw_tool(inner, target)) +} + +fn sample_mesh_keyframes(kfs: &[(f64, FuTriMesh)], time: f64) -> FuTriMesh { + if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 { + return kfs[0].1.clone(); + } + let last = kfs.len() - 1; + if time >= kfs[last].0 { + return kfs[last].1.clone(); + } + let idx = kfs.partition_point(|(t, _)| *t <= time).saturating_sub(1); + let (t0, ref m0) = kfs[idx]; + let (t1, ref m1) = kfs[(idx + 1).min(last)]; + let span = t1 - t0; + if span.abs() < 1e-9 || (time - t0).abs() < 1e-6 { + return m0.clone(); + } + if (t1 - time).abs() < 1e-6 { + return m1.clone(); + } + m0.lerp(m1, (time - t0) / span) +} + +/// Evaluates `(ref_mesh, cur_mesh, ref_frame)` for a `SurfaceTracker` node at `time`. +pub fn eval_surface_mesh( + comp: &Comp, + node: &Node, + time: f64, + ref_frame_override: Option, +) -> Option<(FuTriMesh, FuTriMesh, f64)> { + // Try spline-backed `MeshCustom` first. + if let Some(spline_name) = node.inputs.get("MeshCustom").and_then(|b| b.source_op.as_deref()) { + let tools = comp.raw_root.as_ref()?.get_table("Tools")?; + let stbl = find_raw_tool(tools, spline_name)?; + let kfs_tbl = stbl.get_table("KeyFrames")?; + let mut kfs: Vec<(f64, FuTriMesh)> = Vec::new(); + for (k, v) in &kfs_tbl.entries { + let t = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + if let Some(m) = v + .as_table() + .and_then(|kt| kt.get_table("Value")) + .and_then(FuTriMesh::from_lua_table) + { + kfs.push((t, m)); + } + } + if !kfs.is_empty() { + kfs.sort_by(|a, b| a.0.total_cmp(&b.0)); + let ref_frame = ref_frame_override.unwrap_or(kfs[0].0); + let cur_mesh = sample_mesh_keyframes(&kfs, time); + let mut ref_mesh = sample_mesh_keyframes(&kfs, ref_frame); + if ref_mesh.vertices.len() != cur_mesh.vertices.len() { + // Fall back to the closest keyframe to `ref_frame` with matching vertex count. + ref_mesh = kfs + .iter() + .filter(|(_, m)| m.vertices.len() == cur_mesh.vertices.len()) + .min_by(|(ta, _), (tb, _)| (ta - ref_frame).abs().total_cmp(&(tb - ref_frame).abs())) + .map(|(_, m)| m.clone()) + .unwrap_or_else(|| cur_mesh.clone()); + } + return Some((ref_mesh, cur_mesh, ref_frame)); + } + } + + // Fallback: static `MeshCustom = Input { Value = FuTriMesh { ... } }`. + let static_tbl = node + .inputs + .get("MeshCustom") + .and_then(|b| match b.value.as_ref()? { + ParamValue::Raw(LuaValue::Table(t)) => Some(t), + _ => None, + }) + .or_else(|| { + node.raw + .get_table("Inputs") + .and_then(|i| i.get_table("MeshCustom")) + .and_then(|m| m.get_table("Value")) + })?; + let mesh = FuTriMesh::from_lua_table(static_tbl)?; + let rf = ref_frame_override.unwrap_or(0.0); + Some((mesh.clone(), mesh, rf)) +} + +/// Extracts `WarpableCanvas.Corners` as `[tl, tr, br, bl]` in Fusion Y-up `[0..1]` space. +/// Returns `None` if `WarpableCanvas` corners are absent or invalid. +pub fn extract_warpable_canvas_corners(node: &Node) -> Option<[[f64; 2]; 4]> { + let wc_tbl = node + .inputs + .get("WarpableCanvas") + .and_then(|b| match b.value.as_ref()? { + ParamValue::Raw(LuaValue::Table(t)) => Some(t), + _ => None, + }) + .or_else(|| { + node.raw + .get_table("Inputs") + .and_then(|i| i.get_table("WarpableCanvas")) + .and_then(|w| w.get_table("Value")) + })?; + let corners_tbl = wc_tbl.get_table("Corners")?; + let vals: Vec = corners_tbl + .positional_values() + .filter_map(LuaValue::as_f64) + .collect(); + if vals.len() < 8 || !vals[..8].iter().all(|v| v.is_finite()) { + return None; + } + Some([ + [vals[0], vals[1]], // TL + [vals[2], vals[3]], // TR + [vals[4], vals[5]], // BR + [vals[6], vals[7]], // BL + ]) +} + +/// Evaluates a `Dimension.PlanarTracker` / `Dimension.PlanarTransform` `Matrix` spline input +/// (such as `"Track"` or `"StableTrack"`) at `time`. +pub fn eval_planar_track(comp: &Comp, node: &Node, input_name: &str, time: f64) -> Option { + if let Some(spline_name) = node.inputs.get(input_name).and_then(|b| b.source_op.as_deref()) { + let tools = comp.raw_root.as_ref()?.get_table("Tools")?; + if let Some(stbl) = find_raw_tool(tools, spline_name) + && let Some(kfs_tbl) = stbl.get_table("KeyFrames") + { + let mut kfs: Vec<(f64, PlanarMatrix)> = Vec::new(); + for (k, v) in &kfs_tbl.entries { + let t = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + if let Some(pm) = v + .as_table() + .and_then(|kt| kt.get_table("Value")) + .and_then(PlanarMatrix::from_lua_table) + && !pm.is_bogus + { + kfs.push((t, pm)); + } + } + if !kfs.is_empty() { + kfs.sort_by(|a, b| a.0.total_cmp(&b.0)); + if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + let last = kfs.len() - 1; + if time >= kfs[last].0 { + return Some(kfs[last].1.clone()); + } + let idx = kfs.partition_point(|(t, _)| *t <= time).saturating_sub(1); + let (t0, ref m0) = kfs[idx]; + let (t1, ref m1) = kfs[(idx + 1).min(last)]; + let span = t1 - t0; + if span.abs() < 1e-9 || (time - t0).abs() < 1e-6 { + return Some(m0.clone()); + } + if (t1 - time).abs() < 1e-6 { + return Some(m1.clone()); + } + return Some(m0.lerp(m1, (time - t0) / span)); + } + } + } + + // Fallback: static `Matrix { ... }` on the input itself. + let static_tbl = node + .inputs + .get(input_name) + .and_then(|b| match b.value.as_ref()? { + ParamValue::Raw(LuaValue::Table(t)) => Some(t), + _ => None, + }) + .or_else(|| { + node.raw + .get_table("Inputs") + .and_then(|i| i.get_table(input_name)) + .and_then(|m| m.get_table("Value")) + })?; + let pm = PlanarMatrix::from_lua_table(static_tbl)?; + if pm.is_bogus { + None + } else { + Some(pm) + } +} + +// ============================================================================ +// 2. 3x3 Projective Homography Math +// ============================================================================ + +pub fn normalize_h(h: &[f64; 9]) -> [f64; 9] { + if h[8].abs() > 1e-12 { + let inv = 1.0 / h[8]; + h.map(|v| v * inv) + } else { + let norm = h.iter().map(|v| v * v).sum::().sqrt(); + if norm > 1e-12 { + h.map(|v| v / norm) + } else { + *h + } + } +} + +pub fn mat3_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] { + std::array::from_fn(|k| { + let r = k / 3; + let c = k % 3; + a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c] + }) +} + +pub fn mat3_det(m: &[f64; 9]) -> f64 { + let [a, b, c, d, e, f, g, h, i] = *m; + a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) +} + +pub fn mat3_invert(m: &[f64; 9]) -> Option<[f64; 9]> { + let [a, b, c, d, e, f, g, h, i] = *m; + let adj = [ + e * i - f * h, + c * h - b * i, + b * f - c * e, + f * g - d * i, + a * i - c * g, + c * d - a * f, + d * h - e * g, + b * g - a * h, + a * e - b * d, + ]; + let det = a * adj[0] + b * adj[3] + c * adj[6]; + if det.abs() < 1e-12 { + return None; + } + let inv_det = 1.0 / det; + Some(adj.map(|v| v * inv_det)) +} + +/// Computes the 3x3 projective homography mapping the Fusion Y-up quad `(tl, tr, br, bl)` +/// to the unit square `[0, 1]^2` where `bl -> (0, 0), br -> (1, 0), tr -> (1, 1), tl -> (0, 1)`. +pub fn quad_to_unit_homography( + tl: [f64; 2], + tr: [f64; 2], + br: [f64; 2], + bl: [f64; 2], +) -> [f64; 9] { + let dx1 = br[0] - tr[0]; + let dy1 = br[1] - tr[1]; + let dx2 = tl[0] - tr[0]; + let dy2 = tl[1] - tr[1]; + let sx = bl[0] - br[0] + tr[0] - tl[0]; + let sy = bl[1] - br[1] + tr[1] - tl[1]; + let denom = dx1 * dy2 - dx2 * dy1; + if denom.abs() < 1e-10 { + return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; + } + let g = (sx * dy2 - sy * dx2) / denom; + let h = (dx1 * sy - dy1 * sx) / denom; + let unit_to_quad = [ + br[0] - bl[0] + g * br[0], + tl[0] - bl[0] + h * tl[0], + bl[0], + br[1] - bl[1] + g * br[1], + tl[1] - bl[1] + h * tl[1], + bl[1], + g, + h, + 1.0, + ]; + mat3_invert(&unit_to_quad) + .map(|inv| normalize_h(&inv)) + .unwrap_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]) +} + +// ============================================================================ +// 3. WebGPU-Safe `SurfaceTracker` Mesh Warp Renderer +// ============================================================================ + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct MeshVertex { + cur_pos: [f32; 2], + ref_pos: [f32; 2], + photo_weight: f32, + _pad: f32, +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct MeshWarpUniform { + h0: [f32; 4], + h1: [f32; 4], + h2: [f32; 4], + extra: [f32; 4], +} + +/// Lazily initialized WebGPU-safe render pipelines for `SurfaceTracker` mesh warping. +/// Only renders to `Rgba8Unorm` or `Rgba16Float` (always baseline WebGPU `RENDER_ATTACHMENT`). +pub struct TrackerPipelines { + shader: wgpu::ShaderModule, + bgl: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + sampler: wgpu::Sampler, + pipelines: Mutex>, +} + +impl TrackerPipelines { + pub fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tracker-mesh-shader"), + source: wgpu::ShaderSource::Wgsl(TRACKER_MESH_WGSL.into()), + }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tracker-mesh-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new( + std::mem::size_of::() as u64, + ), + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tracker-mesh-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("tracker-mesh-lin-samp"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + Self { + shader, + bgl, + pipeline_layout, + sampler, + pipelines: Mutex::new(HashMap::new()), + } + } + + fn create_pipeline( + &self, + device: &wgpu::Device, + format: wgpu::TextureFormat, + ) -> wgpu::RenderPipeline { + const VERTEX_ATTRS: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![ + 0 => Float32x2, + 1 => Float32x2, + 2 => Float32, + ]; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("tracker-mesh-pipeline"), + layout: Some(&self.pipeline_layout), + vertex: wgpu::VertexState { + module: &self.shader, + entry_point: Some("vs_mesh"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &VERTEX_ATTRS, + })], + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + unclipped_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &self.shader, + entry_point: Some("fs_mesh"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + } + + /// Rasterizes the tracked 2D triangle mesh (`ref_mesh` -> `cur_mesh`) sampling `overlay_view` + /// through `h_inv_fu` onto `dst_view` (cleared to transparent black). + /// + /// `dst_format` must be a baseline WebGPU renderable format (`Rgba8Unorm` or `Rgba16Float`). + #[allow(clippy::too_many_arguments)] + pub fn render_surface_mesh( + &self, + device: &wgpu::Device, + enc: &mut wgpu::CommandEncoder, + overlay_view: &wgpu::TextureView, + dst_view: &wgpu::TextureView, + dst_format: wgpu::TextureFormat, + ref_mesh: &FuTriMesh, + cur_mesh: &FuTriMesh, + h_inv_fu: [f64; 9], + photo_strength: f32, + ) { + let n_verts = cur_mesh.vertices.len().min(ref_mesh.vertices.len()); + if n_verts < 3 || cur_mesh.faces.len() < 3 { + // Clear target to transparent even if mesh is empty. + let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("surface-tracker-clear"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: dst_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + return; + } + + let mut vertices = Vec::with_capacity(n_verts); + for i in 0..n_verts { + let cur_pw = cur_mesh.photo_weights.get(i).copied().unwrap_or(1.0); + let ref_pw = ref_mesh.photo_weights.get(i).copied().unwrap_or(1.0); + let ratio = if ref_pw.abs() > 1e-4 { cur_pw / ref_pw } else { 1.0 }; + vertices.push(MeshVertex { + cur_pos: cur_mesh.vertices[i], + ref_pos: ref_mesh.vertices[i], + photo_weight: ratio.clamp(0.0, 4.0), + _pad: 0.0, + }); + } + + let max_v = n_verts as u32; + let mut indices = Vec::with_capacity(cur_mesh.faces.len()); + for tri in cur_mesh.faces.chunks_exact(3) { + if tri[0] < max_v && tri[1] < max_v && tri[2] < max_v { + indices.extend_from_slice(tri); + } + } + if indices.is_empty() { + return; + } + + let vbuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("surface-tracker-vbuf"), + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + let ibuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("surface-tracker-ibuf"), + contents: bytemuck::cast_slice(&indices), + usage: wgpu::BufferUsages::INDEX, + }); + let uniform = MeshWarpUniform { + h0: [ + h_inv_fu[0] as f32, + h_inv_fu[1] as f32, + h_inv_fu[2] as f32, + h_inv_fu[3] as f32, + ], + h1: [ + h_inv_fu[4] as f32, + h_inv_fu[5] as f32, + h_inv_fu[6] as f32, + h_inv_fu[7] as f32, + ], + h2: [h_inv_fu[8] as f32, photo_strength, 0.0, 0.0], + extra: [0.0; 4], + }; + let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("surface-tracker-ubuf"), + contents: bytemuck::bytes_of(&uniform), + usage: wgpu::BufferUsages::UNIFORM, + }); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("surface-tracker-bg"), + layout: &self.bgl, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(overlay_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: ubuf.as_entire_binding(), + }, + ], + }); + + let mut cache = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + let pipeline = cache + .entry(dst_format) + .or_insert_with(|| self.create_pipeline(device, dst_format)); + + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("surface-tracker-mesh-pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: dst_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.set_vertex_buffer(0, vbuf.slice(..)); + pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..indices.len() as u32, 0, 0..1); + } +} + +// ============================================================================ +// 4. Live Tracking Helper API (NCC Point Tracker + Normalized DLT Homography) +// ============================================================================ + +#[inline] +fn rgba_luma_bilinear(rgba: &[u8], w: u32, h: u32, x: f64, y: f64) -> f64 { + let wf = (w - 1) as f64; + let hf = (h - 1) as f64; + let cx = x.clamp(0.0, wf); + let cy = y.clamp(0.0, hf); + let x0 = cx.floor() as u32; + let y0 = cy.floor() as u32; + let x1 = (x0 + 1).min(w - 1); + let y1 = (y0 + 1).min(h - 1); + let fx = cx - x0 as f64; + let fy = cy - y0 as f64; + + let sample = |ix: u32, iy: u32| -> f64 { + let idx = ((iy as usize) * (w as usize) + (ix as usize)) * 4; + 0.299 * rgba[idx] as f64 + 0.587 * rgba[idx + 1] as f64 + 0.114 * rgba[idx + 2] as f64 + }; + let v00 = sample(x0, y0); + let v10 = sample(x1, y0); + let v01 = sample(x0, y1); + let v11 = sample(x1, y1); + let top = v00 + (v10 - v00) * fx; + let bot = v01 + (v11 - v01) * fx; + top + (bot - top) * fy +} + +/// Sub-pixel parabolic-refined Zero-Mean Normalized Cross-Correlation (NCC) point tracker. +/// +/// Tracks `prev_pos_fu` (Fusion normalized `[0..1]` Y-up coordinates) from `prev_rgba` to +/// `cur_rgba` within `search_radius_px` using a `(2 * patch_radius_px + 1)^2` template patch. +/// Returns `(new_pos_fu, confidence)` where `confidence` is in `[0.0, 1.0]`. +pub fn track_point_ncc( + prev_rgba: &[u8], + cur_rgba: &[u8], + size: [u32; 2], + prev_pos_fu: [f64; 2], + search_radius_px: i32, + patch_radius_px: i32, +) -> ([f64; 2], f32) { + let [w, h] = size; + if w == 0 || h == 0 { + return (prev_pos_fu, 0.0); + } + let expected_len = (w as usize).saturating_mul(h as usize).saturating_mul(4); + if prev_rgba.len() < expected_len || cur_rgba.len() < expected_len { + return (prev_pos_fu, 0.0); + } + let sr = search_radius_px.max(0); + let pr = patch_radius_px.max(1); + let side = (2 * pr + 1) as usize; + let n_pix = side * side; + + let wf = w as f64; + let hf = h as f64; + let px = prev_pos_fu[0] * wf - 0.5; + let py = (1.0 - prev_pos_fu[1]) * hf - 0.5; + + // Sample template patch centered at exact (sub-pixel) `prev_pos_fu`. + let mut tpl = Vec::with_capacity(n_pix); + let mut tpl_sum = 0.0f64; + for oy in -pr..=pr { + for ox in -pr..=pr { + let v = rgba_luma_bilinear(prev_rgba, w, h, px + ox as f64, py + oy as f64); + tpl.push(v); + tpl_sum += v; + } + } + let tpl_mean = tpl_sum / n_pix as f64; + let mut tpl_var = 0.0f64; + for v in &mut tpl { + *v -= tpl_mean; + tpl_var += *v * *v; + } + if tpl_var < 1e-6 { + return (prev_pos_fu, 0.0); + } + + let grid_side = (2 * sr + 1) as usize; + let mut scores = vec![-1.0f64; grid_side * grid_side]; + let mut best_score = -2.0f64; + let mut best_dx = 0i32; + let mut best_dy = 0i32; + + let mut cand = vec![0.0f64; n_pix]; + for dy in -sr..=sr { + for dx in -sr..=sr { + let cx = px + dx as f64; + let cy = py + dy as f64; + let mut sum = 0.0f64; + let mut k = 0usize; + for oy in -pr..=pr { + for ox in -pr..=pr { + let v = rgba_luma_bilinear(cur_rgba, w, h, cx + ox as f64, cy + oy as f64); + cand[k] = v; + sum += v; + k += 1; + } + } + let mean = sum / n_pix as f64; + let mut num = 0.0f64; + let mut cand_var = 0.0f64; + for i in 0..n_pix { + let d = cand[i] - mean; + num += tpl[i] * d; + cand_var += d * d; + } + let denom = (tpl_var * cand_var).sqrt(); + let score = if denom > 1e-8 { num / denom } else { -1.0 }; + let gx = (dx + sr) as usize; + let gy = (dy + sr) as usize; + scores[gy * grid_side + gx] = score; + if score > best_score { + best_score = score; + best_dx = dx; + best_dy = dy; + } + } + } + + if best_score <= -1.5 { + return (prev_pos_fu, 0.0); + } + + // Parabolic sub-pixel peak refinement along X and Y. + let gx = (best_dx + sr) as usize; + let gy = (best_dy + sr) as usize; + let sub_x = if gx > 0 && gx + 1 < grid_side { + let cm = scores[gy * grid_side + (gx - 1)]; + let c0 = scores[gy * grid_side + gx]; + let cp = scores[gy * grid_side + (gx + 1)]; + let denom = cm - 2.0 * c0 + cp; + if denom < -1e-9 { + (0.5 * (cm - cp) / denom).clamp(-0.5, 0.5) + } else { + 0.0 + } + } else { + 0.0 + }; + let sub_y = if gy > 0 && gy + 1 < grid_side { + let cm = scores[(gy - 1) * grid_side + gx]; + let c0 = scores[gy * grid_side + gx]; + let cp = scores[(gy + 1) * grid_side + gx]; + let denom = cm - 2.0 * c0 + cp; + if denom < -1e-9 { + (0.5 * (cm - cp) / denom).clamp(-0.5, 0.5) + } else { + 0.0 + } + } else { + 0.0 + }; + + let new_px = px + best_dx as f64 + sub_x; + let new_py = py + best_dy as f64 + sub_y; + let new_fu = [(new_px + 0.5) / wf, 1.0 - (new_py + 0.5) / hf]; + (new_fu, best_score.clamp(0.0, 1.0) as f32) +} + +/// Hartley isotropic point normalization: translates centroid to `(0, 0)` and scales average +/// distance from origin to `sqrt(2)`. Returns `(T, T_inv, normalized_points)`. +fn hartley_normalize(pts: &[[f64; 2]]) -> Option<([f64; 9], [f64; 9], Vec<[f64; 2]>)> { + let n = pts.len() as f64; + if pts.is_empty() { + return None; + } + let mut cx = 0.0; + let mut cy = 0.0; + for p in pts { + if !p[0].is_finite() || !p[1].is_finite() { + return None; + } + cx += p[0]; + cy += p[1]; + } + cx /= n; + cy /= n; + + let mut mean_dist = 0.0; + for p in pts { + let dx = p[0] - cx; + let dy = p[1] - cy; + mean_dist += (dx * dx + dy * dy).sqrt(); + } + mean_dist /= n; + if mean_dist < 1e-12 { + return None; + } + let s = std::f64::consts::SQRT_2 / mean_dist; + let inv_s = 1.0 / s; + + let t = [s, 0.0, -s * cx, 0.0, s, -s * cy, 0.0, 0.0, 1.0]; + let t_inv = [inv_s, 0.0, cx, 0.0, inv_s, cy, 0.0, 0.0, 1.0]; + let norm = pts.iter().map(|p| [(p[0] - cx) * s, (p[1] - cy) * s]).collect(); + Some((t, t_inv, norm)) +} + +/// Cyclic Jacobi eigensolver for a 9x9 real symmetric matrix; returns the unit eigenvector +/// corresponding to the smallest eigenvalue. +fn smallest_eigenvector_9x9(mut a: [[f64; 9]; 9]) -> [f64; 9] { + let mut v = [[0.0f64; 9]; 9]; + for (i, row) in v.iter_mut().enumerate() { + row[i] = 1.0; + } + for _sweep in 0..32 { + let mut max_off = 0.0f64; + for p in 0..9 { + for q in (p + 1)..9 { + let apq = a[p][q]; + let abs_apq = apq.abs(); + if abs_apq > max_off { + max_off = abs_apq; + } + if abs_apq < 1e-15 { + continue; + } + let tau = (a[q][q] - a[p][p]) / (2.0 * apq); + let t = if tau >= 0.0 { + 1.0 / (tau + (1.0 + tau * tau).sqrt()) + } else { + -1.0 / (-tau + (1.0 + tau * tau).sqrt()) + }; + let c = 1.0 / (1.0 + t * t).sqrt(); + let s = t * c; + + let app = a[p][p]; + let aqq = a[q][q]; + a[p][p] = app - t * apq; + a[q][q] = aqq + t * apq; + a[p][q] = 0.0; + a[q][p] = 0.0; + + for r in 0..9 { + if r != p && r != q { + let arp = a[r][p]; + let arq = a[r][q]; + let nrp = c * arp - s * arq; + let nrq = s * arp + c * arq; + a[r][p] = nrp; + a[p][r] = nrp; + a[r][q] = nrq; + a[q][r] = nrq; + } + let vrp = v[r][p]; + let vrq = v[r][q]; + v[r][p] = c * vrp - s * vrq; + v[r][q] = s * vrp + c * vrq; + } + } + } + if max_off < 1e-14 { + break; + } + } + let mut min_idx = 0usize; + let mut min_val = a[0][0]; + for (i, row) in a.iter().enumerate().skip(1) { + if row[i] < min_val { + min_val = row[i]; + min_idx = i; + } + } + std::array::from_fn(|r| v[r][min_idx]) +} + +/// Normalized Direct Linear Transform (DLT) 2D projective homography solver (`>= 4` correspondences). +/// +/// Returns a row-major 3x3 column-vector projective matrix `H` mapping `src_pts[i] -> dst_pts[i]` +/// (normalized so `H[8] == 1.0` when non-zero), directly compatible with `Dimension.PlanarTransform`. +pub fn estimate_planar_homography(src_pts: &[[f64; 2]], dst_pts: &[[f64; 2]]) -> Option<[f64; 9]> { + if src_pts.len() != dst_pts.len() || src_pts.len() < 4 { + return None; + } + let (t_src, _, norm_src) = hartley_normalize(src_pts)?; + let (_, t_dst_inv, norm_dst) = hartley_normalize(dst_pts)?; + + // Accumulate 9x9 symmetric normal matrix M = A^T A. + let mut ata = [[0.0f64; 9]; 9]; + for (p, q) in norm_src.iter().zip(norm_dst.iter()) { + let [x, y] = *p; + let [u, v] = *q; + let r1 = [-x, -y, -1.0, 0.0, 0.0, 0.0, u * x, u * y, u]; + let r2 = [0.0, 0.0, 0.0, -x, -y, -1.0, v * x, v * y, v]; + for row in [&r1, &r2] { + for i in 0..9 { + let ri = row[i]; + if ri == 0.0 { + continue; + } + for j in i..9 { + ata[i][j] += ri * row[j]; + } + } + } + } + for i in 0..9 { + for j in 0..i { + ata[i][j] = ata[j][i]; + } + } + + let h_norm = smallest_eigenvector_9x9(ata); + let h = mat3_mul(&mat3_mul(&t_dst_inv, &h_norm), &t_src); + if mat3_det(&h).abs() < 1e-12 || h.iter().any(|v| !v.is_finite()) { + return None; + } + Some(normalize_h(&h)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn track_point_ncc_tracks_subpixel_shift_within_half_pixel() { + let w = 96u32; + let h = 96u32; + let make_img = |cx: f64, cy: f64| -> Vec { + let mut out = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + let dx = x as f64 - cx; + let dy = y as f64 - cy; + // Distinct asymmetric feature blob + ring so NCC peak is sharp and unique. + let g1 = (-((dx * dx + dy * dy) / 14.0)).exp(); + let g2 = (-(((dx - 4.0).powi(2) + (dy + 3.0).powi(2)) / 9.0)).exp(); + let wave = 0.5 + 0.5 * (dx * 0.45).sin() * (dy * 0.35).cos(); + let luma = (25.0 + 180.0 * g1 + 95.0 * g2 + 25.0 * wave * g1).clamp(0.0, 255.0) as u8; + let idx = ((y * w + x) * 4) as usize; + out[idx] = luma; + out[idx + 1] = luma; + out[idx + 2] = luma; + out[idx + 3] = 255; + } + } + out + }; + + let prev_cx = 40.0; + let prev_cy = 44.0; + let shift_x = 5.35; + let shift_y = -3.65; + let prev = make_img(prev_cx, prev_cy); + let cur = make_img(prev_cx + shift_x, prev_cy + shift_y); + + let prev_fu = [(prev_cx + 0.5) / w as f64, 1.0 - (prev_cy + 0.5) / h as f64]; + let (new_fu, conf) = track_point_ncc(&prev, &cur, [w, h], prev_fu, 12, 8); + let got_x = new_fu[0] * w as f64 - 0.5; + let got_y = (1.0 - new_fu[1]) * h as f64 - 0.5; + let err = ((got_x - (prev_cx + shift_x)).powi(2) + (got_y - (prev_cy + shift_y)).powi(2)).sqrt(); + assert!(conf > 0.95, "expected high NCC confidence, got {conf}"); + assert!( + err < 0.5, + "expected sub-pixel NCC error < 0.5 px, got {err:.4} px (got ({got_x:.3}, {got_y:.3}), want ({:.3}, {:.3}))", + prev_cx + shift_x, + prev_cy + shift_y, + ); + } + + #[test] + fn estimate_planar_homography_recovers_projective_matrix() { + let h_true = [ + 1.15, -0.18, 0.07, + 0.12, 0.94, -0.05, + 0.22, -0.14, 1.0, + ]; + let src = [ + [0.1, 0.15], + [0.85, 0.12], + [0.9, 0.88], + [0.15, 0.82], + [0.5, 0.5], + [0.32, 0.67], + ]; + let dst: Vec<[f64; 2]> = src + .iter() + .map(|p| { + let x = h_true[0] * p[0] + h_true[1] * p[1] + h_true[2]; + let y = h_true[3] * p[0] + h_true[4] * p[1] + h_true[5]; + let w = h_true[6] * p[0] + h_true[7] * p[1] + h_true[8]; + [x / w, y / w] + }) + .collect(); + + let est = estimate_planar_homography(&src, &dst).expect("homography"); + for i in 0..9 { + assert!( + (est[i] - h_true[i]).abs() < 1e-6, + "entry {i}: got {}, want {}", + est[i], + h_true[i] + ); + } + } + + #[test] + fn surface_tracker_warps_synthetic_trimesh_over_background() { + // Two-triangle quad covering [0.25..0.5, 0.25..0.5] at ReferenceFrame=0, + // translating to [0.5..0.75, 0.5..0.75] at frame 10! + // Overlay is bright red solid; Input is solid blue. + let src = r#" +Composition { + CurrentTime = 10, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + OV = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + ST1Mesh = BezierSpline { + KeyFrames = { + [0] = { 0, Flags = { Linear = true }, Value = FuTriMesh { + Vertices = { 0.25, 0.25, 0.50, 0.25, 0.50, 0.50, 0.25, 0.50 }, + Faces = { 0, 1, 2, 0, 2, 3 }, + PhotoWeights = { 1, 1, 1, 1 }, + } }, + [10] = { 1, Flags = { Linear = true }, Value = FuTriMesh { + Vertices = { 0.50, 0.50, 0.75, 0.50, 0.75, 0.75, 0.50, 0.75 }, + Faces = { 0, 1, 2, 0, 2, 3 }, + PhotoWeights = { 1, 1, 1, 1 }, + } }, + }, + }, + ST1 = SurfaceTracker { + Inputs = { + ProcessStage = Input { Value = 2, }, + ReferenceFrame = Input { Value = 0, }, + OverlayPlacement = Input { Value = 1, }, + MeshCustom = Input { SourceOp = "ST1Mesh", Source = "Value", }, + WarpableCanvas = Input { + Value = WarpableCanvas { + Corners = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 } + }, + }, + Input = Input { SourceOp = "BG", Source = "Output", }, + Overlay = Input { SourceOp = "OV", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse SurfaceTracker comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let st_id = comp.find_node("ST1").unwrap(); + let (tex, stats) = eng.evaluate(&comp, st_id, 10.0); + assert!(stats.unsupported_nodes.is_empty()); + let rgba = eng.readback_rgba(&tex).expect("readback"); + + // At frame 10, the warped red quad covers Fusion x in [0.5..0.75], y in [0.5..0.75]. + // In top-down pixel coords (64x64): x in [32..48], y in [16..32]. + let px = |x: usize, y: usize| -> [u8; 4] { + let i = (y * 64 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let inside = px(40, 24); + let old_pos = px(24, 40); + assert!(inside[0] > 240 && inside[2] < 15, "warped quad center should be red, got {inside:?}"); + assert!(old_pos[2] > 240 && old_pos[0] < 15, "original quad location should show blue BG, got {old_pos:?}"); + + // Midpoint frame 5 should linearly interpolate vertices to [0.375..0.625, 0.375..0.625] -> center (32, 32). + let (tex5, _) = eng.evaluate(&comp, st_id, 5.0); + let rgba5 = eng.readback_rgba(&tex5).expect("readback f5"); + let mid_idx = (32 * 64 + 32) * 4; + assert!( + rgba5[mid_idx] > 240 && rgba5[mid_idx + 2] < 15, + "interpolated frame 5 center should be red, got {:?}", + &rgba5[mid_idx..mid_idx + 4] + ); + } + + #[test] + fn planar_transform_and_planar_tracker_modes_work() { + // Track shifts current frame right by +0.25 in X relative to RefTime=0: + // cur(x, y) -> ref(x - 0.25, y) + // Row-vector 4x4 ToRef has m12 = -0.25, m13 = 0.0. + let src = r#" +Composition { + CurrentTime = 1, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + Patch = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + MaskRect = RectangleMask { + Inputs = { + Width = Input { Value = 0.25, }, + Height = Input { Value = 0.25, }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Dot = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftGreen = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + EffectMask = Input { SourceOp = "MaskRect", Source = "Mask", }, + }, + }, + BlueBG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + TrackSpline = BezierSpline { + KeyFrames = { + [0] = { 0, Flags = { Linear = true }, Value = Matrix { + RefTime = 0, + RefSize = { 64, 64 }, + RefAspect = { 1, 1 }, + ToRef = { [0] = 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + } }, + [1] = { 1, Flags = { Linear = true }, Value = Matrix { + RefTime = 0, + RefSize = { 64, 64 }, + RefAspect = { 1, 1 }, + ToRef = { [0] = 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -0.25, 0, 0, 1 } + } }, + }, + }, + PT_Fwd = Dimension.PlanarTransform { + Inputs = { + Track = Input { SourceOp = "TrackSpline", Source = "Value", }, + Input = Input { SourceOp = "Dot", Source = "Output", }, + }, + }, + PT_Inv = Dimension.PlanarTransform { + Inputs = { + Invert = Input { Value = 1, }, + Track = Input { SourceOp = "TrackSpline", Source = "Value", }, + Input = Input { SourceOp = "PT_Fwd", Source = "Output", }, + }, + }, + PTrk_Track = Dimension.PlanarTracker { + Inputs = { + OperationMode = Input { Value = FuID { "Track" }, }, + Track = Input { SourceOp = "TrackSpline", Source = "Value", }, + Background = Input { SourceOp = "BlueBG", Source = "Output", }, + }, + }, + PTrk_Steady = Dimension.PlanarTracker { + Inputs = { + OperationMode = Input { Value = FuID { "Steady" }, }, + Track = Input { SourceOp = "TrackSpline", Source = "Value", }, + Background = Input { SourceOp = "PT_Fwd", Source = "Output", }, + }, + }, + PTrk_CornerPin = Dimension.PlanarTracker { + Inputs = { + OperationMode = Input { Value = FuID { "CornerPin" }, }, + Track = Input { SourceOp = "TrackSpline", Source = "Value", }, + Background = Input { SourceOp = "BlueBG", Source = "Output", }, + CornerPin1 = Input { SourceOp = "Patch", Source = "Output", }, + CornerPinBottomLeft = Input { Value = { 0.1, 0.25 }, }, + CornerPinBottomRight = Input { Value = { 0.4, 0.25 }, }, + CornerPinTopRight = Input { Value = { 0.4, 0.75 }, }, + CornerPinTopLeft = Input { Value = { 0.1, 0.75 }, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse Planar comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let px_at = |e: &mut Engine, name: &str, x: usize, y: usize| -> [u8; 4] { + let (tex, stats) = e.evaluate(&comp, comp.find_node(name).unwrap(), 1.0); + assert!(stats.unsupported_nodes.is_empty(), "{name} had unsupported: {:?}", stats.unsupported_nodes); + let rgba = e.readback_rgba(&tex).unwrap(); + let i = (y * 64 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + + // Dot was centered at x=0.25 (px 16). PT_Fwd shifts it by +0.25 to x=0.50 (px 32). + let fwd_shifted = px_at(&mut eng, "PT_Fwd", 32, 32); + let fwd_old = px_at(&mut eng, "PT_Fwd", 16, 32); + assert!(fwd_shifted[1] > 240, "PT_Fwd should move green dot to x=32, got {fwd_shifted:?}"); + assert!(fwd_old[1] < 15, "PT_Fwd old x=16 should be transparent, got {fwd_old:?}"); + + // PT_Inv inverts PT_Fwd back to x=0.25 (px 16). + let inv_restored = px_at(&mut eng, "PT_Inv", 16, 32); + assert!(inv_restored[1] > 240, "PT_Inv should restore green dot to x=16, got {inv_restored:?}"); + + // PlanarTracker Track mode passes through BlueBG. + let trk = px_at(&mut eng, "PTrk_Track", 32, 32); + assert!(trk[2] > 240, "PlanarTracker Track should pass through blue BG, got {trk:?}"); + + // PlanarTracker Steady mode locks PT_Fwd back to RefTime x=0.25 (px 16). + let steady = px_at(&mut eng, "PTrk_Steady", 16, 32); + assert!(steady[1] > 240, "PlanarTracker Steady should stabilize green dot back to x=16, got {steady:?}"); + + // PlanarTracker CornerPin places red quad [0.1..0.4] shifted by +0.25 -> [0.35..0.65] (center x=32) over blue BG. + let cp_inside = px_at(&mut eng, "PTrk_CornerPin", 32, 32); + let cp_outside = px_at(&mut eng, "PTrk_CornerPin", 8, 32); + assert!(cp_inside[0] > 240 && cp_inside[2] < 15, "CornerPin interior should be red, got {cp_inside:?}"); + assert!(cp_outside[2] > 240 && cp_outside[0] < 15, "CornerPin exterior should be blue BG, got {cp_outside:?}"); + } +} diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 1f876b1cbcc712eae5e86aed8742c340e7ff000f..c53d2dd60916429a1da0664c0cf21a3f449e6d16 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -83,6 +83,11 @@ pub fn is_supported_tool(kind: &str) -> bool { | "PipeRouter" | "Fuse.Wireless" | "Tracker" + | "SurfaceTracker" + | "Dimension.PlanarTracker" + | "PlanarTracker" + | "Dimension.PlanarTransform" + | "PlanarTransform" | "MacroOperator" | "GroupOperator" | "TimeStretcher" @@ -610,7 +615,9 @@ impl Comp { pub fn default_main_input_port(kind: &str) -> &'static str { match kind { - "Merge" | "Dissolve" | "ChannelBoolean" => "Background", + "Merge" | "Dissolve" | "ChannelBoolean" | "Dimension.PlanarTracker" | "PlanarTracker" => { + "Background" + } "BitmapMask" => "Image", "Switch" => "Input0", "Fuse.Switch" | "Fuse.SwitchElse" => "Input1", diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index e910688b03638a2b39e45affb9bb75b1fe07909d..854fc5a3e092417cd139869f5faa14758877523e 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -210,7 +210,10 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("Fuse.SwitchElse", "Time, Routing & Utility", "Unit tests", "0.0%", "—"), ToolMeta("PipeRouter", "Time, Routing & Utility", "Suite comps", "0.0%", "—"), ToolMeta("Fuse.Wireless", "Time, Routing & Utility", "Suite comps", "0.0%", "—"), - ToolMeta("Tracker", "Time, Routing & Utility", "Suite comps", "0.0%", "Live optical tracking not implemented; evaluates baked `TrackerModifier` paths."), + ToolMeta("Tracker", "Time, Routing & Utility", "Suite comps", "0.0%", "Evaluates baked `TrackerModifier` paths; live NCC point & planar homography API in `engine::tracker`."), + ToolMeta("SurfaceTracker", "Time, Routing & Utility", "Suite comps", "0.1%–0.5%", "GPU 2D triangle-mesh warp (`FuTriMesh` + `WarpableCanvas`); live NCC & homography API in `engine::tracker`."), + ToolMeta("Dimension.PlanarTracker", "Time, Routing & Utility", "Unit tests", "0.0%", "Evaluates `Track` / `CornerPin` / `Steady` / `Stabilize` modes from baked `Matrix` tracks.", aliases=("PlanarTracker",)), + ToolMeta("Dimension.PlanarTransform", "Transform, Warp & Framing", "Unit tests", "0.0%", "Applies projective 3×3 `ToRef` homography splines (`Invert`, `Blend`, `EffectMask`).", aliases=("PlanarTransform",)), ToolMeta("MacroOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Internal subgraph is read-only in interactive Flow."), ToolMeta("GroupOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Internal subgraph is read-only in interactive Flow."), ToolMeta("Custom", "Time, Routing & Utility", "Suite comps", "0.1%–0.6%", "—"), @@ -248,9 +251,7 @@ class UnsupportedMeta: # Curated notes for prominent real-world unsupported / OFX / Resolve tools. UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( - UnsupportedMeta("SurfaceTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7), - UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), ) @@ -571,7 +572,7 @@ def build_markdown( fusion_builtin_total = 378 non_stock_builtin = { "GroupOperator", "MacroOperator", "PipeRouter", "InvertColor", - "PolylineStroke", "Multistroke", "OpticalFlow", "pDrag", + "PolylineStroke", "Multistroke", "OpticalFlow", "PlanarTracker", "PlanarTransform", "pDrag", "Fuse.AlphaWeightedNoise", "Fuse.CheckerPieceGenerator", "Fuse.Colorize", "Fuse.Cryptomatte", "Fuse.Crystallize", "Fuse.HexagonTiles", "Fuse.KScope", "Fuse.Outline", "Fuse.Switch", "Fuse.SwitchElse", "Fuse.XGlow", "Fuse.XfChroma",