authoravatarclover caruso<git@paperclover.net>2026-11-30 20:25:03-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:40:12-08:00
loga9e082f3772c8342dd079ae2c2823f4b5e9bf91f
tree282ed29e095ce3424b6a11958973414fe53190fb
parentaffa4033bbacab68dca669d1c550f3e7cb5e7227
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix BrightnessContrast negative-gamma/DoD, ColorCurves f16 LUT, DoD masks, and particle caching


8 files changed, 1179 insertions(+), 151 deletions(-)

crates/engine/src/eval/blur_glow.rs+76-2
......@@ -34,13 +34,18 @@ impl Engine {
3434 let ry = y_raw * scale_ref * gauss_k;
3535 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
3636 let clamp_edges = if node.static_str("ClippingMode").unwrap_or("Frame") == "None" { 0.0 } else { 1.0 };
37 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
38 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
3937
4038 let max_r = rx.max(ry);
4139 if max_r < 0.25 || blend <= 1e-6 {
4240 return src;
4341 }
42 let src = if node.connected_node("EffectMask").is_some() {
43 self.crop_to_canvas(enc, src)
44 } else {
45 src
46 };
47 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
48 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
4449
4550 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 }]);
4651 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
......@@ -625,6 +630,11 @@ impl Engine {
625630 let chan = ["Red", "Green", "Blue", "Alpha"]
626631 .map(|c| if comp.eval_number(node, c, time, 1.0, &self.expr) > 0.5 { 1.0 } else { 0.0 });
627632 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
633 let src = if node.connected_node("EffectMask").is_some() {
634 self.crop_to_canvas(enc, src)
635 } else {
636 src
637 };
628638 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
629639 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
630640 let key = self.make_key(
......@@ -1449,4 +1459,68 @@ mod tests {
14491459 near(at(&x_only, 98, 64, 0), 230, "X amount dilates horizontally");
14501460 near(at(&x_only, 64, 98, 0), 26, "YAmount=0 with LockXY=0 leaves vertical edge untouched");
14511461 }
1462
1463 #[test]
1464 fn blur_and_erode_dilate_dod_effect_mask_align_to_canvas() {
1465 let src = r#"Composition {
1466 CurrentTime = 0,
1467 RenderRange = { 0, 0 },
1468 GlobalRange = { 0, 0 },
1469 Tools = ordered() {
1470 Bg = Background {
1471 Inputs = {
1472 Width = Input { Value = 64, },
1473 Height = Input { Value = 64, },
1474 TopLeftRed = Input { Value = 1.0, },
1475 TopLeftAlpha = Input { Value = 1.0, },
1476 },
1477 },
1478 XF = DVE {
1479 Inputs = {
1480 Input = Input { SourceOp = "Bg", Source = "Output", },
1481 Center = Input { Value = { 0.25, 0.5 }, },
1482 },
1483 },
1484 Mask = RectangleMask {
1485 Inputs = {
1486 MaskWidth = Input { Value = 64, },
1487 MaskHeight = Input { Value = 64, },
1488 Center = Input { Value = { 0.875, 0.5 }, },
1489 Width = Input { Value = 0.25, },
1490 Height = Input { Value = 1.0, },
1491 },
1492 },
1493 B = Blur {
1494 Inputs = {
1495 Input = Input { SourceOp = "XF", Source = "Output", },
1496 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1497 XBlurSize = Input { Value = 20.0, },
1498 },
1499 },
1500 ED = ErodeDilate {
1501 Inputs = {
1502 Input = Input { SourceOp = "XF", Source = "Output", },
1503 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1504 Amount = Input { Value = 0.08, },
1505 },
1506 },
1507 },
1508 }"#;
1509 let comp = Comp::from_fusion_str(src).expect("parse DoD mask blur/ed comp");
1510 let Ok(mut eng) = Engine::new_headless() else {
1511 return;
1512 };
1513 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
1514 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
1515 let (b_tex, _) = eng.evaluate(&comp, comp.find_node("B").unwrap(), 0.0);
1516 let b_px = eng.readback_rgba(&b_tex).unwrap();
1517 let (ed_tex, _) = eng.evaluate(&comp, comp.find_node("ED").unwrap(), 0.0);
1518 let ed_px = eng.readback_rgba(&ed_tex).unwrap();
1519 // XF spans [0..48), Mask spans [48..64): so x in [0..47) is outside Mask and must match XF exactly!
1520 for x in 0..47 {
1521 let i = (32 * 64 + x) * 4;
1522 assert_eq!(&b_px[i..i + 4], &xf_px[i..i + 4], "Blur mask misaligned at x={x}");
1523 assert_eq!(&ed_px[i..i + 4], &xf_px[i..i + 4], "ErodeDilate mask misaligned at x={x}");
1524 }
1525 }
14521526}
crates/engine/src/eval/color.rs+268-35
......@@ -20,7 +20,8 @@ impl Engine {
2020 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
2121 return src;
2222 }
23 let src = self.crop_to_canvas(enc, src);
23 let has_mask = node.connected_node("EffectMask").is_some();
24 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
2425 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
2526 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2627
......@@ -89,7 +90,8 @@ impl Engine {
8990 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
9091 return src;
9192 }
92 let src = self.crop_to_canvas(enc, src);
93 let has_mask = node.connected_node("EffectMask").is_some();
94 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
9395 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
9496 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
9597
......@@ -201,6 +203,8 @@ impl Engine {
201203 };
202204 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
203205 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
206 let has_mask = node.connected_node("EffectMask").is_some();
207 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
204208 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
205209 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
206210
......@@ -455,7 +459,7 @@ impl Engine {
455459 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
456460 return src;
457461 }
458 let src = self.crop_to_canvas(enc, src);
462 let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src };
459463 let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32;
460464 let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32;
461465 let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32;
......@@ -499,7 +503,8 @@ impl Engine {
499503 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
500504 return src;
501505 }
502 let src = self.crop_to_canvas(enc, src);
506 let has_mask = node.connected_node("EffectMask").is_some();
507 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
503508 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
504509 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
505510
......@@ -542,6 +547,49 @@ impl Engine {
542547 dst
543548 }
544549
550 pub(super) fn build_color_curves_lut_f16(comp: &Comp, node: &Node) -> ([u16; 256 * 4], u64, bool) {
551 let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s));
552 let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s));
553 let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s));
554 let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s));
555 let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty());
556
557 let mut lut_f16 = [0u16; 256 * 4];
558 for i in 0..256 {
559 let x = i as f64 / 255.0;
560 let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
561 let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
562 let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
563 let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
564 lut_f16[i * 4] = crate::media::f32_to_f16_bits(r as f32);
565 lut_f16[i * 4 + 1] = crate::media::f32_to_f16_bits(g as f32);
566 lut_f16[i * 4 + 2] = crate::media::f32_to_f16_bits(b as f32);
567 lut_f16[i * 4 + 3] = crate::media::f32_to_f16_bits(a as f32);
568 }
569 let mut lh = DefaultHasher::new();
570 lut_f16.hash(&mut lh);
571 (lut_f16, lh.finish(), apply_a)
572 }
573
574 pub(super) fn upload_lut_f16(&self, lut_f16: &[u16; 256 * 4]) -> CachedTexture {
575 let lut_tex = create_texture_dod_fmt(
576 &self.device,
577 [256, 1],
578 [0, 0],
579 [256, 1],
580 BitDepth::Float16,
581 wgpu::TextureFormat::Rgba16Float,
582 0,
583 );
584 self.queue.write_texture(
585 lut_tex.texture.as_image_copy(),
586 bytemuck::cast_slice(lut_f16),
587 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 8), rows_per_image: Some(1) },
588 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
589 );
590 lut_tex
591 }
592
545593 pub(super) fn eval_color_curves(
546594 &mut self,
547595 comp: &Comp,
......@@ -561,33 +609,13 @@ impl Engine {
561609 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
562610 return src;
563611 }
564 let src = self.crop_to_canvas(enc, src);
612 let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src };
565613 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
566614 let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.0, &self.expr) as f32;
567615 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
568616 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
569617
570 let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s));
571 let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s));
572 let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s));
573 let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s));
574 let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty());
575
576 let mut lut_bytes = [0u8; 256 * 4];
577 for i in 0..256 {
578 let x = i as f64 / 255.0;
579 let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
580 let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
581 let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
582 let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
583 lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
584 lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
585 lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
586 lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8;
587 }
588 let mut lh = DefaultHasher::new();
589 lut_bytes.hash(&mut lh);
590 let lut_hash = lh.finish();
618 let (lut_f16, lut_hash, apply_a) = Self::build_color_curves_lut_f16(comp, node);
591619
592620 let mut u = UniformParams::default();
593621 u.p[0] = [prediv, ignore_trans, blend, if mask.is_some() { 1.0 } else { 0.0 }];
......@@ -607,13 +635,7 @@ impl Engine {
607635 stats.cache_misses += 1;
608636 stats.nodes_evaluated += 1;
609637
610 let lut_tex = create_texture(&self.device, [256, 1], 0);
611 self.queue.write_texture(
612 lut_tex.texture.as_image_copy(),
613 &lut_bytes,
614 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
615 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
616 );
638 let lut_tex = self.upload_lut_f16(&lut_f16);
617639 let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key);
618640 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
619641 self.dispatch_op(enc, ShaderOp::ColorCurves, &src.view, &lut_tex.view, mv, &dst, &u);
......@@ -640,7 +662,7 @@ impl Engine {
640662 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
641663 return src;
642664 }
643 let src = self.crop_to_canvas(enc, src);
665 let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src };
644666 let map_space = |s: Option<&str>| -> f32 {
645667 match s.unwrap_or("NoChange") {
646668 "sRGB" => 1.0,
......@@ -695,7 +717,7 @@ impl Engine {
695717 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
696718 return src;
697719 }
698 let src = self.crop_to_canvas(enc, src);
720 let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src };
699721 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
700722 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
701723 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
......@@ -778,6 +800,7 @@ impl Engine {
778800 if blend <= 1e-6 || strength.abs() <= 1e-6 {
779801 return src;
780802 }
803 let src = if node.connected_node("EffectMask").is_some() { self.crop_to_canvas(enc, src) } else { src };
781804 let x_size = comp.eval_number(node, "MasterXSize", time, 1.0, &self.expr) as f32;
782805 let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5;
783806 let y_size = if lock_size {
......@@ -1073,5 +1096,215 @@ mod tests {
10731096 // srgb_to_linear(0.5) = 0.21404 -> ~55
10741097 assert!((p[0] as i32 - 55).abs() <= 2 && p[0] == p[1] && p[1] == p[2], "p={p:?}");
10751098 }
1099
1100 #[test]
1101 fn brightness_contrast_negative_gamma_preserves_transparent_zero() {
1102 // Gain=0.8, Lift=-1.0, Gamma=2.71, Contrast=-0.37 on transparent black (0,0,0,0):
1103 // v = -1.0 must NOT be clamped to 0.0 before Contrast, or it turns into +0.185 (47/255) gray.
1104 let comp = r#"{
1105 Tools = ordered() {
1106 Bg = Background {
1107 Inputs = {
1108 Width = Input { Value = 16, },
1109 Height = Input { Value = 16, },
1110 TopLeftRed = Input { Value = 0.0, },
1111 TopLeftGreen = Input { Value = 0.0, },
1112 TopLeftBlue = Input { Value = 0.0, },
1113 TopLeftAlpha = Input { Value = 0.0, },
1114 },
1115 },
1116 BC = BrightnessContrast {
1117 Inputs = {
1118 Input = Input { SourceOp = "Bg", Source = "Output", },
1119 Gain = Input { Value = 0.8, },
1120 Lift = Input { Value = -1.0, },
1121 Gamma = Input { Value = 2.71, },
1122 Contrast = Input { Value = -0.37, },
1123 },
1124 },
1125 }
1126 }"#;
1127 let p = eval_node_px(comp, "BC");
1128 assert_eq!(p, [0, 0, 0, 0], "transparent black must stay [0,0,0,0], got {p:?}");
1129 }
1130
1131 #[test]
1132 fn color_curves_identity_f16_lut_error_below_1e3() {
1133 let comp_src = r#"{
1134 Tools = ordered() {
1135 Bg = Background {
1136 Inputs = {
1137 Width = Input { Value = 16, },
1138 Height = Input { Value = 16, },
1139 TopLeftRed = Input { Value = 0.1, },
1140 TopLeftGreen = Input { Value = 0.25, },
1141 TopLeftBlue = Input { Value = 0.73, },
1142 TopLeftAlpha = Input { Value = 1.0, },
1143 Depth = Input { Value = 2, },
1144 },
1145 },
1146 CC = ColorCurves {
1147 Inputs = {
1148 Input = Input { SourceOp = "Bg", Source = "Output", },
1149 },
1150 },
1151 }
1152 }"#;
1153 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1154 let id = comp.find_node("CC").expect("CC");
1155 let Ok(mut eng) = Engine::new_headless() else {
1156 return;
1157 };
1158 let (tex, _) = eng.evaluate(&comp, id, 0.0);
1159 assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float);
1160 let [w, h] = tex.size;
1161 let unpadded_bpr = w * 8;
1162 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1163 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
1164 let buf = eng.device().create_buffer(&wgpu::BufferDescriptor {
1165 label: Some("cc-f16-readback"),
1166 size: u64::from(padded_bpr) * u64::from(h),
1167 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1168 mapped_at_creation: false,
1169 });
1170 let mut enc = eng.device().create_command_encoder(&Default::default());
1171 enc.copy_texture_to_buffer(
1172 tex.texture.as_image_copy(),
1173 wgpu::TexelCopyBufferInfo {
1174 buffer: &buf,
1175 layout: wgpu::TexelCopyBufferLayout {
1176 offset: 0,
1177 bytes_per_row: Some(padded_bpr),
1178 rows_per_image: Some(h),
1179 },
1180 },
1181 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
1182 );
1183 eng.queue().submit(Some(enc.finish()));
1184 let slice = buf.slice(..);
1185 let (tx, rx) = std::sync::mpsc::channel();
1186 slice.map_async(wgpu::MapMode::Read, move |res| {
1187 let _ = tx.send(res);
1188 });
1189 let _ = eng.device().poll(wgpu::PollType::Wait {
1190 submission_index: None,
1191 timeout: Some(std::time::Duration::from_secs(10)),
1192 });
1193 rx.recv().unwrap().unwrap();
1194 let data = slice.get_mapped_range().unwrap();
1195 let row = ((h / 2) * padded_bpr) as usize;
1196 let col = ((w / 2) * 8) as usize;
1197 let px_bytes = &data[row + col..row + col + 8];
1198 let f16_to_f32 = |lo: u8, hi: u8| -> f32 {
1199 let h = u16::from_le_bytes([lo, hi]);
1200 let sign = u32::from(h >> 15) << 31;
1201 let exp = u32::from((h >> 10) & 0x1f);
1202 let frac = u32::from(h & 0x3ff);
1203 let bits = if exp == 0 {
1204 if frac == 0 {
1205 sign
1206 } else {
1207 let mut e = 127 - 14;
1208 let mut m = frac;
1209 while (m & 0x400) == 0 {
1210 m <<= 1;
1211 e -= 1;
1212 }
1213 sign | (e << 23) | ((m & 0x3ff) << 13)
1214 }
1215 } else if exp == 0x1f {
1216 sign | (0xff << 23) | (frac << 13)
1217 } else {
1218 sign | ((exp + 112) << 23) | (frac << 13)
1219 };
1220 f32::from_bits(bits)
1221 };
1222 let r = f16_to_f32(px_bytes[0], px_bytes[1]);
1223 let g = f16_to_f32(px_bytes[2], px_bytes[3]);
1224 let b = f16_to_f32(px_bytes[4], px_bytes[5]);
1225 assert!((r - 0.1).abs() < 1e-3, "identity ColorCurves red={r}, expected 0.1");
1226 assert!((g - 0.25).abs() < 1e-3, "identity ColorCurves green={g}, expected 0.25");
1227 assert!((b - 0.73).abs() < 1e-3, "identity ColorCurves blue={b}, expected 0.73");
1228 }
1229
1230 #[test]
1231 fn colorize_and_film_grain_dod_effect_mask_align_to_canvas() {
1232 // Transform shifts a 64x64 image left by 0.25 (creates DoD origin_x < 0, width > 64).
1233 // EffectMask covers only the right quarter (x in [48, 64)) in canvas coordinates.
1234 let comp_src = r#"{
1235 Tools = ordered() {
1236 Bg = Background {
1237 Inputs = {
1238 Width = Input { Value = 64, },
1239 Height = Input { Value = 64, },
1240 TopLeftRed = Input { Value = 0.5, },
1241 TopLeftGreen = Input { Value = 0.5, },
1242 TopLeftBlue = Input { Value = 0.5, },
1243 TopLeftAlpha = Input { Value = 1.0, },
1244 },
1245 },
1246 XF = DVE {
1247 Inputs = {
1248 Input = Input { SourceOp = "Bg", Source = "Output", },
1249 Center = Input { Value = { 0.25, 0.5 }, },
1250 },
1251 },
1252 Mask = RectangleMask {
1253 Inputs = {
1254 MaskWidth = Input { Value = 64, },
1255 MaskHeight = Input { Value = 64, },
1256 Center = Input { Value = { 0.875, 0.5 }, },
1257 Width = Input { Value = 0.25, },
1258 Height = Input { Value = 1.0, },
1259 },
1260 },
1261 CZ = Fuse.Colorize {
1262 Inputs = {
1263 Image = Input { SourceOp = "XF", Source = "Output", },
1264 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1265 R2 = Input { Value = 1.0, },
1266 G2 = Input { Value = 0.0, },
1267 B2 = Input { Value = 0.0, },
1268 A2 = Input { Value = 1.0, },
1269 },
1270 },
1271 FG = FilmGrain {
1272 Inputs = {
1273 Input = Input { SourceOp = "XF", Source = "Output", },
1274 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1275 MasterStrength = Input { Value = 1.0, },
1276 Seed = Input { Value = 7, },
1277 },
1278 },
1279 }
1280 }"#;
1281 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1282 let Ok(mut eng) = Engine::new_headless() else {
1283 return;
1284 };
1285 let (cz_tex, _) = eng.evaluate(&comp, comp.find_node("CZ").unwrap(), 0.0);
1286 let cz_px = eng.readback_rgba(&cz_tex).unwrap();
1287 let at = |buf: &[u8], x: usize, y: usize| -> [u8; 4] {
1288 let i = (y * 64 + x) * 4;
1289 [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
1290 };
1291 // 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)
1292 let inside_xf_outside_mask = at(&cz_px, 32, 32);
1293 assert_eq!(inside_xf_outside_mask[0], inside_xf_outside_mask[1], "x=32 must be unmasked gray: {inside_xf_outside_mask:?}");
1294 // 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]),
1295 // whereas if mask was misplaced onto DoD texel coords it would colorize x < 48!
1296 for x in 0..46 {
1297 let p = at(&cz_px, x, 32);
1298 assert!((p[0] as i32 - p[1] as i32).abs() <= 1, "mask leaked onto x={x}: {p:?}");
1299 }
1300
1301 let (fg_tex, _) = eng.evaluate(&comp, comp.find_node("FG").unwrap(), 0.0);
1302 let fg_px = eng.readback_rgba(&fg_tex).unwrap();
1303 // Outside mask [0..46), FilmGrain must leave XF untouched (gray ~128).
1304 for x in 0..46 {
1305 let p = at(&fg_px, x, 32);
1306 assert!((p[0] as i32 - 128).abs() <= 1, "FilmGrain leaked outside mask at x={x}: {p:?}");
1307 }
1308 }
10761309}
10771310
crates/engine/src/eval/keyers.rs+63
......@@ -15,6 +15,11 @@ impl Engine {
1515 return self.dummy.clone();
1616 };
1717 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
18 let src = if node.connected_node("EffectMask").is_some() {
19 self.crop_to_canvas(enc, src)
20 } else {
21 src
22 };
1823 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1924 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
2025
......@@ -99,5 +104,63 @@ impl Engine {
99104 self.cache.insert(key, dst.clone(), node.id, frame_i);
100105 dst
101106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
102112
113 #[test]
114 fn luma_key_dod_effect_mask_align_to_canvas() {
115 let src = r#"Composition {
116 CurrentTime = 0,
117 RenderRange = { 0, 0 },
118 GlobalRange = { 0, 0 },
119 Tools = ordered() {
120 Bg = Background {
121 Inputs = {
122 Width = Input { Value = 64, },
123 Height = Input { Value = 64, },
124 TopLeftRed = Input { Value = 1.0, },
125 TopLeftAlpha = Input { Value = 1.0, },
126 },
127 },
128 XF = DVE {
129 Inputs = {
130 Input = Input { SourceOp = "Bg", Source = "Output", },
131 Center = Input { Value = { 0.25, 0.5 }, },
132 },
133 },
134 Mask = RectangleMask {
135 Inputs = {
136 MaskWidth = Input { Value = 64, },
137 MaskHeight = Input { Value = 64, },
138 Center = Input { Value = { 0.875, 0.5 }, },
139 Width = Input { Value = 0.25, },
140 Height = Input { Value = 1.0, },
141 },
142 },
143 LK = LumaKeyer {
144 Inputs = {
145 Input = Input { SourceOp = "XF", Source = "Output", },
146 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
147 Low = Input { Value = 0.8, },
148 High = Input { Value = 0.9, },
149 },
150 },
151 },
152 }"#;
153 let comp = Comp::from_fusion_str(src).expect("parse LumaKeyer DoD mask comp");
154 let Ok(mut eng) = Engine::new_headless() else {
155 return;
156 };
157 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
158 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
159 let (lk_tex, _) = eng.evaluate(&comp, comp.find_node("LK").unwrap(), 0.0);
160 let lk_px = eng.readback_rgba(&lk_tex).unwrap();
161 for x in 0..47 {
162 let i = (32 * 64 + x) * 4;
163 assert_eq!(&lk_px[i..i + 4], &xf_px[i..i + 4], "LumaKey mask misaligned at x={x}");
164 }
165 }
103166}
crates/engine/src/eval/transform.rs+297-30
......@@ -189,6 +189,154 @@ fn compute_transform_source_roi(
189189 ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32])
190190}
191191
192fn transform_should_expand_dod(comp: &Comp, start_name: &str) -> bool {
193 let mut queue = vec![start_name];
194 let mut seen = HashSet::new();
195 let mut feeds_dod_reader = false;
196 while let Some(cur_name) = queue.pop() {
197 if !seen.insert(cur_name) {
198 continue;
199 }
200 for n in &comp.nodes {
201 for (port, binding) in &n.inputs {
202 if binding.source_op.as_deref() != Some(cur_name) {
203 continue;
204 }
205 if port == "EffectMask" || port == "GlowMask" {
206 return false;
207 }
208 match n.kind.as_str() {
209 "Saver" | "MediaOut" | "Displace" | "CustomTool" | "Vortex" | "Fuse.KScope" | "UltraKeyer" => {
210 // Terminal or self-cropping ops absorb DoD safely without misaligning downstream.
211 }
212 "Merge" => {
213 if port == "Foreground" {
214 feeds_dod_reader = true;
215 }
216 queue.push(n.name.as_str());
217 }
218 "Transform" | "DVE" | "CornerPositioner" => {
219 if port == "Input" {
220 feeds_dod_reader = true;
221 queue.push(n.name.as_str());
222 } else {
223 return false;
224 }
225 }
226 "BrightnessContrast"
227 | "ColorCorrector"
228 | "ColorCurves"
229 | "ColorGain"
230 | "InvertColor"
231 | "GamutConvert"
232 | "HueCurves"
233 | "ChangeDepth"
234 | "PipeRouter"
235 | "Fuse.Wireless"
236 | "Tracker"
237 | "SetDomain"
238 | "LumaKeyer"
239 | "Fuse.Colorize"
240 | "DirectionalBlur"
241 | "Glow"
242 | "SoftGlow"
243 | "Blur"
244 | "ErodeDilate" => {
245 queue.push(n.name.as_str());
246 }
247 _ => {
248 // Crop, Scale, BetterResize, etc. ignore src.origin.
249 return false;
250 }
251 }
252 }
253 }
254 }
255 feeds_dod_reader
256}
257
258#[allow(clippy::too_many_arguments)]
259fn compute_transform_dst_dod(
260 src: &CachedTexture,
261 center: [f64; 2],
262 pivot: [f64; 2],
263 sx: f32,
264 sy: f32,
265 angle: f32,
266 flip_h: bool,
267 flip_v: bool,
268 max_dim: u32,
269) -> ([i32; 2], [u32; 2]) {
270 let cw = src.canvas_size[0].max(1) as f32;
271 let ch = src.canvas_size[1].max(1) as f32;
272 let sx = sx.max(1e-5);
273 let sy = sy.max(1e-5);
274 let shift_x = center[0] as f32 - 0.5;
275 let shift_y = center[1] as f32 - 0.5;
276 let piv_x = pivot[0] as f32;
277 let piv_y = pivot[1] as f32;
278 let (s, c) = angle.sin_cos();
279
280 let u0 = src.origin[0] as f32 / cw;
281 let u1 = (src.origin[0] + src.size[0] as i32) as f32 / cw;
282 let v0 = 1.0 - (src.origin[1] + src.size[1] as i32) as f32 / ch;
283 let v1 = 1.0 - src.origin[1] as f32 / ch;
284
285 let mut min_x = 0.0_f32;
286 let mut min_y = 0.0_f32;
287 let mut max_x = cw;
288 let mut max_y = ch;
289 for &(fu, fv) in &[(u0, v0), (u1, v0), (u0, v1), (u1, v1)] {
290 let pu = if flip_h { 1.0 - fu } else { fu };
291 let pv = if flip_v { 1.0 - fv } else { fv };
292 let sc_x = (pu - piv_x) * cw * sx;
293 let sc_y = (pv - piv_y) * ch * sy;
294 let rot_x = sc_x * c - sc_y * s;
295 let rot_y = sc_x * s + sc_y * c;
296 let dst_u = rot_x / cw + piv_x + shift_x;
297 let dst_v = rot_y / ch + piv_y + shift_y;
298 let px_x = dst_u * cw;
299 let px_y = (1.0 - dst_v) * ch;
300 min_x = min_x.min(px_x);
301 max_x = max_x.max(px_x);
302 min_y = min_y.min(px_y);
303 max_y = max_y.max(px_y);
304 }
305 min_x = min_x.min(src.origin[0] as f32);
306 max_x = max_x.max((src.origin[0] + src.size[0] as i32) as f32);
307 min_y = min_y.min(src.origin[1] as f32);
308 max_y = max_y.max((src.origin[1] + src.size[1] as i32) as f32);
309
310 let pad = 2_i32;
311 let max_pad = 2048_i32;
312 let mut x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 };
313 let mut y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 };
314 let mut x1 = if max_x > cw + 0.25 {
315 (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad)
316 } else {
317 src.canvas_size[0] as i32
318 };
319 let mut y1 = if max_y > ch + 0.25 {
320 (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad)
321 } else {
322 src.canvas_size[1] as i32
323 };
324 let cap = max_dim.max(src.canvas_size[0]).max(src.canvas_size[1]) as i32;
325 if x1 - x0 > cap {
326 let excess = (x1 - x0) - cap;
327 let trim_l = (0 - x0).max(0).min(excess);
328 x0 += trim_l;
329 x1 -= excess - trim_l;
330 }
331 if y1 - y0 > cap {
332 let excess = (y1 - y0) - cap;
333 let trim_t = (0 - y0).max(0).min(excess);
334 y0 += trim_t;
335 y1 -= excess - trim_t;
336 }
337 ([x0, y0], [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32])
338}
339
192340fn build_cc_uniforms(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine, blend: f32) -> UniformParams {
193341 let mut u = UniformParams::default();
194342 u.p[0] = [
......@@ -466,28 +614,11 @@ impl Engine {
466614 }
467615 let prediv = comp.eval_number(&node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
468616 let ignore_trans = comp.eval_number(&node, "IgnoreTransparent", time, 0.0, &self.expr) as f32;
469 let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s));
470 let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s));
471 let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s));
472 let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s));
473 let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty());
474
475 let mut lut_bytes = [0u8; 256 * 4];
476 for i in 0..256 {
477 let x = i as f64 / 255.0;
478 let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
479 let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
480 let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
481 let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
482 lut_bytes[i * 4] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
483 lut_bytes[i * 4 + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
484 lut_bytes[i * 4 + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
485 lut_bytes[i * 4 + 3] = (a.clamp(0.0, 1.0) * 255.0).round() as u8;
486 }
617 let (lut_f16, mut lut_hash, apply_a) = Self::build_color_curves_lut_f16(comp, &node);
487618 let mut lh = DefaultHasher::new();
488 lut_bytes.hash(&mut lh);
619 lut_hash.hash(&mut lh);
489620 src.origin.hash(&mut lh);
490 let lut_hash = lh.finish();
621 lut_hash = lh.finish();
491622
492623 let mut u = UniformParams::default();
493624 u.p[0] = [prediv, ignore_trans, blend, 0.0];
......@@ -499,13 +630,7 @@ impl Engine {
499630 }
500631 stats.cache_misses += 1;
501632 stats.nodes_evaluated += 1;
502 let lut_tex = create_texture(&self.device, [256, 1], 0);
503 self.queue.write_texture(
504 lut_tex.texture.as_image_copy(),
505 &lut_bytes,
506 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) },
507 wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 },
508 );
633 let lut_tex = self.upload_lut_f16(&lut_f16);
509634 let dst = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, src.depth, key);
510635 self.dispatch_op(enc, ShaderOp::ColorCurves, &src.view, &lut_tex.view, &self.dummy.view, &dst, &u);
511636 self.cache.insert(key, dst.clone(), node.id, frame_i);
......@@ -636,6 +761,18 @@ impl Engine {
636761 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
637762 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
638763
764 let (dst_origin, dst_size) = if !invert
765 && edges.round() as i32 == 0
766 && mask.is_none()
767 && transform_should_expand_dod(comp, &node.name)
768 {
769 let max_dim = self.device.limits().max_texture_dimension_2d.min(4096);
770 compute_transform_dst_dod(&src, center, pivot, sx, sy, angle, flip_h > 0.5, flip_v > 0.5, max_dim)
771 } else {
772 ([0, 0], src.canvas_size)
773 };
774 let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size;
775
639776 let mut u = UniformParams::default();
640777 u.p[0] = [center[0] as f32, center[1] as f32, pivot[0] as f32, pivot[1] as f32];
641778 u.p[1] = [sx, sy, angle, edges];
......@@ -650,9 +787,16 @@ impl Engine {
650787 src.canvas_size[1] as f32,
651788 ];
652789 }
790 if has_dst_dod {
791 u.p[5] = [
792 dst_origin[0] as f32,
793 dst_origin[1] as f32,
794 src.canvas_size[0] as f32,
795 src.canvas_size[1] as f32,
796 ];
797 }
653798
654 let out_size = src.canvas_size;
655 let key = self.make_key(node, "Transform", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
799 let key = self.make_key(node, "Transform", dst_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..6]));
656800 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
657801 stats.cache_hits += 1;
658802 return hit;
......@@ -660,7 +804,8 @@ impl Engine {
660804 stats.cache_misses += 1;
661805 stats.nodes_evaluated += 1;
662806
663 let dst = self.alloc_tex(out_size, src.depth, key);
807 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key);
808 dst.tex_scale = src.tex_scale;
664809 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
665810 self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u);
666811 self.cache.insert(key, dst.clone(), node.id, frame_i);
......@@ -747,6 +892,7 @@ impl Engine {
747892 if blend <= 1e-6 || angle_deg.abs() <= 1e-5 {
748893 return src;
749894 }
895 let src = self.crop_to_canvas(enc, src);
750896 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
751897 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
752898 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
......@@ -1629,4 +1775,125 @@ mod tests {
16291775 let [r, g] = mid_row(1);
16301776 assert!(g > r + 60, "InvertTransform pulls the right (green) side under the middle: {r} {g}");
16311777 }
1778
1779 #[test]
1780 fn transform_dod_preserved_through_bc_into_merge() {
1781 // 64x64 bright red FG is translated left off-canvas by Transform (Center.x = -0.25 -> shift = -0.75 * 64 = -48px),
1782 // passed through BrightnessContrast (unmasked), then merged back onto a 128x64 canvas at Center.x = 0.75.
1783 // Without Transform DoD + unmasked BC DoD preservation, x in [-48..0] would be clipped at x=0!
1784 let src = r#"Composition {
1785 CurrentTime = 0,
1786 RenderRange = { 0, 0 },
1787 GlobalRange = { 0, 0 },
1788 Tools = ordered() {
1789 BG = Background {
1790 Inputs = {
1791 Width = Input { Value = 128, },
1792 Height = Input { Value = 64, },
1793 TopLeftAlpha = Input { Value = 1.0, },
1794 },
1795 },
1796 FG = Background {
1797 Inputs = {
1798 Width = Input { Value = 64, },
1799 Height = Input { Value = 64, },
1800 TopLeftRed = Input { Value = 1.0, },
1801 TopLeftGreen = Input { Value = 0.0, },
1802 TopLeftBlue = Input { Value = 0.0, },
1803 TopLeftAlpha = Input { Value = 1.0, },
1804 },
1805 },
1806 XF = Transform {
1807 Inputs = {
1808 Input = Input { SourceOp = "FG", Source = "Output", },
1809 Center = Input { Value = { -0.25, 0.5 }, },
1810 },
1811 },
1812 BC = BrightnessContrast {
1813 Inputs = {
1814 Input = Input { SourceOp = "XF", Source = "Output", },
1815 Gain = Input { Value = 0.8, },
1816 Lift = Input { Value = -0.2, },
1817 Gamma = Input { Value = 1.5, },
1818 },
1819 },
1820 M = Merge {
1821 Inputs = {
1822 Background = Input { SourceOp = "BG", Source = "Output", },
1823 Foreground = Input { SourceOp = "BC", Source = "Output", },
1824 Center = Input { Value = { 0.75, 0.5 }, },
1825 },
1826 },
1827 },
1828 }"#;
1829 let comp = Comp::from_fusion_str(src).expect("parse Transform DoD comp");
1830 let Ok(mut eng) = Engine::new_headless() else {
1831 return;
1832 };
1833 let (tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
1834 let rgba = eng.readback_rgba(&tex).unwrap();
1835 // Merge places BC's 64x64 logical center (32) at 0.75 * 128 = 96, so x=0 of BC lands at 64.
1836 // The shifted red square spans x in [-48..16) in BC, which lands at [16..80) on BG!
1837 // At x=32 (left of BC's x=0 at 64), red pixels must survive!
1838 let i = (32 * 128 + 32) * 4;
1839 assert!(rgba[i] > 150 && rgba[i + 1] == 0, "expected off-canvas shifted FG via DoD at x=32, got {:?}", &rgba[i..i + 4]);
1840 }
1841
1842 #[test]
1843 fn vortex_dod_input_and_effect_mask_align_to_canvas() {
1844 let src = r#"Composition {
1845 CurrentTime = 0,
1846 RenderRange = { 0, 0 },
1847 GlobalRange = { 0, 0 },
1848 Tools = ordered() {
1849 Stripe = Background {
1850 Inputs = {
1851 Width = Input { Value = 64, },
1852 Height = Input { Value = 64, },
1853 Type = Input { Value = FuID { "Horizontal" }, },
1854 TopLeftRed = Input { Value = 1.0, },
1855 TopLeftAlpha = Input { Value = 1.0, },
1856 TopRightBlue = Input { Value = 1.0, },
1857 TopRightAlpha = Input { Value = 1.0, },
1858 },
1859 },
1860 XF = DVE {
1861 Inputs = {
1862 Input = Input { SourceOp = "Stripe", Source = "Output", },
1863 Center = Input { Value = { 0.25, 0.5 }, },
1864 },
1865 },
1866 Mask = RectangleMask {
1867 Inputs = {
1868 MaskWidth = Input { Value = 64, },
1869 MaskHeight = Input { Value = 64, },
1870 Center = Input { Value = { 0.75, 0.5 }, },
1871 Width = Input { Value = 0.25, },
1872 Height = Input { Value = 1.0, },
1873 },
1874 },
1875 V = Vortex {
1876 Inputs = {
1877 Input = Input { SourceOp = "XF", Source = "Output", },
1878 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1879 Angle = Input { Value = 180.0, },
1880 Size = Input { Value = 0.8, },
1881 },
1882 },
1883 },
1884 }"#;
1885 let comp = Comp::from_fusion_str(src).expect("parse Vortex DoD comp");
1886 let Ok(mut eng) = Engine::new_headless() else {
1887 return;
1888 };
1889 let (v_tex, _) = eng.evaluate(&comp, comp.find_node("V").unwrap(), 0.0);
1890 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
1891 let v_px = eng.readback_rgba(&v_tex).unwrap();
1892 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
1893 // Left of Mask (x in 0..40) must be identical to XF (Vortex must not warp outside canvas mask).
1894 for x in 0..40 {
1895 let i = (32 * 64 + x) * 4;
1896 assert_eq!(&v_px[i..i + 4], &xf_px[i..i + 4], "Vortex mask misaligned at x={x}");
1897 }
1898 }
16321899}
crates/engine/src/particles.rs+445-73
......@@ -3,17 +3,25 @@
33//! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`,
44//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode).
55
6use std::collections::{HashMap, HashSet};
6use std::collections::hash_map::DefaultHasher;
7use std::collections::{BTreeMap, HashMap, HashSet};
8use std::hash::{Hash, Hasher};
79
8use model::{Comp, ExprEngine, Gradient, Node, NodeId};
10use model::{BezierSpline, Comp, ExprEngine, Gradient, InputBinding, Node, NodeId, ParamValue};
911
1012/// Maximum simultaneous live particles kept in a single simulation to prevent
1113/// pathological comps from hanging or exhausting memory.
1214const MAX_PARTICLES: usize = 20_000;
1315
14/// Maximum lookback frames from `target_frame` when `sim_start` is far earlier.
16/// Maximum cold-start lookback frames from `target_frame` when `base_start` is far earlier.
1517const MAX_SIM_WINDOW: i64 = 600;
1618
19/// Periodic snapshot interval (frames from `base_start`) for fast backward scrubbing.
20const SNAPSHOT_INTERVAL: i64 = 60;
21
22/// Maximum periodic snapshots retained per cached particle simulation.
23const MAX_SNAPSHOTS: usize = 32;
24
1725/// Particle integration step: `Velocity` moves `0.1` render widths per frame and
1826/// forces accelerate by `0.1^2` per unit of `Strength`.
1927const VELOCITY_SCALE: f64 = 0.1;
......@@ -39,11 +47,12 @@ pub struct SpriteImage {
3947
4048/// Persistent frame-to-frame cache for deterministic particle simulations.
4149///
42/// Keyed by `(render_node, comp.revision)`. Advancing sequentially `f -> f+1`
43/// only steps 1 frame instead of re-simulating from `sim_start`.
50/// Keyed by `(render_node_name, subgraph_hash)`. Advancing sequentially `f -> f+1`
51/// only steps 1 frame even past `MAX_SIM_WINDOW`, while periodic snapshots every
52/// `SNAPSHOT_INTERVAL` frames accelerate backward scrubbing.
4453#[derive(Default)]
4554pub struct ParticleCache {
46 entries: HashMap<(NodeId, u64), CachedSim>,
55 entries: HashMap<(String, u64), CachedSim>,
4756}
4857
4958impl ParticleCache {
......@@ -54,21 +63,22 @@ impl ParticleCache {
5463
5564#[derive(Clone)]
5665struct CachedSim {
57 sim_start: i64,
66 base_start: i64,
5867 current_frame: i64,
5968 state: SimState,
69 snapshots: BTreeMap<i64, SimState>,
6070}
6171
6272#[derive(Clone, Default)]
6373struct SimState {
6474 particles: Vec<Particle>,
65 /// Fractional emission accumulator per `pEmitter` node.
66 emit_accum: HashMap<NodeId, f64>,
75 /// Fractional emission accumulator per `pEmitter` stable name hash.
76 emit_accum: HashMap<u64, f64>,
6777}
6878
6979#[derive(Clone, Copy, Debug)]
7080struct Particle {
71 emitter_id: NodeId,
81 emitter_hash: u64,
7282 pos: [f64; 3],
7383 vel: [f64; 3],
7484 rot_z: f64,
......@@ -89,15 +99,26 @@ enum ParticleStyleKind {
8999 Brush,
90100}
91101
102/// Stable FNV-1a 64-bit hash of a node name (independent of `NodeId` index).
103#[inline]
104fn stable_name_hash(name: &str) -> u64 {
105 let mut h = 0xcbf2_9ce4_8422_2325_u64;
106 for &b in name.as_bytes() {
107 h ^= u64::from(b);
108 h = h.wrapping_mul(0x0100_0000_01b3);
109 }
110 h
111}
112
92113/// Deterministic SplitMix64 PRNG.
93114#[derive(Clone, Copy)]
94115struct SplitMix64(u64);
95116
96117impl SplitMix64 {
97 fn from_parts(seed: i64, frame: i64, node_id: usize) -> Self {
118 fn from_parts(seed: i64, frame: i64, node_name: &str) -> Self {
98119 let mut s = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
99120 s ^= (frame as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
100 s ^= (node_id as u64).wrapping_mul(0x94D0_49BB_1331_11EB);
121 s ^= stable_name_hash(node_name).wrapping_mul(0x94D0_49BB_1331_11EB);
101122 let mut rng = Self(s ^ 0xD1B5_4A32_D192_ED03);
102123 let _ = rng.next_u64();
103124 rng
......@@ -228,17 +249,19 @@ fn collect_bitmap_sources_dfs(
228249
229250/// Flattened, topologically-ordered particle graph upstream of a `pRender` node.
230251struct ParticlePlan {
231 emitters: Vec<NodeId>,
252 emitters: Vec<(NodeId, u64)>,
232253 /// Forces/modifiers in topological order along with the set of upstream
233 /// emitters whose particles flow through each modifier.
234 modifiers: Vec<(NodeId, HashSet<NodeId>)>,
254 /// emitter name hashes whose particles flow through each modifier.
255 modifiers: Vec<(NodeId, HashSet<u64>)>,
256 emitter_nodes: HashMap<u64, NodeId>,
235257}
236258
237259fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan {
238260 let mut visited = HashSet::new();
239261 let mut emitters = Vec::new();
240262 let mut modifiers = Vec::new();
241 let mut upstream_emitters: HashMap<NodeId, HashSet<NodeId>> = HashMap::new();
263 let mut upstream_emitters: HashMap<NodeId, HashSet<u64>> = HashMap::new();
264 let mut emitter_nodes = HashMap::new();
242265
243266 build_plan_dfs(
244267 comp,
......@@ -247,11 +270,13 @@ fn build_particle_plan(comp: &Comp, render_node: NodeId) -> ParticlePlan {
247270 &mut emitters,
248271 &mut modifiers,
249272 &mut upstream_emitters,
273 &mut emitter_nodes,
250274 );
251275
252276 ParticlePlan {
253277 emitters,
254278 modifiers,
279 emitter_nodes,
255280 }
256281}
257282
......@@ -259,10 +284,11 @@ fn build_plan_dfs(
259284 comp: &Comp,
260285 node_id: NodeId,
261286 visited: &mut HashSet<NodeId>,
262 emitters: &mut Vec<NodeId>,
263 modifiers: &mut Vec<(NodeId, HashSet<NodeId>)>,
264 upstream_emitters: &mut HashMap<NodeId, HashSet<NodeId>>,
265) -> HashSet<NodeId> {
287 emitters: &mut Vec<(NodeId, u64)>,
288 modifiers: &mut Vec<(NodeId, HashSet<u64>)>,
289 upstream_emitters: &mut HashMap<NodeId, HashSet<u64>>,
290 emitter_nodes: &mut HashMap<u64, NodeId>,
291) -> HashSet<u64> {
266292 if let Some(cached) = upstream_emitters.get(&node_id) {
267293 return cached.clone();
268294 }
......@@ -286,14 +312,17 @@ fn build_plan_dfs(
286312 emitters,
287313 modifiers,
288314 upstream_emitters,
315 emitter_nodes,
289316 );
290317 scope.extend(up_set);
291318 }
292319
293320 if node.kind == "pEmitter" {
294321 if !node.bypassed {
295 emitters.push(node_id);
296 scope.insert(node_id);
322 let emitter_hash = stable_name_hash(&node.name);
323 emitters.push((node_id, emitter_hash));
324 emitter_nodes.insert(emitter_hash, node_id);
325 scope.insert(emitter_hash);
297326 }
298327 } else if !node.bypassed
299328 && matches!(
......@@ -314,6 +343,185 @@ fn build_plan_dfs(
314343 scope
315344}
316345
346fn hash_spline(spline: &BezierSpline, h: &mut DefaultHasher) {
347 spline.name.hash(h);
348 spline.keyframes.len().hash(h);
349 for kf in &spline.keyframes {
350 kf.time.to_bits().hash(h);
351 kf.value.to_bits().hash(h);
352 if let Some([lx, ly]) = kf.lh {
353 1u8.hash(h);
354 lx.to_bits().hash(h);
355 ly.to_bits().hash(h);
356 } else {
357 0u8.hash(h);
358 }
359 if let Some([rx, ry]) = kf.rh {
360 1u8.hash(h);
361 rx.to_bits().hash(h);
362 ry.to_bits().hash(h);
363 } else {
364 0u8.hash(h);
365 }
366 [
367 kf.flags.linear,
368 kf.flags.step_in,
369 kf.flags.step_out,
370 kf.flags.loop_after,
371 kf.flags.loop_rel,
372 kf.flags.ping_pong,
373 kf.flags.locked_y,
374 ]
375 .hash(h);
376 (kf.handle_mode as u8).hash(h);
377 }
378}
379
380fn hash_gradient(grad: &Gradient, h: &mut DefaultHasher) {
381 grad.stops.len().hash(h);
382 for stop in &grad.stops {
383 stop.pos.to_bits().hash(h);
384 for c in stop.rgba {
385 c.to_bits().hash(h);
386 }
387 }
388}
389
390fn hash_input_binding(comp: &Comp, binding: &InputBinding, h: &mut DefaultHasher) {
391 binding.source_output.hash(h);
392 binding.expression.hash(h);
393 match &binding.value {
394 None => 0u8.hash(h),
395 Some(ParamValue::Number(v)) => {
396 1u8.hash(h);
397 v.to_bits().hash(h);
398 }
399 Some(ParamValue::Point([x, y])) => {
400 2u8.hash(h);
401 x.to_bits().hash(h);
402 y.to_bits().hash(h);
403 }
404 Some(ParamValue::Text(s)) => {
405 3u8.hash(h);
406 s.hash(h);
407 }
408 Some(ParamValue::FuId(s)) => {
409 4u8.hash(h);
410 s.hash(h);
411 }
412 Some(ParamValue::Gradient(g)) => {
413 5u8.hash(h);
414 hash_gradient(g, h);
415 }
416 Some(ParamValue::Raw(raw)) => {
417 6u8.hash(h);
418 format!("{raw:?}").hash(h);
419 }
420 }
421 binding.source_op.hash(h);
422 if let Some(op) = &binding.source_op {
423 if let Some(sp) = comp.splines.get(op) {
424 hash_spline(sp, h);
425 }
426 if let Some(pp) = comp.poly_paths.get(op) {
427 pp.name.hash(h);
428 pp.displacement_op.hash(h);
429 pp.displacement_value.to_bits().hash(h);
430 pp.closed.hash(h);
431 pp.points.len().hash(h);
432 for pt in &pp.points {
433 pt.x.to_bits().hash(h);
434 pt.y.to_bits().hash(h);
435 pt.lx.to_bits().hash(h);
436 pt.ly.to_bits().hash(h);
437 pt.rx.to_bits().hash(h);
438 pt.ry.to_bits().hash(h);
439 pt.linear.hash(h);
440 }
441 if let Some(disp_op) = &pp.displacement_op {
442 if let Some(sp) = comp.splines.get(disp_op) {
443 hash_spline(sp, h);
444 }
445 }
446 }
447 if let Some(sh) = comp.shakes.get(op) {
448 hash_sorted_inputs(comp, &sh.inputs, h);
449 }
450 if let Some(ex) = comp.expression_modifiers.get(op) {
451 hash_sorted_inputs(comp, &ex.inputs, h);
452 }
453 if let Some(gm) = comp.gradient_modifiers.get(op) {
454 gm.len().hash(h);
455 for (t, g) in gm {
456 t.to_bits().hash(h);
457 hash_gradient(g, h);
458 }
459 }
460 }
461}
462
463fn hash_sorted_inputs(comp: &Comp, inputs: &HashMap<String, InputBinding>, h: &mut DefaultHasher) {
464 let mut keys: Vec<&String> = inputs.keys().collect();
465 keys.sort_unstable();
466 keys.len().hash(h);
467 for k in keys {
468 k.hash(h);
469 hash_input_binding(comp, &inputs[k], h);
470 }
471}
472
473/// Content hash of the particle simulation subgraph upstream of `render_node`.
474/// Unrelated edits outside the particle branch leave this hash unchanged.
475fn particle_subgraph_hash(comp: &Comp, render_node: NodeId, base_start: i64) -> u64 {
476 fn dfs(comp: &Comp, node_id: NodeId, is_root: bool, visited: &mut HashSet<NodeId>, h: &mut DefaultHasher) {
477 if !visited.insert(node_id) {
478 return;
479 }
480 let Some(node) = comp.nodes.get(node_id.0) else {
481 return;
482 };
483 if !is_particle_node_kind(&node.kind) {
484 return;
485 }
486 node.name.hash(h);
487 node.kind.hash(h);
488 node.bypassed.hash(h);
489
490 let mut keys: Vec<&String> = node.inputs.keys().collect();
491 keys.sort_unstable();
492 for k in keys {
493 // `pRender.Width` and bitmap drop target only affect rasterization, not simulation state.
494 if (is_root && k == "Width") || k == "ParticleStyleBitmap.DropToolsHere" {
495 continue;
496 }
497 k.hash(h);
498 hash_input_binding(comp, &node.inputs[k], h);
499 }
500 for up_id in particle_stream_inputs(comp, node) {
501 dfs(comp, up_id, false, visited, h);
502 }
503 }
504
505 let mut h = DefaultHasher::new();
506 base_start.hash(&mut h);
507 let mut visited = HashSet::new();
508 dfs(comp, render_node, true, &mut visited, &mut h);
509 h.finish()
510}
511
512fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {
513 if (frame - cached.base_start).rem_euclid(SNAPSHOT_INTERVAL) == 0 {
514 cached.snapshots.insert(frame, cached.state.clone());
515 while cached.snapshots.len() > MAX_SNAPSHOTS {
516 if let Some(&oldest) = cached.snapshots.keys().next() {
517 cached.snapshots.remove(&oldest);
518 } else {
519 break;
520 }
521 }
522 }
523}
524
317525/// Runs deterministic frame-stepped particle simulation up to `time.floor()` and
318526/// rasterizes all live particles into a premultiplied RGBA8 buffer of size
319527/// `dims[0] * dims[1] * 4`.
......@@ -350,46 +558,63 @@ pub fn render_particles_2d(
350558 } else {
351559 comp.global_range[0]
352560 };
353 let sim_start = base_start.max(target_frame - MAX_SIM_WINDOW);
354 if target_frame < sim_start {
561 if target_frame < base_start {
355562 return out;
356563 }
357564
358 // Evict stale revisions for this render node.
359 let key = (render_node, comp.revision);
565 let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start);
566 let key = (rnode.name.clone(), subgraph_hash);
567 // Evict stale subgraph hashes for this render node while keeping other pRender entries.
360568 cache
361569 .entries
362 .retain(|&(nid, rev), _| nid != render_node || rev == comp.revision);
363
364 let need_reset = match cache.entries.get(&key) {
365 Some(cached) => {
366 target_frame < cached.current_frame
367 || target_frame == sim_start
368 || cached.sim_start != sim_start
570 .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash);
571
572 let cold_sim_start = |target: i64| base_start.max(target - MAX_SIM_WINDOW);
573
574 let need_cold_init = match cache.entries.get_mut(&key) {
575 Some(cached) if cached.base_start == base_start => {
576 if target_frame == cached.current_frame {
577 false
578 } else if target_frame > cached.current_frame {
579 if target_frame - cached.current_frame <= MAX_SIM_WINDOW {
580 for f in (cached.current_frame + 1)..=target_frame {
581 step_simulation(&mut cached.state, comp, &plan, f, expr);
582 maybe_record_snapshot(cached, f);
583 }
584 cached.current_frame = target_frame;
585 false
586 } else {
587 true
588 }
589 } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() {
590 cached.state = snap_state.clone();
591 cached.current_frame = snap_f;
592 for f in (snap_f + 1)..=target_frame {
593 step_simulation(&mut cached.state, comp, &plan, f, expr);
594 maybe_record_snapshot(cached, f);
595 }
596 cached.current_frame = target_frame;
597 false
598 } else {
599 true
600 }
369601 }
370 None => true,
602 _ => true,
371603 };
372604
373 if need_reset {
374 let mut state = SimState::default();
605 if need_cold_init {
606 let sim_start = cold_sim_start(target_frame);
607 let mut sim = CachedSim {
608 base_start,
609 current_frame: target_frame,
610 state: SimState::default(),
611 snapshots: BTreeMap::new(),
612 };
375613 for f in sim_start..=target_frame {
376 step_simulation(&mut state, comp, &plan, f, expr);
377 }
378 cache.entries.insert(
379 key,
380 CachedSim {
381 sim_start,
382 current_frame: target_frame,
383 state,
384 },
385 );
386 } else if let Some(cached) = cache.entries.get_mut(&key) {
387 if target_frame > cached.current_frame {
388 for f in (cached.current_frame + 1)..=target_frame {
389 step_simulation(&mut cached.state, comp, &plan, f, expr);
390 }
391 cached.current_frame = target_frame;
614 step_simulation(&mut sim.state, comp, &plan, f, expr);
615 maybe_record_snapshot(&mut sim, f);
392616 }
617 cache.entries.insert(key.clone(), sim);
393618 }
394619
395620 let Some(cached) = cache.entries.get(&key) else {
......@@ -402,6 +627,7 @@ pub fn render_particles_2d(
402627 dims,
403628 dims[0] as f64 / render_width,
404629 comp,
630 &plan.emitter_nodes,
405631 &cached.state.particles,
406632 time,
407633 expr,
......@@ -447,14 +673,14 @@ fn step_simulation(
447673
448674 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).
449675 let first_new = state.particles.len();
450 for &emitter_id in &plan.emitters {
676 for &(emitter_id, emitter_hash) in &plan.emitters {
451677 if state.particles.len() >= MAX_PARTICLES {
452678 break;
453679 }
454680 let Some(node) = comp.nodes.get(emitter_id.0) else {
455681 continue;
456682 };
457 emit_particles(state, comp, node, emitter_id, frame, t, expr);
683 emit_particles(state, comp, node, emitter_hash, frame, t, expr);
458684 }
459685
460686 // A newborn is damped by friction and then integrated once on its birth frame; other forces
......@@ -479,13 +705,13 @@ fn emit_particles(
479705 state: &mut SimState,
480706 comp: &Comp,
481707 node: &Node,
482 emitter_id: NodeId,
708 emitter_hash: u64,
483709 frame: i64,
484710 t: f64,
485711 expr: &ExprEngine,
486712) {
487713 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
488 let mut rng = SplitMix64::from_parts(seed, frame, emitter_id.0);
714 let mut rng = SplitMix64::from_parts(seed, frame, &node.name);
489715
490716 let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0);
491717 let number_var = comp
......@@ -493,7 +719,7 @@ fn emit_particles(
493719 .max(0.0);
494720
495721 let rate = (number + rng.signed() * number_var).max(0.0);
496 let accum = state.emit_accum.entry(emitter_id).or_insert(0.0);
722 let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0);
497723 *accum += rate;
498724 let mut emit_count = accum.floor() as usize;
499725 *accum -= emit_count as f64;
......@@ -600,7 +826,7 @@ fn emit_particles(
600826 };
601827
602828 state.particles.push(Particle {
603 emitter_id,
829 emitter_hash,
604830 pos,
605831 vel,
606832 rot_z,
......@@ -1068,7 +1294,7 @@ fn apply_modifier(
10681294 particles: &mut [Particle],
10691295 comp: &Comp,
10701296 node: &Node,
1071 scope: &HashSet<NodeId>,
1297 scope: &HashSet<u64>,
10721298 t: f64,
10731299 expr: &ExprEngine,
10741300) {
......@@ -1084,7 +1310,7 @@ fn apply_modifier(
10841310 let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr);
10851311
10861312 for p in particles.iter_mut() {
1087 if !p.alive || !scope.contains(&p.emitter_id) {
1313 if !p.alive || !scope.contains(&p.emitter_hash) {
10881314 continue;
10891315 }
10901316 let dx = tx - p.pos[0];
......@@ -1119,7 +1345,7 @@ fn apply_modifier(
11191345 let az = mag * dir_z.sin();
11201346
11211347 for p in particles.iter_mut() {
1122 if !p.alive || !scope.contains(&p.emitter_id) {
1348 if !p.alive || !scope.contains(&p.emitter_hash) {
11231349 continue;
11241350 }
11251351 p.vel[0] += ax;
......@@ -1140,7 +1366,7 @@ fn apply_modifier(
11401366 1.0
11411367 };
11421368 for p in particles.iter_mut() {
1143 if !p.alive || !scope.contains(&p.emitter_id) {
1369 if !p.alive || !scope.contains(&p.emitter_hash) {
11441370 continue;
11451371 }
11461372 p.vel[0] *= damp;
......@@ -1161,7 +1387,7 @@ fn apply_modifier(
11611387 let time_shift = t * 0.03;
11621388
11631389 for p in particles.iter_mut() {
1164 if !p.alive || !scope.contains(&p.emitter_id) {
1390 if !p.alive || !scope.contains(&p.emitter_hash) {
11651391 continue;
11661392 }
11671393 let qx = p.pos[0] * density + time_shift;
......@@ -1186,7 +1412,7 @@ fn apply_modifier(
11861412 Some("Outside") | Some("Leaving")
11871413 );
11881414 for p in particles.iter_mut() {
1189 if !p.alive || !scope.contains(&p.emitter_id) {
1415 if !p.alive || !scope.contains(&p.emitter_hash) {
11901416 continue;
11911417 }
11921418 let inside = region.contains(p.pos);
......@@ -1203,10 +1429,10 @@ fn apply_modifier(
12031429 let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0);
12041430 let spin = comp.eval_number(node, "Spin", t, 0.0, expr);
12051431 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
1206 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, node.id.0);
1432 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
12071433
12081434 for p in particles.iter_mut() {
1209 if !p.alive || !scope.contains(&p.emitter_id) {
1435 if !p.alive || !scope.contains(&p.emitter_hash) {
12101436 continue;
12111437 }
12121438 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 {
12891515}
12901516
12911517struct EmitterRenderProps<'a> {
1518 emitter_id: NodeId,
12921519 style: ParticleStyleKind,
12931520 tiny_sprite: Option<([f64; 2], SpriteImage)>,
12941521 ngon_sides: f64,
......@@ -1300,16 +1527,20 @@ struct EmitterRenderProps<'a> {
13001527
13011528fn collect_emitter_render_props<'a>(
13021529 comp: &'a Comp,
1530 emitter_nodes: &HashMap<u64, NodeId>,
13031531 particles: &[Particle],
13041532 time: f64,
13051533 expr: &ExprEngine,
1306) -> HashMap<NodeId, EmitterRenderProps<'a>> {
1534) -> HashMap<u64, EmitterRenderProps<'a>> {
13071535 let mut map = HashMap::new();
13081536 for p in particles {
1309 if map.contains_key(&p.emitter_id) {
1537 if map.contains_key(&p.emitter_hash) {
13101538 continue;
13111539 }
1312 let Some(node) = comp.nodes.get(p.emitter_id.0) else {
1540 let Some(&emitter_id) = emitter_nodes.get(&p.emitter_hash) else {
1541 continue;
1542 };
1543 let Some(node) = comp.nodes.get(emitter_id.0) else {
13131544 continue;
13141545 };
13151546 let style = match node.static_str("Style") {
......@@ -1338,8 +1569,9 @@ fn collect_emitter_render_props<'a>(
13381569 None
13391570 };
13401571 map.insert(
1341 p.emitter_id,
1572 p.emitter_hash,
13421573 EmitterRenderProps {
1574 emitter_id,
13431575 style,
13441576 tiny_sprite: tiny_background_sprite(comp, node, time, expr),
13451577 ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0),
......@@ -1385,11 +1617,13 @@ fn tiny_background_sprite(
13851617 Some(([w, h], SpriteImage { size: [1, 1], rgba }))
13861618}
13871619
1620#[allow(clippy::too_many_arguments)]
13881621fn rasterize_particles(
13891622 out: &mut [u8],
13901623 dims: [u32; 2],
13911624 px_scale: f64,
13921625 comp: &Comp,
1626 emitter_nodes: &HashMap<u64, NodeId>,
13931627 particles: &[Particle],
13941628 time: f64,
13951629 expr: &ExprEngine,
......@@ -1399,7 +1633,7 @@ fn rasterize_particles(
13991633 return;
14001634 }
14011635
1402 let props_map = collect_emitter_render_props(comp, particles, time, expr);
1636 let props_map = collect_emitter_render_props(comp, emitter_nodes, particles, time, expr);
14031637 let w = dims[0] as usize;
14041638 let h = dims[1] as usize;
14051639 let w_f = w as f64;
......@@ -1412,7 +1646,7 @@ fn rasterize_particles(
14121646 if !p.alive {
14131647 continue;
14141648 }
1415 let Some(props) = props_map.get(&p.emitter_id) else {
1649 let Some(props) = props_map.get(&p.emitter_hash) else {
14161650 continue;
14171651 };
14181652
......@@ -1463,7 +1697,7 @@ fn rasterize_particles(
14631697 let (sprite, nominal) = match &props.tiny_sprite {
14641698 Some((nominal, sprite)) => (Some(sprite), *nominal),
14651699 None => {
1466 let sprite = sprites.get(&p.emitter_id);
1700 let sprite = sprites.get(&props.emitter_id);
14671701 (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64]))
14681702 }
14691703 };
......@@ -2149,4 +2383,142 @@ Composition {{
21492383 let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new());
21502384 assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]);
21512385 }
2386
2387 #[test]
2388 fn particle_cache_advances_past_600_incrementally_and_scrubs_with_snapshots() {
2389 let comp_src = r#"
2390Composition {
2391 GlobalRange = { 0, 800 },
2392 RenderRange = { 0, 800 },
2393 Tools = {
2394 pEmitter1 = pEmitter {
2395 Inputs = {
2396 RandomSeed = Input { Value = 7, },
2397 Number = Input { Value = 2, },
2398 Lifespan = Input { Value = 25, },
2399 Velocity = Input { Value = 0.2, },
2400 VelocityVariance = Input { Value = 0.1, },
2401 AngleVariance = Input { Value = 180, },
2402 },
2403 },
2404 pRender1 = pRender {
2405 Inputs = {
2406 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2407 },
2408 },
2409 },
2410}
2411"#;
2412 let comp = Comp::from_fusion_str(comp_src).expect("parse particle comp");
2413 let render_id = comp.node_by_name["pRender1"];
2414 let expr = ExprEngine::new();
2415 let sprites = HashMap::new();
2416 let dims = [64, 64];
2417
2418 let mut cache = ParticleCache::default();
2419 let mut last_img = Vec::new();
2420 for f in 580..=625 {
2421 last_img = render_particles_2d(&mut cache, &comp, render_id, f as f64, dims, &expr, &sprites);
2422 }
2423
2424 let key = (
2425 "pRender1".to_owned(),
2426 particle_subgraph_hash(&comp, render_id, 0),
2427 );
2428 let cached = cache.entries.get(&key).expect("cached entry");
2429 assert_eq!(cached.base_start, 0);
2430 assert_eq!(cached.current_frame, 625);
2431 assert!(cached.snapshots.contains_key(&600), "expected snapshot at frame 600");
2432
2433 // Scrubbing back to frame 605 restores snapshot 600 and matches direct render at 605.
2434 let scrub_605 = render_particles_2d(&mut cache, &comp, render_id, 605.0, dims, &expr, &sprites);
2435 let mut fresh_cache = ParticleCache::default();
2436 let fresh_605 = render_particles_2d(&mut fresh_cache, &comp, render_id, 605.0, dims, &expr, &sprites);
2437 assert_eq!(scrub_605, fresh_605, "scrubbed frame 605 must match fresh simulation");
2438
2439 let mut fresh_625_cache = ParticleCache::default();
2440 let fresh_625 = render_particles_2d(&mut fresh_625_cache, &comp, render_id, 625.0, dims, &expr, &sprites);
2441 assert_eq!(last_img, fresh_625, "incremental advance past 600 must match fresh simulation");
2442 }
2443
2444 #[test]
2445 fn particle_cache_ignores_unrelated_comp_edits_and_node_id_shifts() {
2446 let with_unrelated = r#"
2447Composition {
2448 GlobalRange = { 0, 100 },
2449 RenderRange = { 0, 100 },
2450 Tools = {
2451 UnrelatedBg = Background {
2452 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, },
2453 },
2454 pEmitter1 = pEmitter {
2455 Inputs = {
2456 RandomSeed = Input { Value = 19, },
2457 Number = Input { Value = 8, },
2458 Lifespan = Input { Value = 40, },
2459 Velocity = Input { Value = 0.5, },
2460 VelocityVariance = Input { Value = 0.25, },
2461 AngleVariance = Input { Value = 180, },
2462 },
2463 },
2464 pRender1 = pRender {
2465 Inputs = {
2466 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2467 },
2468 },
2469 },
2470}
2471"#;
2472 let without_unrelated = r#"
2473Composition {
2474 GlobalRange = { 0, 100 },
2475 RenderRange = { 0, 100 },
2476 Tools = {
2477 pEmitter1 = pEmitter {
2478 Inputs = {
2479 RandomSeed = Input { Value = 19, },
2480 Number = Input { Value = 8, },
2481 Lifespan = Input { Value = 40, },
2482 Velocity = Input { Value = 0.5, },
2483 VelocityVariance = Input { Value = 0.25, },
2484 AngleVariance = Input { Value = 180, },
2485 },
2486 },
2487 pRender1 = pRender {
2488 Inputs = {
2489 Input = Input { SourceOp = "pEmitter1", Source = "Output", },
2490 },
2491 },
2492 },
2493}
2494"#;
2495 let mut comp_a = Comp::from_fusion_str(with_unrelated).expect("parse comp_a");
2496 let comp_b = Comp::from_fusion_str(without_unrelated).expect("parse comp_b");
2497 let ra = comp_a.node_by_name["pRender1"];
2498 let rb = comp_b.node_by_name["pRender1"];
2499 assert_ne!(ra, rb, "deleting UnrelatedBg should shift NodeIds");
2500
2501 let expr = ExprEngine::new();
2502 let sprites = HashMap::new();
2503 let dims = [64, 64];
2504
2505 let mut cache_a = ParticleCache::default();
2506 let img_a_20 = render_particles_2d(&mut cache_a, &comp_a, ra, 20.0, dims, &expr, &sprites);
2507
2508 // Bumping comp.revision (simulating unrelated node edit) reuses cached simulation.
2509 comp_a.revision += 99;
2510 let hash_before = particle_subgraph_hash(&comp_a, ra, 0);
2511 let hash_after_del = particle_subgraph_hash(&comp_b, rb, 0);
2512 assert_eq!(hash_before, hash_after_del, "subgraph hash must ignore NodeId shifts and unrelated nodes");
2513
2514 let mut cache_b = ParticleCache::default();
2515 let img_b_20 = render_particles_2d(&mut cache_b, &comp_b, rb, 20.0, dims, &expr, &sprites);
2516 assert_eq!(img_a_20, img_b_20, "deleting an unrelated node must not re-randomize particles");
2517
2518 // Stepping comp_b using cache_a (which has old NodeIds!) must still match fresh comp_b at frame 21.
2519 let img_a_to_b_21 = render_particles_2d(&mut cache_a, &comp_b, rb, 21.0, dims, &expr, &sprites);
2520 let mut fresh_b = ParticleCache::default();
2521 let img_b_21 = render_particles_2d(&mut fresh_b, &comp_b, rb, 21.0, dims, &expr, &sprites);
2522 assert_eq!(img_a_to_b_21, img_b_21);
2523 }
21522524}
crates/engine/src/shaders/color.wgsl+9-6
......@@ -35,8 +35,8 @@ fn bc_curve_scalar(v_in: f32, low: f32, high: f32, gain: f32, lift: f32, gamma:
3535 v = (v - low) / span;
3636 }
3737 v = v * (gain - lift) + lift;
38 if (gamma != 1.0) {
39 v = pow(max(v, 0.0), 1.0 / gamma);
38 if (gamma != 1.0 && v > 0.0) {
39 v = pow(v, 1.0 / gamma);
4040 }
4141 v = (v - 0.5) * (1.0 + contrast) + 0.5;
4242 v = v + brightness;
......@@ -463,12 +463,15 @@ fn color_curves_op(@builtin(global_invocation_id) gid: vec3<u32>) {
463463 rgb = clamp(rgb / src.a, vec3<f32>(0.0), vec3<f32>(1.0));
464464 }
465465
466 let r = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.r, 0.0, 1.0), 0.5), 0.0).r;
467 let g = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.g, 0.0, 1.0), 0.5), 0.0).g;
468 let b = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(rgb.b, 0.0, 1.0), 0.5), 0.0).b;
466 let lut_n = f32(textureDimensions(src_b).x);
467 let lut_u = (vec3<f32>(0.5) + clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * (lut_n - 1.0)) / lut_n;
468 let r = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u.r, 0.5), 0.0).r;
469 let g = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u.g, 0.5), 0.0).g;
470 let b = textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u.b, 0.5), 0.0).b;
469471 var a = src.a;
470472 if (apply_a) {
471 a = textureSampleLevel(src_b, samp_lin, vec2<f32>(clamp(src.a, 0.0, 1.0), 0.5), 0.0).a;
473 let a_u = (0.5 + clamp(src.a, 0.0, 1.0) * (lut_n - 1.0)) / lut_n;
474 a = textureSampleLevel(src_b, samp_lin, vec2<f32>(a_u, 0.5), 0.0).a;
472475 }
473476
474477 var out_rgb = vec3<f32>(r, g, b);
crates/engine/src/shaders/keyers_gen.wgsl+3-1
......@@ -115,7 +115,9 @@ fn fast_noise_op(@builtin(global_invocation_id) gid: vec3<u32>) {
115115 val = clamp(val + 0.5 * brightness, 0.0, 1.0);
116116
117117 // Fusion leaves the ramp color unpremultiplied; downstream Merge treats it as premultiplied
118 store_dst(vec2<i32>(gid.xy), textureSampleLevel(src_b, samp_lin, vec2<f32>(val, 0.5), 0.0));
118 let lut_n = f32(textureDimensions(src_b).x);
119 let lut_u = (0.5 + clamp(val, 0.0, 1.0) * (lut_n - 1.0)) / lut_n;
120 store_dst(vec2<i32>(gid.xy), textureSampleLevel(src_b, samp_lin, vec2<f32>(lut_u, 0.5), 0.0));
119121}
120122// ============================================================================
121123// 12. Fuse.Outline (Clover's exact 2020 Outline.fuse passes!)
crates/engine/src/shaders/transform.wgsl+18-4
......@@ -9,8 +9,16 @@
99fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
1010 let dims = textureDimensions(dst_tex);
1111 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
12 let fdims = vec2<f32>(dims);
13 let fu = pix_to_fu(gid.xy, dims);
12 let has_dst_dod = u.p[5].z > 0.5 && u.p[5].w > 0.5;
13 let fdims = select(vec2<f32>(dims), u.p[5].zw, has_dst_dod);
14 let fu = select(
15 pix_to_fu(gid.xy, dims),
16 vec2<f32>(
17 (f32(gid.x) + 0.5 + u.p[5].x) / u.p[5].z,
18 1.0 - (f32(gid.y) + 0.5 + u.p[5].y) / u.p[5].w,
19 ),
20 has_dst_dod,
21 );
1422
1523 let center = u.p[0].xy;
1624 let pivot = u.p[0].zw;
......@@ -43,7 +51,11 @@ fn transform_op(@builtin(global_invocation_id) gid: vec3<u32>) {
4351 let nearest = u.p[3].y > 0.5;
4452 let orig = sample_dod_edges_mode(src_a, fu, 0, u.p[4], nearest);
4553 let moved = sample_dod_edges_mode(src_a, src_fu, edges, u.p[4], nearest);
46 let raw_mask = read_mask(gid.xy, dims, u.p[2].w, u.p[3].x);
54 let raw_mask = select(
55 read_mask(gid.xy, dims, u.p[2].w, u.p[3].x),
56 read_mask_uv(fu_to_uv(fu), u.p[2].w, u.p[3].x),
57 has_dst_dod,
58 );
4759 let mbm = u.p[3].z > 0.5;
4860 let m = select(raw_mask, 1.0, mbm) * u.p[2].z;
4961 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<u32>) {
194206 var grad_sum = vec4<f32>(0.0);
195207 let inv_steps = 1.0 / f32(steps);
196208
209 let grad_n = f32(textureDimensions(src_b).x);
197210 for (var i = 0; i <= steps; i = i + 1) {
198211 let n = f32(i) * inv_steps;
199 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(n, 0.5), 0.0);
212 let grad_u = (0.5 + clamp(n, 0.0, 1.0) * (grad_n - 1.0)) / grad_n;
213 let grad = textureSampleLevel(src_b, samp_lin, vec2<f32>(grad_u, 0.5), 0.0);
200214
201215 let cur_c = mix(vec2<f32>(0.5, 0.5), center, n);
202216 let cur_sx = max(mix(1.0, xsize, n), 1e-4);