diff --git a/crates/engine/src/eval/blur_glow.rs b/crates/engine/src/eval/blur_glow.rs index c383cbcf8cb7e10306d876b5ac70f00f5c24b719..937bf6a770c6fc75380791a56c3d5cdef726e78f 100644 --- a/crates/engine/src/eval/blur_glow.rs +++ b/crates/engine/src/eval/blur_glow.rs @@ -34,13 +34,18 @@ impl Engine { let ry = y_raw * scale_ref * gauss_k; let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 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 max_r = rx.max(ry); if max_r < 0.25 || blend <= 1e-6 { return src; } + let src = if node.connected_node("EffectMask").is_some() { + self.crop_to_canvas(enc, src) + } else { + 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 key = self.make_key(node, "Blur", src.size, &[src.content_hash, mask_hash], &[rx, ry, blend, mode, clamp_edges, if mask_inv { 1.0 } else { 0.0 }]); if let Some(hit) = self.cache.get(key, node.id, frame_i) { @@ -625,6 +630,11 @@ impl Engine { let chan = ["Red", "Green", "Blue", "Alpha"] .map(|c| if comp.eval_number(node, c, time, 1.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }); let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let src = if node.connected_node("EffectMask").is_some() { + self.crop_to_canvas(enc, src) + } else { + 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 key = self.make_key( @@ -1449,4 +1459,68 @@ mod tests { near(at(&x_only, 98, 64, 0), 230, "X amount dilates horizontally"); near(at(&x_only, 64, 98, 0), 26, "YAmount=0 with LockXY=0 leaves vertical edge untouched"); } + + #[test] + fn blur_and_erode_dilate_dod_effect_mask_align_to_canvas() { + let src = 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.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + XF = DVE { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Mask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, + MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.875, 0.5 }, }, + Width = Input { Value = 0.25, }, + Height = Input { Value = 1.0, }, + }, + }, + B = Blur { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + XBlurSize = Input { Value = 20.0, }, + }, + }, + ED = ErodeDilate { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + Amount = Input { Value = 0.08, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse DoD mask blur/ed comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); + let xf_px = eng.readback_rgba(&xf_tex).unwrap(); + let (b_tex, _) = eng.evaluate(&comp, comp.find_node("B").unwrap(), 0.0); + let b_px = eng.readback_rgba(&b_tex).unwrap(); + let (ed_tex, _) = eng.evaluate(&comp, comp.find_node("ED").unwrap(), 0.0); + let ed_px = eng.readback_rgba(&ed_tex).unwrap(); + // XF spans [0..48), Mask spans [48..64): so x in [0..47) is outside Mask and must match XF exactly! + for x in 0..47 { + let i = (32 * 64 + x) * 4; + assert_eq!(&b_px[i..i + 4], &xf_px[i..i + 4], "Blur mask misaligned at x={x}"); + assert_eq!(&ed_px[i..i + 4], &xf_px[i..i + 4], "ErodeDilate mask misaligned at x={x}"); + } + } } diff --git a/crates/engine/src/eval/color.rs b/crates/engine/src/eval/color.rs index a301908a07e696e4fd7f0e4ea53b17f91cc13bbc..e6fce90739c0bfa54ad977647948db46a0804e6e 100644 --- a/crates/engine/src/eval/color.rs +++ b/crates/engine/src/eval/color.rs @@ -20,7 +20,8 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let has_mask = node.connected_node("EffectMask").is_some(); + let src = if has_mask { self.crop_to_canvas(enc, src) } else { 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); @@ -89,7 +90,8 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let has_mask = node.connected_node("EffectMask").is_some(); + let src = if has_mask { self.crop_to_canvas(enc, src) } else { 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); @@ -201,6 +203,8 @@ impl Engine { }; let src = self.eval_node(comp, src_id, time, enc, visiting, stats); let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + let has_mask = node.connected_node("EffectMask").is_some(); + let src = if has_mask { self.crop_to_canvas(enc, src) } else { 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); @@ -455,7 +459,7 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src }; let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32; let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32; let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32; @@ -499,7 +503,8 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let has_mask = node.connected_node("EffectMask").is_some(); + let src = if has_mask { self.crop_to_canvas(enc, src) } else { 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); @@ -542,52 +547,75 @@ impl Engine { dst } - pub(super) fn eval_color_curves( - &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 mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; - if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { - return src; - } - let src = self.crop_to_canvas(enc, src); - let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; - let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.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); - + pub(super) fn build_color_curves_lut_f16(comp: &Comp, node: &Node) -> ([u16; 256 * 4], u64, bool) { let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s)); let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s)); let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s)); let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s)); let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty()); - let mut lut_bytes = [0u8; 256 * 4]; + let mut lut_f16 = [0u16; 256 * 4]; for i in 0..256 { let x = i as f64 / 255.0; let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); - lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8; + lut_f16[i * 4] = crate::media::f32_to_f16_bits(r as f32); + lut_f16[i * 4 + 1] = crate::media::f32_to_f16_bits(g as f32); + lut_f16[i * 4 + 2] = crate::media::f32_to_f16_bits(b as f32); + lut_f16[i * 4 + 3] = crate::media::f32_to_f16_bits(a as f32); } let mut lh = DefaultHasher::new(); - lut_bytes.hash(&mut lh); - let lut_hash = lh.finish(); + lut_f16.hash(&mut lh); + (lut_f16, lh.finish(), apply_a) + } + + pub(super) fn upload_lut_f16(&self, lut_f16: &[u16; 256 * 4]) -> CachedTexture { + let lut_tex = create_texture_dod_fmt( + &self.device, + [256, 1], + [0, 0], + [256, 1], + BitDepth::Float16, + wgpu::TextureFormat::Rgba16Float, + 0, + ); + self.queue.write_texture( + lut_tex.texture.as_image_copy(), + bytemuck::cast_slice(lut_f16), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 8), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, + ); + lut_tex + } + + pub(super) fn eval_color_curves( + &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 mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; + if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { + return src; + } + let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src }; + let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; + let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.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 (lut_f16, lut_hash, apply_a) = Self::build_color_curves_lut_f16(comp, node); let mut u = UniformParams::default(); u.p[0] = [prediv, ignore_trans, blend, if mask.is_some() { 1.0 } else { 0.0 }]; @@ -607,13 +635,7 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let lut_tex = create_texture(&self.device, [256, 1], 0); - self.queue.write_texture( - lut_tex.texture.as_image_copy(), - &lut_bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, - wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, - ); + let lut_tex = self.upload_lut_f16(&lut_f16); let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::ColorCurves, &src.view, &lut_tex.view, mv, &dst, &u); @@ -640,7 +662,7 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src }; let map_space = |s: Option<&str>| -> f32 { match s.unwrap_or("NoChange") { "sRGB" => 1.0, @@ -695,7 +717,7 @@ impl Engine { if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) { return src; } - let src = self.crop_to_canvas(enc, src); + let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src }; let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.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); @@ -778,6 +800,7 @@ impl Engine { if blend <= 1e-6 || strength.abs() <= 1e-6 { return src; } + let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src }; let x_size = comp.eval_number(node, "MasterXSize", time, 1.0, &self.expr) as f32; let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5; let y_size = if lock_size { @@ -1073,5 +1096,215 @@ mod tests { // srgb_to_linear(0.5) = 0.21404 -> ~55 assert!((p[0] as i32 - 55).abs() <= 2 && p[0] == p[1] && p[1] == p[2], "p={p:?}"); } + + #[test] + fn brightness_contrast_negative_gamma_preserves_transparent_zero() { + // Gain=0.8, Lift=-1.0, Gamma=2.71, Contrast=-0.37 on transparent black (0,0,0,0): + // v = -1.0 must NOT be clamped to 0.0 before Contrast, or it turns into +0.185 (47/255) gray. + let comp = r#"{ + Tools = ordered() { + Bg = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopLeftAlpha = Input { Value = 0.0, }, + }, + }, + BC = BrightnessContrast { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Gain = Input { Value = 0.8, }, + Lift = Input { Value = -1.0, }, + Gamma = Input { Value = 2.71, }, + Contrast = Input { Value = -0.37, }, + }, + }, + } + }"#; + let p = eval_node_px(comp, "BC"); + assert_eq!(p, [0, 0, 0, 0], "transparent black must stay [0,0,0,0], got {p:?}"); + } + + #[test] + fn color_curves_identity_f16_lut_error_below_1e3() { + let comp_src = r#"{ + Tools = ordered() { + Bg = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.1, }, + TopLeftGreen = Input { Value = 0.25, }, + TopLeftBlue = Input { Value = 0.73, }, + TopLeftAlpha = Input { Value = 1.0, }, + Depth = Input { Value = 2, }, + }, + }, + CC = ColorCurves { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let id = comp.find_node("CC").expect("CC"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (tex, _) = eng.evaluate(&comp, id, 0.0); + assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float); + let [w, h] = tex.size; + let unpadded_bpr = w * 8; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf = eng.device().create_buffer(&wgpu::BufferDescriptor { + label: Some("cc-f16-readback"), + size: u64::from(padded_bpr) * u64::from(h), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = eng.device().create_command_encoder(&Default::default()); + enc.copy_texture_to_buffer( + tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + eng.queue().submit(Some(enc.finish())); + let slice = buf.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + let _ = eng.device().poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }); + rx.recv().unwrap().unwrap(); + let data = slice.get_mapped_range().unwrap(); + let row = ((h / 2) * padded_bpr) as usize; + let col = ((w / 2) * 8) as usize; + let px_bytes = &data[row + col..row + col + 8]; + let f16_to_f32 = |lo: u8, hi: u8| -> f32 { + let h = u16::from_le_bytes([lo, hi]); + let sign = u32::from(h >> 15) << 31; + let exp = u32::from((h >> 10) & 0x1f); + let frac = u32::from(h & 0x3ff); + let bits = if exp == 0 { + if frac == 0 { + sign + } else { + let mut e = 127 - 14; + let mut m = frac; + while (m & 0x400) == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 0x3ff) << 13) + } + } else if exp == 0x1f { + sign | (0xff << 23) | (frac << 13) + } else { + sign | ((exp + 112) << 23) | (frac << 13) + }; + f32::from_bits(bits) + }; + let r = f16_to_f32(px_bytes[0], px_bytes[1]); + let g = f16_to_f32(px_bytes[2], px_bytes[3]); + let b = f16_to_f32(px_bytes[4], px_bytes[5]); + assert!((r - 0.1).abs() < 1e-3, "identity ColorCurves red={r}, expected 0.1"); + assert!((g - 0.25).abs() < 1e-3, "identity ColorCurves green={g}, expected 0.25"); + assert!((b - 0.73).abs() < 1e-3, "identity ColorCurves blue={b}, expected 0.73"); + } + + #[test] + fn colorize_and_film_grain_dod_effect_mask_align_to_canvas() { + // Transform shifts a 64x64 image left by 0.25 (creates DoD origin_x < 0, width > 64). + // EffectMask covers only the right quarter (x in [48, 64)) in canvas coordinates. + let comp_src = r#"{ + Tools = ordered() { + Bg = 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.0, }, + }, + }, + XF = DVE { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Mask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, + MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.875, 0.5 }, }, + Width = Input { Value = 0.25, }, + Height = Input { Value = 1.0, }, + }, + }, + CZ = Fuse.Colorize { + Inputs = { + Image = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + R2 = Input { Value = 1.0, }, + G2 = Input { Value = 0.0, }, + B2 = Input { Value = 0.0, }, + A2 = Input { Value = 1.0, }, + }, + }, + FG = FilmGrain { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + MasterStrength = Input { Value = 1.0, }, + Seed = Input { Value = 7, }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (cz_tex, _) = eng.evaluate(&comp, comp.find_node("CZ").unwrap(), 0.0); + let cz_px = eng.readback_rgba(&cz_tex).unwrap(); + let at = |buf: &[u8], x: usize, y: usize| -> [u8; 4] { + let i = (y * 64 + x) * 4; + [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] + }; + // x=32 is inside shifted Bg [0..48) and OUTSIDE Mask [48..64): must stay un-colorized (0,0,0,0 at 48+, gray at 32) + let inside_xf_outside_mask = at(&cz_px, 32, 32); + assert_eq!(inside_xf_outside_mask[0], inside_xf_outside_mask[1], "x=32 must be unmasked gray: {inside_xf_outside_mask:?}"); + // x=56 is inside Mask [48..64) and outside shifted Bg -> remains transparent [0,0,0,0] (or colorized with c1=0,0,0,0 -> [0,0,0,0]), + // whereas if mask was misplaced onto DoD texel coords it would colorize x < 48! + for x in 0..46 { + let p = at(&cz_px, x, 32); + assert!((p[0] as i32 - p[1] as i32).abs() <= 1, "mask leaked onto x={x}: {p:?}"); + } + + let (fg_tex, _) = eng.evaluate(&comp, comp.find_node("FG").unwrap(), 0.0); + let fg_px = eng.readback_rgba(&fg_tex).unwrap(); + // Outside mask [0..46), FilmGrain must leave XF untouched (gray ~128). + for x in 0..46 { + let p = at(&fg_px, x, 32); + assert!((p[0] as i32 - 128).abs() <= 1, "FilmGrain leaked outside mask at x={x}: {p:?}"); + } + } } diff --git a/crates/engine/src/eval/keyers.rs b/crates/engine/src/eval/keyers.rs index 30a612593448301de92fc32f143e9076363cd41a..9c117a3e4e814c800fbe43e79260fe6096ea001e 100644 --- a/crates/engine/src/eval/keyers.rs +++ b/crates/engine/src/eval/keyers.rs @@ -15,6 +15,11 @@ impl Engine { return self.dummy.clone(); }; let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let src = if node.connected_node("EffectMask").is_some() { + self.crop_to_canvas(enc, src) + } else { + 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); @@ -99,5 +104,63 @@ impl Engine { self.cache.insert(key, dst.clone(), node.id, frame_i); dst } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn luma_key_dod_effect_mask_align_to_canvas() { + let src = 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.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + XF = DVE { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Center = Input { Value = { 0.25, 0.5 }, }, + }, + }, + Mask = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 64, }, + MaskHeight = Input { Value = 64, }, + Center = Input { Value = { 0.875, 0.5 }, }, + Width = Input { Value = 0.25, }, + Height = Input { Value = 1.0, }, + }, + }, + LK = LumaKeyer { + Inputs = { + Input = Input { SourceOp = "XF", Source = "Output", }, + EffectMask = Input { SourceOp = "Mask", Source = "Mask", }, + Low = Input { Value = 0.8, }, + High = Input { Value = 0.9, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse LumaKeyer DoD mask comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0); + let xf_px = eng.readback_rgba(&xf_tex).unwrap(); + let (lk_tex, _) = eng.evaluate(&comp, comp.find_node("LK").unwrap(), 0.0); + let lk_px = eng.readback_rgba(&lk_tex).unwrap(); + for x in 0..47 { + let i = (32 * 64 + x) * 4; + assert_eq!(&lk_px[i..i + 4], &xf_px[i..i + 4], "LumaKey mask misaligned at x={x}"); + } + } } diff --git a/crates/engine/src/eval/transform.rs b/crates/engine/src/eval/transform.rs index 6b18ebd0034e9c0aebe94b3e9e6b4ca8a8a8dfad..d7a7dea35c6aee946cd3d51476ca7005d5b38749 100644 --- a/crates/engine/src/eval/transform.rs +++ b/crates/engine/src/eval/transform.rs @@ -189,6 +189,154 @@ fn compute_transform_source_roi( ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32]) } +fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool { + let mut queue = vec![start_name]; + let mut seen = HashSet::new(); + let mut feeds_dod_reader = false; + while let Some(cur_name) = queue.pop() { + if !seen.insert(cur_name) { + continue; + } + for n in &comp.nodes { + for (port, binding) in &n.inputs { + if binding.source_op.as_deref() != Some(cur_name) { + continue; + } + if port == "EffectMask" || port == "GlowMask" { + return false; + } + match n.kind.as_str() { + "Saver" | "MediaOut" | "Displace" | "CustomTool" | "Vortex" | "Fuse.KScope" | "UltraKeyer" => { + // Terminal or self-cropping ops absorb DoD safely without misaligning downstream. + } + "Merge" => { + if port == "Foreground" { + feeds_dod_reader = true; + } + queue.push(n.name.as_str()); + } + "Transform" | "DVE" | "CornerPositioner" => { + if port == "Input" { + feeds_dod_reader = true; + queue.push(n.name.as_str()); + } else { + return false; + } + } + "BrightnessContrast" + | "ColorCorrector" + | "ColorCurves" + | "ColorGain" + | "InvertColor" + | "GamutConvert" + | "HueCurves" + | "ChangeDepth" + | "PipeRouter" + | "Fuse.Wireless" + | "Tracker" + | "SetDomain" + | "LumaKeyer" + | "Fuse.Colorize" + | "DirectionalBlur" + | "Glow" + | "SoftGlow" + | "Blur" + | "ErodeDilate" => { + queue.push(n.name.as_str()); + } + _ => { + // Crop, Scale, BetterResize, etc. ignore src.origin. + return false; + } + } + } + } + } + feeds_dod_reader +} + +#[allow(clippy::too_many_arguments)] +fn compute_transform_dst_dod( + src: &CachedTexture, + center: [f64; 2], + pivot: [f64; 2], + sx: f32, + sy: f32, + angle: f32, + flip_h: bool, + flip_v: bool, + max_dim: u32, +) -> ([i32; 2], [u32; 2]) { + let cw = src.canvas_size[0].max(1) as f32; + let ch = src.canvas_size[1].max(1) as f32; + let sx = sx.max(1e-5); + let sy = sy.max(1e-5); + let shift_x = center[0] as f32 - 0.5; + let shift_y = center[1] as f32 - 0.5; + let piv_x = pivot[0] as f32; + let piv_y = pivot[1] as f32; + let (s, c) = angle.sin_cos(); + + let u0 = src.origin[0] as f32 / cw; + let u1 = (src.origin[0] + src.size[0] as i32) as f32 / cw; + let v0 = 1.0 - (src.origin[1] + src.size[1] as i32) as f32 / ch; + let v1 = 1.0 - src.origin[1] as f32 / ch; + + let mut min_x = 0.0_f32; + let mut min_y = 0.0_f32; + let mut max_x = cw; + let mut max_y = ch; + for &(fu, fv) in &[(u0, v0), (u1, v0), (u0, v1), (u1, v1)] { + let pu = if flip_h { 1.0 - fu } else { fu }; + let pv = if flip_v { 1.0 - fv } else { fv }; + let sc_x = (pu - piv_x) * cw * sx; + let sc_y = (pv - piv_y) * ch * sy; + let rot_x = sc_x * c - sc_y * s; + let rot_y = sc_x * s + sc_y * c; + let dst_u = rot_x / cw + piv_x + shift_x; + let dst_v = rot_y / ch + piv_y + shift_y; + let px_x = dst_u * cw; + let px_y = (1.0 - dst_v) * ch; + min_x = min_x.min(px_x); + max_x = max_x.max(px_x); + min_y = min_y.min(px_y); + max_y = max_y.max(px_y); + } + min_x = min_x.min(src.origin[0] as f32); + max_x = max_x.max((src.origin[0] + src.size[0] as i32) as f32); + min_y = min_y.min(src.origin[1] as f32); + max_y = max_y.max((src.origin[1] + src.size[1] as i32) as f32); + + let pad = 2_i32; + let max_pad = 2048_i32; + let mut x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 }; + let mut y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 }; + let mut x1 = if max_x > cw + 0.25 { + (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad) + } else { + src.canvas_size[0] as i32 + }; + let mut y1 = if max_y > ch + 0.25 { + (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad) + } else { + src.canvas_size[1] as i32 + }; + let cap = max_dim.max(src.canvas_size[0]).max(src.canvas_size[1]) as i32; + if x1 - x0 > cap { + let excess = (x1 - x0) - cap; + let trim_l = (0 - x0).max(0).min(excess); + x0 += trim_l; + x1 -= excess - trim_l; + } + if y1 - y0 > cap { + let excess = (y1 - y0) - cap; + let trim_t = (0 - y0).max(0).min(excess); + y0 += trim_t; + y1 -= excess - trim_t; + } + ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32]) +} + fn build_cc_uniforms(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine, blend: f32) -> UniformParams { let mut u = UniformParams::default(); u.p[0] = [ @@ -466,28 +614,11 @@ impl Engine { } let prediv = comp.eval_number(&node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32; let ignore_trans = comp.eval_number(&node, "IgnoreTransparent", time, 0.0, &self.expr) as f32; - let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s)); - let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s)); - let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s)); - let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s)); - let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty()); - - let mut lut_bytes = [0u8; 256 * 4]; - for i in 0..256 { - let x = i as f64 / 255.0; - let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); - let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); - let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); - let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x)); - lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8; - lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8; - } + let (lut_f16, mut lut_hash, apply_a) = Self::build_color_curves_lut_f16(comp, &node); let mut lh = DefaultHasher::new(); - lut_bytes.hash(&mut lh); + lut_hash.hash(&mut lh); src.origin.hash(&mut lh); - let lut_hash = lh.finish(); + lut_hash = lh.finish(); let mut u = UniformParams::default(); u.p[0] = [prediv, ignore_trans, blend, 0.0]; @@ -499,13 +630,7 @@ impl Engine { } stats.cache_misses += 1; stats.nodes_evaluated += 1; - let lut_tex = create_texture(&self.device, [256, 1], 0); - self.queue.write_texture( - lut_tex.texture.as_image_copy(), - &lut_bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, - wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, - ); + let lut_tex = self.upload_lut_f16(&lut_f16); let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key); self.dispatch_op(enc, ShaderOp::ColorCurves, &src.view, &lut_tex.view, &self.dummy.view, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -636,6 +761,18 @@ impl Engine { 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 (dst_origin, dst_size) = if !invert + && edges.round() as i32 == 0 + && mask.is_none() + && transform_should_expand_dod(comp, &node.name) + { + let max_dim = self.device.limits().max_texture_dimension_2d.min(4096); + compute_transform_dst_dod(&src, center, pivot, sx, sy, angle, flip_h > 0.5, flip_v > 0.5, max_dim) + } else { + ([0, 0], src.canvas_size) + }; + let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size; + let mut u = UniformParams::default(); u.p[0] = [center[0] as f32, center[1] as f32, pivot[0] as f32, pivot[1] as f32]; u.p[1] = [sx, sy, angle, edges]; @@ -650,9 +787,16 @@ impl Engine { src.canvas_size[1] as f32, ]; } + if has_dst_dod { + u.p[5] = [ + dst_origin[0] as f32, + dst_origin[1] as f32, + src.canvas_size[0] as f32, + src.canvas_size[1] as f32, + ]; + } - let out_size = src.canvas_size; - let key = self.make_key(node, "Transform", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5])); + let key = self.make_key(node, "Transform", 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; @@ -660,7 +804,8 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let dst = self.alloc_tex(out_size, src.depth, key); + let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key); + dst.tex_scale = src.tex_scale; let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u); self.cache.insert(key, dst.clone(), node.id, frame_i); @@ -747,6 +892,7 @@ impl Engine { if blend <= 1e-6 || angle_deg.abs() <= 1e-5 { 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 center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); @@ -1629,4 +1775,125 @@ mod tests { 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}"); + } + } } diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index b56128e809036837b28115b8a3a6105a70acbe72..4f1a1f5af8fa0f44c458a6b4d4bf7d2eb373aa91 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -3,17 +3,25 @@ //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode). -use std::collections::{HashMap, HashSet}; +use std::collections::hash_map::DefaultHasher; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::hash::{Hash, Hasher}; -use model::{Comp, ExprEngine, Gradient, Node, NodeId}; +use model::{BezierSpline, Comp, ExprEngine, Gradient, InputBinding, Node, NodeId, ParamValue}; /// Maximum simultaneous live particles kept in a single simulation to prevent /// pathological comps from hanging or exhausting memory. const MAX_PARTICLES: usize = 20_000; -/// Maximum lookback frames from `target_frame` when `sim_start` is far earlier. +/// Maximum cold-start lookback frames from `target_frame` when `base_start` is far earlier. const MAX_SIM_WINDOW: i64 = 600; +/// Periodic snapshot interval (frames from `base_start`) for fast backward scrubbing. +const SNAPSHOT_INTERVAL: i64 = 60; + +/// Maximum periodic snapshots retained per cached particle simulation. +const MAX_SNAPSHOTS: usize = 32; + /// Particle integration step: `Velocity` moves `0.1` render widths per frame and /// forces accelerate by `0.1^2` per unit of `Strength`. const VELOCITY_SCALE: f64 = 0.1; @@ -39,11 +47,12 @@ pub struct SpriteImage { /// Persistent frame-to-frame cache for deterministic particle simulations. /// -/// Keyed by `(render_node, comp.revision)`. Advancing sequentially `f -> f+1` -/// only steps 1 frame instead of re-simulating from `sim_start`. +/// Keyed by `(render_node_name, subgraph_hash)`. Advancing sequentially `f -> f+1` +/// only steps 1 frame even past `MAX_SIM_WINDOW`, while periodic snapshots every +/// `SNAPSHOT_INTERVAL` frames accelerate backward scrubbing. #[derive(Default)] pub struct ParticleCache { - entries: HashMap<(NodeId, u64), CachedSim>, + entries: HashMap<(String, u64), CachedSim>, } impl ParticleCache { @@ -54,21 +63,22 @@ impl ParticleCache { #[derive(Clone)] struct CachedSim { - sim_start: i64, + base_start: i64, current_frame: i64, state: SimState, + snapshots: BTreeMap, } #[derive(Clone, Default)] struct SimState { particles: Vec, - /// Fractional emission accumulator per `pEmitter` node. - emit_accum: HashMap, + /// Fractional emission accumulator per `pEmitter` stable name hash. + emit_accum: HashMap, } #[derive(Clone, Copy, Debug)] struct Particle { - emitter_id: NodeId, + emitter_hash: u64, pos: [f64; 3], vel: [f64; 3], rot_z: f64, @@ -89,15 +99,26 @@ enum ParticleStyleKind { Brush, } +/// Stable FNV-1a 64-bit hash of a node name (independent of `NodeId` index). +#[inline] +fn stable_name_hash(name: &str) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325_u64; + for &b in name.as_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} + /// Deterministic SplitMix64 PRNG. #[derive(Clone, Copy)] struct SplitMix64(u64); impl SplitMix64 { - fn from_parts(seed: i64, frame: i64, node_id: usize) -> Self { + fn from_parts(seed: i64, frame: i64, node_name: &str) -> Self { let mut s = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); s ^= (frame as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9); - s ^= (node_id as u64).wrapping_mul(0x94D0_49BB_1331_11EB); + s ^= stable_name_hash(node_name).wrapping_mul(0x94D0_49BB_1331_11EB); let mut rng = Self(s ^ 0xD1B5_4A32_D192_ED03); let _ = rng.next_u64(); rng @@ -228,17 +249,19 @@ fn collect_bitmap_sources_dfs( /// Flattened, topologically-ordered particle graph upstream of a `pRender` node. struct ParticlePlan { - emitters: Vec, + emitters: Vec<(NodeId, u64)>, /// Forces/modifiers in topological order along with the set of upstream - /// emitters whose particles flow through each modifier. - modifiers: Vec<(NodeId, HashSet)>, + /// emitter name hashes whose particles flow through each modifier. + modifiers: Vec<(NodeId, HashSet)>, + emitter_nodes: HashMap, } fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan { let mut visited = HashSet::new(); let mut emitters = Vec::new(); let mut modifiers = Vec::new(); - let mut upstream_emitters: HashMap> = HashMap::new(); + let mut upstream_emitters: HashMap> = HashMap::new(); + let mut emitter_nodes = HashMap::new(); build_plan_dfs( comp, @@ -247,11 +270,13 @@ fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan { &mut emitters, &mut modifiers, &mut upstream_emitters, + &mut emitter_nodes, ); ParticlePlan { emitters, modifiers, + emitter_nodes, } } @@ -259,10 +284,11 @@ fn build_plan_dfs( comp: &Comp, node_id: NodeId, visited: &mut HashSet, - emitters: &mut Vec, - modifiers: &mut Vec<(NodeId, HashSet)>, - upstream_emitters: &mut HashMap>, -) -> HashSet { + emitters: &mut Vec<(NodeId, u64)>, + modifiers: &mut Vec<(NodeId, HashSet)>, + upstream_emitters: &mut HashMap>, + emitter_nodes: &mut HashMap, +) -> HashSet { if let Some(cached) = upstream_emitters.get(&node_id) { return cached.clone(); } @@ -286,14 +312,17 @@ fn build_plan_dfs( emitters, modifiers, upstream_emitters, + emitter_nodes, ); scope.extend(up_set); } if node.kind == "pEmitter" { if !node.bypassed { - emitters.push(node_id); - scope.insert(node_id); + let emitter_hash = stable_name_hash(&node.name); + emitters.push((node_id, emitter_hash)); + emitter_nodes.insert(emitter_hash, node_id); + scope.insert(emitter_hash); } } else if !node.bypassed && matches!( @@ -314,6 +343,185 @@ fn build_plan_dfs( scope } +fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) { + spline.name.hash(h); + spline.keyframes.len().hash(h); + for kf in &spline.keyframes { + kf.time.to_bits().hash(h); + kf.value.to_bits().hash(h); + if let Some([lx, ly]) = kf.lh { + 1u8.hash(h); + lx.to_bits().hash(h); + ly.to_bits().hash(h); + } else { + 0u8.hash(h); + } + if let Some([rx, ry]) = kf.rh { + 1u8.hash(h); + rx.to_bits().hash(h); + ry.to_bits().hash(h); + } else { + 0u8.hash(h); + } + [ + kf.flags.linear, + kf.flags.step_in, + kf.flags.step_out, + kf.flags.loop_after, + kf.flags.loop_rel, + kf.flags.ping_pong, + kf.flags.locked_y, + ] + .hash(h); + (kf.handle_mode as u8).hash(h); + } +} + +fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) { + grad.stops.len().hash(h); + for stop in &grad.stops { + stop.pos.to_bits().hash(h); + for c in stop.rgba { + c.to_bits().hash(h); + } + } +} + +fn hash_input_binding(comp: &Comp, binding: &InputBinding, h: &mut DefaultHasher) { + binding.source_output.hash(h); + binding.expression.hash(h); + match &binding.value { + None => 0u8.hash(h), + Some(ParamValue::Number(v)) => { + 1u8.hash(h); + v.to_bits().hash(h); + } + Some(ParamValue::Point([x, y])) => { + 2u8.hash(h); + x.to_bits().hash(h); + y.to_bits().hash(h); + } + Some(ParamValue::Text(s)) => { + 3u8.hash(h); + s.hash(h); + } + Some(ParamValue::FuId(s)) => { + 4u8.hash(h); + s.hash(h); + } + Some(ParamValue::Gradient(g)) => { + 5u8.hash(h); + hash_gradient(g, h); + } + Some(ParamValue::Raw(raw)) => { + 6u8.hash(h); + format!("{raw:?}").hash(h); + } + } + binding.source_op.hash(h); + if let Some(op) = &binding.source_op { + if let Some(sp) = comp.splines.get(op) { + hash_spline(sp, h); + } + if let Some(pp) = comp.poly_paths.get(op) { + pp.name.hash(h); + pp.displacement_op.hash(h); + pp.displacement_value.to_bits().hash(h); + pp.closed.hash(h); + pp.points.len().hash(h); + for pt in &pp.points { + pt.x.to_bits().hash(h); + pt.y.to_bits().hash(h); + pt.lx.to_bits().hash(h); + pt.ly.to_bits().hash(h); + pt.rx.to_bits().hash(h); + pt.ry.to_bits().hash(h); + pt.linear.hash(h); + } + if let Some(disp_op) = &pp.displacement_op { + if let Some(sp) = comp.splines.get(disp_op) { + hash_spline(sp, h); + } + } + } + if let Some(sh) = comp.shakes.get(op) { + hash_sorted_inputs(comp, &sh.inputs, h); + } + if let Some(ex) = comp.expression_modifiers.get(op) { + hash_sorted_inputs(comp, &ex.inputs, h); + } + if let Some(gm) = comp.gradient_modifiers.get(op) { + gm.len().hash(h); + for (t, g) in gm { + t.to_bits().hash(h); + hash_gradient(g, h); + } + } + } +} + +fn hash_sorted_inputs(comp: &Comp, inputs: &HashMap, h: &mut DefaultHasher) { + let mut keys: Vec<&String> = inputs.keys().collect(); + keys.sort_unstable(); + keys.len().hash(h); + for k in keys { + k.hash(h); + hash_input_binding(comp, &inputs[k], h); + } +} + +/// Content hash of the particle simulation subgraph upstream of `render_node`. +/// Unrelated edits outside the particle branch leave this hash unchanged. +fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 { + fn dfs(comp: &Comp, node_id: NodeId, is_root: bool, visited: &mut HashSet, h: &mut DefaultHasher) { + if !visited.insert(node_id) { + return; + } + let Some(node) = comp.nodes.get(node_id.0) else { + return; + }; + if !is_particle_node_kind(&node.kind) { + return; + } + node.name.hash(h); + node.kind.hash(h); + node.bypassed.hash(h); + + let mut keys: Vec<&String> = node.inputs.keys().collect(); + keys.sort_unstable(); + for k in keys { + // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state. + if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" { + continue; + } + k.hash(h); + hash_input_binding(comp, &node.inputs[k], h); + } + for up_id in particle_stream_inputs(comp, node) { + dfs(comp, up_id, false, visited, h); + } + } + + let mut h = DefaultHasher::new(); + base_start.hash(&mut h); + let mut visited = HashSet::new(); + dfs(comp, render_node, true, &mut visited, &mut h); + h.finish() +} + +fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) { + if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 { + cached.snapshots.insert(frame, cached.state.clone()); + while cached.snapshots.len() > MAX_SNAPSHOTS { + if let Some(&oldest) = cached.snapshots.keys().next() { + cached.snapshots.remove(&oldest); + } else { + break; + } + } + } +} + /// Runs deterministic frame-stepped particle simulation up to `time.floor()` and /// rasterizes all live particles into a premultiplied RGBA8 buffer of size /// `dims[0] * dims[1] * 4`. @@ -350,46 +558,63 @@ pub fn render_particles_2d( } else { comp.global_range[0] }; - let sim_start = base_start.max(target_frame - MAX_SIM_WINDOW); - if target_frame < sim_start { + if target_frame < base_start { return out; } - // Evict stale revisions for this render node. - let key = (render_node, comp.revision); + let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); + let key = (rnode.name.clone(), subgraph_hash); + // Evict stale subgraph hashes for this render node while keeping other pRender entries. cache .entries - .retain(|&(nid, rev), _| nid != render_node || rev == comp.revision); + .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash); - let need_reset = match cache.entries.get(&key) { - Some(cached) => { - target_frame < cached.current_frame - || target_frame == sim_start - || cached.sim_start != sim_start + let cold_sim_start = |target: i64| base_start.max(target - MAX_SIM_WINDOW); + + let need_cold_init = match cache.entries.get_mut(&key) { + Some(cached) if cached.base_start == base_start => { + if target_frame == cached.current_frame { + false + } else if target_frame > cached.current_frame { + if target_frame - cached.current_frame <= MAX_SIM_WINDOW { + for f in (cached.current_frame + 1)..=target_frame { + step_simulation(&mut cached.state, comp, &plan, f, expr); + maybe_record_snapshot(cached, f); + } + cached.current_frame = target_frame; + false + } else { + true + } + } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() { + cached.state = snap_state.clone(); + cached.current_frame = snap_f; + for f in (snap_f + 1)..=target_frame { + step_simulation(&mut cached.state, comp, &plan, f, expr); + maybe_record_snapshot(cached, f); + } + cached.current_frame = target_frame; + false + } else { + true + } } - None => true, + _ => true, }; - if need_reset { - let mut state = SimState::default(); + if need_cold_init { + let sim_start = cold_sim_start(target_frame); + let mut sim = CachedSim { + base_start, + current_frame: target_frame, + state: SimState::default(), + snapshots: BTreeMap::new(), + }; for f in sim_start..=target_frame { - step_simulation(&mut state, comp, &plan, f, expr); - } - cache.entries.insert( - key, - CachedSim { - sim_start, - current_frame: target_frame, - state, - }, - ); - } else if let Some(cached) = cache.entries.get_mut(&key) { - if target_frame > cached.current_frame { - for f in (cached.current_frame + 1)..=target_frame { - step_simulation(&mut cached.state, comp, &plan, f, expr); - } - cached.current_frame = target_frame; + step_simulation(&mut sim.state, comp, &plan, f, expr); + maybe_record_snapshot(&mut sim, f); } + cache.entries.insert(key.clone(), sim); } let Some(cached) = cache.entries.get(&key) else { @@ -402,6 +627,7 @@ pub fn render_particles_2d( dims, dims[0] as f64 / render_width, comp, + &plan.emitter_nodes, &cached.state.particles, time, expr, @@ -447,14 +673,14 @@ fn step_simulation( // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region). let first_new = state.particles.len(); - for &emitter_id in &plan.emitters { + for &(emitter_id, emitter_hash) in &plan.emitters { if state.particles.len() >= MAX_PARTICLES { break; } let Some(node) = comp.nodes.get(emitter_id.0) else { continue; }; - emit_particles(state, comp, node, emitter_id, frame, t, expr); + emit_particles(state, comp, node, emitter_hash, frame, t, expr); } // A newborn is damped by friction and then integrated once on its birth frame; other forces @@ -479,13 +705,13 @@ fn emit_particles( state: &mut SimState, comp: &Comp, node: &Node, - emitter_id: NodeId, + emitter_hash: u64, frame: i64, t: f64, expr: &ExprEngine, ) { let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; - let mut rng = SplitMix64::from_parts(seed, frame, emitter_id.0); + let mut rng = SplitMix64::from_parts(seed, frame, &node.name); let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0); let number_var = comp @@ -493,7 +719,7 @@ fn emit_particles( .max(0.0); let rate = (number + rng.signed() * number_var).max(0.0); - let accum = state.emit_accum.entry(emitter_id).or_insert(0.0); + let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0); *accum += rate; let mut emit_count = accum.floor() as usize; *accum -= emit_count as f64; @@ -600,7 +826,7 @@ fn emit_particles( }; state.particles.push(Particle { - emitter_id, + emitter_hash, pos, vel, rot_z, @@ -1068,7 +1294,7 @@ fn apply_modifier( particles: &mut [Particle], comp: &Comp, node: &Node, - scope: &HashSet, + scope: &HashSet, t: f64, expr: &ExprEngine, ) { @@ -1084,7 +1310,7 @@ fn apply_modifier( let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr); for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } let dx = tx - p.pos[0]; @@ -1119,7 +1345,7 @@ fn apply_modifier( let az = mag * dir_z.sin(); for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } p.vel[0] += ax; @@ -1140,7 +1366,7 @@ fn apply_modifier( 1.0 }; for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } p.vel[0] *= damp; @@ -1161,7 +1387,7 @@ fn apply_modifier( let time_shift = t * 0.03; for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } let qx = p.pos[0] * density + time_shift; @@ -1186,7 +1412,7 @@ fn apply_modifier( Some("Outside") | Some("Leaving") ); for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } let inside = region.contains(p.pos); @@ -1203,10 +1429,10 @@ fn apply_modifier( let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0); let spin = comp.eval_number(node, "Spin", t, 0.0, expr); let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; - let mut rng = SplitMix64::from_parts(seed, t.round() as i64, node.id.0); + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); for p in particles.iter_mut() { - if !p.alive || !scope.contains(&p.emitter_id) { + if !p.alive || !scope.contains(&p.emitter_hash) { continue; } let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else { @@ -1289,6 +1515,7 @@ fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 { } struct EmitterRenderProps<'a> { + emitter_id: NodeId, style: ParticleStyleKind, tiny_sprite: Option<([f64; 2], SpriteImage)>, ngon_sides: f64, @@ -1300,16 +1527,20 @@ struct EmitterRenderProps<'a> { fn collect_emitter_render_props<'a>( comp: &'a Comp, + emitter_nodes: &HashMap, particles: &[Particle], time: f64, expr: &ExprEngine, -) -> HashMap> { +) -> HashMap> { let mut map = HashMap::new(); for p in particles { - if map.contains_key(&p.emitter_id) { + if map.contains_key(&p.emitter_hash) { continue; } - let Some(node) = comp.nodes.get(p.emitter_id.0) else { + let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else { + continue; + }; + let Some(node) = comp.nodes.get(emitter_id.0) else { continue; }; let style = match node.static_str("Style") { @@ -1338,8 +1569,9 @@ fn collect_emitter_render_props<'a>( None }; map.insert( - p.emitter_id, + p.emitter_hash, EmitterRenderProps { + emitter_id, style, tiny_sprite: tiny_background_sprite(comp, node, time, expr), ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0), @@ -1385,11 +1617,13 @@ fn tiny_background_sprite( Some(([w, h], SpriteImage { size: [1, 1], rgba })) } +#[allow(clippy::too_many_arguments)] fn rasterize_particles( out: &mut [u8], dims: [u32; 2], px_scale: f64, comp: &Comp, + emitter_nodes: &HashMap, particles: &[Particle], time: f64, expr: &ExprEngine, @@ -1399,7 +1633,7 @@ fn rasterize_particles( return; } - let props_map = collect_emitter_render_props(comp, particles, time, expr); + let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr); let w = dims[0] as usize; let h = dims[1] as usize; let w_f = w as f64; @@ -1412,7 +1646,7 @@ fn rasterize_particles( if !p.alive { continue; } - let Some(props) = props_map.get(&p.emitter_id) else { + let Some(props) = props_map.get(&p.emitter_hash) else { continue; }; @@ -1463,7 +1697,7 @@ fn rasterize_particles( let (sprite, nominal) = match &props.tiny_sprite { Some((nominal, sprite)) => (Some(sprite), *nominal), None => { - let sprite = sprites.get(&p.emitter_id); + let sprite = sprites.get(&props.emitter_id); (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64])) } }; @@ -2149,4 +2383,142 @@ Composition {{ let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new()); assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]); } + + #[test] + fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() { + let comp_src = r#" +Composition { + GlobalRange = { 0, 800 }, + RenderRange = { 0, 800 }, + Tools = { + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 7, }, + Number = Input { Value = 2, }, + Lifespan = Input { Value = 25, }, + Velocity = Input { Value = 0.2, }, + VelocityVariance = Input { Value = 0.1, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp"); + let render_id = comp.node_by_name["pRender1"]; + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + let dims = [64, 64]; + + let mut cache = ParticleCache::default(); + let mut last_img = Vec::new(); + for f in 580..=625 { + last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites); + } + + let key = ( + "pRender1".to_owned(), + particle_subgraph_hash(&comp, render_id, 0), + ); + let cached = cache.entries.get(&key).expect("cached entry"); + assert_eq!(cached.base_start, 0); + assert_eq!(cached.current_frame, 625); + assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600"); + + // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605. + let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites); + let mut fresh_cache = ParticleCache::default(); + let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites); + assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation"); + + let mut fresh_625_cache = ParticleCache::default(); + let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites); + assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation"); + } + + #[test] + fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() { + let with_unrelated = r#" +Composition { + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Tools = { + UnrelatedBg = Background { + Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, }, + }, + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 19, }, + Number = Input { Value = 8, }, + Lifespan = Input { Value = 40, }, + Velocity = Input { Value = 0.5, }, + VelocityVariance = Input { Value = 0.25, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let without_unrelated = r#" +Composition { + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Tools = { + pEmitter1 = pEmitter { + Inputs = { + RandomSeed = Input { Value = 19, }, + Number = Input { Value = 8, }, + Lifespan = Input { Value = 40, }, + Velocity = Input { Value = 0.5, }, + VelocityVariance = Input { Value = 0.25, }, + AngleVariance = Input { Value = 180, }, + }, + }, + pRender1 = pRender { + Inputs = { + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + }, + }, +} +"#; + let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a"); + let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b"); + let ra = comp_a.node_by_name["pRender1"]; + let rb = comp_b.node_by_name["pRender1"]; + assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds"); + + let expr = ExprEngine::new(); + let sprites = HashMap::new(); + let dims = [64, 64]; + + let mut cache_a = ParticleCache::default(); + let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites); + + // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation. + comp_a.revision += 99; + let hash_before = particle_subgraph_hash(&comp_a, ra, 0); + let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0); + assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes"); + + let mut cache_b = ParticleCache::default(); + let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites); + assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles"); + + // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21. + let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites); + let mut fresh_b = ParticleCache::default(); + let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites); + assert_eq!(img_a_to_b_21, img_b_21); + } } diff --git a/crates/engine/src/shaders/color.wgsl b/crates/engine/src/shaders/color.wgsl index fe1da773bc46aeb2f31fb1a309a7c81b6a4c0b35..8a539629a4554c73bf4baa7fea406a241ebf6b37 100644 --- a/crates/engine/src/shaders/color.wgsl +++ b/crates/engine/src/shaders/color.wgsl @@ -35,8 +35,8 @@ fn bc_curve_scalar(v_in: f32, low: f32, high: f32, gain: f32, lift: f32, gamma: v = (v - low) / span; } v = v * (gain - lift) + lift; - if (gamma != 1.0) { - v = pow(max(v, 0.0), 1.0 / gamma); + if (gamma != 1.0 && v > 0.0) { + v = pow(v, 1.0 / gamma); } v = (v - 0.5) * (1.0 + contrast) + 0.5; v = v + brightness; @@ -463,12 +463,15 @@ fn color_curves_op(@builtin(global_invocation_id) gid: vec3) { rgb = clamp(rgb / src.a, vec3(0.0), vec3(1.0)); } - let r = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.r, 0.0, 1.0), 0.5), 0.0).r; - let g = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.g, 0.0, 1.0), 0.5), 0.0).g; - let b = textureSampleLevel(src_b, samp_lin, vec2(clamp(rgb.b, 0.0, 1.0), 0.5), 0.0).b; + let lut_n = f32(textureDimensions(src_b).x); + let lut_u = (vec3(0.5) + clamp(rgb, vec3(0.0), vec3(1.0)) * (lut_n - 1.0)) / lut_n; + let r = textureSampleLevel(src_b, samp_lin, vec2(lut_u.r, 0.5), 0.0).r; + let g = textureSampleLevel(src_b, samp_lin, vec2(lut_u.g, 0.5), 0.0).g; + let b = textureSampleLevel(src_b, samp_lin, vec2(lut_u.b, 0.5), 0.0).b; var a = src.a; if (apply_a) { - a = textureSampleLevel(src_b, samp_lin, vec2(clamp(src.a, 0.0, 1.0), 0.5), 0.0).a; + let a_u = (0.5 + clamp(src.a, 0.0, 1.0) * (lut_n - 1.0)) / lut_n; + a = textureSampleLevel(src_b, samp_lin, vec2(a_u, 0.5), 0.0).a; } var out_rgb = vec3(r, g, b); diff --git a/crates/engine/src/shaders/keyers_gen.wgsl b/crates/engine/src/shaders/keyers_gen.wgsl index 21cd37cf1096b6a89abb31f8d824fc57e07da675..3156f4f25d0a3038eb5c8bc870f8ad1067f309b8 100644 --- a/crates/engine/src/shaders/keyers_gen.wgsl +++ b/crates/engine/src/shaders/keyers_gen.wgsl @@ -115,7 +115,9 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3) { val = clamp(val + 0.5 * brightness, 0.0, 1.0); // Fusion leaves the ramp color unpremultiplied; downstream Merge treats it as premultiplied - store_dst(vec2(gid.xy), textureSampleLevel(src_b, samp_lin, vec2(val, 0.5), 0.0)); + let lut_n = f32(textureDimensions(src_b).x); + let lut_u = (0.5 + clamp(val, 0.0, 1.0) * (lut_n - 1.0)) / lut_n; + store_dst(vec2(gid.xy), textureSampleLevel(src_b, samp_lin, vec2(lut_u, 0.5), 0.0)); } // ============================================================================ // 12. Fuse.Outline (Clover's exact 2020 Outline.fuse passes!) diff --git a/crates/engine/src/shaders/transform.wgsl b/crates/engine/src/shaders/transform.wgsl index 6a47b084a55fe226c8ea59596ed18c7cd6fb53b4..2650fef8d28c6aed128214f5c88e25238b350e7a 100644 --- a/crates/engine/src/shaders/transform.wgsl +++ b/crates/engine/src/shaders/transform.wgsl @@ -9,8 +9,16 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3) { let dims = textureDimensions(dst_tex); if (gid.x >= dims.x || gid.y >= dims.y) { return; } - let fdims = vec2(dims); - let fu = pix_to_fu(gid.xy, dims); + let has_dst_dod = u.p[5].z > 0.5 && u.p[5].w > 0.5; + let fdims = select(vec2(dims), u.p[5].zw, has_dst_dod); + let fu = select( + pix_to_fu(gid.xy, dims), + vec2( + (f32(gid.x) + 0.5 + u.p[5].x) / u.p[5].z, + 1.0 - (f32(gid.y) + 0.5 + u.p[5].y) / u.p[5].w, + ), + has_dst_dod, + ); let center = u.p[0].xy; let pivot = u.p[0].zw; @@ -43,7 +51,11 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3) { let nearest = u.p[3].y > 0.5; let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest); let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest); - let raw_mask = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x); + let raw_mask = select( + read_mask(gid.xy, dims, u.p[2].w, u.p[3].x), + read_mask_uv(fu_to_uv(fu), u.p[2].w, u.p[3].x), + has_dst_dod, + ); let mbm = u.p[3].z > 0.5; let m = select(raw_mask, 1.0, mbm) * u.p[2].z; var out_col = mix(orig, moved, clamp(m, 0.0, 1.0)); @@ -194,9 +206,11 @@ fn xf_chroma_op(@builtin(global_invocation_id) gid: vec3) { var grad_sum = vec4(0.0); let inv_steps = 1.0 / f32(steps); + let grad_n = f32(textureDimensions(src_b).x); for (var i = 0; i <= steps; i = i + 1) { let n = f32(i) * inv_steps; - let grad = textureSampleLevel(src_b, samp_lin, vec2(n, 0.5), 0.0); + let grad_u = (0.5 + clamp(n, 0.0, 1.0) * (grad_n - 1.0)) / grad_n; + let grad = textureSampleLevel(src_b, samp_lin, vec2(grad_u, 0.5), 0.0); let cur_c = mix(vec2(0.5, 0.5), center, n); let cur_sx = max(mix(1.0, xsize, n), 1e-4);