diff --git a/crates/engine/src/eval/transform.rs b/crates/engine/src/eval/transform.rs index 390def500f619be576d6af9cb0e292551d6d5b8d..35034b63ef3b21801bf60cd943b689887d2d6c8a 100644 --- a/crates/engine/src/eval/transform.rs +++ b/crates/engine/src/eval/transform.rs @@ -1,48 +1,9 @@ use super::*; -/// Deterministic LuaJIT 2.x TW223 PRNG (`math.randomseed` + `math.random`) matching -/// Fusion `Duplicate.fuse` `RandomSeed` jitter draws. -struct LuaJitPrng { - u: [u64; 4], -} - -impl LuaJitPrng { - fn new(seed: f64) -> Self { - let mut r: u32 = 0x1109_0601; - let mut d = seed; - let mut u = [0u64; 4]; - for slot in &mut u { - let m = 1u64 << (r & 255); - r >>= 8; - d = d * std::f64::consts::PI + std::f64::consts::E; - let bits = d.to_bits(); - *slot = if bits < m { bits + m } else { bits }; - } - let mut rng = Self { u }; - for _ in 0..10 { - rng.next_u64(); - } - rng - } - - fn next_u64(&mut self) -> u64 { - let step = |z: u64, s1: u32, s2: u32, sh: u32, s3: u32| -> u64 { - let mask = u64::MAX << sh; - (((z << s1) ^ z) >> s2) ^ ((z & mask) << s3) - }; - self.u[0] = step(self.u[0], 31, 45, 1, 18); - self.u[1] = step(self.u[1], 19, 30, 6, 28); - self.u[2] = step(self.u[2], 24, 48, 9, 7); - self.u[3] = step(self.u[3], 21, 39, 17, 8); - self.u[0] ^ self.u[1] ^ self.u[2] ^ self.u[3] - } - - fn next_signed(&mut self) -> f32 { - let bits = (self.next_u64() & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000; - let u01 = f64::from_bits(bits) - 1.0; - (2.0 * u01 - 1.0) as f32 - } -} +mod dve; +mod warps_fuses; +#[cfg(test)] +mod tests; /// Follows bypassed nodes and routers upstream to the node that actually produces the image. pub(super) fn unwrap_passthrough(comp: &Comp, start_id: NodeId) -> NodeId { @@ -899,1794 +860,4 @@ impl Engine { ["ProcessRed", "ProcessGreen", "ProcessBlue", "ProcessAlpha"] .map(|c| if comp.eval_number(node, c, time, 1.0, &self.expr) > 0.5 { 0.0 } else { 1.0 }) } - - pub(super) fn eval_displace( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s)); - if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) { - return src; - } - let src = self.crop_to_canvas(enc, src); - let fg = match fg_id { - Some(id) => { - let fg = self.eval_node(comp, id, time, enc, visiting, stats); - self.crop_to_canvas(enc, fg) - } - None => self.dummy.clone(), - }; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - - // Without a map Displace is an identity warp; only MultiplyByMask still applies. - let mapped = if fg_id.is_some() { 1.0 } else { 0.0 }; - let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 }; - let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped; - let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped; - let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32; - let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32; - let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32; - let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32; - let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped; - let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped; - let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped; - // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus. - let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr); - let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs(); - let light_dir = [ - ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32, - ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32, - ]; - let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32; - let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - - let mut u = UniformParams::default(); - u.p[0] = [kind, xr, yr, xo]; - u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; - u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; - u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; - u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel]; - - let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - let dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - if light_power <= 1e-6 { - self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &dst, &u); - } else { - let displaced = self.alloc_tex_like(&src, src.depth, 0); - self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &displaced, &u); - // The Gaussian commutes with the central difference, so blur the height map once. - let sigma = if spread > 1e-4 { 0.3 + spread * src.size[0] as f32 / 240.0 } else { 0.0 }; - let height = self.blur_separable(enc, &fg, sigma / 0.45, sigma / 0.45, 0.0, 1.0); - let mut lit = u; - lit.p[5][0] = 1.0; - self.dispatch_op(enc, ShaderOp::Displace, &displaced.view, &height.view, mv, &dst, &lit); - } - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn eval_vortex( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - let angle_deg = comp.eval_number(node, "Angle", time, 180.0, &self.expr) as f32; - if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) { - return src; - } - let skip = self.process_skip(comp, node, time); - if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) { - return src; - } - 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 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 center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; - let power = comp.eval_number(node, "Power", time, 2.0, &self.expr).max(0.0) as f32; - - let mut u = UniformParams::default(); - u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, angle_deg.to_radians()]; - u.p[1] = [power, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; - u.p[2][0] = if mbm { 1.0 } else { 0.0 }; - u.p[3] = skip; - - let key = self.make_key(node, "Vortex", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - let dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Vortex, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - /// Row-major projective matrix (`h22 = 1`) taking the unit square's `(bl, br, tr, tl)` corners to the given quad. - fn quad_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> Option<[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 None; - } - let g = (sx * dy2 - sy * dx2) / denom; - let h = (dx1 * sy - dy1 * sx) / denom; - Some([ - 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, - ]) - } - - /// Adjugate (inverse up to scale) of a row-major 3x3 matrix. - fn adjugate(m: &[f64; 9]) -> [f64; 9] { - let [a, b, c, d, e, f, g, h, i] = *m; - [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] - } - - fn mat_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] { - std::array::from_fn(|k| (0..3).map(|j| a[k / 3 * 3 + j] * b[j * 3 + k % 3]).sum()) - } - - /// Inverse 3x3 projective homography mapping destination quad `(bl, br, tr, tl)` back to unit square `[0,1]^2`. - pub(super) fn quad_inverse_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] { - Self::quad_homography(bl, br, tr, tl) - .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |h| Self::adjugate(&h).map(|v| v as f32)) - } - - pub(super) fn eval_corner_positioner( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { - return src; - } - let src = self.crop_to_canvas(enc, src); - // Corner `Offset`s shift the matching source-UV corner against the offset, so positive values extend the sampled quad. - let corner = |name: &str, default: [f64; 2]| { - let p = comp.eval_point(node, name, time, default, &self.expr); - let off = [ - comp.eval_number(node, &format!("{name}OffsetX"), time, 0.0, &self.expr), - comp.eval_number(node, &format!("{name}OffsetY"), time, 0.0, &self.expr), - ]; - (p, off) - }; - let [(bl, bl_o), (br, br_o), (tr, tr_o), (tl, tl_o)] = [ - corner("BottomLeft", [0.0, 0.3]), - corner("BottomRight", [1.0, 0.1]), - corner("TopRight", [0.9, 1.0]), - corner("TopLeft", [0.1, 0.9]), - ]; - let src_uv = |u: [f64; 2], o: [f64; 2]| [u[0] - o[0], u[1] - o[1]]; - let (s_bl, s_br, s_tr, s_tl) = (src_uv([0.0, 0.0], bl_o), src_uv([1.0, 0.0], br_o), src_uv([1.0, 1.0], tr_o), src_uv([0.0, 1.0], tl_o)); - let h_inv = match (Self::quad_homography(bl, br, tr, tl), Self::quad_homography(s_bl, s_br, s_tr, s_tl)) { - (Some(out), Some(src)) => Self::mat_mul(&src, &Self::adjugate(&out)).map(|v| v as f32), - _ => [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], - }; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - - let mut u = UniformParams::default(); - u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]]; - u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]]; - u.p[2] = [h_inv[8], 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 comp.eval_number(node, "MappingType", time, 1.0, &self.expr) < 0.5 { - u.p[3][3] = 1.0; - let add_off = |p: [f64; 2], o: [f64; 2]| [p[0] + o[0], p[1] + o[1]]; - let quads = [ - [add_off(bl, bl_o), add_off(br, br_o)], - [add_off(tr, tr_o), add_off(tl, tl_o)], - [[0.0, 0.0], [1.0, 0.0]], - [[1.0, 1.0], [0.0, 1.0]], - ]; - for (row, pts) in quads.iter().enumerate() { - u.p[6 + row] = [pts[0][0] as f32, pts[0][1] as f32, pts[1][0] as f32, pts[1][1] as f32]; - } - } - u.p[5] = self.process_skip(comp, node, time); - let key = self.make_key(node, "CornerPos", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10])); - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - let dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - pub(super) fn eval_dve( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { - return src; - } - let skip = self.process_skip(comp, node, time); - if skip.iter().all(|&s| s > 0.5) { - return src; - } - let src = self.crop_to_canvas(enc, src); - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); - let z_pivot = comp.eval_number(node, "ZPivot", time, 0.0, &self.expr); - let z_move = comp.eval_number(node, "ZMove", time, 1.0, &self.expr); - let rx = comp.eval_number(node, "XRotation", time, 0.0, &self.expr).to_radians(); - let ry = comp.eval_number(node, "YRotation", time, 0.0, &self.expr).to_radians(); - let rz = comp.eval_number(node, "ZRotation", time, 0.0, &self.expr).to_radians(); - let x_shear = comp.eval_number(node, "XShear", time, 0.0, &self.expr); - let y_shear = comp.eval_number(node, "YShear", time, 0.0, &self.expr); - let rot_order = match node.static_str("RotationOrder") { - Some(s) => s, - None => match comp.eval_number(node, "RotationOrder", time, 5.0, &self.expr).round() as i32 { - 0 => "XYZ", - 1 => "XZY", - 2 => "YXZ", - 3 => "YZX", - 4 => "ZXY", - _ => "ZYX", - }, - }; - let aspect = src.canvas_size[0] as f64 / src.canvas_size[1].max(1) as f64; - - // Fusion DVE rotates card corners around Pivot (starting at z = +ZPivot so ZPivot > 0 moves - // the card away from the camera even at 0 rotation), applies XShear/YShear, and projects with 1 / (ZMove + z). - let (sx, cx) = rx.sin_cos(); - let (sy, cy) = ry.sin_cos(); - let (sz, cz) = rz.sin_cos(); - let project = |u_c: f64, v_c: f64| -> [f64; 2] { - let rx0 = u_c - pivot[0]; - let ry0 = (v_c - pivot[1]) / aspect; - let mut x = rx0 - x_shear * ry0; - let mut y = ry0 - y_shear * rx0; - let mut z = z_pivot; - for b in rot_order.bytes() { - match b { - b'X' | b'x' => { - let ny = y * cx + z * sx; - let nz = -y * sx + z * cx; - y = ny; - z = nz; - } - b'Y' | b'y' => { - let nx = x * cy - z * sy; - let nz = x * sy + z * cy; - x = nx; - z = nz; - } - b'Z' | b'z' => { - let nx = x * cz - y * sz; - let ny = x * sz + y * cz; - x = nx; - y = ny; - } - _ => {} - } - } - let z_cam = (z_move + z).max(0.05); - let inv_z = 1.0 / z_cam; - [ - pivot[0] + (x + (center[0] - 0.5) * z_move) * inv_z, - pivot[1] + ((y + (center[1] - 0.5) / aspect * z_move) * aspect) * inv_z, - ] - }; - let bl = project(0.0, 0.0); - let br = project(1.0, 0.0); - let tr = project(1.0, 1.0); - let tl = project(0.0, 1.0); - let h_inv = Self::quad_inverse_homography(bl, br, tr, tl); - - // Expand DoD when projected card corners extend beyond canvas (so downstream Merge preserves edges) - let cw = src.canvas_size[0].max(1) as f64; - let ch = src.canvas_size[1].max(1) as f64; - let mut min_x = cw; - let mut max_x = 0.0_f64; - let mut min_y = ch; - let mut max_y = 0.0_f64; - for c in [bl, br, tr, tl] { - let px = c[0] * cw; - let py = (1.0 - c[1]) * ch; - min_x = min_x.min(px); - max_x = max_x.max(px); - min_y = min_y.min(py); - max_y = max_y.max(py); - } - let pad = 2_i32; - let max_pad = 1024_i32; - let x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 }; - let y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 }; - let x1 = if max_x > cw + 0.25 { - (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad) - } else { - src.canvas_size[0] as i32 - }; - let y1 = if max_y > ch + 0.25 { - (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad) - } else { - src.canvas_size[1] as i32 - }; - let dst_origin = [x0, y0]; - let dst_size = [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32]; - let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size; - - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - - let mut u = UniformParams::default(); - u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]]; - u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]]; - u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; - u.p[3] = [0.0, if mbm { 1.0 } else { 0.0 }, 0.0, 0.0]; - if has_dst_dod { - u.p[4] = [ - dst_origin[0] as f32, - dst_origin[1] as f32, - src.canvas_size[0] as f32, - src.canvas_size[1] as f32, - ]; - } - u.p[5] = skip; - let key = self.make_key(node, "DVE", 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 mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key); - dst.tex_scale *= src.tex_scale; - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::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 camera_shake_offset( - time: f64, - x_dev: f64, - y_dev: f64, - r_dev: f64, - strength: f64, - speed: f64, - randomness: f64, - method: i32, - ) -> (f32, f32, f32) { - let x_dev = x_dev.clamp(0.0, 1.0); - let y_dev = y_dev.clamp(0.0, 1.0); - let r_dev = r_dev.clamp(0.0, 1.0); - let speed = speed.clamp(0.0, 1.0); - let randomness = randomness.clamp(0.0, 1.0); - - // Probed Fusion 21.1: angular rate is `0.3 / (1.1 - Speed)` rad/frame; - // X uses sin(rate*t) + Randomness offset, Y uses cos(sqrt(0.75)*rate*(t + dt_y)), - // Rotation uses 5 deg * sin(1.1*rate*(t + dt_r)) with dt_r ~ Randomness^2. - let rate = 0.3 / (1.1 - speed); - let wave_sin = |theta: f64| -> f64 { - match method { - 1 => 2.0 * (theta * 0.5).sin().abs() - 1.0, - 2 => if theta.sin() > 0.0 { 1.0 } else { -1.0 }, - _ => theta.sin(), - } - }; - let wave_cos = |theta: f64| -> f64 { - match method { - 1 => 2.0 * (theta * 0.5).cos().abs() - 1.0, - 2 => if theta.cos() > 0.0 { 1.0 } else { -1.0 }, - _ => theta.cos(), - } - }; - let time_band = |at_0: f64, at_1: f64, at_neg1: f64, steady: f64| -> f64 { - if time.abs() < 0.5 { - at_0 - } else if (time - 1.0).abs() < 0.5 { - at_1 - } else if (time + 1.0).abs() < 0.5 { - at_neg1 - } else { - steady - } - }; - let x_rand = time_band(0.3125, 0.44, 0.39, 1.0 / 3.0) * randomness; - let dt_y = time_band(-0.84, 1.10, -0.66, -1.547) * randomness; - let dt_r = time_band(0.83, 0.23, 0.25, 0.511) * (randomness * randomness); - - let dx = x_dev * strength * 0.2 * (wave_sin(rate * time) + x_rand); - let dy = y_dev * strength * 0.2 * wave_cos(0.75_f64.sqrt() * rate * (time + dt_y)); - let angle = (r_dev * strength * 5.0 * wave_sin(1.1 * rate * (time + dt_r))).to_radians() as f32; - (dx as f32, dy as f32, angle) - } - - pub(super) fn eval_camera_shake( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - let strength = comp.eval_number(node, "OverallStrength", time, 1.0, &self.expr); - if (blend <= 1e-6 || strength.abs() <= 1e-6) && !self.multiplies_by_mask(comp, node, time) { - return src; - } - let x_dev = comp.eval_number(node, "XDeviation", time, 0.2, &self.expr); - let y_dev = comp.eval_number(node, "YDeviation", time, 0.2, &self.expr); - let r_dev = comp.eval_number(node, "RotationDeviation", time, 0.2, &self.expr); - let speed = comp.eval_number(node, "Speed", time, 0.8, &self.expr); - let randomness = comp.eval_number(node, "Randomness", time, 0.5, &self.expr); - let method = comp.eval_number(node, "FrequencyMethod", time, 0.0, &self.expr).round() as i32; - let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32; - let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; - - let (dx, dy, angle) = Self::camera_shake_offset(time, x_dev, y_dev, r_dev, strength, speed, randomness, method); - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats); - let mask = mask.map(|m| self.crop_to_canvas(enc, m)); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [0.5 + dx, 0.5 + dy, 0.5, 0.5]; - u.p[1] = [1.0, 1.0, angle, edges]; - u.p[2] = [0.0, 0.0, blend, if mask.is_some() { 1.0 } else { 0.0 }]; - let invert = comp.eval_number(node, "InvertTransform", time, 0.0, &self.expr) > 0.5; - let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, if mbm { 1.0 } else { 0.0 }, if invert { 1.0 } else { 0.0 }]; - if src.has_dod() { - u.p[4] = [ - src.origin[0] as f32, - src.origin[1] as f32, - src.canvas_size[0] as f32, - src.canvas_size[1] as f32, - ]; - } - u.p[6] = self.process_skip(comp, node, time); - let out_size = src.canvas_size; - let key = self.make_key(node, "CamShake", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..7])); - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - let mut dst = self.alloc_tex(out_size, src.depth, key); - dst.tex_scale *= src.tex_scale; - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } - - pub(super) fn eval_duplicate( - &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("Background") - .or_else(|| node.connected_node("Input")) - .and_then(|s| comp.find_node(s)) - else { - return self.dummy.clone(); - }; - let base = self.eval_node(comp, src_id, time, enc, visiting, stats); - let copies_f = comp.eval_number(node, "Copies", time, 2.0, &self.expr).clamp(0.0, 64.0) as f32; - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - let mbm = self.multiplies_by_mask(comp, node, time); - let proc_b0 = comp.eval_number(node, "ProcessWhenBlendIs00", time, 0.0, &self.expr) > 0.5; - if blend <= 1e-6 && !mbm && !proc_b0 { - return base; - } - let skip = self.process_skip(comp, node, time); - if skip.iter().all(|&s| s > 0.5) && !mbm { - return base; - } - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); - let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5; - let fallback_size = comp.eval_number(node, "Size", time, 1.0, &self.expr); - let x_size = comp.eval_number(node, "XSize", time, fallback_size, &self.expr) as f32; - let y_size = if lock_size { x_size } else { comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32 }; - let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; - let fallback_gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr); - let red_gain = comp.eval_number(node, "RedGain", time, fallback_gain, &self.expr) as f32; - let green_gain = comp.eval_number(node, "GreenGain", time, fallback_gain, &self.expr) as f32; - let blue_gain = comp.eval_number(node, "BlueGain", time, fallback_gain, &self.expr) as f32; - let alpha_gain = comp.eval_number(node, "AlphaGain", time, fallback_gain, &self.expr) as f32; - let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32; - let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32; - let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr); - let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5; - let layer_blend = comp.eval_number(node, "LayerBlend", time, 1.0, &self.expr) as f32; - let random_seed = comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr); - let j_center = comp.eval_point(node, "JitterCenter", time, [0.0, 0.0], &self.expr); - let j_pivot = comp.eval_point(node, "JitterPivot", time, [0.0, 0.0], &self.expr); - let j_lock_size = comp.eval_number(node, "JitterLockSize", time, 1.0, &self.expr) > 0.5; - let j_x_size = comp.eval_number(node, "JitterXSize", time, 0.0, &self.expr) as f32; - let j_y_size = if j_lock_size { - j_x_size - } else { - comp.eval_number(node, "JitterYSize", time, 0.0, &self.expr) as f32 - }; - let j_angle = comp.eval_number(node, "JitterAngle", time, 0.0, &self.expr) as f32; - let j_red_gain = comp.eval_number(node, "JitterRedGain", time, 0.0, &self.expr) as f32; - let j_green_gain = comp.eval_number(node, "JitterGreenGain", time, 0.0, &self.expr) as f32; - let j_blue_gain = comp.eval_number(node, "JitterBlueGain", time, 0.0, &self.expr) as f32; - let j_alpha_gain = comp.eval_number(node, "JitterAlphaGain", time, 0.0, &self.expr) as f32; - let j_layer_blend = comp.eval_number(node, "JitterLayerBlend", time, 0.0, &self.expr) as f32; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let params = [ - copies_f, - center[0] as f32, - center[1] as f32, - pivot[0] as f32, - pivot[1] as f32, - x_size, - y_size, - angle_deg, - red_gain, - green_gain, - blue_gain, - alpha_gain, - sub_add, - burn_in, - blend, - time_off as f32, - if merge_under { 1.0 } else { 0.0 }, - if mbm { 1.0 } else { 0.0 }, - if proc_b0 { 1.0 } else { 0.0 }, - skip[0], - skip[1], - skip[2], - skip[3], - layer_blend, - random_seed as f32, - j_center[0] as f32, - j_center[1] as f32, - j_pivot[0] as f32, - j_pivot[1] as f32, - if j_lock_size { 1.0 } else { 0.0 }, - j_x_size, - j_y_size, - j_angle, - j_red_gain, - j_green_gain, - j_blue_gain, - j_alpha_gain, - j_layer_blend, - ]; - let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], ¶ms); - 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 need_post = mask.is_some() - || (blend - 1.0).abs() > 1e-5 - || skip.iter().any(|&s| s > 0.5); - - let mut accum = if copies_f <= 1.0 + 1e-4 { - let w = copies_f.clamp(0.0, 1.0); - if w >= 1.0 - 1e-4 { - base.clone() - } else { - let scaled = self.alloc_tex_like(&base, base.depth, if need_post { 0 } else { key }); - let mut u = UniformParams::default(); - u.p[0] = [0.5, 0.5, 1.0, 0.0]; - u.p[1] = [w, 1.0, 0.0, 0.0]; - u.p[3] = [0.0, 0.0, base.canvas_size[0] as f32, base.canvas_size[1] as f32]; - u.p[6] = [0.0, 1.0, 0.0, 0.0]; - let zero = create_texture(&self.device, base.size, 0); - self.dispatch_op(enc, ShaderOp::Merge, &zero.view, &base.view, &self.dummy.view, &scaled, &u); - scaled - } - } else { - let full = copies_f.floor() as i32; - let frac = copies_f - full as f32; - let n_extra = (copies_f.ceil() as i32 - 1).max(1); - let dx = center[0] as f32 - 0.5; - let dy = center[1] as f32 - 0.5; - let any_jitter = j_center[0].abs() > 1e-6 - || j_center[1].abs() > 1e-6 - || j_pivot[0].abs() > 1e-6 - || j_pivot[1].abs() > 1e-6 - || j_x_size.abs() > 1e-6 - || j_y_size.abs() > 1e-6 - || j_angle.abs() > 1e-6 - || j_red_gain.abs() > 1e-6 - || j_green_gain.abs() > 1e-6 - || j_blue_gain.abs() > 1e-6 - || j_alpha_gain.abs() > 1e-6 - || j_layer_blend.abs() > 1e-6; - let mut prng = any_jitter.then(|| LuaJitPrng::new(random_seed)); - let mut cur_acc = base.clone(); - for i in 1..=n_extra { - let fi = i as f32; - let draws = if let Some(rng) = prng.as_mut() { - [ - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - rng.next_signed(), - ] - } else { - [0.0; 12] - }; - let d_ys = if j_lock_size { draws[4] } else { draws[5] }; - let mut copy_src = if time_off.abs() > 1e-4 { - self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats) - } else { - base.clone() - }; - let layer_w_base = (layer_blend + j_layer_blend * draws[11]).max(0.0); - let layer_w_raw = if i == n_extra && frac > 1e-4 { - layer_w_base * frac - } else { - layer_w_base - }; - let (layer_scale_fg, layer_w) = if layer_w_raw > 1.0 + 1e-4 { - (layer_w_raw, 1.0) - } else { - (1.0, layer_w_raw) - }; - let rg_i = (red_gain.powi(i) + j_red_gain * draws[7]).max(0.0) * layer_scale_fg; - let gg_i = (green_gain.powi(i) + j_green_gain * draws[8]).max(0.0) * layer_scale_fg; - let bg_i = (blue_gain.powi(i) + j_blue_gain * draws[9]).max(0.0) * layer_scale_fg; - if (rg_i - 1.0).abs() > 1e-4 || (gg_i - 1.0).abs() > 1e-4 || (bg_i - 1.0).abs() > 1e-4 { - let gained = self.alloc_tex_like(©_src, copy_src.depth, 0); - let mut ug = UniformParams::default(); - ug.p[0] = [rg_i, gg_i, bg_i, 0.0]; - ug.p[1] = [0.0, 0.0, 0.0, 1.0]; - ug.p[2] = [1.0, 1.0, 1.0, 1.0]; - ug.p[4] = [0.0, 1.0, 1.0, 0.0]; - ug.p[9] = [1.0, 0.0, 1.0, 0.0]; - self.dispatch_op(enc, ShaderOp::ColorGain, ©_src.view, &self.dummy.view, &self.dummy.view, &gained, &ug); - copy_src = gained; - } - let ag_raw = (alpha_gain.powi(i) + j_alpha_gain * draws[10]).max(0.0) * layer_scale_fg; - let ag_i = if ag_raw > 1.0 + 1e-4 { - let gained_a = self.alloc_tex_like(©_src, copy_src.depth, 0); - let mut ubc = UniformParams::default(); - ubc.p[0] = [ag_raw, 0.0, 1.0, 0.0]; - ubc.p[1] = [0.0, 1.0, 0.0, 1.0]; - ubc.p[2] = [0.0, 0.0, 0.0, 1.0]; - ubc.p[3] = [0.0, 0.0, 0.0, 1.0]; - ubc.p[4] = [1.0, 1.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Bc, ©_src.view, &self.dummy.view, &self.dummy.view, &gained_a, &ubc); - copy_src = gained_a; - 1.0 - } else { - ag_raw.clamp(0.0, 1.0) - }; - let cx = 0.5 + dx * fi + (j_center[0] as f32) * draws[0]; - let cy = 0.5 + dy * fi + (j_center[1] as f32) * draws[1]; - let px = pivot[0] as f32 + (j_pivot[0] as f32) * draws[2]; - let py = pivot[1] as f32 + (j_pivot[1] as f32) * draws[3]; - let sc_x = (x_size.powi(i) + j_x_size * draws[4]).max(1e-4); - let sc_y = (y_size.powi(i) + j_y_size * d_ys).max(1e-4); - let ang = (angle_deg * fi + j_angle * draws[6]).to_radians(); - let need_xform = (sc_x - sc_y).abs() > 1e-4 - || (px - 0.5).abs() > 1e-4 - || (py - 0.5).abs() > 1e-4; - - let is_last = i == n_extra; - let next = self.alloc_tex_like(&base, base.depth, if is_last && !need_post { key } else { 0 }); - let mut u = UniformParams::default(); - if need_xform { - let xformed = self.alloc_tex_like(©_src, copy_src.depth, 0); - let mut ut = UniformParams::default(); - ut.p[0] = [cx, cy, px, py]; - ut.p[1] = [sc_x, sc_y, ang, 0.0]; - ut.p[2] = [0.0, 0.0, 1.0, 0.0]; - ut.p[3] = [0.0, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Transform, ©_src.view, &self.dummy.view, &self.dummy.view, &xformed, &ut); - copy_src = xformed; - u.p[0] = [0.5, 0.5, 1.0, 0.0]; - } else { - u.p[0] = [cx, cy, sc_x, ang]; - } - u.p[1] = [layer_w, ag_i, 0.0, 0.0]; - u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }]; - u.p[3] = [0.0, 0.0, copy_src.canvas_size[0] as f32, copy_src.canvas_size[1] as f32]; - u.p[6] = [burn_in, sub_add, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::Merge, &cur_acc.view, ©_src.view, &self.dummy.view, &next, &u); - cur_acc = next; - } - cur_acc - }; - - if need_post { - let out = self.alloc_tex_like(&base, base.depth, key); - let mut ud = UniformParams::default(); - ud.p[0] = [ - 1.0, - blend, - if mask.is_some() { 1.0 } else { 0.0 }, - if mask_inv { 1.0 } else { 0.0 }, - ]; - ud.p[1] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; - ud.p[2] = [1.0 - skip[0], 1.0 - skip[1], 1.0 - skip[2], 1.0 - skip[3]]; - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::Dissolve, &base.view, &accum.view, mv, &out, &ud); - accum = out; - } - - self.cache.insert(key, accum.clone(), node.id, frame_i); - accum - } - - pub(super) fn eval_kscope( - &mut self, - comp: &Comp, - node: &Node, - time: f64, - frame_i: i64, - enc: &mut wgpu::CommandEncoder, - visiting: &mut HashSet<(NodeId, i64)>, - stats: &mut EvalStats, - ) -> CachedTexture { - let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { - return self.dummy.clone(); - }; - let src = self.eval_node(comp, src_id, time, enc, visiting, stats); - let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; - if blend <= 1e-6 { - return src; - } - let src = self.crop_to_canvas(enc, src); - let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); - let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32; - let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); - let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians(); - let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32; - let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32; - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); - let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); - - let mut u = UniformParams::default(); - u.p[0] = [center[0] as f32, center[1] as f32, slices, angle]; - u.p[1] = [cap_angle, scale, edges, blend]; - u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0]; - - let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); - if let Some(hit) = self.cache.get(key, node.id, frame_i) { - stats.cache_hits += 1; - return hit; - } - stats.cache_misses += 1; - stats.nodes_evaluated += 1; - let dst = self.alloc_tex_like(&src, src.depth, key); - let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); - self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u); - self.cache.insert(key, dst.clone(), node.id, frame_i); - dst - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Engine; - - #[test] - fn test_fuse_kscope_6_slice_symmetry() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 0.0, }, - TopRightBlue = Input { Value = 1.0, }, - }, - }, - KS1 = Fuse.KScope { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - Slices = Input { Value = 6, }, - Scale = Input { Value = 1.0, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse KScope comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let node_id = comp.find_node("KS1").expect("KS1"); - let (tex, _) = eng.evaluate(&comp, node_id, 0.0); - let rgba = eng.readback_rgba(&tex).expect("readback KScope"); - let [w, h] = tex.size; - assert_eq!((w, h), (128, 128)); - // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact! - let px = |x: usize, y: usize| -> [u8; 4] { - let i = (y * 128 + x) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - let a = px(64 + 28, 64 + 12); - let b = px(64 + 28, 63 - 12); - for c in 0..3 { - let diff = (a[c] as i32 - b[c] as i32).abs(); - assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}"); - } - } - - #[test] - fn test_upstream_infinite_edge_mode_propagates_through_point_ops_and_disabled_dirblur() { - let src = r#"Composition { - CurrentTime = 3050, - RenderRange = { 3000, 3100 }, - GlobalRange = { 3000, 3100 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - TopLeftRed = Input { Value = 0.2, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - FG1 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 0.0, }, - TopRightBlue = Input { Value = 1.0, }, - }, - }, - Merge23 = Merge { - Inputs = { - Background = Input { SourceOp = "BG1", Source = "Output", }, - Foreground = Input { SourceOp = "FG1", Source = "Output", }, - Edges = Input { Value = 3, }, - }, - }, - CC1 = ColorCorrector { - Inputs = { - Input = Input { SourceOp = "Merge23", Source = "Output", }, - }, - }, - BG2 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - CC_BG = ColorCorrector { - Inputs = { - Input = Input { SourceOp = "BG2", Source = "Output", }, - }, - }, - Merge24 = Merge { - Inputs = { - Background = Input { SourceOp = "CC_BG", Source = "Output", }, - Foreground = Input { SourceOp = "CC1", Source = "Output", }, - }, - }, - Infrared = ColorCurves { - Inputs = { - Input = Input { SourceOp = "Merge24", Source = "Output", }, - }, - }, - CC2 = ColorCorrector { - Inputs = { - Input = Input { SourceOp = "Infrared", Source = "Output", }, - }, - }, - DirBlur = DirectionalBlur { - Inputs = { - Blend = Input { Value = 0.0, }, - Length = Input { Value = 0.05, }, - Input = Input { SourceOp = "CC2", Source = "Output", }, - }, - }, - DirBlurActive = DirectionalBlur { - Inputs = { - Blend = Input { Value = 1.0, }, - Length = Input { Value = 0.05, }, - Input = Input { SourceOp = "CC2", Source = "Output", }, - }, - }, - XF = Transform { - Inputs = { - Center = Input { Value = { 0.75, 0.5 }, }, - Edges = Input { Value = 2, }, - Input = Input { SourceOp = "DirBlur", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse mirror propagation comp"); - let expr = ExprEngine::new(); - let dir_blur_id = comp.find_node("DirBlur").expect("DirBlur"); - let dir_blur_active_id = comp.find_node("DirBlurActive").expect("DirBlurActive"); - assert_eq!( - upstream_infinite_edge_mode(&comp, dir_blur_id, 3050.0, &expr), - Some(3.0), - "Merge(Edges=3) should propagate through point ops, Merge(BG=CC(Background)), and DirectionalBlur(Blend=0)" - ); - assert_eq!( - upstream_infinite_edge_mode(&comp, dir_blur_active_id, 3050.0, &expr), - None, - "Active DirectionalBlur (Blend=1) should stop RoI edge-mode propagation" - ); - - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let xf_id = comp.find_node("XF").expect("XF"); - let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0); - let rgba = eng.readback_rgba(&tex).expect("readback XF"); - // Center.x = 0.75 shifts image right by 16px: x=0..16 samples mirrored x=16..0 - // rather than duplicating x=0! On a red->blue gradient, x=2 should be noticeably - // bluer than x=15 (which sits right next to the red left edge). - let px = |x: usize| -> [u8; 4] { - let i = (32 * 64 + x) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - let far_left = px(2); - let seam = px(15); - assert!( - far_left[2] > seam[2] + 20, - "expected mirrored left edge (far_left={far_left:?} bluer than seam={seam:?}), not Duplicate streak" - ); - } - - #[test] - fn test_merge_mirror_edges_phase_with_cropped_fg_and_offset() { - // Reproduces crazy_3050's Merge23(Edges=3, Center={0.125,0.5}, Size=0.75, cropped FG) -> - // CC1 -> Merge24(Edges=0) -> ColorCurves -> CC2 -> DirBlur(Blend=0) -> Transform(Edges=2, Center={0.6875,0.5}). - // Shifting Transform right by 24px (0.1875 * 128) pulls u < 0 from upstream: - // FG is a 32x128 Red->Blue horizontal gradient centered at x=16 with Size=0.75 (24px wide -> x=[4..28]). - // Mirroring FG across its own left edge x=4 means canvas x=-4 (output x=20) samples near Red (x=12), - // while output x=8 (canvas x=-16) reflects past x=4..28 to Blue, NOT BG1 green or canvas x=0 mirror! - let src = r#"Composition { - CurrentTime = 3050, - RenderRange = { 3000, 3100 }, - GlobalRange = { 3000, 3100 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - TopLeftRed = Input { Value = 0.0, }, - TopLeftGreen = Input { Value = 1.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - FG1 = Background { - Inputs = { - Width = Input { Value = 32, }, - Height = Input { Value = 128, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopRightRed = Input { Value = 0.0, }, - TopRightGreen = Input { Value = 0.0, }, - TopRightBlue = Input { Value = 1.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - Merge23 = Merge { - Inputs = { - Background = Input { SourceOp = "BG1", Source = "Output", }, - Foreground = Input { SourceOp = "FG1", Source = "Output", }, - Center = Input { Value = { 0.125, 0.5 }, }, - Size = Input { Value = 0.75, }, - Edges = Input { Value = 3, }, - }, - }, - CC1 = ColorCorrector { - Inputs = { - Input = Input { SourceOp = "Merge23", Source = "Output", }, - }, - }, - BG2 = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - Merge24 = Merge { - Inputs = { - Background = Input { SourceOp = "BG2", Source = "Output", }, - Foreground = Input { SourceOp = "CC1", Source = "Output", }, - }, - }, - DirBlur = DirectionalBlur { - Inputs = { - Blend = Input { Value = 0.0, }, - Length = Input { Value = 0.05, }, - Input = Input { SourceOp = "Merge24", Source = "Output", }, - }, - }, - XF = Transform { - Inputs = { - Center = Input { Value = { 0.6875, 0.5 }, }, - Edges = Input { Value = 2, }, - Input = Input { SourceOp = "DirBlur", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse offset Merge(Edges=3) comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let xf_id = comp.find_node("XF").expect("XF"); - let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0); - let rgba = eng.readback_rgba(&tex).expect("readback XF"); - let px = |x: usize| -> [u8; 4] { - let i = (64 * 128 + x) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - // Output x=20 corresponds to canvas x=-4 (mirrored around FG left edge x=4 -> canvas x=12, red-dominant). - // Output x=4 corresponds to canvas x=-20 (mirrors onto far side of FG -> blue-dominant). - // Crucially, green from BG1 must NOT appear at x < 24 (canvas x < 0)! - let out_near_left_fg = px(20); - let out_far_mirrored = px(4); - assert!( - out_near_left_fg[1] < 20 && out_far_mirrored[1] < 20, - "BG1 green must be transparent outside [0,W] (got near={out_near_left_fg:?}, far={out_far_mirrored:?})" - ); - assert!( - out_far_mirrored[2] > out_near_left_fg[2] + 60, - "cropped FG Mirror phase should reflect across FG bounds x=4 (far={out_far_mirrored:?} bluer than near={out_near_left_fg:?})" - ); - } - - #[test] - fn test_dve_pivot_center_zmove_and_dod_expansion() { - // 64x48 foreground transformed by DVE (ZMove=0.75 zooms card larger than 64x48) - // and merged over 128x128 black background must preserve pixels outside 64x48 via DoD! - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - FG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 48, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.5, }, - TopLeftBlue = Input { Value = 0.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - DVE1 = DVE { - Inputs = { - Input = Input { SourceOp = "FG", Source = "Output", }, - XRotation = Input { Value = 15.0, }, - YRotation = Input { Value = -25.0, }, - ZRotation = Input { Value = 10.0, }, - ZMove = Input { Value = 0.75, }, - Pivot = Input { Value = { 0.3, 0.6 }, }, - Center = Input { Value = { 0.45, 0.55 }, }, - }, - }, - Out = Merge { - Inputs = { - Background = Input { SourceOp = "BG", Source = "Output", }, - Foreground = Input { SourceOp = "DVE1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let out_id = comp.find_node("Out").unwrap(); - let (out_tex, stats) = eng.evaluate(&comp, out_id, 0.0); - assert!(stats.unsupported_nodes.is_empty()); - let px = eng.readback_rgba(&out_tex).unwrap(); - // Outside original 64x48 centered box (x in 32..96, y in 40..88) at x=110, y=64 - // must still show orange card due to ZMove=0.75 + YRotation=-25 DoD expansion! - let expanded_right = (64 * 128 + 110) * 4; - assert!( - px[expanded_right] > 200 && px[expanded_right + 1] > 100, - "expected expanded orange DVE region outside 64x48 at x=110, got {:?}", - &px[expanded_right..expanded_right + 4] - ); - } - - #[test] - fn transform_multiply_by_mask_zeroes_outside_effect_mask() { - let src = |mbm: u8| { - format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, - Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }}, - MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, - XF = Transform {{ Inputs = {{ MultiplyByMask = Input {{ Value = {mbm}, }}, - Input = Input {{ SourceOp = "BG", Source = "Output", }}, - EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }}, - }} }}"# - ) - }; - if Engine::new_headless().is_err() { - return; - } - let px = |mbm: u8, x: usize, y: usize| { - let mut eng = Engine::new_headless().unwrap(); - let comp = Comp::from_fusion_str(&src(mbm)).unwrap(); - let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let i = (y * 64 + x) * 4; - [rgba[i], rgba[i + 3]] - }; - assert_eq!(px(0, 2, 2), [255, 255], "effect mask only blends; identity transform is unchanged"); - assert_eq!(px(1, 2, 2), [0, 0], "outside the mask is zeroed"); - assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept"); - } - - #[test] - fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() { - // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask. - let cases = [ - ("Drip", "Amplitude = Input { Value = 0, },", false), - ("Dent", "Strength = Input { Value = 0, },", false), - ("Vortex", "Angle = Input { Value = 0, },", false), - ("Displace", "", false), - ("Drip", "Blend = Input { Value = 0, },", true), - ("Vortex", "Blend = Input { Value = 0, },", true), - ]; - if Engine::new_headless().is_err() { - return; - } - for (kind, inputs, survives) in cases { - let src = format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, - Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }}, - MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, - FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs} - Input = Input {{ SourceOp = "BG", Source = "Output", }}, - EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }}, - }} }}"# - ); - let comp = Comp::from_fusion_str(&src).unwrap(); - let mut eng = Engine::new_headless().unwrap(); - let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3]; - assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask"); - assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask"); - } - } - - #[test] - fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() { - // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond - // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped. - let lit = |inputs: &str| -> [u8; 4] { - let src = format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, - TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, - TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, - Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, - D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs} - Input = Input {{ SourceOp = "Flat", Source = "Output", }}, - Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }}, - }} }}"# - ); - let comp = Comp::from_fusion_str(&src).unwrap(); - let mut eng = Engine::new_headless().unwrap(); - let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let i = (32 * 64 + 32) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - if Engine::new_headless().is_err() { - return; - } - let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}"); - // Ramp slope per tap pair is 2/63 of full scale = ~8 levels. - near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8); - near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8); - near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128); - // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively. - near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8); - // LightChannel 4 lights every channel from alpha, which is flat. - near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128); - near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128); - } - - #[test] - fn transform_invert_transform_shifts_the_opposite_way() { - let src = |invert: u8| { - format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, - TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, - TopRightRed = Input {{ Value = 0, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 0, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, - XF = Transform {{ Inputs = {{ InvertTransform = Input {{ Value = {invert}, }}, - Center = Input {{ Value = {{ 0.75, 0.5 }}, }}, Input = Input {{ SourceOp = "BG", Source = "Output", }}, }}, }}, - }} }}"# - ) - }; - if Engine::new_headless().is_err() { - return; - } - let mid_row = |invert: u8| { - let mut eng = Engine::new_headless().unwrap(); - let comp = Comp::from_fusion_str(&src(invert)).unwrap(); - let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let i = (32 * 64 + 32) * 4; - [rgba[i], rgba[i + 1]] - }; - let [r, g] = mid_row(0); - assert!(r > g + 60, "Center +0.25 moves the left (red) side under the middle: {r} {g}"); - let [r, g] = mid_row(1); - assert!(g > r + 60, "InvertTransform pulls the right (green) side under the middle: {r} {g}"); - } - - #[test] - fn transform_dod_preserved_through_bc_into_merge() { - // 64x64 bright red FG is translated left off-canvas by Transform (Center.x = -0.25 -> shift = -0.75 * 64 = -48px), - // passed through BrightnessContrast (unmasked), then merged back onto a 128x64 canvas at Center.x = 0.75. - // Without Transform DoD + unmasked BC DoD preservation, x in [-48..0] would be clipped at x=0! - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 0 }, - GlobalRange = { 0, 0 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 64, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - FG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftGreen = Input { Value = 0.0, }, - TopLeftBlue = Input { Value = 0.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - XF = Transform { - Inputs = { - Input = Input { SourceOp = "FG", Source = "Output", }, - Center = Input { Value = { -0.25, 0.5 }, }, - }, - }, - BC = BrightnessContrast { - Inputs = { - Input = Input { SourceOp = "XF", Source = "Output", }, - Gain = Input { Value = 0.8, }, - Lift = Input { Value = -0.2, }, - Gamma = Input { Value = 1.5, }, - }, - }, - M = Merge { - Inputs = { - Background = Input { SourceOp = "BG", Source = "Output", }, - Foreground = Input { SourceOp = "BC", Source = "Output", }, - Center = Input { Value = { 0.75, 0.5 }, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse Transform DoD comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let (tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - // Merge places BC's 64x64 logical center (32) at 0.75 * 128 = 96, so x=0 of BC lands at 64. - // The shifted red square spans x in [-48..16) in BC, which lands at [16..80) on BG! - // At x=32 (left of BC's x=0 at 64), red pixels must survive! - let i = (32 * 128 + 32) * 4; - assert!(rgba[i] > 150 && rgba[i + 1] == 0, "expected off-canvas shifted FG via DoD at x=32, got {:?}", &rgba[i..i + 4]); - } - - #[test] - fn vortex_dod_input_and_effect_mask_align_to_canvas() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 0 }, - GlobalRange = { 0, 0 }, - Tools = ordered() { - Stripe = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - TopRightBlue = Input { Value = 1.0, }, - TopRightAlpha = Input { Value = 1.0, }, - }, - }, - XF = DVE { - Inputs = { - Input = Input { SourceOp = "Stripe", Source = "Output", }, - Center = Input { Value = { 0.25, 0.5 }, }, - }, - }, - Mask = RectangleMask { - Inputs = { - MaskWidth = Input { Value = 64, }, - MaskHeight = Input { Value = 64, }, - Center = Input { Value = { 0.75, 0.5 }, }, - Width = Input { Value = 0.25, }, - Height = Input { Value = 1.0, }, - }, - }, - V = Vortex { - Inputs = { - Input = Input { SourceOp = "XF", Source = "Output", }, - EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, - Angle = Input { Value = 180.0, }, - Size = Input { Value = 0.8, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse Vortex DoD comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let (v_tex, _) = eng.evaluate(&comp, comp.find_node("V").unwrap(), 0.0); - let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); - let v_px = eng.readback_rgba(&v_tex).unwrap(); - let xf_px = eng.readback_rgba(&xf_tex).unwrap(); - // Left of Mask (x in 0..40) must be identical to XF (Vortex must not warp outside canvas mask). - for x in 0..40 { - let i = (32 * 64 + x) * 4; - assert_eq!(&v_px[i..i + 4], &xf_px[i..i + 4], "Vortex mask misaligned at x={x}"); - } - } - - #[test] - fn camera_shake_dod_input_and_effect_mask_align_to_canvas() { - let src = r#"Composition { - CurrentTime = 2, - RenderRange = { 0, 5 }, - GlobalRange = { 0, 5 }, - Tools = ordered() { - Stripe = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Type = Input { Value = FuID { "Horizontal" }, }, - TopLeftRed = Input { Value = 1.0, }, - TopLeftAlpha = Input { Value = 1.0, }, - TopRightBlue = Input { Value = 1.0, }, - TopRightAlpha = Input { Value = 1.0, }, - }, - }, - XF = DVE { - Inputs = { - Input = Input { SourceOp = "Stripe", Source = "Output", }, - Center = Input { Value = { 0.25, 0.5 }, }, - }, - }, - Mask = RectangleMask { - Inputs = { - Center = Input { Value = { 0.875, 0.5 }, }, - Width = Input { Value = 0.25, }, - Height = Input { Value = 1.0, }, - }, - }, - CS = CameraShake { - Inputs = { - Input = Input { SourceOp = "XF", Source = "Output", }, - EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, - XDeviation = Input { Value = 0.25, }, - YDeviation = Input { Value = 0.25, }, - RotationDeviation = Input { Value = 25.0, }, - OverallStrength = Input { Value = 1.0, }, - Speed = Input { Value = 3.0, }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse CameraShake DoD comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 2.0); - let (cs_tex, _) = eng.evaluate(&comp, comp.find_node("CS").unwrap(), 2.0); - assert_eq!(cs_tex.size, [64, 64]); - assert_eq!(cs_tex.origin, [0, 0]); - assert_eq!(cs_tex.canvas_size, [64, 64]); - let xf_px = eng.readback_rgba(&xf_tex).unwrap(); - let cs_px = eng.readback_rgba(&cs_tex).unwrap(); - // Mask covers [48..64), so x in [0..46) must match XF on canvas exactly. - for x in 0..46 { - let i = (32 * 64 + x) * 4; - assert_eq!(&cs_px[i..i + 4], &xf_px[i..i + 4], "CameraShake mask misaligned at x={x}"); - } - } - #[test] - fn corner_positioner_defaults_to_fusion_quad_and_offsets_extend_the_sampled_quad() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, - CP = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, }, - CPO = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, TopLeftOffsetX = Input { Value = 1, }, }, }, - }, }"#; - let comp = Comp::from_fusion_str(src).expect("parse corner positioner comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let alpha = |eng: &mut Engine, name: &str, x: usize, y: usize| { - let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); - eng.readback_rgba(&tex).unwrap()[(y * 64 + x) * 4 + 3] - }; - // Default quad TL(0.1, 0.9) .. BR(1, 0.1): the bottom-left canvas corner lies outside, the center inside. - assert_eq!(alpha(&mut eng, "CP", 1, 62), 0); - assert_eq!(alpha(&mut eng, "CP", 32, 32), 255); - // An X offset of 1 samples the source from u = -1, so the top-left of the quad turns transparent. - assert_eq!(alpha(&mut eng, "CPO", 8, 8), 0); - assert_eq!(alpha(&mut eng, "CPO", 56, 40), 255); - } - - fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec, crate::cache::EvalStats) { - let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t); - (eng.readback_rgba(&tex).unwrap(), stats) - } - - #[test] - fn corner_positioner_linear_quad_rotated_90_degrees_is_not_blank() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, - CP = CornerPositioner { Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - MappingType = Input { Value = 0, }, - BottomLeft = Input { Value = { 0.7, 0.3 }, }, - BottomRight = Input { Value = { 0.7, 0.7 }, }, - TopRight = Input { Value = { 0.3, 0.7 }, }, - TopLeft = Input { Value = { 0.3, 0.3 }, }, - }, }, - }, }"#; - let comp = Comp::from_fusion_str(src).expect("parse comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0); - let a = |x: usize, y: usize| px[(y * 64 + x) * 4 + 3]; - assert_eq!(a(32, 32), 255, "vertical top/bottom edges still map the quad interior"); - assert_eq!(a(4, 4), 0, "outside the quad stays transparent"); - } - - #[test] - fn corner_positioner_multiply_by_mask_applies_at_zero_blend() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, - M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, }, - CP = CornerPositioner { Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - EffectMask = Input { SourceOp = "M", Source = "Mask", }, - MultiplyByMask = Input { Value = 1, }, - Blend = Input { Value = 0, }, - }, }, - }, }"#; - let comp = Comp::from_fusion_str(src).expect("parse comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0); - assert_eq!(px[(32 * 64 + 32) * 4 + 3], 0, "Blend=0 with MultiplyByMask zeroes the frame"); - } - - #[test] - fn effect_mask_channel_remap_is_applied_and_cached() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, - M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, }, - Plain = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, }, }, - Half = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, MaskHigh = Input { Value = 2, }, }, }, - }, }"#; - let comp = Comp::from_fusion_str(src).expect("parse comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let center = (32 * 64 + 32) * 4 + 3; - assert_eq!(eval_px(&comp, &mut eng, "Plain", 0.0).0[center], 255); - let (half, _) = eval_px(&comp, &mut eng, "Half", 0.0); - assert!((half[center] as i32 - 128).abs() <= 2, "MaskHigh=2 halves mask coverage: {}", half[center]); - let (_, stats) = eval_px(&comp, &mut eng, "Half", 1.0); - assert_eq!(stats.nodes_evaluated, 0, "remapped mask and Transform come from the cache on a static frame"); - } - - #[test] - fn displace_light_with_full_spread_is_a_two_tap_pass() { - let src = |light: f64| format!(r#"Composition {{ Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, - Ramp = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, - TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, - TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, - D = Displace {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Foreground = Input {{ SourceOp = "Ramp", Source = "Output", }}, - LightPower = Input {{ Value = {light}, }}, Spread = Input {{ Value = 1, }}, RefractionStrength = Input {{ Value = 0, }}, }}, }}, - }}, }}"#); - let Ok(mut eng) = Engine::new_headless() else { return }; - let lit = Comp::from_fusion_str(&src(1.0)).expect("parse lit comp"); - let flat = Comp::from_fusion_str(&src(0.0)).expect("parse flat comp"); - let (lit_px, _) = eval_px(&lit, &mut eng, "D", 0.0); - let (flat_px, _) = eval_px(&flat, &mut eng, "D", 0.0); - assert!(lit_px.iter().zip(&flat_px).any(|(a, b)| a.abs_diff(*b) > 2), "slope lighting must change the image"); - } - - #[test] - fn vortex_clamp_edges_and_process_skip_with_mbm() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, - TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, - M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, }, - V = Vortex { Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - Size = Input { Value = 2.0, }, - EffectMask = Input { SourceOp = "M", Source = "Mask", }, - MultiplyByMask = Input { Value = 1, }, - ProcessRed = Input { Value = 0, }, - }, }, - } }"#; - let comp = Comp::from_fusion_str(src).expect("parse vortex comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let (px, _) = eval_px(&comp, &mut eng, "V", 0.0); - // Outside mask must be zeroed even for ProcessRed=0; inside mask stays solid red. - assert_eq!(&px[0..4], &[0, 0, 0, 0]); - let center = (32 * 64 + 32) * 4; - assert_eq!(&px[center..center + 4], &[255, 0, 0, 255]); - } - - #[test] - fn dve_rotation_order_zpivot_shear_and_alpha_mode() { - let src = |rot_ord: u8, zpivot: f64, xshear: f64, alpha_mode: u8| format!(r#"Composition {{ Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 0.5, }}, }}, }}, - D = DVE {{ Inputs = {{ - Input = Input {{ SourceOp = "BG", Source = "Output", }}, - RotationOrder = Input {{ Value = {rot_ord}, }}, - XRotation = Input {{ Value = 25, }}, - YRotation = Input {{ Value = 35, }}, - ZRotation = Input {{ Value = 40, }}, - ZPivot = Input {{ Value = {zpivot}, }}, - XShear = Input {{ Value = {xshear}, }}, - AlphaMode = Input {{ Value = {alpha_mode}, }}, - }}, }}, - }} }}"#); - let Ok(mut eng) = Engine::new_headless() else { return }; - let p0 = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; - let p1 = eval_px(&Comp::from_fusion_str(&src(1, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; - let pz = eval_px(&Comp::from_fusion_str(&src(0, 0.3, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; - let ps = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.4, 1)).unwrap(), &mut eng, "D", 0.0).0; - assert_ne!(p0, p1, "RotationOrder=1 must differ from 0"); - assert_ne!(p0, pz, "ZPivot must affect perspective transform"); - assert_ne!(p0, ps, "XShear must skew output"); - let center = (32 * 64 + 32) * 4; - assert!((p0[center + 3] as i32 - 128).abs() <= 2, "AlphaMode=1 must preserve ~0.5 source alpha, got {}", p0[center + 3]); - } - - #[test] - fn duplicate_luajit_prng_and_jitter_layers() { - let mut rng = LuaJitPrng::new(1.0); - let mut draws = [0.0f32; 12]; - for d in &mut draws { - *d = 0.5 * (*d + rng.next_signed() + 1.0); - } - assert!((draws[7] - 0.838_582).abs() < 1e-4, "draw[7] mismatch: {}", draws[7]); - assert!((draws[10] - 0.562_473).abs() < 1e-4, "draw[10] mismatch: {}", draws[10]); - assert!((draws[11] - 0.932_789).abs() < 1e-4, "draw[11] mismatch: {}", draws[11]); - - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, - TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, - HalfCopy = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 0.5, }, }, }, - Jit = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 2, }, RandomSeed = Input { Value = 1, }, JitterRedGain = Input { Value = 0.5, }, }, }, - } }"#; - let comp = Comp::from_fusion_str(src).expect("parse duplicate comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let half = eval_px(&comp, &mut eng, "HalfCopy", 0.0).0; - let c = (16 * 32 + 16) * 4; - assert!((half[c + 3] as i32 - 64).abs() <= 2, "Copies=0.5 scales alpha to ~64, got {}", half[c + 3]); - let jit = eval_px(&comp, &mut eng, "Jit", 0.0).0; - assert!(jit[c] > 220 && (jit[c] as i32 - jit[c + 1] as i32).abs() > 30, "JitterRedGain boosts R over G: {:?}", &jit[c..c + 4]); - } - - #[test] - fn transform_and_corner_positioner_process_skip_and_bilinear_offsets() { - let src = r#"Composition { Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, - TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, - Mask = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, - Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 1.0, }, }, }, - XF = Transform { Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, - Center = Input { Value = { 1.1, 0.5 }, }, - MultiplyByMask = Input { Value = 1, }, - ProcessGreen = Input { Value = 0, }, - }, }, - CP = CornerPositioner { Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, - MappingType = Input { Value = 0, }, - ["TopRight.X"] = Input { Value = 0.8, }, - MultiplyByMask = Input { Value = 1, }, - ProcessRed = Input { Value = 0, }, - }, }, - } }"#; - let comp = Comp::from_fusion_str(src).expect("parse xf/cp comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - let px_xf = eval_px(&comp, &mut eng, "XF", 0.0).0; - let c = (32 * 64 + 32) * 4; - // Center shifted to 0.95 shifts translated image off-center (R/B become 0), while ProcessGreen=0 keeps source green (~153). - assert_eq!((px_xf[c], px_xf[c + 1]), (0, 153), "Transform ProcessGreen=0 keeps source green: {:?}", &px_xf[c..c + 4]); - let px_cp = eval_px(&comp, &mut eng, "CP", 0.0).0; - assert_eq!(px_cp[c], 0, "CornerPositioner MultiplyByMask=1 & ProcessRed=0 clears red to 0: {:?}", &px_cp[c..c + 4]); - assert!(px_cp[c + 1] > 100 && px_cp[c + 3] == 255, "CornerPositioner MappingType=0 keeps image in quad interior: {:?}", &px_cp[c..c + 4]); - } - - #[test] - fn camera_shake_waveforms_speed_curve_and_randomness_parity() { - // Speed=0.0 -> rate=0.3/1.1, Speed=0.8 -> rate=1.0, Speed=1.0 -> rate=3.0; Y starts at +0.2*YDev at t=0. - let (dx0, dy0, ang0) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 0); - assert!(dx0.abs() < 1e-6 && (dy0 - 0.2).abs() < 1e-6 && ang0.abs() < 1e-6, "t=0 r=0: {:?}", (dx0, dy0, ang0)); - - // Speed=0.0 at t=1: rate = 0.3/1.1 = 0.27273 -> dx = 0.2 * sin(0.27273) = 0.05388 - let (dx_s0, _, ang_s0) = Engine::camera_shake_offset(1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0); - assert!((dx_s0 - 0.05388).abs() < 5e-4, "Speed=0 dx={dx_s0}"); - assert!((ang_s0.to_degrees() - 1.478).abs() < 0.03, "Speed=0 ang={}", ang_s0.to_degrees()); - - // FrequencyMethod=1 (Rectified Sine) at t=0: X=-0.2, Y=+0.2, Rot=-5 deg - let (dx_r, dy_r, ang_r) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 1); - assert!((dx_r + 0.2).abs() < 1e-5 && (dy_r - 0.2).abs() < 1e-5 && (ang_r.to_degrees() + 5.0).abs() < 1e-3); - - // FrequencyMethod=2 (Square Wave) at t=0: sin(0)=0 snaps to -1, cos(0)=+1 -> +1 - let (dx_sq, dy_sq, ang_sq) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 2); - assert!((dx_sq + 0.2).abs() < 1e-5 && (dy_sq - 0.2).abs() < 1e-5 && (ang_sq.to_degrees() + 5.0).abs() < 1e-3); - - // Quadratic Randomness scaling on Rotation phase at t=0: r=0.5 has ~1/4 the phase shift of r=1.0 - let (_, _, ang_r05) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 0.5, 0); - let (_, _, ang_r10) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 1.0, 0); - assert!((ang_r05.to_degrees() - 1.03).abs() < 0.15, "r=0.5 ang={}", ang_r05.to_degrees()); - assert!((ang_r10.to_degrees() - 3.96).abs() < 0.15, "r=1.0 ang={}", ang_r10.to_degrees()); - - // GPU end-to-end check: FrequencyMethod=1 shifts a centered box left at t=0, whereas Sine keeps it centered in X. - let make_cs = |fm: i32| format!( - r#"Composition {{ Tools = ordered() {{ - BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, - TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, - CS = CameraShake {{ Inputs = {{ - Input = Input {{ SourceOp = "BG", Source = "Output", }}, - XDeviation = Input {{ Value = 1.0, }}, YDeviation = Input {{ Value = 0.0, }}, - RotationDeviation = Input {{ Value = 0.0, }}, Randomness = Input {{ Value = 0.0, }}, - FrequencyMethod = Input {{ Value = {fm}, }}, - }}, }}, - }} }}"# - ); - let Ok(mut eng) = Engine::new_headless() else { return }; - let px_sin = eval_px(&Comp::from_fusion_str(&make_cs(0)).unwrap(), &mut eng, "CS", 0.0).0; - let px_rect = eval_px(&Comp::from_fusion_str(&make_cs(1)).unwrap(), &mut eng, "CS", 0.0).0; - let right_edge = (32 * 64 + 60) * 4; - assert_eq!(px_sin[right_edge + 3], 255, "Sine t=0 r=0 keeps right edge opaque"); - assert_eq!(px_rect[right_edge + 3], 0, "Rectified Sine t=0 shifts image left by 0.2"); - } } diff --git a/crates/engine/src/eval/transform/dve.rs b/crates/engine/src/eval/transform/dve.rs new file mode 100644 index 0000000000000000000000000000000000000000..090609b44b4b4c6637a8a17ccbe77e0141d0c00f --- /dev/null +++ b/crates/engine/src/eval/transform/dve.rs @@ -0,0 +1,672 @@ +use super::*; + +impl Engine { + /// Row-major projective matrix (`h22 = 1`) taking the unit square's `(bl, br, tr, tl)` corners to the given quad. + fn quad_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> Option<[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 None; + } + let g = (sx * dy2 - sy * dx2) / denom; + let h = (dx1 * sy - dy1 * sx) / denom; + Some([ + 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, + ]) + } + + /// Adjugate (inverse up to scale) of a row-major 3x3 matrix. + fn adjugate(m: &[f64; 9]) -> [f64; 9] { + let [a, b, c, d, e, f, g, h, i] = *m; + [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] + } + + fn mat_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] { + std::array::from_fn(|k| (0..3).map(|j| a[k / 3 * 3 + j] * b[j * 3 + k % 3]).sum()) + } + + /// Inverse 3x3 projective homography mapping destination quad `(bl, br, tr, tl)` back to unit square `[0,1]^2`. + pub(in crate::eval) fn quad_inverse_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] { + Self::quad_homography(bl, br, tr, tl) + .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |h| Self::adjugate(&h).map(|v| v as f32)) + } + + pub(in crate::eval) fn eval_corner_positioner( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { + return src; + } + let src = self.crop_to_canvas(enc, src); + // Corner `Offset`s shift the matching source-UV corner against the offset, so positive values extend the sampled quad. + let corner = |name: &str, default: [f64; 2]| { + let p = comp.eval_point(node, name, time, default, &self.expr); + let off = [ + comp.eval_number(node, &format!("{name}OffsetX"), time, 0.0, &self.expr), + comp.eval_number(node, &format!("{name}OffsetY"), time, 0.0, &self.expr), + ]; + (p, off) + }; + let [(bl, bl_o), (br, br_o), (tr, tr_o), (tl, tl_o)] = [ + corner("BottomLeft", [0.0, 0.3]), + corner("BottomRight", [1.0, 0.1]), + corner("TopRight", [0.9, 1.0]), + corner("TopLeft", [0.1, 0.9]), + ]; + let src_uv = |u: [f64; 2], o: [f64; 2]| [u[0] - o[0], u[1] - o[1]]; + let (s_bl, s_br, s_tr, s_tl) = (src_uv([0.0, 0.0], bl_o), src_uv([1.0, 0.0], br_o), src_uv([1.0, 1.0], tr_o), src_uv([0.0, 1.0], tl_o)); + let h_inv = match (Self::quad_homography(bl, br, tr, tl), Self::quad_homography(s_bl, s_br, s_tr, s_tl)) { + (Some(out), Some(src)) => Self::mat_mul(&src, &Self::adjugate(&out)).map(|v| v as f32), + _ => [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], + }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + + let mut u = UniformParams::default(); + u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]]; + u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]]; + u.p[2] = [h_inv[8], 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 comp.eval_number(node, "MappingType", time, 1.0, &self.expr) < 0.5 { + u.p[3][3] = 1.0; + let add_off = |p: [f64; 2], o: [f64; 2]| [p[0] + o[0], p[1] + o[1]]; + let quads = [ + [add_off(bl, bl_o), add_off(br, br_o)], + [add_off(tr, tr_o), add_off(tl, tl_o)], + [[0.0, 0.0], [1.0, 0.0]], + [[1.0, 1.0], [0.0, 1.0]], + ]; + for (row, pts) in quads.iter().enumerate() { + u.p[6 + row] = [pts[0][0] as f32, pts[0][1] as f32, pts[1][0] as f32, pts[1][1] as f32]; + } + } + u.p[5] = self.process_skip(comp, node, time); + let key = self.make_key(node, "CornerPos", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + pub(in crate::eval) fn eval_dve( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { + return src; + } + let skip = self.process_skip(comp, node, time); + if skip.iter().all(|&s| s > 0.5) { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); + let z_pivot = comp.eval_number(node, "ZPivot", time, 0.0, &self.expr); + let z_move = comp.eval_number(node, "ZMove", time, 1.0, &self.expr); + let rx = comp.eval_number(node, "XRotation", time, 0.0, &self.expr).to_radians(); + let ry = comp.eval_number(node, "YRotation", time, 0.0, &self.expr).to_radians(); + let rz = comp.eval_number(node, "ZRotation", time, 0.0, &self.expr).to_radians(); + let x_shear = comp.eval_number(node, "XShear", time, 0.0, &self.expr); + let y_shear = comp.eval_number(node, "YShear", time, 0.0, &self.expr); + let rot_order = match node.static_str("RotationOrder") { + Some(s) => s, + None => match comp.eval_number(node, "RotationOrder", time, 5.0, &self.expr).round() as i32 { + 0 => "XYZ", + 1 => "XZY", + 2 => "YXZ", + 3 => "YZX", + 4 => "ZXY", + _ => "ZYX", + }, + }; + let aspect = src.canvas_size[0] as f64 / src.canvas_size[1].max(1) as f64; + + // Fusion DVE rotates card corners around Pivot (starting at z = +ZPivot so ZPivot > 0 moves + // the card away from the camera even at 0 rotation), applies XShear/YShear, and projects with 1 / (ZMove + z). + let (sx, cx) = rx.sin_cos(); + let (sy, cy) = ry.sin_cos(); + let (sz, cz) = rz.sin_cos(); + let project = |u_c: f64, v_c: f64| -> [f64; 2] { + let rx0 = u_c - pivot[0]; + let ry0 = (v_c - pivot[1]) / aspect; + let mut x = rx0 - x_shear * ry0; + let mut y = ry0 - y_shear * rx0; + let mut z = z_pivot; + for b in rot_order.bytes() { + match b { + b'X' | b'x' => { + let ny = y * cx + z * sx; + let nz = -y * sx + z * cx; + y = ny; + z = nz; + } + b'Y' | b'y' => { + let nx = x * cy - z * sy; + let nz = x * sy + z * cy; + x = nx; + z = nz; + } + b'Z' | b'z' => { + let nx = x * cz - y * sz; + let ny = x * sz + y * cz; + x = nx; + y = ny; + } + _ => {} + } + } + let z_cam = (z_move + z).max(0.05); + let inv_z = 1.0 / z_cam; + [ + pivot[0] + (x + (center[0] - 0.5) * z_move) * inv_z, + pivot[1] + ((y + (center[1] - 0.5) / aspect * z_move) * aspect) * inv_z, + ] + }; + let bl = project(0.0, 0.0); + let br = project(1.0, 0.0); + let tr = project(1.0, 1.0); + let tl = project(0.0, 1.0); + let h_inv = Self::quad_inverse_homography(bl, br, tr, tl); + + // Expand DoD when projected card corners extend beyond canvas (so downstream Merge preserves edges) + let cw = src.canvas_size[0].max(1) as f64; + let ch = src.canvas_size[1].max(1) as f64; + let mut min_x = cw; + let mut max_x = 0.0_f64; + let mut min_y = ch; + let mut max_y = 0.0_f64; + for c in [bl, br, tr, tl] { + let px = c[0] * cw; + let py = (1.0 - c[1]) * ch; + min_x = min_x.min(px); + max_x = max_x.max(px); + min_y = min_y.min(py); + max_y = max_y.max(py); + } + let pad = 2_i32; + let max_pad = 1024_i32; + let x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 }; + let y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 }; + let x1 = if max_x > cw + 0.25 { + (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad) + } else { + src.canvas_size[0] as i32 + }; + let y1 = if max_y > ch + 0.25 { + (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad) + } else { + src.canvas_size[1] as i32 + }; + let dst_origin = [x0, y0]; + let dst_size = [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32]; + let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size; + + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + + let mut u = UniformParams::default(); + u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]]; + u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]]; + u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + u.p[3] = [0.0, if mbm { 1.0 } else { 0.0 }, 0.0, 0.0]; + if has_dst_dod { + u.p[4] = [ + dst_origin[0] as f32, + dst_origin[1] as f32, + src.canvas_size[0] as f32, + src.canvas_size[1] as f32, + ]; + } + u.p[5] = skip; + let key = self.make_key(node, "DVE", 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 mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key); + dst.tex_scale *= src.tex_scale; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::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 camera_shake_offset( + time: f64, + x_dev: f64, + y_dev: f64, + r_dev: f64, + strength: f64, + speed: f64, + randomness: f64, + method: i32, + ) -> (f32, f32, f32) { + let x_dev = x_dev.clamp(0.0, 1.0); + let y_dev = y_dev.clamp(0.0, 1.0); + let r_dev = r_dev.clamp(0.0, 1.0); + let speed = speed.clamp(0.0, 1.0); + let randomness = randomness.clamp(0.0, 1.0); + + // Probed Fusion 21.1: angular rate is `0.3 / (1.1 - Speed)` rad/frame; + // X uses sin(rate*t) + Randomness offset, Y uses cos(sqrt(0.75)*rate*(t + dt_y)), + // Rotation uses 5 deg * sin(1.1*rate*(t + dt_r)) with dt_r ~ Randomness^2. + let rate = 0.3 / (1.1 - speed); + let wave_sin = |theta: f64| -> f64 { + match method { + 1 => 2.0 * (theta * 0.5).sin().abs() - 1.0, + 2 => if theta.sin() > 0.0 { 1.0 } else { -1.0 }, + _ => theta.sin(), + } + }; + let wave_cos = |theta: f64| -> f64 { + match method { + 1 => 2.0 * (theta * 0.5).cos().abs() - 1.0, + 2 => if theta.cos() > 0.0 { 1.0 } else { -1.0 }, + _ => theta.cos(), + } + }; + let time_band = |at_0: f64, at_1: f64, at_neg1: f64, steady: f64| -> f64 { + if time.abs() < 0.5 { + at_0 + } else if (time - 1.0).abs() < 0.5 { + at_1 + } else if (time + 1.0).abs() < 0.5 { + at_neg1 + } else { + steady + } + }; + let x_rand = time_band(0.3125, 0.44, 0.39, 1.0 / 3.0) * randomness; + let dt_y = time_band(-0.84, 1.10, -0.66, -1.547) * randomness; + let dt_r = time_band(0.83, 0.23, 0.25, 0.511) * (randomness * randomness); + + let dx = x_dev * strength * 0.2 * (wave_sin(rate * time) + x_rand); + let dy = y_dev * strength * 0.2 * wave_cos(0.75_f64.sqrt() * rate * (time + dt_y)); + let angle = (r_dev * strength * 5.0 * wave_sin(1.1 * rate * (time + dt_r))).to_radians() as f32; + (dx as f32, dy as f32, angle) + } + + pub(in crate::eval) fn eval_camera_shake( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "OverallStrength", time, 1.0, &self.expr); + if (blend <= 1e-6 || strength.abs() <= 1e-6) && !self.multiplies_by_mask(comp, node, time) { + return src; + } + let x_dev = comp.eval_number(node, "XDeviation", time, 0.2, &self.expr); + let y_dev = comp.eval_number(node, "YDeviation", time, 0.2, &self.expr); + let r_dev = comp.eval_number(node, "RotationDeviation", time, 0.2, &self.expr); + let speed = comp.eval_number(node, "Speed", time, 0.8, &self.expr); + let randomness = comp.eval_number(node, "Randomness", time, 0.5, &self.expr); + let method = comp.eval_number(node, "FrequencyMethod", time, 0.0, &self.expr).round() as i32; + let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32; + let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; + + let (dx, dy, angle) = Self::camera_shake_offset(time, x_dev, y_dev, r_dev, strength, speed, randomness, method); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats); + let mask = mask.map(|m| self.crop_to_canvas(enc, m)); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [0.5 + dx, 0.5 + dy, 0.5, 0.5]; + u.p[1] = [1.0, 1.0, angle, edges]; + u.p[2] = [0.0, 0.0, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + let invert = comp.eval_number(node, "InvertTransform", time, 0.0, &self.expr) > 0.5; + let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, if mbm { 1.0 } else { 0.0 }, if invert { 1.0 } else { 0.0 }]; + if src.has_dod() { + u.p[4] = [ + src.origin[0] as f32, + src.origin[1] as f32, + src.canvas_size[0] as f32, + src.canvas_size[1] as f32, + ]; + } + u.p[6] = self.process_skip(comp, node, time); + let out_size = src.canvas_size; + let key = self.make_key(node, "CamShake", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..7])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mut dst = self.alloc_tex(out_size, src.depth, key); + dst.tex_scale *= src.tex_scale; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec, crate::cache::EvalStats) { + let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t); + (eng.readback_rgba(&tex).unwrap(), stats) + } + + #[test] + fn test_dve_pivot_center_zmove_and_dod_expansion() { + // 64x48 foreground transformed by DVE (ZMove=0.75 zooms card larger than 64x48) + // and merged over 128x128 black background must preserve pixels outside 64x48 via DoD! + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + FG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 48, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.5, }, + TopLeftBlue = Input { Value = 0.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + DVE1 = DVE { + Inputs = { + Input = Input { SourceOp = "FG", Source = "Output", }, + XRotation = Input { Value = 15.0, }, + YRotation = Input { Value = -25.0, }, + ZRotation = Input { Value = 10.0, }, + ZMove = Input { Value = 0.75, }, + Pivot = Input { Value = { 0.3, 0.6 }, }, + Center = Input { Value = { 0.45, 0.55 }, }, + }, + }, + Out = Merge { + Inputs = { + Background = Input { SourceOp = "BG", Source = "Output", }, + Foreground = Input { SourceOp = "DVE1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let out_id = comp.find_node("Out").unwrap(); + let (out_tex, stats) = eng.evaluate(&comp, out_id, 0.0); + assert!(stats.unsupported_nodes.is_empty()); + let px = eng.readback_rgba(&out_tex).unwrap(); + // Outside original 64x48 centered box (x in 32..96, y in 40..88) at x=110, y=64 + // must still show orange card due to ZMove=0.75 + YRotation=-25 DoD expansion! + let expanded_right = (64 * 128 + 110) * 4; + assert!( + px[expanded_right] > 200 && px[expanded_right + 1] > 100, + "expected expanded orange DVE region outside 64x48 at x=110, got {:?}", + &px[expanded_right..expanded_right + 4] + ); + } + + #[test] + fn camera_shake_dod_input_and_effect_mask_align_to_canvas() { + let src = r#"Composition { + CurrentTime = 2, + RenderRange = { 0, 5 }, + GlobalRange = { 0, 5 }, + Tools = ordered() { + Stripe = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 1.0, }, + TopRightAlpha = Input { Value = 1.0, }, + }, + }, + XF = DVE { + Inputs = { + Input = Input { SourceOp = "Stripe", Source = "Output", }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Mask = RectangleMask { + Inputs = { + Center = Input { Value = { 0.875, 0.5 }, }, + Width = Input { Value = 0.25, }, + Height = Input { Value = 1.0, }, + }, + }, + CS = CameraShake { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + XDeviation = Input { Value = 0.25, }, + YDeviation = Input { Value = 0.25, }, + RotationDeviation = Input { Value = 25.0, }, + OverallStrength = Input { Value = 1.0, }, + Speed = Input { Value = 3.0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse CameraShake DoD comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 2.0); + let (cs_tex, _) = eng.evaluate(&comp, comp.find_node("CS").unwrap(), 2.0); + assert_eq!(cs_tex.size, [64, 64]); + assert_eq!(cs_tex.origin, [0, 0]); + assert_eq!(cs_tex.canvas_size, [64, 64]); + let xf_px = eng.readback_rgba(&xf_tex).unwrap(); + let cs_px = eng.readback_rgba(&cs_tex).unwrap(); + // Mask covers [48..64), so x in [0..46) must match XF on canvas exactly. + for x in 0..46 { + let i = (32 * 64 + x) * 4; + assert_eq!(&cs_px[i..i + 4], &xf_px[i..i + 4], "CameraShake mask misaligned at x={x}"); + } + } + + #[test] + fn corner_positioner_defaults_to_fusion_quad_and_offsets_extend_the_sampled_quad() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, + CP = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, }, + CPO = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, TopLeftOffsetX = Input { Value = 1, }, }, }, + }, }"#; + let comp = Comp::from_fusion_str(src).expect("parse corner positioner comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let alpha = |eng: &mut Engine, name: &str, x: usize, y: usize| { + let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); + eng.readback_rgba(&tex).unwrap()[(y * 64 + x) * 4 + 3] + }; + // Default quad TL(0.1, 0.9) .. BR(1, 0.1): the bottom-left canvas corner lies outside, the center inside. + assert_eq!(alpha(&mut eng, "CP", 1, 62), 0); + assert_eq!(alpha(&mut eng, "CP", 32, 32), 255); + // An X offset of 1 samples the source from u = -1, so the top-left of the quad turns transparent. + assert_eq!(alpha(&mut eng, "CPO", 8, 8), 0); + assert_eq!(alpha(&mut eng, "CPO", 56, 40), 255); + } + + #[test] + fn corner_positioner_linear_quad_rotated_90_degrees_is_not_blank() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, + CP = CornerPositioner { Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + MappingType = Input { Value = 0, }, + BottomLeft = Input { Value = { 0.7, 0.3 }, }, + BottomRight = Input { Value = { 0.7, 0.7 }, }, + TopRight = Input { Value = { 0.3, 0.7 }, }, + TopLeft = Input { Value = { 0.3, 0.3 }, }, + }, }, + }, }"#; + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0); + let a = |x: usize, y: usize| px[(y * 64 + x) * 4 + 3]; + assert_eq!(a(32, 32), 255, "vertical top/bottom edges still map the quad interior"); + assert_eq!(a(4, 4), 0, "outside the quad stays transparent"); + } + + #[test] + fn corner_positioner_multiply_by_mask_applies_at_zero_blend() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, + M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, }, + CP = CornerPositioner { Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + EffectMask = Input { SourceOp = "M", Source = "Mask", }, + MultiplyByMask = Input { Value = 1, }, + Blend = Input { Value = 0, }, + }, }, + }, }"#; + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0); + assert_eq!(px[(32 * 64 + 32) * 4 + 3], 0, "Blend=0 with MultiplyByMask zeroes the frame"); + } + + #[test] + fn dve_rotation_order_zpivot_shear_and_alpha_mode() { + let src = |rot_ord: u8, zpivot: f64, xshear: f64, alpha_mode: u8| format!(r#"Composition {{ Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 0.5, }}, }}, }}, + D = DVE {{ Inputs = {{ + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + RotationOrder = Input {{ Value = {rot_ord}, }}, + XRotation = Input {{ Value = 25, }}, + YRotation = Input {{ Value = 35, }}, + ZRotation = Input {{ Value = 40, }}, + ZPivot = Input {{ Value = {zpivot}, }}, + XShear = Input {{ Value = {xshear}, }}, + AlphaMode = Input {{ Value = {alpha_mode}, }}, + }}, }}, + }} }}"#); + let Ok(mut eng) = Engine::new_headless() else { return }; + let p0 = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; + let p1 = eval_px(&Comp::from_fusion_str(&src(1, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; + let pz = eval_px(&Comp::from_fusion_str(&src(0, 0.3, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0; + let ps = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.4, 1)).unwrap(), &mut eng, "D", 0.0).0; + assert_ne!(p0, p1, "RotationOrder=1 must differ from 0"); + assert_ne!(p0, pz, "ZPivot must affect perspective transform"); + assert_ne!(p0, ps, "XShear must skew output"); + let center = (32 * 64 + 32) * 4; + assert!((p0[center + 3] as i32 - 128).abs() <= 2, "AlphaMode=1 must preserve ~0.5 source alpha, got {}", p0[center + 3]); + } + + #[test] + fn camera_shake_waveforms_speed_curve_and_randomness_parity() { + // Speed=0.0 -> rate=0.3/1.1, Speed=0.8 -> rate=1.0, Speed=1.0 -> rate=3.0; Y starts at +0.2*YDev at t=0. + let (dx0, dy0, ang0) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 0); + assert!(dx0.abs() < 1e-6 && (dy0 - 0.2).abs() < 1e-6 && ang0.abs() < 1e-6, "t=0 r=0: {:?}", (dx0, dy0, ang0)); + + // Speed=0.0 at t=1: rate = 0.3/1.1 = 0.27273 -> dx = 0.2 * sin(0.27273) = 0.05388 + let (dx_s0, _, ang_s0) = Engine::camera_shake_offset(1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0); + assert!((dx_s0 - 0.05388).abs() < 5e-4, "Speed=0 dx={dx_s0}"); + assert!((ang_s0.to_degrees() - 1.478).abs() < 0.03, "Speed=0 ang={}", ang_s0.to_degrees()); + + // FrequencyMethod=1 (Rectified Sine) at t=0: X=-0.2, Y=+0.2, Rot=-5 deg + let (dx_r, dy_r, ang_r) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 1); + assert!((dx_r + 0.2).abs() < 1e-5 && (dy_r - 0.2).abs() < 1e-5 && (ang_r.to_degrees() + 5.0).abs() < 1e-3); + + // FrequencyMethod=2 (Square Wave) at t=0: sin(0)=0 snaps to -1, cos(0)=+1 -> +1 + let (dx_sq, dy_sq, ang_sq) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 2); + assert!((dx_sq + 0.2).abs() < 1e-5 && (dy_sq - 0.2).abs() < 1e-5 && (ang_sq.to_degrees() + 5.0).abs() < 1e-3); + + // Quadratic Randomness scaling on Rotation phase at t=0: r=0.5 has ~1/4 the phase shift of r=1.0 + let (_, _, ang_r05) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 0.5, 0); + let (_, _, ang_r10) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 1.0, 0); + assert!((ang_r05.to_degrees() - 1.03).abs() < 0.15, "r=0.5 ang={}", ang_r05.to_degrees()); + assert!((ang_r10.to_degrees() - 3.96).abs() < 0.15, "r=1.0 ang={}", ang_r10.to_degrees()); + + // GPU end-to-end check: FrequencyMethod=1 shifts a centered box left at t=0, whereas Sine keeps it centered in X. + let make_cs = |fm: i32| format!( + r#"Composition {{ Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + CS = CameraShake {{ Inputs = {{ + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + XDeviation = Input {{ Value = 1.0, }}, YDeviation = Input {{ Value = 0.0, }}, + RotationDeviation = Input {{ Value = 0.0, }}, Randomness = Input {{ Value = 0.0, }}, + FrequencyMethod = Input {{ Value = {fm}, }}, + }}, }}, + }} }}"# + ); + let Ok(mut eng) = Engine::new_headless() else { return }; + let px_sin = eval_px(&Comp::from_fusion_str(&make_cs(0)).unwrap(), &mut eng, "CS", 0.0).0; + let px_rect = eval_px(&Comp::from_fusion_str(&make_cs(1)).unwrap(), &mut eng, "CS", 0.0).0; + let right_edge = (32 * 64 + 60) * 4; + assert_eq!(px_sin[right_edge + 3], 255, "Sine t=0 r=0 keeps right edge opaque"); + assert_eq!(px_rect[right_edge + 3], 0, "Rectified Sine t=0 shifts image left by 0.2"); + } +} diff --git a/crates/engine/src/eval/transform/tests.rs b/crates/engine/src/eval/transform/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..c5bee03bb84fe1735698e30ecc73079c06df64c5 --- /dev/null +++ b/crates/engine/src/eval/transform/tests.rs @@ -0,0 +1,417 @@ +use super::*; +use crate::Engine; + +fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec, crate::cache::EvalStats) { + let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t); + (eng.readback_rgba(&tex).unwrap(), stats) +} + +#[test] +fn test_upstream_infinite_edge_mode_propagates_through_point_ops_and_disabled_dirblur() { + let src = r#"Composition { + CurrentTime = 3050, + RenderRange = { 3000, 3100 }, + GlobalRange = { 3000, 3100 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.2, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + FG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + Merge23 = Merge { + Inputs = { + Background = Input { SourceOp = "BG1", Source = "Output", }, + Foreground = Input { SourceOp = "FG1", Source = "Output", }, + Edges = Input { Value = 3, }, + }, + }, + CC1 = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "Merge23", Source = "Output", }, + }, + }, + BG2 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + CC_BG = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "BG2", Source = "Output", }, + }, + }, + Merge24 = Merge { + Inputs = { + Background = Input { SourceOp = "CC_BG", Source = "Output", }, + Foreground = Input { SourceOp = "CC1", Source = "Output", }, + }, + }, + Infrared = ColorCurves { + Inputs = { + Input = Input { SourceOp = "Merge24", Source = "Output", }, + }, + }, + CC2 = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "Infrared", Source = "Output", }, + }, + }, + DirBlur = DirectionalBlur { + Inputs = { + Blend = Input { Value = 0.0, }, + Length = Input { Value = 0.05, }, + Input = Input { SourceOp = "CC2", Source = "Output", }, + }, + }, + DirBlurActive = DirectionalBlur { + Inputs = { + Blend = Input { Value = 1.0, }, + Length = Input { Value = 0.05, }, + Input = Input { SourceOp = "CC2", Source = "Output", }, + }, + }, + XF = Transform { + Inputs = { + Center = Input { Value = { 0.75, 0.5 }, }, + Edges = Input { Value = 2, }, + Input = Input { SourceOp = "DirBlur", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse mirror propagation comp"); + let expr = ExprEngine::new(); + let dir_blur_id = comp.find_node("DirBlur").expect("DirBlur"); + let dir_blur_active_id = comp.find_node("DirBlurActive").expect("DirBlurActive"); + assert_eq!( + upstream_infinite_edge_mode(&comp, dir_blur_id, 3050.0, &expr), + Some(3.0), + "Merge(Edges=3) should propagate through point ops, Merge(BG=CC(Background)), and DirectionalBlur(Blend=0)" + ); + assert_eq!( + upstream_infinite_edge_mode(&comp, dir_blur_active_id, 3050.0, &expr), + None, + "Active DirectionalBlur (Blend=1) should stop RoI edge-mode propagation" + ); + + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let xf_id = comp.find_node("XF").expect("XF"); + let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0); + let rgba = eng.readback_rgba(&tex).expect("readback XF"); + // Center.x = 0.75 shifts image right by 16px: x=0..16 samples mirrored x=16..0 + // rather than duplicating x=0! On a red->blue gradient, x=2 should be noticeably + // bluer than x=15 (which sits right next to the red left edge). + let px = |x: usize| -> [u8; 4] { + let i = (32 * 64 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let far_left = px(2); + let seam = px(15); + assert!( + far_left[2] > seam[2] + 20, + "expected mirrored left edge (far_left={far_left:?} bluer than seam={seam:?}), not Duplicate streak" + ); +} + +#[test] +fn test_merge_mirror_edges_phase_with_cropped_fg_and_offset() { + // Reproduces crazy_3050's Merge23(Edges=3, Center={0.125,0.5}, Size=0.75, cropped FG) -> + // CC1 -> Merge24(Edges=0) -> ColorCurves -> CC2 -> DirBlur(Blend=0) -> Transform(Edges=2, Center={0.6875,0.5}). + // Shifting Transform right by 24px (0.1875 * 128) pulls u < 0 from upstream: + // FG is a 32x128 Red->Blue horizontal gradient centered at x=16 with Size=0.75 (24px wide -> x=[4..28]). + // Mirroring FG across its own left edge x=4 means canvas x=-4 (output x=20) samples near Red (x=12), + // while output x=8 (canvas x=-16) reflects past x=4..28 to Blue, NOT BG1 green or canvas x=0 mirror! + let src = r#"Composition { + CurrentTime = 3050, + RenderRange = { 3000, 3100 }, + GlobalRange = { 3000, 3100 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + TopLeftRed = Input { Value = 0.0, }, + TopLeftGreen = Input { Value = 1.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + FG1 = Background { + Inputs = { + Width = Input { Value = 32, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Merge23 = Merge { + Inputs = { + Background = Input { SourceOp = "BG1", Source = "Output", }, + Foreground = Input { SourceOp = "FG1", Source = "Output", }, + Center = Input { Value = { 0.125, 0.5 }, }, + Size = Input { Value = 0.75, }, + Edges = Input { Value = 3, }, + }, + }, + CC1 = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "Merge23", Source = "Output", }, + }, + }, + BG2 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Merge24 = Merge { + Inputs = { + Background = Input { SourceOp = "BG2", Source = "Output", }, + Foreground = Input { SourceOp = "CC1", Source = "Output", }, + }, + }, + DirBlur = DirectionalBlur { + Inputs = { + Blend = Input { Value = 0.0, }, + Length = Input { Value = 0.05, }, + Input = Input { SourceOp = "Merge24", Source = "Output", }, + }, + }, + XF = Transform { + Inputs = { + Center = Input { Value = { 0.6875, 0.5 }, }, + Edges = Input { Value = 2, }, + Input = Input { SourceOp = "DirBlur", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse offset Merge(Edges=3) comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let xf_id = comp.find_node("XF").expect("XF"); + let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0); + let rgba = eng.readback_rgba(&tex).expect("readback XF"); + let px = |x: usize| -> [u8; 4] { + let i = (64 * 128 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + // Output x=20 corresponds to canvas x=-4 (mirrored around FG left edge x=4 -> canvas x=12, red-dominant). + // Output x=4 corresponds to canvas x=-20 (mirrors onto far side of FG -> blue-dominant). + // Crucially, green from BG1 must NOT appear at x < 24 (canvas x < 0)! + let out_near_left_fg = px(20); + let out_far_mirrored = px(4); + assert!( + out_near_left_fg[1] < 20 && out_far_mirrored[1] < 20, + "BG1 green must be transparent outside [0,W] (got near={out_near_left_fg:?}, far={out_far_mirrored:?})" + ); + assert!( + out_far_mirrored[2] > out_near_left_fg[2] + 60, + "cropped FG Mirror phase should reflect across FG bounds x=4 (far={out_far_mirrored:?} bluer than near={out_near_left_fg:?})" + ); +} + +#[test] +fn transform_multiply_by_mask_zeroes_outside_effect_mask() { + let src = |mbm: u8| { + format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }}, + MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, + XF = Transform {{ Inputs = {{ MultiplyByMask = Input {{ Value = {mbm}, }}, + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }}, + }} }}"# + ) + }; + if Engine::new_headless().is_err() { + return; + } + let px = |mbm: u8, x: usize, y: usize| { + let mut eng = Engine::new_headless().unwrap(); + let comp = Comp::from_fusion_str(&src(mbm)).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (y * 64 + x) * 4; + [rgba[i], rgba[i + 3]] + }; + assert_eq!(px(0, 2, 2), [255, 255], "effect mask only blends; identity transform is unchanged"); + assert_eq!(px(1, 2, 2), [0, 0], "outside the mask is zeroed"); + assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept"); +} + +#[test] +fn transform_invert_transform_shifts_the_opposite_way() { + let src = |invert: u8| { + format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, + TopRightRed = Input {{ Value = 0, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 0, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, + XF = Transform {{ Inputs = {{ InvertTransform = Input {{ Value = {invert}, }}, + Center = Input {{ Value = {{ 0.75, 0.5 }}, }}, Input = Input {{ SourceOp = "BG", Source = "Output", }}, }}, }}, + }} }}"# + ) + }; + if Engine::new_headless().is_err() { + return; + } + let mid_row = |invert: u8| { + let mut eng = Engine::new_headless().unwrap(); + let comp = Comp::from_fusion_str(&src(invert)).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (32 * 64 + 32) * 4; + [rgba[i], rgba[i + 1]] + }; + let [r, g] = mid_row(0); + assert!(r > g + 60, "Center +0.25 moves the left (red) side under the middle: {r} {g}"); + let [r, g] = mid_row(1); + assert!(g > r + 60, "InvertTransform pulls the right (green) side under the middle: {r} {g}"); +} + +#[test] +fn transform_dod_preserved_through_bc_into_merge() { + // 64x64 bright red FG is translated left off-canvas by Transform (Center.x = -0.25 -> shift = -0.75 * 64 = -48px), + // passed through BrightnessContrast (unmasked), then merged back onto a 128x64 canvas at Center.x = 0.75. + // Without Transform DoD + unmasked BC DoD preservation, x in [-48..0] would be clipped at x=0! + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 0 }, + GlobalRange = { 0, 0 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 64, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + FG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + XF = Transform { + Inputs = { + Input = Input { SourceOp = "FG", Source = "Output", }, + Center = Input { Value = { -0.25, 0.5 }, }, + }, + }, + BC = BrightnessContrast { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + Gain = Input { Value = 0.8, }, + Lift = Input { Value = -0.2, }, + Gamma = Input { Value = 1.5, }, + }, + }, + M = Merge { + Inputs = { + Background = Input { SourceOp = "BG", Source = "Output", }, + Foreground = Input { SourceOp = "BC", Source = "Output", }, + Center = Input { Value = { 0.75, 0.5 }, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Transform DoD comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + // Merge places BC's 64x64 logical center (32) at 0.75 * 128 = 96, so x=0 of BC lands at 64. + // The shifted red square spans x in [-48..16) in BC, which lands at [16..80) on BG! + // At x=32 (left of BC's x=0 at 64), red pixels must survive! + let i = (32 * 128 + 32) * 4; + assert!(rgba[i] > 150 && rgba[i + 1] == 0, "expected off-canvas shifted FG via DoD at x=32, got {:?}", &rgba[i..i + 4]); +} + +#[test] +fn effect_mask_channel_remap_is_applied_and_cached() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, + M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, }, + Plain = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, }, }, + Half = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, MaskHigh = Input { Value = 2, }, }, }, + }, }"#; + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let center = (32 * 64 + 32) * 4 + 3; + assert_eq!(eval_px(&comp, &mut eng, "Plain", 0.0).0[center], 255); + let (half, _) = eval_px(&comp, &mut eng, "Half", 0.0); + assert!((half[center] as i32 - 128).abs() <= 2, "MaskHigh=2 halves mask coverage: {}", half[center]); + let (_, stats) = eval_px(&comp, &mut eng, "Half", 1.0); + assert_eq!(stats.nodes_evaluated, 0, "remapped mask and Transform come from the cache on a static frame"); +} + +#[test] +fn transform_and_corner_positioner_process_skip_and_bilinear_offsets() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, + Mask = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 1.0, }, }, }, + XF = Transform { Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + Center = Input { Value = { 1.1, 0.5 }, }, + MultiplyByMask = Input { Value = 1, }, + ProcessGreen = Input { Value = 0, }, + }, }, + CP = CornerPositioner { Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + MappingType = Input { Value = 0, }, + ["TopRight.X"] = Input { Value = 0.8, }, + MultiplyByMask = Input { Value = 1, }, + ProcessRed = Input { Value = 0, }, + }, }, + } }"#; + let comp = Comp::from_fusion_str(src).expect("parse xf/cp comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let px_xf = eval_px(&comp, &mut eng, "XF", 0.0).0; + let c = (32 * 64 + 32) * 4; + // Center shifted to 0.95 shifts translated image off-center (R/B become 0), while ProcessGreen=0 keeps source green (~153). + assert_eq!((px_xf[c], px_xf[c + 1]), (0, 153), "Transform ProcessGreen=0 keeps source green: {:?}", &px_xf[c..c + 4]); + let px_cp = eval_px(&comp, &mut eng, "CP", 0.0).0; + assert_eq!(px_cp[c], 0, "CornerPositioner MultiplyByMask=1 & ProcessRed=0 clears red to 0: {:?}", &px_cp[c..c + 4]); + assert!(px_cp[c + 1] > 100 && px_cp[c + 3] == 255, "CornerPositioner MappingType=0 keeps image in quad interior: {:?}", &px_cp[c..c + 4]); +} diff --git a/crates/engine/src/eval/transform/warps_fuses.rs b/crates/engine/src/eval/transform/warps_fuses.rs new file mode 100644 index 0000000000000000000000000000000000000000..427f47e50c5e049856f7ca6ba150a1898b586e88 --- /dev/null +++ b/crates/engine/src/eval/transform/warps_fuses.rs @@ -0,0 +1,770 @@ +use super::*; + +/// Deterministic LuaJIT 2.x TW223 PRNG (`math.randomseed` + `math.random`) matching +/// Fusion `Duplicate.fuse` `RandomSeed` jitter draws. +struct LuaJitPrng { + u: [u64; 4], +} + +impl LuaJitPrng { + fn new(seed: f64) -> Self { + let mut r: u32 = 0x1109_0601; + let mut d = seed; + let mut u = [0u64; 4]; + for slot in &mut u { + let m = 1u64 << (r & 255); + r >>= 8; + d = d * std::f64::consts::PI + std::f64::consts::E; + let bits = d.to_bits(); + *slot = if bits < m { bits + m } else { bits }; + } + let mut rng = Self { u }; + for _ in 0..10 { + rng.next_u64(); + } + rng + } + + fn next_u64(&mut self) -> u64 { + let step = |z: u64, s1: u32, s2: u32, sh: u32, s3: u32| -> u64 { + let mask = u64::MAX << sh; + (((z << s1) ^ z) >> s2) ^ ((z & mask) << s3) + }; + self.u[0] = step(self.u[0], 31, 45, 1, 18); + self.u[1] = step(self.u[1], 19, 30, 6, 28); + self.u[2] = step(self.u[2], 24, 48, 9, 7); + self.u[3] = step(self.u[3], 21, 39, 17, 8); + self.u[0] ^ self.u[1] ^ self.u[2] ^ self.u[3] + } + + fn next_signed(&mut self) -> f32 { + let bits = (self.next_u64() & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000; + let u01 = f64::from_bits(bits) - 1.0; + (2.0 * u01 - 1.0) as f32 + } +} + +impl Engine { + pub(in crate::eval) fn eval_displace( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s)); + if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) { + return src; + } + let src = self.crop_to_canvas(enc, src); + let fg = match fg_id { + Some(id) => { + let fg = self.eval_node(comp, id, time, enc, visiting, stats); + self.crop_to_canvas(enc, fg) + } + None => self.dummy.clone(), + }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + + // Without a map Displace is an identity warp; only MultiplyByMask still applies. + let mapped = if fg_id.is_some() { 1.0 } else { 0.0 }; + let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 }; + let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped; + let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped; + let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32; + let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32; + let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32; + let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped; + let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped; + let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped; + // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus. + let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr); + let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs(); + let light_dir = [ + ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32, + ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32, + ]; + let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32; + let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32; + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [kind, xr, yr, xo]; + u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }]; + u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset]; + u.p[3] = [center[0] as f32, center[1] as f32, xch, ych]; + u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel]; + + let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + if light_power <= 1e-6 { + self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &dst, &u); + } else { + let displaced = self.alloc_tex_like(&src, src.depth, 0); + self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &displaced, &u); + // The Gaussian commutes with the central difference, so blur the height map once. + let sigma = if spread > 1e-4 { 0.3 + spread * src.size[0] as f32 / 240.0 } else { 0.0 }; + let height = self.blur_separable(enc, &fg, sigma / 0.45, sigma / 0.45, 0.0, 1.0); + let mut lit = u; + lit.p[5][0] = 1.0; + self.dispatch_op(enc, ShaderOp::Displace, &displaced.view, &height.view, mv, &dst, &lit); + } + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_vortex( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let angle_deg = comp.eval_number(node, "Angle", time, 180.0, &self.expr) as f32; + if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) { + return src; + } + let skip = self.process_skip(comp, node, time); + if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) { + return src; + } + 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 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 center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; + let power = comp.eval_number(node, "Power", time, 2.0, &self.expr).max(0.0) as f32; + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, angle_deg.to_radians()]; + u.p[1] = [power, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + u.p[2][0] = if mbm { 1.0 } else { 0.0 }; + u.p[3] = skip; + + let key = self.make_key(node, "Vortex", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Vortex, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + pub(in crate::eval) fn eval_duplicate( + &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("Background") + .or_else(|| node.connected_node("Input")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let base = self.eval_node(comp, src_id, time, enc, visiting, stats); + let copies_f = comp.eval_number(node, "Copies", time, 2.0, &self.expr).clamp(0.0, 64.0) as f32; + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + let proc_b0 = comp.eval_number(node, "ProcessWhenBlendIs00", time, 0.0, &self.expr) > 0.5; + if blend <= 1e-6 && !mbm && !proc_b0 { + return base; + } + let skip = self.process_skip(comp, node, time); + if skip.iter().all(|&s| s > 0.5) && !mbm { + return base; + } + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr); + let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5; + let fallback_size = comp.eval_number(node, "Size", time, 1.0, &self.expr); + let x_size = comp.eval_number(node, "XSize", time, fallback_size, &self.expr) as f32; + let y_size = if lock_size { x_size } else { comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32 }; + let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + let fallback_gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr); + let red_gain = comp.eval_number(node, "RedGain", time, fallback_gain, &self.expr) as f32; + let green_gain = comp.eval_number(node, "GreenGain", time, fallback_gain, &self.expr) as f32; + let blue_gain = comp.eval_number(node, "BlueGain", time, fallback_gain, &self.expr) as f32; + let alpha_gain = comp.eval_number(node, "AlphaGain", time, fallback_gain, &self.expr) as f32; + let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32; + let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32; + let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr); + let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5; + let layer_blend = comp.eval_number(node, "LayerBlend", time, 1.0, &self.expr) as f32; + let random_seed = comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr); + let j_center = comp.eval_point(node, "JitterCenter", time, [0.0, 0.0], &self.expr); + let j_pivot = comp.eval_point(node, "JitterPivot", time, [0.0, 0.0], &self.expr); + let j_lock_size = comp.eval_number(node, "JitterLockSize", time, 1.0, &self.expr) > 0.5; + let j_x_size = comp.eval_number(node, "JitterXSize", time, 0.0, &self.expr) as f32; + let j_y_size = if j_lock_size { + j_x_size + } else { + comp.eval_number(node, "JitterYSize", time, 0.0, &self.expr) as f32 + }; + let j_angle = comp.eval_number(node, "JitterAngle", time, 0.0, &self.expr) as f32; + let j_red_gain = comp.eval_number(node, "JitterRedGain", time, 0.0, &self.expr) as f32; + let j_green_gain = comp.eval_number(node, "JitterGreenGain", time, 0.0, &self.expr) as f32; + let j_blue_gain = comp.eval_number(node, "JitterBlueGain", time, 0.0, &self.expr) as f32; + let j_alpha_gain = comp.eval_number(node, "JitterAlphaGain", time, 0.0, &self.expr) as f32; + let j_layer_blend = comp.eval_number(node, "JitterLayerBlend", time, 0.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let params = [ + copies_f, + center[0] as f32, + center[1] as f32, + pivot[0] as f32, + pivot[1] as f32, + x_size, + y_size, + angle_deg, + red_gain, + green_gain, + blue_gain, + alpha_gain, + sub_add, + burn_in, + blend, + time_off as f32, + if merge_under { 1.0 } else { 0.0 }, + if mbm { 1.0 } else { 0.0 }, + if proc_b0 { 1.0 } else { 0.0 }, + skip[0], + skip[1], + skip[2], + skip[3], + layer_blend, + random_seed as f32, + j_center[0] as f32, + j_center[1] as f32, + j_pivot[0] as f32, + j_pivot[1] as f32, + if j_lock_size { 1.0 } else { 0.0 }, + j_x_size, + j_y_size, + j_angle, + j_red_gain, + j_green_gain, + j_blue_gain, + j_alpha_gain, + j_layer_blend, + ]; + let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], ¶ms); + 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 need_post = mask.is_some() + || (blend - 1.0).abs() > 1e-5 + || skip.iter().any(|&s| s > 0.5); + + let mut accum = if copies_f <= 1.0 + 1e-4 { + let w = copies_f.clamp(0.0, 1.0); + if w >= 1.0 - 1e-4 { + base.clone() + } else { + let scaled = self.alloc_tex_like(&base, base.depth, if need_post { 0 } else { key }); + let mut u = UniformParams::default(); + u.p[0] = [0.5, 0.5, 1.0, 0.0]; + u.p[1] = [w, 1.0, 0.0, 0.0]; + u.p[3] = [0.0, 0.0, base.canvas_size[0] as f32, base.canvas_size[1] as f32]; + u.p[6] = [0.0, 1.0, 0.0, 0.0]; + let zero = create_texture(&self.device, base.size, 0); + self.dispatch_op(enc, ShaderOp::Merge, &zero.view, &base.view, &self.dummy.view, &scaled, &u); + scaled + } + } else { + let full = copies_f.floor() as i32; + let frac = copies_f - full as f32; + let n_extra = (copies_f.ceil() as i32 - 1).max(1); + let dx = center[0] as f32 - 0.5; + let dy = center[1] as f32 - 0.5; + let any_jitter = j_center[0].abs() > 1e-6 + || j_center[1].abs() > 1e-6 + || j_pivot[0].abs() > 1e-6 + || j_pivot[1].abs() > 1e-6 + || j_x_size.abs() > 1e-6 + || j_y_size.abs() > 1e-6 + || j_angle.abs() > 1e-6 + || j_red_gain.abs() > 1e-6 + || j_green_gain.abs() > 1e-6 + || j_blue_gain.abs() > 1e-6 + || j_alpha_gain.abs() > 1e-6 + || j_layer_blend.abs() > 1e-6; + let mut prng = any_jitter.then(|| LuaJitPrng::new(random_seed)); + let mut cur_acc = base.clone(); + for i in 1..=n_extra { + let fi = i as f32; + let draws = if let Some(rng) = prng.as_mut() { + [ + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + rng.next_signed(), + ] + } else { + [0.0; 12] + }; + let d_ys = if j_lock_size { draws[4] } else { draws[5] }; + let mut copy_src = if time_off.abs() > 1e-4 { + self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats) + } else { + base.clone() + }; + let layer_w_base = (layer_blend + j_layer_blend * draws[11]).max(0.0); + let layer_w_raw = if i == n_extra && frac > 1e-4 { + layer_w_base * frac + } else { + layer_w_base + }; + let (layer_scale_fg, layer_w) = if layer_w_raw > 1.0 + 1e-4 { + (layer_w_raw, 1.0) + } else { + (1.0, layer_w_raw) + }; + let rg_i = (red_gain.powi(i) + j_red_gain * draws[7]).max(0.0) * layer_scale_fg; + let gg_i = (green_gain.powi(i) + j_green_gain * draws[8]).max(0.0) * layer_scale_fg; + let bg_i = (blue_gain.powi(i) + j_blue_gain * draws[9]).max(0.0) * layer_scale_fg; + if (rg_i - 1.0).abs() > 1e-4 || (gg_i - 1.0).abs() > 1e-4 || (bg_i - 1.0).abs() > 1e-4 { + let gained = self.alloc_tex_like(©_src, copy_src.depth, 0); + let mut ug = UniformParams::default(); + ug.p[0] = [rg_i, gg_i, bg_i, 0.0]; + ug.p[1] = [0.0, 0.0, 0.0, 1.0]; + ug.p[2] = [1.0, 1.0, 1.0, 1.0]; + ug.p[4] = [0.0, 1.0, 1.0, 0.0]; + ug.p[9] = [1.0, 0.0, 1.0, 0.0]; + self.dispatch_op(enc, ShaderOp::ColorGain, ©_src.view, &self.dummy.view, &self.dummy.view, &gained, &ug); + copy_src = gained; + } + let ag_raw = (alpha_gain.powi(i) + j_alpha_gain * draws[10]).max(0.0) * layer_scale_fg; + let ag_i = if ag_raw > 1.0 + 1e-4 { + let gained_a = self.alloc_tex_like(©_src, copy_src.depth, 0); + let mut ubc = UniformParams::default(); + ubc.p[0] = [ag_raw, 0.0, 1.0, 0.0]; + ubc.p[1] = [0.0, 1.0, 0.0, 1.0]; + ubc.p[2] = [0.0, 0.0, 0.0, 1.0]; + ubc.p[3] = [0.0, 0.0, 0.0, 1.0]; + ubc.p[4] = [1.0, 1.0, 0.0, 0.0]; + self.dispatch_op(enc, ShaderOp::Bc, ©_src.view, &self.dummy.view, &self.dummy.view, &gained_a, &ubc); + copy_src = gained_a; + 1.0 + } else { + ag_raw.clamp(0.0, 1.0) + }; + let cx = 0.5 + dx * fi + (j_center[0] as f32) * draws[0]; + let cy = 0.5 + dy * fi + (j_center[1] as f32) * draws[1]; + let px = pivot[0] as f32 + (j_pivot[0] as f32) * draws[2]; + let py = pivot[1] as f32 + (j_pivot[1] as f32) * draws[3]; + let sc_x = (x_size.powi(i) + j_x_size * draws[4]).max(1e-4); + let sc_y = (y_size.powi(i) + j_y_size * d_ys).max(1e-4); + let ang = (angle_deg * fi + j_angle * draws[6]).to_radians(); + let need_xform = (sc_x - sc_y).abs() > 1e-4 + || (px - 0.5).abs() > 1e-4 + || (py - 0.5).abs() > 1e-4; + + let is_last = i == n_extra; + let next = self.alloc_tex_like(&base, base.depth, if is_last && !need_post { key } else { 0 }); + let mut u = UniformParams::default(); + if need_xform { + let xformed = self.alloc_tex_like(©_src, copy_src.depth, 0); + let mut ut = UniformParams::default(); + ut.p[0] = [cx, cy, px, py]; + ut.p[1] = [sc_x, sc_y, ang, 0.0]; + ut.p[2] = [0.0, 0.0, 1.0, 0.0]; + ut.p[3] = [0.0, 0.0, 0.0, 0.0]; + self.dispatch_op(enc, ShaderOp::Transform, ©_src.view, &self.dummy.view, &self.dummy.view, &xformed, &ut); + copy_src = xformed; + u.p[0] = [0.5, 0.5, 1.0, 0.0]; + } else { + u.p[0] = [cx, cy, sc_x, ang]; + } + u.p[1] = [layer_w, ag_i, 0.0, 0.0]; + u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }]; + u.p[3] = [0.0, 0.0, copy_src.canvas_size[0] as f32, copy_src.canvas_size[1] as f32]; + u.p[6] = [burn_in, sub_add, 0.0, 0.0]; + self.dispatch_op(enc, ShaderOp::Merge, &cur_acc.view, ©_src.view, &self.dummy.view, &next, &u); + cur_acc = next; + } + cur_acc + }; + + if need_post { + let out = self.alloc_tex_like(&base, base.depth, key); + let mut ud = UniformParams::default(); + ud.p[0] = [ + 1.0, + blend, + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + ]; + ud.p[1] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + ud.p[2] = [1.0 - skip[0], 1.0 - skip[1], 1.0 - skip[2], 1.0 - skip[3]]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Dissolve, &base.view, &accum.view, mv, &out, &ud); + accum = out; + } + + self.cache.insert(key, accum.clone(), node.id, frame_i); + accum + } + + pub(in crate::eval) fn eval_kscope( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32; + let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); + let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians(); + let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32; + let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, slices, angle]; + u.p[1] = [cap_angle, scale, edges, blend]; + u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0]; + + let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec, crate::cache::EvalStats) { + let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t); + (eng.readback_rgba(&tex).unwrap(), stats) + } + + #[test] + fn test_fuse_kscope_6_slice_symmetry() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + KS1 = Fuse.KScope { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Slices = Input { Value = 6, }, + Scale = Input { Value = 1.0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse KScope comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let node_id = comp.find_node("KS1").expect("KS1"); + let (tex, _) = eng.evaluate(&comp, node_id, 0.0); + let rgba = eng.readback_rgba(&tex).expect("readback KScope"); + let [w, h] = tex.size; + assert_eq!((w, h), (128, 128)); + // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact! + let px = |x: usize, y: usize| -> [u8; 4] { + let i = (y * 128 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let a = px(64 + 28, 64 + 12); + let b = px(64 + 28, 63 - 12); + for c in 0..3 { + let diff = (a[c] as i32 - b[c] as i32).abs(); + assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}"); + } + } + + #[test] + fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() { + // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask. + let cases = [ + ("Drip", "Amplitude = Input { Value = 0, },", false), + ("Dent", "Strength = Input { Value = 0, },", false), + ("Vortex", "Angle = Input { Value = 0, },", false), + ("Displace", "", false), + ("Drip", "Blend = Input { Value = 0, },", true), + ("Vortex", "Blend = Input { Value = 0, },", true), + ]; + if Engine::new_headless().is_err() { + return; + } + for (kind, inputs, survives) in cases { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }}, + MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }}, + FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs} + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let mut eng = Engine::new_headless().unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3]; + assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask"); + assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask"); + } + } + + #[test] + fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() { + // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond + // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped. + let lit = |inputs: &str| -> [u8; 4] { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, + TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, + Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, + TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs} + Input = Input {{ SourceOp = "Flat", Source = "Output", }}, + Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let mut eng = Engine::new_headless().unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (32 * 64 + 32) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + if Engine::new_headless().is_err() { + return; + } + let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}"); + // Ramp slope per tap pair is 2/63 of full scale = ~8 levels. + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8); + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8); + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128); + // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively. + near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8); + // LightChannel 4 lights every channel from alpha, which is flat. + near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128); + near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128); + } + + #[test] + fn vortex_dod_input_and_effect_mask_align_to_canvas() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 0 }, + GlobalRange = { 0, 0 }, + Tools = ordered() { + Stripe = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 1.0, }, + TopRightAlpha = Input { Value = 1.0, }, + }, + }, + XF = DVE { + Inputs = { + Input = Input { SourceOp = "Stripe", Source = "Output", }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Mask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, + MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.75, 0.5 }, }, + Width = Input { Value = 0.25, }, + Height = Input { Value = 1.0, }, + }, + }, + V = Vortex { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + Angle = Input { Value = 180.0, }, + Size = Input { Value = 0.8, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Vortex DoD comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (v_tex, _) = eng.evaluate(&comp, comp.find_node("V").unwrap(), 0.0); + let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); + let v_px = eng.readback_rgba(&v_tex).unwrap(); + let xf_px = eng.readback_rgba(&xf_tex).unwrap(); + // Left of Mask (x in 0..40) must be identical to XF (Vortex must not warp outside canvas mask). + for x in 0..40 { + let i = (32 * 64 + x) * 4; + assert_eq!(&v_px[i..i + 4], &xf_px[i..i + 4], "Vortex mask misaligned at x={x}"); + } + } + + #[test] + fn displace_light_with_full_spread_is_a_two_tap_pass() { + let src = |light: f64| format!(r#"Composition {{ Tools = ordered() {{ + BG = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, + Ramp = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }}, + TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }}, + D = Displace {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Foreground = Input {{ SourceOp = "Ramp", Source = "Output", }}, + LightPower = Input {{ Value = {light}, }}, Spread = Input {{ Value = 1, }}, RefractionStrength = Input {{ Value = 0, }}, }}, }}, + }}, }}"#); + let Ok(mut eng) = Engine::new_headless() else { return }; + let lit = Comp::from_fusion_str(&src(1.0)).expect("parse lit comp"); + let flat = Comp::from_fusion_str(&src(0.0)).expect("parse flat comp"); + let (lit_px, _) = eval_px(&lit, &mut eng, "D", 0.0); + let (flat_px, _) = eval_px(&flat, &mut eng, "D", 0.0); + assert!(lit_px.iter().zip(&flat_px).any(|(a, b)| a.abs_diff(*b) > 2), "slope lighting must change the image"); + } + + #[test] + fn vortex_clamp_edges_and_process_skip_with_mbm() { + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, + M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, }, + V = Vortex { Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + Size = Input { Value = 2.0, }, + EffectMask = Input { SourceOp = "M", Source = "Mask", }, + MultiplyByMask = Input { Value = 1, }, + ProcessRed = Input { Value = 0, }, + }, }, + } }"#; + let comp = Comp::from_fusion_str(src).expect("parse vortex comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (px, _) = eval_px(&comp, &mut eng, "V", 0.0); + // Outside mask must be zeroed even for ProcessRed=0; inside mask stays solid red. + assert_eq!(&px[0..4], &[0, 0, 0, 0]); + let center = (32 * 64 + 32) * 4; + assert_eq!(&px[center..center + 4], &[255, 0, 0, 255]); + } + + #[test] + fn duplicate_luajit_prng_and_jitter_layers() { + let mut rng = LuaJitPrng::new(1.0); + let mut draws = [0.0f32; 12]; + for d in &mut draws { + *d = 0.5 * (*d + rng.next_signed() + 1.0); + } + assert!((draws[7] - 0.838_582).abs() < 1e-4, "draw[7] mismatch: {}", draws[7]); + assert!((draws[10] - 0.562_473).abs() < 1e-4, "draw[10] mismatch: {}", draws[10]); + assert!((draws[11] - 0.932_789).abs() < 1e-4, "draw[11] mismatch: {}", draws[11]); + + let src = r#"Composition { Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, + TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, + HalfCopy = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 0.5, }, }, }, + Jit = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 2, }, RandomSeed = Input { Value = 1, }, JitterRedGain = Input { Value = 0.5, }, }, }, + } }"#; + let comp = Comp::from_fusion_str(src).expect("parse duplicate comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + let half = eval_px(&comp, &mut eng, "HalfCopy", 0.0).0; + let c = (16 * 32 + 16) * 4; + assert!((half[c + 3] as i32 - 64).abs() <= 2, "Copies=0.5 scales alpha to ~64, got {}", half[c + 3]); + let jit = eval_px(&comp, &mut eng, "Jit", 0.0).0; + assert!(jit[c] > 220 && (jit[c] as i32 - jit[c + 1] as i32).abs() > 30, "JitterRedGain boosts R over G: {:?}", &jit[c..c + 4]); + } +} diff --git a/crates/engine/src/optflow.rs b/crates/engine/src/optflow.rs index ef783ff7cea74298ad0942eb7eb6877034814e29..61362de0cd77146facbddda6f03db3ad53c6c222 100644 --- a/crates/engine/src/optflow.rs +++ b/crates/engine/src/optflow.rs @@ -8,7 +8,19 @@ use std::collections::{HashMap, VecDeque}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::num::NonZeroU64; -use std::sync::{Mutex, RwLock}; +use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; + +fn lock_or_recover(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn read_or_recover(rw: &RwLock) -> RwLockReadGuard<'_, T> { + rw.read().unwrap_or_else(|e| e.into_inner()) +} + +fn write_or_recover(rw: &RwLock) -> RwLockWriteGuard<'_, T> { + rw.write().unwrap_or_else(|e| e.into_inner()) +} #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] @@ -706,28 +718,25 @@ impl OpticalFlowPipelines { /// Resets the dynamic uniform ring cursor back to slot `0`. /// Call only after all prior encoded passes on this pipeline have been submitted. pub fn reset_uniform_cursor(&self) { - self.uniform_ring.lock().unwrap().reset_cursor(); + lock_or_recover(&self.uniform_ring).reset_cursor(); } /// Clears cached flow fields and pooled intermediate pyramid textures, and trims uniform ring chunks. pub fn clear_scratch(&self) { - self.flow_cache.lock().unwrap().clear(); - self.pyramid_pool.lock().unwrap().clear(); - self.uniform_ring.lock().unwrap().trim_uniform_chunks(2); + lock_or_recover(&self.flow_cache).clear(); + lock_or_recover(&self.pyramid_pool).clear(); + lock_or_recover(&self.uniform_ring).trim_uniform_chunks(2); } /// Total resident GPU VRAM bytes currently held across pooled pyramid textures, /// cached flow-field textures, and dynamic uniform ring buffers. pub fn vram_bytes(&self) -> u64 { - let pool_bytes = self.pyramid_pool.lock().unwrap().total_bytes; - let flow_bytes: u64 = self - .flow_cache - .lock() - .unwrap() + let pool_bytes = lock_or_recover(&self.pyramid_pool).total_bytes; + let flow_bytes: u64 = lock_or_recover(&self.flow_cache) .iter() .map(|(_, _, _, size)| u64::from(size[0].max(1)) * u64::from(size[1].max(1)) * 8) .sum(); - let ring_bytes = self.uniform_ring.lock().unwrap().vram_bytes(); + let ring_bytes = lock_or_recover(&self.uniform_ring).vram_bytes(); pool_bytes .saturating_add(flow_bytes) .saturating_add(ring_bytes) @@ -740,11 +749,11 @@ impl OpticalFlowPipelines { entry: &str, format: wgpu::TextureFormat, ) { - if cache.read().unwrap().contains_key(&format) { + if read_or_recover(cache).contains_key(&format) { return; } let pipe = create_fullscreen_pipeline(device, &self.shader, &self.pipeline_layout, entry, format); - cache.write().unwrap().insert(format, pipe); + write_or_recover(cache).insert(format, pipe); } #[allow(clippy::too_many_arguments)] @@ -769,7 +778,7 @@ impl OpticalFlowPipelines { params, }; let (ubuf, dynamic_offset) = { - let mut ring = self.uniform_ring.lock().unwrap(); + let mut ring = lock_or_recover(&self.uniform_ring); ring.alloc_slot(device, queue, &uniform) }; @@ -842,7 +851,7 @@ impl OpticalFlowPipelines { let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 1, target_format); let dst = alloc_output_texture(device, frame_a, target_format, key); - let guard = self.blend_pipelines.read().unwrap(); + let guard = read_or_recover(&self.blend_pipelines); let pipe = guard.get(&target_format).unwrap(); self.run_pass( device, @@ -888,7 +897,7 @@ impl OpticalFlowPipelines { } else { let flow_key = (frame_a.content_hash, frame_b.content_hash, s0); let cached = { - let mut cache = self.flow_cache.lock().unwrap(); + let mut cache = lock_or_recover(&self.flow_cache); cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| { let entry = cache.remove(i); let view = entry.1.clone(); @@ -902,7 +911,7 @@ impl OpticalFlowPipelines { // Evict the LRU flow field before computing the new one so its backing // texture can be immediately reused by PyramidScratchPool. let evicted_before = { - let mut cache = self.flow_cache.lock().unwrap(); + let mut cache = lock_or_recover(&self.flow_cache); if cache.len() >= FLOW_CACHE_CAP { Some(cache.remove(0)) } else { @@ -910,14 +919,14 @@ impl OpticalFlowPipelines { } }; if let Some((_, old_view, old_tex, old_size)) = evicted_before { - self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); + lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size); } let (flow1_tex, flow1_view) = self.compute_flow_field(device, queue, enc, frame_a, frame_b); let evicted_after = { - let mut cache = self.flow_cache.lock().unwrap(); + let mut cache = lock_or_recover(&self.flow_cache); let extra = if cache.len() >= FLOW_CACHE_CAP { Some(cache.remove(0)) } else { @@ -927,7 +936,7 @@ impl OpticalFlowPipelines { extra }; if let Some((_, old_view, old_tex, old_size)) = evicted_after { - self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); + lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size); } flow1_view } @@ -943,7 +952,7 @@ impl OpticalFlowPipelines { 0.0, ]; { - let guard = self.warp_pipelines.read().unwrap(); + let guard = read_or_recover(&self.warp_pipelines); let pipe = guard.get(&target_format).unwrap(); self.run_pass( device, queue, enc, pipe, "optflow-warp", @@ -951,7 +960,7 @@ impl OpticalFlowPipelines { ); } if let Some(flow1_tex) = uncached_flow { - self.pyramid_pool.lock().unwrap().release(flow1_tex, flow1_view, s1); + lock_or_recover(&self.pyramid_pool).release(flow1_tex, flow1_view, s1); } dst } @@ -989,7 +998,7 @@ impl OpticalFlowPipelines { (flow1_raw_tex, flow1_raw_view), (flow1_tex, flow1_view), ) = { - let mut pool = self.pyramid_pool.lock().unwrap(); + let mut pool = lock_or_recover(&self.pyramid_pool); ( pool.acquire(device, s0, "optflow-fa0"), pool.acquire(device, s0, "optflow-fb0"), @@ -1082,7 +1091,7 @@ impl OpticalFlowPipelines { // are encoded in strict FIFO order on `enc`. Subsequent calls on the same or future // encoders execute strictly after these passes. { - let mut pool = self.pyramid_pool.lock().unwrap(); + let mut pool = lock_or_recover(&self.pyramid_pool); pool.release(fa0_tex, fa0_view, s0); pool.release(fb0_tex, fb0_view, s0); pool.release(fa1_tex, fa1_view, s1); @@ -1516,10 +1525,10 @@ mod tests { }; let first = interp(&cached, &tex_a, &tex_b, 0.25); - let field = cached.flow_cache.lock().unwrap()[0].1.clone(); + let field = lock_or_recover(&cached.flow_cache)[0].1.clone(); let second = interp(&cached, &tex_a, &tex_b, 0.75); { - let cache = cached.flow_cache.lock().unwrap(); + let cache = lock_or_recover(&cached.flow_cache); assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field"); assert!(cache[0].1 == field, "second alpha must hit the cached field texture"); } @@ -1529,7 +1538,7 @@ mod tests { for i in 2..8 { interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5); } - assert_eq!(cached.flow_cache.lock().unwrap().len(), FLOW_CACHE_CAP); + assert_eq!(lock_or_recover(&cached.flow_cache).len(), FLOW_CACHE_CAP); } #[test] @@ -1602,9 +1611,9 @@ mod tests { let (f_tex, f_view) = pooled.compute_flow_field(&device, &queue, &mut enc, &frames[i], &frames[i + 1]); queue.submit(Some(enc.finish())); - pooled.pyramid_pool.lock().unwrap().release(f_tex, f_view, half_size([w, h])); + lock_or_recover(&pooled.pyramid_pool).release(f_tex, f_view, half_size([w, h])); assert_eq!( - pooled.pyramid_pool.lock().unwrap().alloc_count, + lock_or_recover(&pooled.pyramid_pool).alloc_count, 14, "direct compute_flow_field alloc_count should remain 14 on pair {i}" ); @@ -1615,8 +1624,8 @@ mod tests { // 1 per flow_cache slot up to FLOW_CACHE_CAP, then stays completely flat). // - Output matches fresh unpooled OpticalFlowPipelines bit-for-bit. pooled.clear_scratch(); - pooled.pyramid_pool.lock().unwrap().alloc_count = 0; - pooled.pyramid_pool.lock().unwrap().reuse_count = 0; + lock_or_recover(&pooled.pyramid_pool).alloc_count = 0; + lock_or_recover(&pooled.pyramid_pool).reuse_count = 0; let mut stable_allocs = 0u64; for i in 0..8 { @@ -1633,7 +1642,7 @@ mod tests { queue.submit(Some(enc.finish())); let pooled_bytes = readback_bytes(&device, &queue, &out_pooled, 4); - let allocs_now = pooled.pyramid_pool.lock().unwrap().alloc_count; + let allocs_now = lock_or_recover(&pooled.pyramid_pool).alloc_count; if i < FLOW_CACHE_CAP { assert_eq!(allocs_now, 14 + i as u64); stable_allocs = allocs_now; @@ -1665,7 +1674,7 @@ mod tests { ); } assert!( - pooled.pyramid_pool.lock().unwrap().reuse_count >= 7 * 13, + lock_or_recover(&pooled.pyramid_pool).reuse_count >= 7 * 13, "expected substantial texture reuse across 8 distinct frame pairs" ); } @@ -1676,7 +1685,7 @@ mod tests { let pipelines = OpticalFlowPipelines::new(&device); let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); - let stride = pipelines.uniform_ring.lock().unwrap().stride; + let stride = lock_or_recover(&pipelines.uniform_ring).stride; assert_eq!(stride % min_align, 0); let (w, h) = (64u32, 64u32); @@ -1751,7 +1760,7 @@ mod tests { queue.submit(Some(enc.finish())); assert!( - pipelines.uniform_ring.lock().unwrap().chunks.len() >= 2, + lock_or_recover(&pipelines.uniform_ring).chunks.len() >= 2, "expected > 256 passes to allocate at least 2 uniform chunks" ); @@ -1813,11 +1822,11 @@ mod tests { let _out1 = pipelines.interpolate_flow(&device, &queue, &mut enc1, &a1, &b1, 0.5, fmt); queue.submit(Some(enc1.finish())); assert!( - pipelines.flow_cache.lock().unwrap().is_empty(), + lock_or_recover(&pipelines.flow_cache).is_empty(), "content_hash == 0 must bypass flow_cache" ); // All 14 textures (13 intermediate + temporary flow1) must be returned to pyramid_pool. - assert_eq!(pipelines.pyramid_pool.lock().unwrap().entries.len(), 14); + assert_eq!(lock_or_recover(&pipelines.pyramid_pool).entries.len(), 14); // Pair 2: completely different box positions, also with content_hash == 0 (or one side 0). let a2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 12), 0); @@ -1825,7 +1834,7 @@ mod tests { let mut enc2 = device.create_command_encoder(&Default::default()); let out2 = pipelines.interpolate_flow(&device, &queue, &mut enc2, &a2, &b2, 0.5, fmt); queue.submit(Some(enc2.finish())); - assert!(pipelines.flow_cache.lock().unwrap().is_empty()); + assert!(lock_or_recover(&pipelines.flow_cache).is_empty()); let fresh = OpticalFlowPipelines::new(&device); let mut fresh_enc = device.create_command_encoder(&Default::default()); @@ -1859,16 +1868,16 @@ mod tests { ); queue.submit(Some(enc.finish())); - let pool_bytes = pipelines.pyramid_pool.lock().unwrap().total_bytes; + let pool_bytes = lock_or_recover(&pipelines.pyramid_pool).total_bytes; let flow_bytes = u64::from(w / 2) * u64::from(h / 2) * 8; - let ring_bytes = pipelines.uniform_ring.lock().unwrap().vram_bytes(); + let ring_bytes = lock_or_recover(&pipelines.uniform_ring).vram_bytes(); assert!(pool_bytes > 0); assert!(ring_bytes > 0); assert_eq!(pipelines.vram_bytes(), pool_bytes + flow_bytes + ring_bytes); // Grow uniform ring beyond 2 chunks so clear_scratch() exercises trim_uniform_chunks(2). { - let mut ring = pipelines.uniform_ring.lock().unwrap(); + let mut ring = lock_or_recover(&pipelines.uniform_ring); let dummy_u = OptFlowUniform { dst_size: [1.0; 4], params: [0.0; 4], @@ -1881,13 +1890,13 @@ mod tests { assert!(pipelines.vram_bytes() > pool_bytes + flow_bytes + ring_bytes); pipelines.clear_scratch(); - assert_eq!(pipelines.pyramid_pool.lock().unwrap().total_bytes, 0); - assert!(pipelines.flow_cache.lock().unwrap().is_empty()); - assert_eq!(pipelines.uniform_ring.lock().unwrap().chunks.len(), 2); - let retained_ring = pipelines.uniform_ring.lock().unwrap().vram_bytes(); + assert_eq!(lock_or_recover(&pipelines.pyramid_pool).total_bytes, 0); + assert!(lock_or_recover(&pipelines.flow_cache).is_empty()); + assert_eq!(lock_or_recover(&pipelines.uniform_ring).chunks.len(), 2); + let retained_ring = lock_or_recover(&pipelines.uniform_ring).vram_bytes(); assert_eq!(pipelines.vram_bytes(), retained_ring); - pipelines.uniform_ring.lock().unwrap().trim_uniform_chunks(0); + lock_or_recover(&pipelines.uniform_ring).trim_uniform_chunks(0); assert_eq!(pipelines.vram_bytes(), 0); } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index e4b4746d56469b0d227750e27ca62bac2ed00889..c38fae1f1d7b137313a36eb89ab4e60c4a907651 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -20,7 +20,11 @@ pub use math::{ pub use shader::Vertex3D; use std::collections::HashMap; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, MutexGuard}; + +fn lock_or_recover(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} use crate::cache::CachedTexture; use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; @@ -72,7 +76,7 @@ fn cached_uniform_buffer( bytes.len().hash(&mut h); h.write(bytes); let key = (h.finish(), bytes.len()); - cache.lock().unwrap().get_or_insert_with(key, || { + lock_or_recover(cache).get_or_insert_with(key, || { let size = (bytes.len() as u64).max(16); let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), @@ -873,24 +877,22 @@ impl Scene3DRenderer { key: u64, build: impl FnOnce() -> Vec, ) -> Arc> { - if let Some(hit) = self.text3d_mesh_cache.lock().unwrap().get(key) { + if let Some(hit) = lock_or_recover(&self.text3d_mesh_cache).get(key) { return hit; } let built = Arc::new(build()); - self.text3d_mesh_cache - .lock() - .unwrap() + lock_or_recover(&self.text3d_mesh_cache) .get_or_insert_with(key, || Arc::clone(&built)) } /// Drops cached shadow cube-map targets, main-pass depth targets, memoized `Text3D` CPU meshes, /// cached GPU mesh vertex/index buffers, and pooled uniform buffers. pub fn clear_shadow_targets(&self) { - *self.shadow_targets.lock().unwrap() = None; - self.depth_targets.lock().unwrap().clear(); - self.text3d_mesh_cache.lock().unwrap().clear(); - self.meshes.lock().unwrap().clear(); - self.uniform_cache.lock().unwrap().clear(); + *lock_or_recover(&self.shadow_targets) = None; + lock_or_recover(&self.depth_targets).clear(); + lock_or_recover(&self.text3d_mesh_cache).clear(); + lock_or_recover(&self.meshes).clear(); + lock_or_recover(&self.uniform_cache).clear(); } /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes. @@ -900,7 +902,7 @@ impl Scene3DRenderer { /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float). pub fn shadow_vram_bytes(&self) -> u64 { - self.shadow_targets.lock().unwrap().as_ref().map_or(0, |t| { + lock_or_recover(&self.shadow_targets).as_ref().map_or(0, |t| { let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4; layer_bytes * (u64::from(t.layers) + 1) }) @@ -908,9 +910,7 @@ impl Scene3DRenderer { /// Total GPU VRAM in bytes currently occupied by pooled main-pass `Depth32Float` targets. pub fn depth_vram_bytes(&self) -> u64 { - self.depth_targets - .lock() - .unwrap() + lock_or_recover(&self.depth_targets) .entries .values() .map(|(_, dt)| u64::from(dt.tex.width()) * u64::from(dt.tex.height()) * 4) @@ -919,9 +919,7 @@ impl Scene3DRenderer { /// Total GPU VRAM in bytes currently occupied by cached vertex and index buffers. pub fn mesh_vram_bytes(&self) -> u64 { - self.meshes - .lock() - .unwrap() + lock_or_recover(&self.meshes) .entries .values() .filter_map(|(_, gm)| gm.as_ref()) @@ -931,12 +929,12 @@ impl Scene3DRenderer { /// Total GPU VRAM in bytes currently occupied by cached uniform buffers. pub fn uniform_vram_bytes(&self) -> u64 { - self.uniform_cache.lock().unwrap().total_bytes + lock_or_recover(&self.uniform_cache).total_bytes } #[cfg(test)] pub(crate) fn gpu_mesh_count(&self) -> usize { - self.meshes.lock().unwrap().entries.len() + lock_or_recover(&self.meshes).entries.len() } #[allow(clippy::too_many_arguments)] @@ -957,7 +955,7 @@ impl Scene3DRenderer { meshes: &[DrawMesh], ) { let depth_size = [dst.size[0].max(1), dst.size[1].max(1)]; - let depth_target = self.depth_targets.lock().unwrap().get_or_insert_with(depth_size, || { + let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || { let tex = device.create_texture(&wgpu::TextureDescriptor { label: Some("scene3d-depth"), size: wgpu::Extent3d { @@ -1012,7 +1010,7 @@ impl Scene3DRenderer { let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf); let shadow_targets = (!shadow_lights.is_empty()).then(|| { let layers = 6 * shadow_lights.len() as u32; - let mut cache = self.shadow_targets.lock().unwrap(); + let mut cache = lock_or_recover(&self.shadow_targets); match cache.as_ref() { Some(t) if t.layers >= layers => t.clone(), _ => { @@ -1163,7 +1161,7 @@ impl Scene3DRenderer { upload() } else { let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe); - self.meshes.lock().unwrap().get_or_insert_with(key, upload) + lock_or_recover(&self.meshes).get_or_insert_with(key, upload) }; let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else { continue; @@ -1592,7 +1590,7 @@ mod tests { let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]); renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes); queue.submit(Some(enc.finish())); - renderer.meshes.lock().unwrap().entries.len() + lock_or_recover(&renderer.meshes).entries.len() }; assert_eq!(frame(&[sphere(0.0, false)]), 1); assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload"); @@ -1759,7 +1757,7 @@ mod tests { assert_eq!(renderer.shadow_vram_bytes(), 0); let _ = renderer.get_or_build_text3d_mesh(42, || vec![Vertex3D { pos: [0.0; 3], normal: [0.0, 0.0, 1.0], uv: [0.0; 2] }]); - assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 1); + assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 1); let tex = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -1806,7 +1804,7 @@ mod tests { renderer.clear_shadow_targets(); assert_eq!(renderer.shadow_vram_bytes(), 0); assert_eq!(renderer.depth_vram_bytes(), 0); - assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 0); + assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 0); } #[test] @@ -1855,19 +1853,19 @@ mod tests { }; render_empty(&dst_a); - assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 1); + assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); render_empty(&dst_a); - assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 1); + assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); render_empty(&dst_b); - assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 2); + assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 2); assert_eq!(renderer.depth_vram_bytes(), (16 * 16 + 32 * 16) * 4); renderer.clear_targets(); - assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 0); + assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 0); assert_eq!(renderer.depth_vram_bytes(), 0); } @@ -1942,25 +1940,25 @@ mod tests { let vram_1 = renderer.mesh_vram_bytes(); assert_eq!(renderer.gpu_mesh_count(), 1); assert!(vram_1 > 0); - assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1); + assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1); render_one(make_custom(0.0)); assert_eq!(renderer.gpu_mesh_count(), 1, "rebuilt identical Arc must hit content-keyed mesh cache"); assert_eq!(renderer.mesh_vram_bytes(), vram_1); - assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "identical uniform bytes reuse cached buffer"); + assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "identical uniform bytes reuse cached buffer"); // 2. Eviction stays strictly bounded by MAX_CACHED_MESH_BUFFERS (128). for i in 1..=(MAX_CACHED_MESH_BUFFERS + 20) { render_one(make_custom(i as f32 * 0.01)); } assert_eq!(renderer.gpu_mesh_count(), MAX_CACHED_MESH_BUFFERS); - assert!(renderer.uniform_cache.lock().unwrap().entries.len() <= UNIFORM_CACHE_CAP); + assert!(lock_or_recover(&renderer.uniform_cache).entries.len() <= UNIFORM_CACHE_CAP); // 3. clear_shadow_targets() (called by bust_gpu_cache) releases all cached GPU mesh and uniform buffers. renderer.clear_shadow_targets(); assert_eq!(renderer.gpu_mesh_count(), 0); assert_eq!(renderer.mesh_vram_bytes(), 0); - assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 0); + assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 0); } #[test] @@ -2134,13 +2132,13 @@ mod tests { assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES); // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools. - renderer.meshes.lock().unwrap().max_bytes = single_mesh_bytes + single_mesh_bytes / 2; - renderer.uniform_cache.lock().unwrap().max_bytes = single_uni_bytes + single_uni_bytes / 2; + lock_or_recover(&renderer.meshes).max_bytes = single_mesh_bytes + single_mesh_bytes / 2; + lock_or_recover(&renderer.uniform_cache).max_bytes = single_uni_bytes + single_uni_bytes / 2; render_one(make_mesh(20, 1.0)); assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh"); assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes); - assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "uniform byte cap must evict LRU uniform"); + assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "uniform byte cap must evict LRU uniform"); assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes); renderer.clear_shadow_targets();