1use super::*;
2use crate::Engine;
3use model::Comp;
4
5fn mk_comp(tools: &str) -> Comp {
6 let src = format!(
7 "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}"
8 );
9 Comp::from_fusion_str(&src).expect("parse AutoMatte test comp")
10}
11
12fn px_u8(buf: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
13 let i = ((y * w + x) * 4) as usize;
14 buf[i..i + 4].try_into().unwrap()
15}
16
17fn px_f32(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] {
18 let i = ((y * w + x) * 4) as usize;
19 buf[i..i + 4].try_into().unwrap()
20}
21
22/// 1. Exact GPU verification of Clover's `polish_alpha` (haze floor elimination, ceiling clamping,
23/// toe compression below 0.15 while keeping strands >= 0.15 exact, plus Invert/Blur/Morpho/Modes).
24#[test]
25fn polish_alpha_floor_ceiling_toe_and_modes() {
26 let Ok(mut eng) = Engine::new_headless() else { return };
27 let comp = mk_comp(
28 r#"
29 Plate = Background {
30 Inputs = {
31 Width = Input { Value = 64, }, Height = Input { Value = 16, },
32 Depth = Input { Value = 3, },
33 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, },
34 },
35 },
36 AM = AutoMatte {
37 Inputs = {
38 Input = Input { SourceOp = "Plate", Source = "Output", },
39 OutputMode = Input { Value = 1, },
40 },
41 },
42 AMInv = AutoMatte {
43 Inputs = {
44 Input = Input { SourceOp = "Plate", Source = "Output", },
45 OutputMode = Input { Value = 1, },
46 Invert = Input { Value = 1, },
47 },
48 },
49 AMOverlay = AutoMatte {
50 Inputs = {
51 Input = Input { SourceOp = "Plate", Source = "Output", },
52 OutputMode = Input { Value = 2, },
53 },
54 },
55 "#,
56 );
57
58 // Build a 64x16 horizontal ramp of raw alpha values covering haze, toe, strands, and ceiling
59 let w = 64u32;
60 let h = 16u32;
61 let mut ramp = vec![0.0_f32; (w * h) as usize];
62 for y in 0..h {
63 for x in 0..w {
64 ramp[(y * w + x) as usize] = x as f32 / (w - 1) as f32;
65 }
66 }
67 eng.auto_matte_cache.insert_alpha_f32("AM", 0, [w, h], ramp.clone());
68 eng.auto_matte_cache.insert_alpha_f32("AMInv", 0, [w, h], ramp.clone());
69 eng.auto_matte_cache.insert_alpha_f32("AMOverlay", 0, [w, h], ramp);
70
71 let (tex, _) = eng.evaluate(&comp, comp.find_node("AM").unwrap(), 0.0);
72 let f32_buf = eng.readback_rgba_f32(&tex).unwrap();
73
74 // Check every column against Clover's exact `polish_alpha` formula
75 let lo = 0.045_f32;
76 let hi = 0.985_f32;
77 let toe_gamma = 1.35_f32;
78 for x in 0..w {
79 let raw = x as f32 / (w - 1) as f32;
80 let lin = ((raw - lo) / (hi - lo)).clamp(0.0, 1.0);
81 let expected = if lin < 0.15 {
82 (lin / 0.15).powf(toe_gamma) * 0.15
83 } else {
84 lin
85 };
86 let got = px_f32(&f32_buf, w, x, 8);
87 assert!(
88 (got[3] - expected).abs() < 2e-3,
89 "polish_alpha mismatch at x={x} (raw={raw:.4}): got={:.5} expected={:.5}",
90 got[3],
91 expected
92 );
93 // OutputMode = 1 outputs grayscale (a, a, a, a)
94 assert!((got[0] - got[3]).abs() < 2e-3);
95 }
96
97 // Haze <= 0.045 (x=0,1,2 -> raw <= 0.0317) must be exact 0.0
98 assert_eq!(px_f32(&f32_buf, w, 2, 8)[3], 0.0, "VAE haze <= 0.045 must be eliminated");
99 // Ceiling >= 0.985 (x=63 -> raw=1.0) must be exact 1.0
100 assert_eq!(px_f32(&f32_buf, w, 63, 8)[3], 1.0, "Ceiling >= 0.985 must clamp to 1.0");
101 // Toe compression (x=7 -> raw=0.1111 -> lin=0.0703 < 0.15) strictly compressed below linear
102 let toe_raw = 7.0_f32 / 63.0;
103 let toe_lin = (toe_raw - lo) / (hi - lo);
104 let toe_got = px_f32(&f32_buf, w, 7, 8)[3];
105 assert!(toe_got > 0.0 && toe_got < toe_lin - 0.01, "toe must compress misty halo: got={toe_got} lin={toe_lin}");
106 // Strand > 0.15 (x=20 -> raw=0.3175 -> lin=0.2899) untouched by toe
107 let strand_raw = 20.0_f32 / 63.0;
108 let strand_lin = (strand_raw - lo) / (hi - lo);
109 let strand_got = px_f32(&f32_buf, w, 20, 8)[3];
110 assert!((strand_got - strand_lin).abs() < 2e-3, "strand > 0.15 must stay crisp: got={strand_got} lin={strand_lin}");
111
112 // Invert = 1 flips alpha
113 let (inv_tex, _) = eng.evaluate(&comp, comp.find_node("AMInv").unwrap(), 0.0);
114 let inv_buf = eng.readback_rgba_f32(&inv_tex).unwrap();
115 assert_eq!(px_f32(&inv_buf, w, 2, 8)[3], 1.0);
116 assert_eq!(px_f32(&inv_buf, w, 63, 8)[3], 0.0);
117
118 // OutputMode = 2 renders opaque ruby overlay where alpha == 1, untouched plate where alpha == 0
119 let (ov_tex, _) = eng.evaluate(&comp, comp.find_node("AMOverlay").unwrap(), 0.0);
120 let ov_buf = eng.readback_rgba_f32(&ov_tex).unwrap();
121 let bg_px = px_f32(&ov_buf, w, 1, 8);
122 let fg_px = px_f32(&ov_buf, w, 63, 8);
123 assert!((bg_px[0] - 0.8).abs() < 1e-2 && (bg_px[3] - 1.0).abs() < 1e-2);
124 assert!(fg_px[0] > bg_px[0] + 0.05 && fg_px[1] < bg_px[1] - 0.1, "overlay tints foreground ruby: {fg_px:?}");
125}
126
127/// 2. GPU `hair_safe_decontaminate`: eliminates neon-cyan background spill inside semi-transparent
128/// hair edge pixels while keeping solid interior (`alpha > 0.94`) RGB bit-exact.
129#[test]
130fn hair_safe_decontaminate_kills_cyan_spill_and_preserves_solid_interior() {
131 let Ok(mut eng) = Engine::new_headless() else { return };
132 // Left half [0..26): pure solid brown hair RGB = (0.44, 0.22, 0.10)
133 // Middle band [26..36): wispy hair heavily contaminated with neon cyan (0.0, 1.0, 1.0)
134 // Right half [36..64): pure neon cyan background (0.0, 1.0, 1.0)
135 let comp = mk_comp(
136 r#"
137 CyanBg = Background {
138 Inputs = {
139 Width = Input { Value = 64, }, Height = Input { Value = 64, },
140 TopLeftRed = Input { Value = 0.0, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftBlue = Input { Value = 1.0, },
141 },
142 },
143 HairMask = RectangleMask {
144 Inputs = {
145 MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
146 Center = Input { Value = { 0.20, 0.5 }, }, Width = Input { Value = 0.40, }, Height = Input { Value = 1.0, },
147 },
148 },
149 HairFg = Background {
150 Inputs = {
151 Width = Input { Value = 64, }, Height = Input { Value = 64, },
152 TopLeftRed = Input { Value = 0.44, }, TopLeftGreen = Input { Value = 0.22, }, TopLeftBlue = Input { Value = 0.10, },
153 EffectMask = Input { SourceOp = "HairMask", Source = "Mask", },
154 },
155 },
156 SpillMask = RectangleMask {
157 Inputs = {
158 MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
159 Center = Input { Value = { 0.48, 0.5 }, }, Width = Input { Value = 0.16, }, Height = Input { Value = 1.0, },
160 },
161 },
162 SpillBand = Background {
163 Inputs = {
164 Width = Input { Value = 64, }, Height = Input { Value = 64, },
165 TopLeftRed = Input { Value = 0.15, }, TopLeftGreen = Input { Value = 0.85, }, TopLeftBlue = Input { Value = 0.90, },
166 EffectMask = Input { SourceOp = "SpillMask", Source = "Mask", },
167 },
168 },
169 M1 = Merge {
170 Inputs = {
171 Background = Input { SourceOp = "CyanBg", Source = "Output", },
172 Foreground = Input { SourceOp = "HairFg", Source = "Output", },
173 },
174 },
175 Plate = Merge {
176 Inputs = {
177 Background = Input { SourceOp = "M1", Source = "Output", },
178 Foreground = Input { SourceOp = "SpillBand", Source = "Output", },
179 },
180 },
181 AMClean = AutoMatte {
182 Inputs = {
183 Input = Input { SourceOp = "Plate", Source = "Output", },
184 Decontaminate = Input { Value = 1.0, },
185 AlphaFloor = Input { Value = 0.0, },
186 AlphaCeiling = Input { Value = 1.0, },
187 ToeGamma = Input { Value = 1.0, },
188 },
189 },
190 AMRaw = AutoMatte {
191 Inputs = {
192 Input = Input { SourceOp = "Plate", Source = "Output", },
193 Decontaminate = Input { Value = 0.0, },
194 AlphaFloor = Input { Value = 0.0, },
195 AlphaCeiling = Input { Value = 1.0, },
196 ToeGamma = Input { Value = 1.0, },
197 },
198 },
199 "#,
200 );
201
202 let (w, h) = (64u32, 64u32);
203 let mut alpha = vec![0.0_f32; (w * h) as usize];
204 for y in 0..h {
205 for x in 0..w {
206 let a = if x < 25 {
207 1.0
208 } else if x < 36 {
209 // Semi-transparent wispy hair strands (< 0.85) sitting directly over cyan spill
210 0.50
211 } else {
212 0.0
213 };
214 alpha[(y * w + x) as usize] = a;
215 }
216 }
217 eng.auto_matte_cache.insert_alpha_f32("AMClean", 0, [w, h], alpha.clone());
218 eng.auto_matte_cache.insert_alpha_f32("AMRaw", 0, [w, h], alpha);
219
220 let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0);
221 let plate_px = eng.readback_rgba(&plate_tex).unwrap();
222
223 let (clean_tex, _) = eng.evaluate(&comp, comp.find_node("AMClean").unwrap(), 0.0);
224 let clean_px = eng.readback_rgba(&clean_tex).unwrap();
225
226 let (raw_tex, _) = eng.evaluate(&comp, comp.find_node("AMRaw").unwrap(), 0.0);
227 let raw_px = eng.readback_rgba(&raw_tex).unwrap();
228
229 // 1. Solid interior (x=10, y=32, alpha=1.0) MUST be bit-exact to original Plate
230 assert_eq!(
231 px_u8(&clean_px, w, 10, 32),
232 px_u8(&plate_px, w, 10, 32),
233 "solid interior (alpha > 0.94) must remain bit-exact"
234 );
235
236 // 2. Wispy edge pixel (x=30, y=32, alpha=0.50): unpremultiplied foreground must match clean
237 // brown hair (~112, 56, 26), completely removing the cyan spill (~38, 217, 230) seen in AMRaw!
238 let wisp_clean = px_u8(&clean_px, w, 30, 32);
239 let wisp_raw = px_u8(&raw_px, w, 30, 32);
240 assert!((wisp_clean[3] as i32 - 128).abs() <= 2, "wisp alpha preserved: {wisp_clean:?}");
241 let clean_unpremult_r = wisp_clean[0] as f32 / (wisp_clean[3] as f32 / 255.0);
242 let clean_unpremult_g = wisp_clean[1] as f32 / (wisp_clean[3] as f32 / 255.0);
243 let clean_unpremult_b = wisp_clean[2] as f32 / (wisp_clean[3] as f32 / 255.0);
244 let raw_unpremult_b = wisp_raw[2] as f32 / (wisp_raw[3] as f32 / 255.0);
245
246 assert!(
247 raw_unpremult_b > 200.0,
248 "sanity check: raw non-decontaminated wisp carries heavy cyan blue spill ({raw_unpremult_b:.1})"
249 );
250 assert!(
251 clean_unpremult_r > 95.0 && clean_unpremult_g < 75.0 && clean_unpremult_b < 45.0,
252 "hair_safe_decontaminate must replace cyan spill with clean extrapolated brown hair: clean=({clean_unpremult_r:.1}, {clean_unpremult_g:.1}, {clean_unpremult_b:.1})"
253 );
254
255 // 3. Background (x=55, y=32, alpha=0.0) must be transparent black
256 assert_eq!(px_u8(&clean_px, w, 55, 32), [0, 0, 0, 0]);
257}
258
259/// 3. Built-in GPU point-seeded segmentation (`+`/`-` click points + bilateral edge refinement,
260/// plus `AutoPerson` center-salient heuristic with zero clicks).
261#[test]
262fn gpu_seeded_segmentation_separates_fg_from_bg() {
263 let Ok(mut eng) = Engine::new_headless() else { return };
264 let comp = mk_comp(
265 r#"
266 BlueBg = Background {
267 Inputs = {
268 Width = Input { Value = 64, }, Height = Input { Value = 64, },
269 TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.16, }, TopLeftBlue = Input { Value = 0.86, },
270 },
271 },
272 BoxM = RectangleMask {
273 Inputs = {
274 MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
275 Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 0.45, }, Height = Input { Value = 0.45, },
276 },
277 },
278 RedObj = Background {
279 Inputs = {
280 Width = Input { Value = 64, }, Height = Input { Value = 64, },
281 TopLeftRed = Input { Value = 0.88, }, TopLeftGreen = Input { Value = 0.12, }, TopLeftBlue = Input { Value = 0.10, },
282 EffectMask = Input { SourceOp = "BoxM", Source = "Mask", },
283 },
284 },
285 Plate = Merge {
286 Inputs = {
287 Background = Input { SourceOp = "BlueBg", Source = "Output", },
288 Foreground = Input { SourceOp = "RedObj", Source = "Output", },
289 },
290 },
291 AMPoints = AutoMatte {
292 Inputs = {
293 Input = Input { SourceOp = "Plate", Source = "Output", },
294 Points = Input { Value = "0.50,0.50,+;0.10,0.10,-;0.90,0.90,-", },
295 QualityTier = Input { Value = 1, },
296 },
297 },
298 AMAutoPerson = AutoMatte {
299 Inputs = {
300 Input = Input { SourceOp = "Plate", Source = "Output", },
301 PromptMode = Input { Value = 1, },
302 QualityTier = Input { Value = 0, },
303 },
304 },
305 "#,
306 );
307
308 // Explicit +/- click points
309 let (tex, _) = eng.evaluate(&comp, comp.find_node("AMPoints").unwrap(), 0.0);
310 let buf = eng.readback_rgba(&tex).unwrap();
311 let center = px_u8(&buf, 64, 32, 32);
312 let corner_tl = px_u8(&buf, 64, 4, 4);
313 let corner_br = px_u8(&buf, 64, 60, 60);
314 assert!(center[3] >= 245 && center[0] > 200, "foreground center must be opaque red: {center:?}");
315 assert!(corner_tl[3] <= 5 && corner_br[3] <= 5, "background corners must be keyed out: tl={corner_tl:?} br={corner_br:?}");
316
317 // AutoPerson mode with zero manual points
318 let (ap_tex, _) = eng.evaluate(&comp, comp.find_node("AMAutoPerson").unwrap(), 0.0);
319 let ap_buf = eng.readback_rgba(&ap_tex).unwrap();
320 assert!(px_u8(&ap_buf, 64, 32, 32)[3] >= 240, "AutoPerson center subject must be opaque");
321 assert!(px_u8(&ap_buf, 64, 4, 4)[3] <= 10, "AutoPerson border background must be transparent");
322}
323
324/// 4. `AutoMatteCache` per-frame injection, disk `CacheDir` PNG loading, real Fusion `MagicMask`
325/// `MagicMaskStrokes` spline parsing, and empty-stroke passthrough (0.00% MAE).
326#[test]
327fn cache_injection_and_fusion_magic_mask_strokes_and_empty_passthrough() {
328 let Ok(mut eng) = Engine::new_headless() else { return };
329
330 // Real Fusion MagicMask comp structure matching `/Volumes/Project/trees/fusion/21_ground.comp`
331 let comp = mk_comp(
332 r#"
333 GreenBg = Background {
334 Inputs = {
335 Width = Input { Value = 64, }, Height = Input { Value = 64, },
336 TopLeftRed = Input { Value = 0.08, }, TopLeftGreen = Input { Value = 0.72, }, TopLeftBlue = Input { Value = 0.14, },
337 },
338 },
339 CircleM = EllipseMask {
340 Inputs = {
341 MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
342 Center = Input { Value = { 0.35, 0.65 }, }, Width = Input { Value = 0.35, }, Height = Input { Value = 0.35, },
343 },
344 },
345 OrangeSubject = Background {
346 Inputs = {
347 Width = Input { Value = 64, }, Height = Input { Value = 64, },
348 TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.45, }, TopLeftBlue = Input { Value = 0.05, },
349 EffectMask = Input { SourceOp = "CircleM", Source = "Mask", },
350 },
351 },
352 Plate = Merge {
353 Inputs = {
354 Background = Input { SourceOp = "GreenBg", Source = "Output", },
355 Foreground = Input { SourceOp = "OrangeSubject", Source = "Output", },
356 },
357 },
358 MagicMask1 = MagicMask {
359 Inputs = {
360 ReferenceTime = Input { Value = 2466, Disabled = true, },
361 UseLegacyMagicMask = Input { Value = 0, Disabled = true, },
362 Strokes = Input { SourceOp = "MagicMask1Strokes", Source = "Value", },
363 Input = Input { SourceOp = "Plate", Source = "Output", },
364 },
365 },
366 MagicMask1Strokes = BezierSpline {
367 KeyFrames = {
368 [2466] = { 0, Flags = { Linear = true, LockedY = true }, Value = MagicMaskStrokes {
369 PosStrokes = {
370 { 0.35, 0.65 },
371 { 0.38, 0.62 },
372 },
373 NegStrokes = {
374 { 0.85, 0.20 },
375 }
376 } }
377 }
378 },
379 EmptyMagicMask = MagicMask {
380 Inputs = {
381 Input = Input { SourceOp = "Plate", Source = "Output", },
382 },
383 },
384 "#,
385 );
386
387 // Verify Fusion MagicMaskStrokes extraction (Y-up preserved accurately!)
388 let mm1_node = comp.node(comp.find_node("MagicMask1").unwrap());
389 let params = extract_magic_mask_params(&comp, mm1_node, 2466.0, &eng.expr);
390 assert!(params.is_magic_mask);
391 assert_eq!(params.points.len(), 3);
392 assert!(params.points[0].positive && (params.points[0].x - 0.35).abs() < 1e-5 && (params.points[0].y - 0.65).abs() < 1e-5);
393 assert!(!params.points[2].positive && (params.points[2].x - 0.85).abs() < 1e-5 && (params.points[2].y - 0.20).abs() < 1e-5);
394
395 // Evaluate MagicMask1 on GPU: Fusion Y-up (0.35, 0.65) -> GPU pixel (~22, ~22) is orange subject;
396 // Fusion Y-up (0.85, 0.20) -> GPU pixel (~54, ~51) is green background!
397 let (mm_tex, _) = eng.evaluate(&comp, comp.find_node("MagicMask1").unwrap(), 2466.0);
398 let mm_buf = eng.readback_rgba(&mm_tex).unwrap();
399 let subj_px = px_u8(&mm_buf, 64, 22, 22);
400 let bg_px = px_u8(&mm_buf, 64, 54, 51);
401 assert!(subj_px[3] >= 240, "MagicMask positive stroke subject must be opaque: {subj_px:?}");
402 assert!(bg_px[3] <= 10, "MagicMask negative stroke background must be transparent: {bg_px:?}");
403
404 // Empty MagicMask (no strokes, no cached matte) MUST pass foreground through bit-for-bit (0.00% MAE)
405 let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0);
406 let (empty_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0);
407 assert_eq!(
408 eng.readback_rgba(&empty_tex).unwrap(),
409 eng.readback_rgba(&plate_tex).unwrap(),
410 "empty MagicMask must pass through input bit-exact with 0.00% MAE"
411 );
412
413 // Now inject a cached neural matte into EmptyMagicMask for frame 0 -> must immediately override
414 // passthrough and bust OutputCache automatically!
415 let mut right_half = vec![0.0_f32; 64 * 64];
416 for y in 0..64 {
417 for x in 32..64 {
418 right_half[y * 64 + x] = 1.0;
419 }
420 }
421 eng.auto_matte_cache.insert_alpha_f32("EmptyMagicMask", 0, [64, 64], right_half);
422 let (injected_tex, _) = eng.evaluate(&comp, comp.find_node("EmptyMagicMask").unwrap(), 0.0);
423 let inj_buf = eng.readback_rgba(&injected_tex).unwrap();
424 assert_eq!(px_u8(&inj_buf, 64, 8, 32)[3], 0, "cached matte left half must be transparent");
425 assert_eq!(px_u8(&inj_buf, 64, 56, 32)[3], 255, "cached matte right half must be opaque");
426
427 // Disk CacheDir PNG loading test (native only)
428 #[cfg(not(target_arch = "wasm32"))]
429 {
430 let tmp_dir = std::env::temp_dir().join(format!("fission_automate_test_{}", std::process::id()));
431 let _ = std::fs::remove_dir_all(&tmp_dir);
432 std::fs::create_dir_all(&tmp_dir).unwrap();
433 let mut png_img = image::GrayImage::new(32, 32);
434 for y in 0..32 {
435 for x in 0..32 {
436 png_img.put_pixel(x, y, image::Luma([if y < 16 { 255 } else { 0 }]));
437 }
438 }
439 png_img.save(tmp_dir.join("0005.png")).unwrap();
440
441 let disk_comp = mk_comp(&format!(
442 r#"
443 Bg = Background {{ Inputs = {{ Width = Input {{ Value = 32, }}, Height = Input {{ Value = 32, }}, TopLeftRed = Input {{ Value = 1.0, }}, }}, }},
444 DiskAM = AutoMatte {{
445 Inputs = {{
446 Input = Input {{ SourceOp = "Bg", Source = "Output", }},
447 CacheDir = Input {{ Value = "{}", }},
448 OutputMode = Input {{ Value = 1, }},
449 }},
450 }},
451 "#,
452 tmp_dir.to_string_lossy().replace('\\', "/")
453 ));
454 let (disk_tex, _) = eng.evaluate(&disk_comp, disk_comp.find_node("DiskAM").unwrap(), 5.0);
455 let disk_buf = eng.readback_rgba(&disk_tex).unwrap();
456 assert_eq!(px_u8(&disk_buf, 32, 16, 4)[3], 255, "top half from 0005.png must be opaque");
457 assert_eq!(px_u8(&disk_buf, 32, 16, 28)[3], 0, "bottom half from 0005.png must be transparent");
458 let _ = std::fs::remove_dir_all(&tmp_dir);
459 }
460}
461
462/// 5. MatteContractExpand + MatteBlur + EffectMask + Blend=0 verification.
463#[test]
464fn matte_contract_expand_blur_and_effect_mask() {
465 let Ok(mut eng) = Engine::new_headless() else { return };
466 let comp = mk_comp(
467 r#"
468 Plate = Background {
469 Inputs = {
470 Width = Input { Value = 64, }, Height = Input { Value = 64, },
471 TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.2, },
472 },
473 },
474 AMExpand = AutoMatte {
475 Inputs = {
476 Input = Input { SourceOp = "Plate", Source = "Output", },
477 MatteContractExpand = Input { Value = 3.0, },
478 OutputMode = Input { Value = 1, },
479 },
480 },
481 AMContract = AutoMatte {
482 Inputs = {
483 Input = Input { SourceOp = "Plate", Source = "Output", },
484 MatteContractExpand = Input { Value = -3.0, },
485 OutputMode = Input { Value = 1, },
486 },
487 },
488 AMBlur = AutoMatte {
489 Inputs = {
490 Input = Input { SourceOp = "Plate", Source = "Output", },
491 MatteBlur = Input { Value = 2.5, },
492 OutputMode = Input { Value = 1, },
493 },
494 },
495 AMBlendZero = AutoMatte {
496 Inputs = {
497 Input = Input { SourceOp = "Plate", Source = "Output", },
498 Blend = Input { Value = 0.0, },
499 },
500 },
501 "#,
502 );
503
504 let mut box_alpha = vec![0.0_f32; 64 * 64];
505 for y in 20..44 {
506 for x in 20..44 {
507 box_alpha[y * 64 + x] = 1.0;
508 }
509 }
510 for name in ["AMExpand", "AMContract", "AMBlur", "AMBlendZero"] {
511 eng.auto_matte_cache.insert_alpha_f32(name, 0, [64, 64], box_alpha.clone());
512 }
513
514 let (exp_tex, _) = eng.evaluate(&comp, comp.find_node("AMExpand").unwrap(), 0.0);
515 let exp_buf = eng.readback_rgba(&exp_tex).unwrap();
516 let (con_tex, _) = eng.evaluate(&comp, comp.find_node("AMContract").unwrap(), 0.0);
517 let con_buf = eng.readback_rgba(&con_tex).unwrap();
518
519 let exp_count = exp_buf.chunks_exact(4).filter(|p| p[3] > 200).count();
520 let con_count = con_buf.chunks_exact(4).filter(|p| p[3] > 200).count();
521 assert!(
522 exp_count > con_count + 400,
523 "expanded matte ({exp_count}) must be substantially larger than contracted ({con_count})"
524 );
525
526 let (blur_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlur").unwrap(), 0.0);
527 let blur_buf = eng.readback_rgba(&blur_tex).unwrap();
528 let edge_a = px_u8(&blur_buf, 64, 20, 32)[3];
529 assert!(edge_a > 40 && edge_a < 220, "MatteBlur must produce smooth edge alpha: {edge_a}");
530
531 let (plate_tex, _) = eng.evaluate(&comp, comp.find_node("Plate").unwrap(), 0.0);
532 let (b0_tex, _) = eng.evaluate(&comp, comp.find_node("AMBlendZero").unwrap(), 0.0);
533 assert_eq!(
534 eng.readback_rgba(&b0_tex).unwrap(),
535 eng.readback_rgba(&plate_tex).unwrap(),
536 "Blend = 0 must pass input through untouched"
537 );
538}
539
540/// 6. EffectMask gating, proxy_scale=2 decontamination scaling, and native AutoMatteRunner validation.
541#[test]
542fn effect_mask_proxy_scale_and_runner_api() {
543 let Ok(mut eng) = Engine::new_headless() else { return };
544 let comp = mk_comp(
545 r#"
546 Plate = Background {
547 Inputs = {
548 Width = Input { Value = 64, }, Height = Input { Value = 64, },
549 TopLeftRed = Input { Value = 0.80, }, TopLeftGreen = Input { Value = 0.30, }, TopLeftBlue = Input { Value = 0.20, },
550 },
551 },
552 LeftMask = RectangleMask {
553 Inputs = {
554 MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
555 Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, },
556 },
557 },
558 AMMasked = AutoMatte {
559 Inputs = {
560 Input = Input { SourceOp = "Plate", Source = "Output", },
561 EffectMask = Input { SourceOp = "LeftMask", Source = "Mask", },
562 },
563 },
564 "#,
565 );
566 // All-zero cached matte: inside LeftMask (left half) becomes transparent, outside LeftMask (right half)
567 // stays original Plate because EffectMask gates the AutoMatte effect!
568 eng.auto_matte_cache
569 .insert_alpha_f32("AMMasked", 0, [64, 64], vec![0.0_f32; 64 * 64]);
570
571 let (tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 0.0);
572 let buf = eng.readback_rgba(&tex).unwrap();
573 assert_eq!(px_u8(&buf, 64, 8, 32)[3], 0, "inside EffectMask must apply zero alpha");
574 assert_eq!(px_u8(&buf, 64, 56, 32)[3], 255, "outside EffectMask must keep original Plate");
575
576 // Proxy scale = 2: full-res 64x64 cached matte resamples cleanly to 32x32 output
577 eng.proxy_scale = 2;
578 eng.auto_matte_cache
579 .insert_alpha_f32("AMMasked", 1, [64, 64], vec![1.0_f32; 64 * 64]);
580 let (proxy_tex, _) = eng.evaluate(&comp, comp.find_node("AMMasked").unwrap(), 1.0);
581 assert_eq!(proxy_tex.size, [32, 32]);
582 let pbuf = eng.readback_rgba(&proxy_tex).unwrap();
583 assert_eq!(px_u8(&pbuf, 32, 4, 16)[3], 255, "proxy_scale=2 resampled cached matte must stay opaque");
584
585 #[cfg(not(target_arch = "wasm32"))]
586 {
587 let runner = AutoMatteRunner::new(
588 AutoMatteWorkerConfig {
589 python_bin: std::path::PathBuf::from("/nonexistent/python"),
590 worker_script: std::path::PathBuf::from("/nonexistent/worker.py"),
591 output_dir: std::env::temp_dir(),
592 },
593 eng.auto_matte_cache.clone(),
594 );
595 let err = runner.spawn_job(AutoMatteJobRequest {
596 node_name: "AMMasked".into(),
597 input_path: std::path::PathBuf::from("/nonexistent/clip.mov"),
598 frame_range: [0, 0],
599 quality_tier: QualityTier::HeroHair,
600 prompt_mode: PromptMode::ClickPoints,
601 prompts: vec![PromptPoint::positive(0.5, 0.5)],
602 });
603 assert!(err.is_err(), "missing worker binary must return clean Err without panicking");
604 }
605}
606