1use super::*;
2
3/// One ColorCorrector "Levels" block (`Master`/`Shadows`/`MidTones`/`Highlights` x `RGB`/`Red`/`Green`/`Blue`).
4#[derive(Clone, Copy)]
5struct CcLevels {
6 contrast: f32,
7 gain: f32,
8 lift: f32,
9 gamma: f32,
10 brightness: f32,
11 low: f32,
12 mid: f32,
13 high: f32,
14 out_low: f32,
15 out_high: f32,
16}
17
18impl CcLevels {
19 fn read(comp: &Comp, node: &Node, time: f64, range: &str, expr: &ExprEngine) -> [CcLevels; 4] {
20 ["RGB", "Red", "Green", "Blue"].map(|set| {
21 let n = |name: &str, default: f64| comp.eval_number(node, &format!("{range}{set}{name}"), time, default, expr) as f32;
22 CcLevels {
23 contrast: n("Contrast", 1.0),
24 gain: n("Gain", 1.0),
25 lift: n("Lift", 0.0),
26 gamma: n("Gamma", 1.0).max(1e-4),
27 brightness: n("Brightness", 0.0),
28 low: n("Low", 0.0),
29 mid: n("Mid", 1.0).max(1e-4),
30 high: n("High", 1.0),
31 out_low: n("OutputLow", 0.0),
32 out_high: n("OutputHigh", 1.0),
33 }
34 })
35 }
36
37 fn is_neutral(&self) -> bool {
38 [self.contrast, self.gain, self.gamma, self.mid, self.high, self.out_high].iter().all(|v| (v - 1.0).abs() < 1e-6)
39 && [self.lift, self.brightness, self.low, self.out_low].iter().all(|v| v.abs() < 1e-6)
40 }
41
42 /// Effective curve for a chain of blocks, as three texels: `(contrast, slope, offset, brightness)`,
43 /// `(in_scale, in_offset, gamma, 0)` and `(out_scale, out_offset, 0, 0)`. Contrast, slope and gamma multiply while lift and
44 /// brightness add; the input and output ranges compose one after another.
45 fn combine(chain: &[&CcLevels]) -> [[f32; 4]; 3] {
46 let (mut contrast, mut slope, mut offset, mut bright, mut gamma) = (1.0, 1.0, 0.0, 0.0, 1.0);
47 let (mut in_scale, mut in_offset, mut out_scale, mut out_offset) = (1.0, 0.0, 1.0, 0.0);
48 for l in chain {
49 contrast *= l.contrast;
50 slope *= l.gain - l.lift;
51 offset += l.lift;
52 bright += l.brightness;
53 gamma *= l.gamma * l.mid;
54 let span = (l.high - l.low).max(1e-5);
55 in_scale /= span;
56 in_offset = (in_offset - l.low) / span;
57 let out_span = l.out_high - l.out_low;
58 out_scale *= out_span;
59 out_offset = out_offset * out_span + l.out_low;
60 }
61 // Curve table is uploaded as Rgba16Float (max 65504); when `low >= high` collapses `span` to
62 // `1e-5`, `in_scale` reaches 1e5+ and overflows f16 to Inf (producing Inf - Inf = NaN in the
63 // shader). Rescaling `(in_scale, in_offset)` together keeps the exact step threshold
64 // `-in_offset / in_scale` while staying finite in f16.
65 let max_in = in_scale.abs().max(in_offset.abs());
66 if max_in > 4096.0 {
67 let s = 4096.0 / max_in;
68 in_scale *= s;
69 in_offset *= s;
70 }
71 [[contrast, slope, offset, bright], [in_scale, in_offset, gamma, 0.0], [out_scale, out_offset, 0.0, 0.0]]
72 }
73}
74
75#[derive(Clone, Copy)]
76struct GamutSpec {
77 primaries: [[f64; 2]; 4], // R, G, B, White xy
78 gamma: f64,
79 limit: f64,
80 slope: f64,
81}
82
83fn gamut_space_spec(
84 comp: &Comp,
85 node: &Node,
86 time: f64,
87 expr: &ExprEngine,
88 space: &str,
89 is_src: bool,
90) -> Option<GamutSpec> {
91 const D65: [f64; 2] = [0.312713, 0.329016];
92 const D50: [f64; 2] = [0.3457, 0.3585];
93 const D60: [f64; 2] = [0.32168, 0.33767];
94 const SRGB_P: [[f64; 2]; 4] = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65];
95 let spec = |primaries, gamma, limit, slope| Some(GamutSpec { primaries, gamma, limit, slope });
96 match space {
97 "sRGB" | "Rec709Display" => spec(SRGB_P, 2.4, 0.0031308, 12.92),
98 "SimplifiedsRGB" => spec(SRGB_P, 2.2, 0.0, 1.0),
99 "Rec709" | "Rec.709" | "ARRIRec709" => spec(SRGB_P, 1.0 / 0.45, 0.018, 4.5),
100 "WideGamut" => spec([[0.735, 0.265], [0.115, 0.826], [0.157, 0.018], D50], 2.2, 0.0, 1.0),
101 "Adobe" => spec([[0.64, 0.33], [0.21, 0.71], [0.15, 0.06], D65], 563.0 / 256.0, 0.0, 1.0),
102 "Rec2020" => spec([[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65], 1.0 / 0.45, 0.0180539685, 4.5),
103 "P3D65" => spec([[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65], 2.4, 0.0031308, 12.92),
104 "P3D60" => spec([[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D60], 2.6, 0.0, 1.0),
105 "DCI" => spec([[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], [0.314, 0.351]], 2.6, 0.0, 1.0),
106 "ACES" => spec([[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.077], D60], 1.0, 0.0, 1.0),
107 "ACEScg" => spec([[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60], 1.0, 0.0, 1.0),
108 "ProPhoto" => spec([[0.734699, 0.265301], [0.159597, 0.840403], [0.036598, 0.000105], D50], 1.8, 1.0 / 512.0, 16.0),
109 "RedWideGamut" => spec([[0.780308, 0.304253], [0.121595, 1.493994], [0.095612, -0.084589], D65], 1.0, 0.0, 1.0),
110 "Custom" => {
111 let pfx = if is_src { "CustomSource" } else { "CustomOutput" };
112 let r = comp.eval_point(node, &format!("{pfx}Red"), time, [0.64, 0.33], expr);
113 let g = comp.eval_point(node, &format!("{pfx}Green"), time, [0.30, 0.60], expr);
114 let b = comp.eval_point(node, &format!("{pfx}Blue"), time, [0.15, 0.06], expr);
115 let w = comp.eval_point(node, &format!("{pfx}White"), time, [D65[0], D65[1]], expr);
116 let gamma = comp.eval_number(node, &format!("{pfx}Gamma"), time, 2.4, expr);
117 let limit = comp.eval_number(node, &format!("{pfx}Limit"), time, 0.0031308, expr);
118 let slope = comp.eval_number(node, &format!("{pfx}Slope"), time, 12.92, expr);
119 spec([r, g, b, w], gamma, limit, slope)
120 }
121 _ => None,
122 }
123}
124
125/// Parametric transfer parameters `[gamma, limit, slope, a_off]` matching Fusion's `Custom` / ICC curve.
126fn gamut_transfer_params(gamma: f64, limit: f64, slope: f64) -> Option<[f32; 4]> {
127 if (gamma - 1.0).abs() < 1e-5 && limit <= 1e-6 && (slope - 1.0).abs() < 1e-5 {
128 return None;
129 }
130 let g = gamma.max(1e-4);
131 let lim = limit.max(0.0);
132 let slp = slope.max(1e-6);
133 let a_off = if lim <= 1e-7 {
134 0.0
135 } else {
136 let lg = lim.powf(1.0 / g);
137 ((lg - slp * lim) / (1.0 - lg).max(1e-6)).max(0.0)
138 };
139 Some([g as f32, lim as f32, slp as f32, a_off as f32])
140}
141
142fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
143 let [a, b, c] = m[0];
144 let [d, e, f] = m[1];
145 let [g, h, i] = m[2];
146 let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
147 let inv = if det.abs() > 1e-12 { 1.0 / det } else { 0.0 };
148 [
149 [(e * i - f * h) * inv, (c * h - b * i) * inv, (b * f - c * e) * inv],
150 [(f * g - d * i) * inv, (a * i - c * g) * inv, (c * d - a * f) * inv],
151 [(d * h - e * g) * inv, (b * g - a * h) * inv, (a * e - b * d) * inv],
152 ]
153}
154
155fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
156 std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum()))
157}
158
159fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {
160 std::array::from_fn(|r| (0..3).map(|c| m[r][c] * v[c]).sum())
161}
162
163fn primaries_to_xyz(p: [[f64; 2]; 4]) -> [[f64; 3]; 3] {
164 let xy_xyz = |xy: [f64; 2]| [xy[0] / xy[1].max(1e-6), 1.0, (1.0 - xy[0] - xy[1]) / xy[1].max(1e-6)];
165 let [xr, xg, xb, xw] = [xy_xyz(p[0]), xy_xyz(p[1]), xy_xyz(p[2]), xy_xyz(p[3])];
166 let base = [[xr[0], xg[0], xb[0]], [xr[1], xg[1], xb[1]], [xr[2], xg[2], xb[2]]];
167 let s = mat3_vec(mat3_inv(base), xw);
168 std::array::from_fn(|r| std::array::from_fn(|c| base[r][c] * s[c]))
169}
170
171fn gamut_conversion_matrix(src: [[f64; 2]; 4], dst: [[f64; 2]; 4], white_adapt: bool) -> [[f32; 3]; 3] {
172 const BRADFORD: [[f64; 3]; 3] = [
173 [0.8951, 0.2664, -0.1614],
174 [-0.7502, 1.7135, 0.0367],
175 [0.0389, -0.0685, 1.0296],
176 ];
177 let m_src = primaries_to_xyz(src);
178 let m_dst_inv = mat3_inv(primaries_to_xyz(dst));
179 let m = if white_adapt && ((src[3][0] - dst[3][0]).abs() > 1e-6 || (src[3][1] - dst[3][1]).abs() > 1e-6) {
180 let ws = [src[3][0] / src[3][1].max(1e-6), 1.0, (1.0 - src[3][0] - src[3][1]) / src[3][1].max(1e-6)];
181 let wd = [dst[3][0] / dst[3][1].max(1e-6), 1.0, (1.0 - dst[3][0] - dst[3][1]) / dst[3][1].max(1e-6)];
182 let cs = mat3_vec(BRADFORD, ws);
183 let cd = mat3_vec(BRADFORD, wd);
184 let diag = [
185 [cd[0] / cs[0].max(1e-6), 0.0, 0.0],
186 [0.0, cd[1] / cs[1].max(1e-6), 0.0],
187 [0.0, 0.0, cd[2] / cs[2].max(1e-6)],
188 ];
189 let adapt = mat3_mul(mat3_inv(BRADFORD), mat3_mul(diag, BRADFORD));
190 mat3_mul(m_dst_inv, mat3_mul(adapt, m_src))
191 } else {
192 mat3_mul(m_dst_inv, m_src)
193 };
194 std::array::from_fn(|r| std::array::from_fn(|c| m[r][c] as f32))
195}
196
197impl Engine {
198 /// Resolves `EffectMask` on `node`, walking tool-level `SourceOp` instances when `EffectMask`
199 /// is not explicitly present (connected or cleared) in `node`'s own `Inputs` table.
200 pub(super) fn resolve_effect_mask_id(comp: &Comp, node: &Node) -> Option<NodeId> {
201 if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
202 return Some(id);
203 }
204 let has_explicit_mask_entry = |n: &Node| -> bool {
205 n.raw
206 .get_table("Inputs")
207 .and_then(|t| t.get("EffectMask"))
208 .is_some()
209 };
210 if has_explicit_mask_entry(node) {
211 return None;
212 }
213 let mut visited = HashSet::new();
214 visited.insert(node.id);
215 let mut cur = node;
216 for _ in 0..8 {
217 let master_name = cur.raw.get_str("SourceOp")?;
218 let mid = comp.find_node(master_name)?;
219 if !visited.insert(mid) {
220 break;
221 }
222 let master = comp.node(mid);
223 if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
224 return Some(mask_id);
225 }
226 if has_explicit_mask_entry(master) {
227 return None;
228 }
229 cur = master;
230 }
231 None
232 }
233
234 pub(super) fn eval_bc(
235 &mut self,
236 comp: &Comp,
237 node: &Node,
238 time: f64,
239 frame_i: i64,
240 enc: &mut wgpu::CommandEncoder,
241 visiting: &mut HashSet<(NodeId, i64)>,
242 stats: &mut EvalStats,
243 ) -> CachedTexture {
244 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
245 return self.dummy.clone();
246 };
247 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
248 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
249 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
250 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
251 if blend <= 1e-6 && !(mbm && has_mask) {
252 return src;
253 }
254 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
255 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
256 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
257
258 let mut u = UniformParams::default();
259 u.p[0] = [
260 comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32,
261 comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32,
262 comp.eval_number(node, "Gamma", time, 1.0, &self.expr) as f32,
263 comp.eval_number(node, "Contrast", time, 0.0, &self.expr) as f32,
264 ];
265 u.p[1] = [
266 comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32,
267 comp.eval_number(node, "Saturation", time, 1.0, &self.expr) as f32,
268 comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32,
269 blend,
270 ];
271 u.p[2] = [
272 if mask.is_some() { 1.0 } else { 0.0 },
273 if mask_inv { 1.0 } else { 0.0 },
274 comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32,
275 comp.eval_number(node, "High", time, 1.0, &self.expr) as f32,
276 ];
277 u.p[3] = [
278 comp.eval_number(node, "Red", time, 1.0, &self.expr) as f32,
279 comp.eval_number(node, "Green", time, 1.0, &self.expr) as f32,
280 comp.eval_number(node, "Blue", time, 1.0, &self.expr) as f32,
281 comp.eval_number(node, "Alpha", time, 0.0, &self.expr) as f32,
282 ];
283 u.p[4] = [
284 comp.eval_number(node, "ClipBlack", time, 0.0, &self.expr) as f32,
285 comp.eval_number(node, "ClipWhite", time, 0.0, &self.expr) as f32,
286 if mbm { 1.0 } else { 0.0 },
287 0.0,
288 ];
289
290 u.p[6][0] = comp.eval_number(node, "Direction", time, 0.0, &self.expr).round() as f32;
291 u.p[7] = self.process_skip(comp, node, time);
292 let comp_dims = self.scaled_dims(comp.width, comp.height);
293 let lift = u.p[0][1];
294 let gamma = u.p[0][2].max(1e-4);
295 let contrast = u.p[0][3];
296 let brightness = u.p[1][0];
297 let prediv = u.p[1][2];
298 let low = u.p[2][2];
299 let high = u.p[2][3];
300 let clip_black = u.p[4][0];
301 let clip_white = u.p[4][1];
302
303 let mut v0 = lift;
304 if (gamma - 1.0).abs() > 1e-5 && v0 > 0.0 {
305 v0 = v0.powf(1.0 / gamma);
306 }
307 v0 = (v0 - 0.5) * (1.0 + contrast) + 0.5 + brightness;
308 if low.abs() > 1e-5 || (high - 1.0).abs() > 1e-5 {
309 v0 = (v0 - low) / (high - low).max(1e-5);
310 }
311 if clip_black > 0.5 {
312 v0 = v0.max(0.0);
313 }
314 if clip_white > 0.5 {
315 v0 = v0.min(1.0);
316 }
317
318 let expand_dod = !has_mask
319 && prediv < 0.5
320 && v0.abs() > 1e-4
321 && (src.size[0] < comp_dims[0] || src.size[1] < comp_dims[1]);
322 let (work_src, out_origin, out_size) = if expand_dod {
323 let ox = src.origin[0].min(-((comp_dims[0] as i32 - src.canvas_size[0] as i32) / 2));
324 let oy = src.origin[1].min(-((comp_dims[1] as i32 - src.canvas_size[1] as i32) / 2));
325 let x1 = (src.origin[0] + src.size[0] as i32).max(ox + comp_dims[0] as i32);
326 let y1 = (src.origin[1] + src.size[1] as i32).max(oy + comp_dims[1] as i32);
327 let exp_size = [(x1 - ox).max(1) as u32, (y1 - oy).max(1) as u32];
328 (src.clone(), [ox, oy], exp_size)
329 } else {
330 (src.clone(), src.origin, src.size)
331 };
332 if expand_dod {
333 let x0 = (src.origin[0] - out_origin[0]) as f32;
334 let y0 = (src.origin[1] - out_origin[1]) as f32;
335 u.p[4][3] = 1.0;
336 u.p[5] = [x0, y0, x0 + src.size[0] as f32, y0 + src.size[1] as f32];
337 }
338
339 let key = self.make_key(node, "BC", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..8]));
340 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
341 stats.cache_hits += 1;
342 return hit;
343 }
344 stats.cache_misses += 1;
345 stats.nodes_evaluated += 1;
346 let eval_src = if expand_dod {
347 let padded = self.alloc_tex_dod(out_size, out_origin, src.canvas_size, src.depth, 0);
348 let mut u_pad = UniformParams::default();
349 u_pad.p[0] = [-100.0, -100.0, 100.0, 100.0];
350 u_pad.p[1] = [out_origin[0] as f32, out_origin[1] as f32, src.canvas_size[0].max(1) as f32, src.canvas_size[1].max(1) as f32];
351 u_pad.p[2] = [src.origin[0] as f32, src.origin[1] as f32, src.size[0] as f32, src.size[1] as f32];
352 self.dispatch_op(enc, ShaderOp::SetDomain, &work_src.view, &self.dummy.view, &self.dummy.view, &padded, &u_pad);
353 padded
354 } else {
355 work_src
356 };
357 let mut dst = self.alloc_tex_dod(out_size, out_origin, src.canvas_size, src.depth, key);
358 dst.tex_scale = src.tex_scale;
359 dst.edge_mode = src.edge_mode;
360 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
361 self.dispatch_op(enc, ShaderOp::Bc, &eval_src.view, &self.dummy.view, mv, &dst, &u);
362 if src.aux.is_some() && dst.size == src.size {
363 dst.set_aux(src.aux.clone());
364 }
365 self.cache.insert(key, dst.clone(), node.id, frame_i);
366 dst
367 }
368
369 pub(super) fn eval_cc(
370 &mut self,
371 comp: &Comp,
372 node: &Node,
373 time: f64,
374 frame_i: i64,
375 enc: &mut wgpu::CommandEncoder,
376 visiting: &mut HashSet<(NodeId, i64)>,
377 stats: &mut EvalStats,
378 ) -> CachedTexture {
379 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
380 return self.dummy.clone();
381 };
382 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
383 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
384 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
385 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
386 if blend <= 1e-6 && !(mbm && has_mask) {
387 return src;
388 }
389 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
390 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
391 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
392
393 let levels: [[CcLevels; 4]; 4] = ["Master", "Shadows", "MidTones", "Highlights"]
394 .map(|range| CcLevels::read(comp, node, time, range, &self.expr));
395 let wheel = |i: usize| -> [f32; 4] {
396 let n = |name: &str, default: f64| comp.eval_number(node, &format!("{name}{i}"), time, default, &self.expr) as f32;
397 [n("WheelHue", 0.0), n("WheelSaturation", 1.0), n("WheelTintAngle", 0.0), n("WheelTintLength", 0.0)]
398 };
399 let wheels = [wheel(1), wheel(2), wheel(3), wheel(4)];
400 // Fusion ColorCorrector TintMode: 0 = RGB cube tilt matrix, 1 = additive+luma tint, 2 (default when omitted) = luma-weighted tint.
401 let tint_mode = comp.eval_number(node, "TintMode", time, 2.0, &self.expr) as f32;
402 let wheel_is_active = |w: [f32; 4]| w[0].abs() > 1e-5 || (w[1] - 1.0).abs() > 1e-5 || w[3].abs() > 1e-5;
403 let has_smh = (1..4).any(|r| wheel_is_active(wheels[r]) || levels[r].iter().any(|l| !l.is_neutral()));
404
405 let mut u = UniformParams::default();
406 u.p[0] = wheels[0];
407 u.p[2] = [0.0, comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }];
408 u.p[3] = [mask_inv as u8 as f32, tint_mode, has_smh as u8 as f32, mbm as u8 as f32];
409 u.p[4] = wheels[1];
410 u.p[6] = wheels[2];
411 u.p[7] = wheels[3];
412 u.p[10] = self.process_skip(comp, node, time);
413 u.p[11][0] = 1.0;
414
415 // Per range (master alone, then master combined with each of Shadows/MidTones/Highlights) and channel: 3 texels of effective curve terms.
416 let mut table = [0u16; 12 * 3 * 4];
417 let mut table_f32 = Vec::with_capacity(12 * 3 * 4);
418 for range in 0..4 {
419 for ch in 0..3 {
420 let mut chain = vec![&levels[0][0], &levels[0][1 + ch]];
421 if range > 0 {
422 chain.extend([&levels[range][0], &levels[range][1 + ch]]);
423 }
424 let texels = CcLevels::combine(&chain);
425 for (k, texel) in texels.iter().enumerate() {
426 for (c, v) in texel.iter().enumerate() {
427 table[((ch * 12) + range * 3 + k) * 4 + c] = crate::media::f32_to_f16_bits(*v);
428 table_f32.push(*v);
429 }
430 }
431 }
432 }
433
434 let key = self.make_key(
435 node,
436 "CC",
437 src.size,
438 &[src.content_hash, mask_hash],
439 &[bytemuck::cast_slice::<[f32; 4], f32>(&u.p[..12]), &table_f32].concat(),
440 );
441 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
442 stats.cache_hits += 1;
443 return hit;
444 }
445 stats.cache_misses += 1;
446 stats.nodes_evaluated += 1;
447 let curve_tex = self.pipelines.borrow_mut().get_or_upload_lut_tex(
448 &self.device,
449 &self.queue,
450 [12, 3],
451 BitDepth::Float16,
452 wgpu::TextureFormat::Rgba16Float,
453 12 * 8,
454 bytemuck::cast_slice(&table),
455 );
456 let mut dst = self.alloc_tex_like(&src, src.depth, key);
457 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
458 self.dispatch_op(enc, ShaderOp::Cc, &src.view, &curve_tex.view, mv, &dst, &u);
459 if src.aux.is_some() {
460 dst.set_aux(src.aux.clone());
461 }
462 self.cache.insert(key, dst.clone(), node.id, frame_i);
463 dst
464 }
465
466 pub(super) fn eval_colorize(
467 &mut self,
468 comp: &Comp,
469 node: &Node,
470 time: f64,
471 frame_i: i64,
472 enc: &mut wgpu::CommandEncoder,
473 visiting: &mut HashSet<(NodeId, i64)>,
474 stats: &mut EvalStats,
475 ) -> CachedTexture {
476 let Some(src_id) = node.connected_node("Image").or_else(|| node.connected_node("Input")).and_then(|s| comp.find_node(s)) else {
477 return self.dummy.clone();
478 };
479 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
480 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
481 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
482 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
483 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
484 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
485
486 let mut u = UniformParams::default();
487 // Colorize.fuse defaults: Color 1 = (0,0,0,0), Color 2 = (1,1,1,1)
488 u.p[0] = [
489 comp.eval_number(node, "R1", time, 0.0, &self.expr) as f32,
490 comp.eval_number(node, "G1", time, 0.0, &self.expr) as f32,
491 comp.eval_number(node, "B1", time, 0.0, &self.expr) as f32,
492 comp.eval_number(node, "A1", time, 0.0, &self.expr) as f32,
493 ];
494 u.p[1] = [
495 comp.eval_number(node, "R2", time, 1.0, &self.expr) as f32,
496 comp.eval_number(node, "G2", time, 1.0, &self.expr) as f32,
497 comp.eval_number(node, "B2", time, 1.0, &self.expr) as f32,
498 comp.eval_number(node, "A2", time, 1.0, &self.expr) as f32,
499 ];
500 u.p[2] = [
501 comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32,
502 if mask.is_some() { 1.0 } else { 0.0 },
503 if mask_inv { 1.0 } else { 0.0 },
504 if mbm { 1.0 } else { 0.0 },
505 ];
506
507 let key = self.make_key(node, "Fuse.Colorize", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
508 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
509 stats.cache_hits += 1;
510 return hit;
511 }
512 stats.cache_misses += 1;
513 stats.nodes_evaluated += 1;
514 let dst = self.alloc_tex_like(&src, src.depth, key);
515 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
516 self.dispatch_op(enc, ShaderOp::Colorize, &src.view, &self.dummy.view, mv, &dst, &u);
517 self.cache.insert(key, dst.clone(), node.id, frame_i);
518 dst
519 }
520
521 pub(super) fn eval_custom(
522 &mut self,
523 comp: &Comp,
524 node: &Node,
525 time: f64,
526 frame_i: i64,
527 comp_dims: [u32; 2],
528 enc: &mut wgpu::CommandEncoder,
529 visiting: &mut HashSet<(NodeId, i64)>,
530 stats: &mut EvalStats,
531 ) -> CachedTexture {
532 let img1_raw = node
533 .connected_node("Image1")
534 .and_then(|s| comp.find_node(s))
535 .map(|id| self.eval_node(comp, id, time, enc, visiting, stats));
536 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
537 let mbm = self.multiplies_by_mask(comp, node, time);
538 if blend <= 1e-6 && !mbm {
539 return img1_raw.unwrap_or_else(|| self.dummy.clone());
540 }
541 let img1 = img1_raw.clone().map(|t| self.crop_to_canvas(enc, t));
542 let img2 = node
543 .connected_node("Image2")
544 .and_then(|s| comp.find_node(s))
545 .map(|id| {
546 let t = self.eval_node(comp, id, time, enc, visiting, stats);
547 self.crop_to_canvas(enc, t)
548 });
549 let img3 = node
550 .connected_node("Image3")
551 .and_then(|s| comp.find_node(s))
552 .map(|id| {
553 let t = self.eval_node(comp, id, time, enc, visiting, stats);
554 self.crop_to_canvas(enc, t)
555 });
556
557 let size = img1.as_ref().map_or(comp_dims, |t| t.size);
558 let depth = self.node_depth(comp, node, time, img1.as_ref().map(|t| t.depth));
559 let eff_depth = self.effective_depth(depth);
560 let (mask, mask_inv) =
561 self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
562
563 let setup_names = ["Setup1", "Setup2", "Setup3", "Setup4"];
564 let inter_names = [
565 ("Intermediate1", "Inter1"),
566 ("Intermediate2", "Inter2"),
567 ("Intermediate3", "Inter3"),
568 ("Intermediate4", "Inter4"),
569 ("Intermediate5", "Inter5"),
570 ("Intermediate6", "Inter6"),
571 ("Intermediate7", "Inter7"),
572 ("Intermediate8", "Inter8"),
573 ];
574 let program = crate::custom_shader::CustomProgram {
575 setups: std::array::from_fn(|i| comp.eval_text(node, setup_names[i], time, "0", &self.expr)),
576 intermediates: std::array::from_fn(|i| {
577 let (primary, alias) = inter_names[i];
578 if node.inputs.contains_key(primary) {
579 comp.eval_text(node, primary, time, "0", &self.expr)
580 } else if node.inputs.contains_key(alias) {
581 comp.eval_text(node, alias, time, "0", &self.expr)
582 } else {
583 "0".to_owned()
584 }
585 }),
586 red: comp.eval_text(node, "RedExpression", time, "r1", &self.expr),
587 green: comp.eval_text(node, "GreenExpression", time, "g1", &self.expr),
588 blue: comp.eval_text(node, "BlueExpression", time, "b1", &self.expr),
589 alpha: comp.eval_text(node, "AlphaExpression", time, "a1", &self.expr),
590 }
591 .normalized();
592 // Default expressions leave every pixel alone, so the upstream image and its DoD pass straight through.
593 if let Some(raw) = img1_raw.as_ref().filter(|t| t.has_dod() && t.depth == depth && !mbm) {
594 if [&program.red, &program.green, &program.blue, &program.alpha] == ["r1", "g1", "b1", "a1"] {
595 return raw.clone();
596 }
597 }
598
599 let pscale = self.proxy_scale.max(1);
600 let w1 = (size[0] * pscale) as f32;
601 let h1 = (size[1] * pscale) as f32;
602 let (w2, h2) = img2
603 .as_ref()
604 .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32));
605 let (w3, h3) = img3
606 .as_ref()
607 .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32));
608
609 let n = |k: &str| comp.eval_number(node, k, time, 0.0, &self.expr) as f32;
610 let pt = |k: &str| {
611 let p = comp.eval_point(node, k, time, [0.5, 0.5], &self.expr);
612 [p[0] as f32, p[1] as f32]
613 };
614 let p1 = pt("PointIn1");
615 let p2 = pt("PointIn2");
616 let p3 = pt("PointIn3");
617 let p4 = pt("PointIn4");
618
619 let lut_names = ["LUTIn1", "LUTIn2", "LUTIn3", "LUTIn4"];
620 let lut_splines: [Option<&model::BezierSpline>; 4] = std::array::from_fn(|idx| {
621 node.connected_node(lut_names[idx])
622 .and_then(|s| comp.splines.get(s))
623 .filter(|sp| !sp.keyframes.is_empty())
624 });
625 let mut luts = [[0.0f32; 4]; 256];
626 for (i, slot) in luts.iter_mut().enumerate() {
627 let x = i as f64 / 255.0;
628 for ch in 0..4 {
629 slot[ch] = lut_splines[ch].map_or(x as f32, |sp| sp.eval(x) as f32);
630 }
631 }
632 let mut lh = DefaultHasher::new();
633 bytemuck::cast_slice::<[f32; 4], u8>(&luts).hash(&mut lh);
634 let lut_hash = lh.finish();
635
636 let params = crate::custom_shader::CustomParams {
637 n0: [n("NumberIn1"), n("NumberIn2"), n("NumberIn3"), n("NumberIn4")],
638 n1: [n("NumberIn5"), n("NumberIn6"), n("NumberIn7"), n("NumberIn8")],
639 p0: [p1[0], p1[1], p2[0], p2[1]],
640 p1: [p3[0], p3[1], p4[0], p4[1]],
641 img_dims1: [w1, h1, w2, h2],
642 // Under MultiplyByMask the program renders unmasked at full blend and the combine pass below applies both.
643 img_dims2: [w3, h3, time as f32, if mbm { 1.0 } else { blend }],
644 mask_proc: [
645 if mask.is_some() && !mbm { 1.0 } else { 0.0 },
646 if mask_inv { 1.0 } else { 0.0 },
647 comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32,
648 comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32,
649 ],
650 proc_ba: [
651 comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32,
652 comp.eval_number(node, "ProcessAlpha", time, 1.0, &self.expr) as f32,
653 if eff_depth.is_float() { 1.0 } else { 0.0 },
654 0.0,
655 ],
656 luts,
657 };
658
659 let prog_hash = program.program_hash();
660 let scalar_slice: [[f32; 4]; 8] = [
661 params.n0,
662 params.n1,
663 params.p0,
664 params.p1,
665 params.img_dims1,
666 params.img_dims2,
667 params.mask_proc,
668 params.proc_ba,
669 ];
670 let key = self.make_key(
671 node,
672 "CustomTool",
673 size,
674 &[
675 img1.as_ref().map_or(0, |t| t.content_hash),
676 img2.as_ref().map_or(0, |t| t.content_hash),
677 img3.as_ref().map_or(0, |t| t.content_hash),
678 mask.as_ref().map_or(0, |m| m.content_hash),
679 prog_hash,
680 lut_hash,
681 eff_depth as u64,
682 mbm as u64,
683 blend.to_bits() as u64,
684 ],
685 bytemuck::cast_slice(&scalar_slice),
686 );
687 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
688 stats.cache_hits += 1;
689 return hit;
690 }
691 stats.cache_misses += 1;
692 stats.nodes_evaluated += 1;
693
694 let mut dst = self.alloc_tex(size, eff_depth, key);
695 if let Some(t) = &img1 {
696 dst.tex_scale *= t.tex_scale;
697 }
698 let rendered = if mbm { self.alloc_tex(size, eff_depth, 0) } else { dst.clone() };
699 let v1 = img1.as_ref().map_or(&self.dummy.view, |t| &t.view);
700 let v2 = img2.as_ref().map_or(&self.dummy.view, |t| &t.view);
701 let v3 = img3.as_ref().map_or(&self.dummy.view, |t| &t.view);
702 let vm = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
703
704 let ok = self.custom_shaders.dispatch(
705 &self.device,
706 &self.queue,
707 enc,
708 &program,
709 dst.format,
710 v1,
711 v2,
712 v3,
713 vm,
714 &rendered.view,
715 dst.size,
716 &params,
717 );
718 if ok && mbm {
719 let mut um = UniformParams::default();
720 um.p[0] = [1.0, blend, 1.0, mask_inv as u8 as f32];
721 um.p[1] = [4.0, 0.0, 0.0, 2.0]; // mode 4 = MixOnly, scaled from black
722 um.p[3] = self.process_skip(comp, node, time);
723 self.dispatch_op(enc, ShaderOp::GlowAdd, v1, &rendered.view, vm, &dst, &um);
724 }
725 if ok {
726 self.cache.insert(key, dst.clone(), node.id, frame_i);
727 dst
728 } else {
729 img1.unwrap_or_else(|| self.dummy.clone())
730 }
731 }
732
733 pub(super) fn eval_invert(
734 &mut self,
735 comp: &Comp,
736 node: &Node,
737 time: f64,
738 frame_i: i64,
739 enc: &mut wgpu::CommandEncoder,
740 visiting: &mut HashSet<(NodeId, i64)>,
741 stats: &mut EvalStats,
742 ) -> CachedTexture {
743 let Some(src_id) = node
744 .connected_node("Input")
745 .or_else(|| node.connected_node("Image1"))
746 .and_then(|s| comp.find_node(s))
747 else {
748 return self.dummy.clone();
749 };
750 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
751 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
752 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
753 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
754 if blend <= 1e-6 && !(mbm && has_mask) {
755 return src;
756 }
757 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
758 let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32;
759 let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32;
760 let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32;
761 let proc_a = comp.eval_number(node, "ProcessAlpha", time, 0.0, &self.expr) as f32;
762 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
763 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
764
765 let mut u = UniformParams::default();
766 u.p[0] = [proc_r, proc_g, proc_b, proc_a];
767 u.p[1] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }];
768 let key = self.make_key(node, "Invert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..2]));
769 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
770 stats.cache_hits += 1;
771 return hit;
772 }
773 stats.cache_misses += 1;
774 stats.nodes_evaluated += 1;
775 let mut dst = self.alloc_tex_like(&src, src.depth, key);
776 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
777 self.dispatch_op(enc, ShaderOp::Invert, &src.view, &self.dummy.view, mv, &dst, &u);
778 if src.aux.is_some() {
779 dst.set_aux(src.aux.clone());
780 }
781 self.cache.insert(key, dst.clone(), node.id, frame_i);
782 dst
783 }
784
785 pub(super) fn eval_color_gain(
786 &mut self,
787 comp: &Comp,
788 node: &Node,
789 time: f64,
790 frame_i: i64,
791 enc: &mut wgpu::CommandEncoder,
792 visiting: &mut HashSet<(NodeId, i64)>,
793 stats: &mut EvalStats,
794 ) -> CachedTexture {
795 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
796 return self.dummy.clone();
797 };
798 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
799 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
800 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
801 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
802 if blend <= 1e-6 && !(mbm && has_mask) {
803 return src;
804 }
805 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
806 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
807 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
808
809 let lock_rgb = comp.eval_number(node, "LockRGB", time, 0.0, &self.expr) > 0.5;
810 let high_hue = comp.eval_number(node, "HighHue", time, 0.0, &self.expr) as f32;
811 let mid_hue = comp.eval_number(node, "MidHue", time, 0.0, &self.expr) as f32;
812 let dark_hue = comp.eval_number(node, "DarkHue", time, 0.0, &self.expr) as f32;
813 let gain_r = comp.eval_number(node, "GainRed", time, 1.0, &self.expr) as f32;
814 let gain_g = if lock_rgb { gain_r } else { comp.eval_number(node, "GainGreen", time, 1.0, &self.expr) as f32 };
815 let gain_b = if lock_rgb { gain_r } else { comp.eval_number(node, "GainBlue", time, 1.0, &self.expr) as f32 };
816 let lift_r = comp.eval_number(node, "LiftRed", time, 0.0, &self.expr) as f32;
817 let lift_g = if lock_rgb { lift_r } else { comp.eval_number(node, "LiftGreen", time, 0.0, &self.expr) as f32 };
818 let lift_b = if lock_rgb { lift_r } else { comp.eval_number(node, "LiftBlue", time, 0.0, &self.expr) as f32 };
819 let gamma_r = comp.eval_number(node, "GammaRed", time, 1.0, &self.expr) as f32;
820 let gamma_g = if lock_rgb { gamma_r } else { comp.eval_number(node, "GammaGreen", time, 1.0, &self.expr) as f32 };
821 let gamma_b = if lock_rgb { gamma_r } else { comp.eval_number(node, "GammaBlue", time, 1.0, &self.expr) as f32 };
822 let sat_r = comp.eval_number(node, "SaturationRed", time, 1.0, &self.expr) as f32;
823 let sat_g = if lock_rgb { sat_r } else { comp.eval_number(node, "SaturationGreen", time, 1.0, &self.expr) as f32 };
824 let sat_b = if lock_rgb { sat_r } else { comp.eval_number(node, "SaturationBlue", time, 1.0, &self.expr) as f32 };
825 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
826
827 let mut u = UniformParams::default();
828 u.p[0] = [gain_r, gain_g, gain_b, prediv];
829 u.p[1] = [lift_r, lift_g, lift_b, blend];
830 u.p[2] = [gamma_r, gamma_g, gamma_b, sat_r];
831 u.p[3] = [dark_hue, mid_hue, high_hue, if mask.is_some() { 1.0 } else { 0.0 }];
832 u.p[4] = [if mask_inv { 1.0 } else { 0.0 }, sat_g, sat_b, if mbm { 1.0 } else { 0.0 }];
833 for (slot, range) in [(5, "High"), (6, "Mid"), (7, "Dark")] {
834 let n = |axis: &str| comp.eval_number(node, &format!("{range}{axis}"), time, 0.0, &self.expr) as f32;
835 u.p[slot] = [n("RedCyan"), n("GreenMagenta"), n("BlueYellow"), n("Brightness")];
836 }
837 u.p[8] = self.process_skip(comp, node, time);
838 u.p[9] = [
839 comp.eval_number(node, "GainAlpha", time, 1.0, &self.expr) as f32,
840 comp.eval_number(node, "LiftAlpha", time, 0.0, &self.expr) as f32,
841 comp.eval_number(node, "GammaAlpha", time, 1.0, &self.expr) as f32,
842 0.0,
843 ];
844
845 let key = self.make_key(node, "ColorGain", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10]));
846 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
847 stats.cache_hits += 1;
848 return hit;
849 }
850 stats.cache_misses += 1;
851 stats.nodes_evaluated += 1;
852 let mut dst = self.alloc_tex_like(&src, src.depth, key);
853 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
854 self.dispatch_op(enc, ShaderOp::ColorGain, &src.view, &self.dummy.view, mv, &dst, &u);
855 if src.aux.is_some() {
856 dst.set_aux(src.aux.clone());
857 }
858 self.cache.insert(key, dst.clone(), node.id, frame_i);
859 dst
860 }
861
862 pub(super) fn build_color_curves_lut_f16(comp: &Comp, node: &Node) -> ([u16; 256 * 4], u64, bool) {
863 let sp_r = node.connected_node("Red").and_then(|s| comp.splines.get(s));
864 let sp_g = node.connected_node("Green").and_then(|s| comp.splines.get(s));
865 let sp_b = node.connected_node("Blue").and_then(|s| comp.splines.get(s));
866 let sp_a = node.connected_node("Alpha").and_then(|s| comp.splines.get(s));
867 let apply_a = sp_a.is_some_and(|sp| !sp.keyframes.is_empty());
868
869 let mut lut_f16 = [0u16; 256 * 4];
870 for i in 0..256 {
871 let x = i as f64 / 255.0;
872 let r = sp_r.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
873 let g = sp_g.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
874 let b = sp_b.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
875 let a = sp_a.filter(|s| !s.keyframes.is_empty()).map_or(x, |s| s.eval(x));
876 lut_f16[i * 4] = crate::media::f32_to_f16_bits(r as f32);
877 lut_f16[i * 4 + 1] = crate::media::f32_to_f16_bits(g as f32);
878 lut_f16[i * 4 + 2] = crate::media::f32_to_f16_bits(b as f32);
879 lut_f16[i * 4 + 3] = crate::media::f32_to_f16_bits(a as f32);
880 }
881 let mut lh = DefaultHasher::new();
882 lut_f16.hash(&mut lh);
883 (lut_f16, lh.finish(), apply_a)
884 }
885
886 pub(super) fn upload_lut_f16(&self, lut_f16: &[u16; 256 * 4]) -> CachedTexture {
887 self.pipelines.borrow_mut().get_or_upload_lut_tex(
888 &self.device,
889 &self.queue,
890 [256, 1],
891 BitDepth::Float16,
892 wgpu::TextureFormat::Rgba16Float,
893 256 * 8,
894 bytemuck::cast_slice(lut_f16),
895 )
896 }
897
898 /// Returns `(y0, y1, slope0, slope1)` for RGBA `ColorCurves` linear tangent extrapolation
899 /// outside `[0, 1]`, matching Fusion 21.1's `ColorCurves` HDR behavior.
900 fn color_curves_extrap_params(comp: &Comp, node: &Node) -> ([f32; 4], [f32; 4], [f32; 4], [f32; 4]) {
901 let mut y0 = [0.0_f32; 4];
902 let mut y1 = [1.0_f32; 4];
903 let mut s0 = [1.0_f32; 4];
904 let mut s1 = [1.0_f32; 4];
905 for (i, port) in ["Red", "Green", "Blue", "Alpha"].iter().enumerate() {
906 if let Some(sp) = node
907 .connected_node(port)
908 .and_then(|s| comp.splines.get(s))
909 .filter(|s| !s.keyframes.is_empty())
910 {
911 let v0 = sp.eval(0.0);
912 let v1 = sp.eval(1.0);
913 y0[i] = if v0.is_finite() { v0 as f32 } else { 0.0 };
914 y1[i] = if v1.is_finite() { v1 as f32 } else { 1.0 };
915
916 let kfs = &sp.keyframes;
917 let first_t = kfs[0].time;
918 let last_t = kfs[kfs.len() - 1].time;
919
920 s0[i] = if kfs.len() < 2 || first_t > 0.0 {
921 0.0
922 } else {
923 let seg_idx = kfs.partition_point(|k| k.time <= 0.0).saturating_sub(1);
924 let k0 = &kfs[seg_idx];
925 let k1 = &kfs[(seg_idx + 1).min(kfs.len() - 1)];
926 let dt = (k1.time - 0.0).abs();
927 if dt < 1e-12 || k0.flags.step_out || k1.flags.step_in {
928 0.0
929 } else {
930 let eps = 1e-4_f64.min(0.25 * dt).max(1e-7);
931 let slope = (sp.eval(eps) - v0) / eps;
932 if slope.is_finite() { (slope as f32).clamp(-1e3, 1e3) } else { 0.0 }
933 }
934 };
935
936 s1[i] = if kfs.len() < 2 || last_t < 1.0 {
937 0.0
938 } else {
939 let seg_idx = kfs.partition_point(|k| k.time < 1.0).saturating_sub(1);
940 let k0 = &kfs[seg_idx];
941 let k1 = &kfs[(seg_idx + 1).min(kfs.len() - 1)];
942 let dt = (1.0 - k0.time).abs();
943 if dt < 1e-12 || k0.flags.step_out || k1.flags.step_in {
944 0.0
945 } else {
946 let eps = 1e-4_f64.min(0.25 * dt).max(1e-7);
947 let slope = (v1 - sp.eval(1.0 - eps)) / eps;
948 if slope.is_finite() { (slope as f32).clamp(-1e3, 1e3) } else { 0.0 }
949 }
950 };
951 }
952 }
953 (y0, y1, s0, s1)
954 }
955
956 pub(super) fn eval_color_curves(
957 &mut self,
958 comp: &Comp,
959 node: &Node,
960 time: f64,
961 frame_i: i64,
962 enc: &mut wgpu::CommandEncoder,
963 visiting: &mut HashSet<(NodeId, i64)>,
964 stats: &mut EvalStats,
965 ) -> CachedTexture {
966 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
967 return self.dummy.clone();
968 };
969 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
970 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
971 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
972 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
973 if blend <= 1e-6 && !(mbm && has_mask) {
974 return src;
975 }
976 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
977 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
978 let ignore_trans = comp.eval_number(node, "IgnoreTransparent", time, 0.0, &self.expr) as f32;
979 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
980 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
981
982 let (lut_f16, lut_hash, apply_a) = Self::build_color_curves_lut_f16(comp, node);
983 let (y0, y1, s0, s1) = Self::color_curves_extrap_params(comp, node);
984
985 let mut u = UniformParams::default();
986 u.p[0] = [prediv, ignore_trans, blend, if mask.is_some() { 1.0 } else { 0.0 }];
987 u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if apply_a { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, 0.0];
988 u.p[2] = y0;
989 u.p[3] = y1;
990 u.p[4] = s0;
991 u.p[5] = s1;
992
993 let key = self.make_key(
994 node,
995 "ColorCurves",
996 src.size,
997 &[src.content_hash, mask_hash, lut_hash],
998 bytemuck::cast_slice(&u.p[..6]),
999 );
1000 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1001 stats.cache_hits += 1;
1002 return hit;
1003 }
1004 stats.cache_misses += 1;
1005 stats.nodes_evaluated += 1;
1006
1007 let lut_tex = self.upload_lut_f16(&lut_f16);
1008 let mut dst = self.alloc_tex_like(&src, src.depth, key);
1009 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1010 self.dispatch_op(enc, ShaderOp::ColorCurves, &src.view, &lut_tex.view, mv, &dst, &u);
1011 if src.aux.is_some() {
1012 dst.set_aux(src.aux.clone());
1013 }
1014 self.cache.insert(key, dst.clone(), node.id, frame_i);
1015 dst
1016 }
1017
1018 pub(super) fn eval_gamut_convert(
1019 &mut self,
1020 comp: &Comp,
1021 node: &Node,
1022 time: f64,
1023 frame_i: i64,
1024 enc: &mut wgpu::CommandEncoder,
1025 visiting: &mut HashSet<(NodeId, i64)>,
1026 stats: &mut EvalStats,
1027 ) -> CachedTexture {
1028 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1029 return self.dummy.clone();
1030 };
1031 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1032 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1033 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1034 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
1035 if blend <= 1e-6 && !(mbm && has_mask) {
1036 return src;
1037 }
1038 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
1039 let src_name = node.static_str("SourceSpace").unwrap_or("NoChange");
1040 let dst_name = node.static_str("OutputSpace").unwrap_or("NoChange");
1041 let remove_gamma = comp.eval_number(node, "RemoveGamma", time, 1.0, &self.expr) > 0.5;
1042 let add_gamma = comp.eval_number(node, "AddGamma", time, 1.0, &self.expr) > 0.5;
1043 let white_adapt = comp.eval_number(node, "WhiteAdaptation", time, 1.0, &self.expr) > 0.5;
1044
1045 let src_spec = gamut_space_spec(comp, node, time, &self.expr, src_name, true);
1046 let dst_spec = gamut_space_spec(comp, node, time, &self.expr, dst_name, false);
1047
1048 let src_xfer = src_spec.filter(|_| remove_gamma).and_then(|s| gamut_transfer_params(s.gamma, s.limit, s.slope));
1049 let dst_xfer = dst_spec.filter(|_| add_gamma).and_then(|s| gamut_transfer_params(s.gamma, s.limit, s.slope));
1050 let mat = match (src_spec, dst_spec) {
1051 (Some(s), Some(d)) if src_name != dst_name || src_name == "Custom" => {
1052 Some(gamut_conversion_matrix(s.primaries, d.primaries, white_adapt))
1053 }
1054 _ => None,
1055 };
1056 let skip = self.process_skip(comp, node, time);
1057 if src_xfer.is_none() && dst_xfer.is_none() && mat.is_none() && !(mbm && has_mask) {
1058 return src;
1059 }
1060 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
1061 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1062 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1063
1064 let mut u = UniformParams::default();
1065 u.p[0] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1066 u.p[1] = [
1067 if mbm { 1.0 } else { 0.0 },
1068 if src_xfer.is_some() { 1.0 } else { 0.0 },
1069 if dst_xfer.is_some() { 1.0 } else { 0.0 },
1070 if mat.is_some() { 1.0 } else { 0.0 },
1071 ];
1072 u.p[2] = src_xfer.unwrap_or([1.0, 0.0, 1.0, 0.0]);
1073 u.p[3] = dst_xfer.unwrap_or([1.0, 0.0, 1.0, 0.0]);
1074 let m = mat.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
1075 u.p[4] = [m[0][0], m[0][1], m[0][2], 0.0];
1076 u.p[5] = [m[1][0], m[1][1], m[1][2], 0.0];
1077 u.p[6] = [m[2][0], m[2][1], m[2][2], 0.0];
1078 u.p[7] = skip;
1079 let key = self.make_key(node, "GamutConvert", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..8]));
1080 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1081 stats.cache_hits += 1;
1082 return hit;
1083 }
1084 stats.cache_misses += 1;
1085 stats.nodes_evaluated += 1;
1086 let mut dst = self.alloc_tex_like(&src, src.depth, key);
1087 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1088 self.dispatch_op(enc, ShaderOp::GamutConvert, &src.view, &self.dummy.view, mv, &dst, &u);
1089 if src.aux.is_some() {
1090 dst.set_aux(src.aux.clone());
1091 }
1092 self.cache.insert(key, dst.clone(), node.id, frame_i);
1093 dst
1094 }
1095
1096 pub(super) fn eval_hue_curves(
1097 &mut self,
1098 comp: &Comp,
1099 node: &Node,
1100 time: f64,
1101 frame_i: i64,
1102 enc: &mut wgpu::CommandEncoder,
1103 visiting: &mut HashSet<(NodeId, i64)>,
1104 stats: &mut EvalStats,
1105 ) -> CachedTexture {
1106 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1107 return self.dummy.clone();
1108 };
1109 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1110 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1111 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1112 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
1113 if blend <= 1e-6 && !(mbm && has_mask) {
1114 return src;
1115 }
1116 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
1117 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
1118 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1119 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1120
1121 let curve_names = ["Hue", "Sat", "Lum", "Red", "Green", "Blue", "RedSuppress", "GreenSuppress", "BlueSuppress"];
1122 let curves: [Option<&model::BezierSpline>; 9] = std::array::from_fn(|idx| {
1123 node.connected_node(curve_names[idx]).and_then(|s| comp.splines.get(s))
1124 });
1125
1126 // Bake 256x3 RGBA8 LUT over Hue domain [0..6], encoded as val * 64 so neutral 1.0 is exact
1127 let mut lut = vec![0u8; 256 * 3 * 4];
1128 let enc_u8 = |v: f64| (v * 64.0).clamp(0.0, 255.0).round() as u8;
1129 for i in 0..256 {
1130 let hx = (i as f64 / 255.0) * 6.0;
1131 let eval_c = |ci: usize| curves[ci].map_or(1.0, |s| s.eval(hx));
1132 // Row 0: Hue, Sat, Lum
1133 let p0 = i * 4;
1134 lut[p0] = enc_u8(eval_c(0));
1135 lut[p0 + 1] = enc_u8(eval_c(1));
1136 lut[p0 + 2] = enc_u8(eval_c(2));
1137 lut[p0 + 3] = 255;
1138 // Row 1: Red, Green, Blue
1139 let p1 = (256 + i) * 4;
1140 lut[p1] = enc_u8(eval_c(3));
1141 lut[p1 + 1] = enc_u8(eval_c(4));
1142 lut[p1 + 2] = enc_u8(eval_c(5));
1143 lut[p1 + 3] = 255;
1144 // Row 2: RedSuppress, GreenSuppress, BlueSuppress
1145 let p2 = (512 + i) * 4;
1146 lut[p2] = enc_u8(eval_c(6));
1147 lut[p2 + 1] = enc_u8(eval_c(7));
1148 lut[p2 + 2] = enc_u8(eval_c(8));
1149 lut[p2 + 3] = 255;
1150 }
1151 let mut lh = DefaultHasher::new();
1152 lut.hash(&mut lh);
1153 let lut_hash = lh.finish();
1154
1155 let mut u = UniformParams::default();
1156 u.p[0] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1157 u.p[1] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1158 let key = self.make_key(node, "HueCurves", src.size, &[src.content_hash, mask_hash, lut_hash], bytemuck::cast_slice(&u.p[..2]));
1159 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1160 stats.cache_hits += 1;
1161 return hit;
1162 }
1163 stats.cache_misses += 1;
1164 stats.nodes_evaluated += 1;
1165
1166 let lut_tex = self.pipelines.borrow_mut().get_or_upload_lut_tex(
1167 &self.device,
1168 &self.queue,
1169 [256, 3],
1170 BitDepth::Int8,
1171 wgpu::TextureFormat::Rgba8Unorm,
1172 256 * 4,
1173 &lut,
1174 );
1175 let mut dst = self.alloc_tex_like(&src, src.depth, key);
1176 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1177 self.dispatch_op(enc, ShaderOp::HueCurves, &src.view, &lut_tex.view, mv, &dst, &u);
1178 if src.aux.is_some() {
1179 dst.set_aux(src.aux.clone());
1180 }
1181 self.cache.insert(key, dst.clone(), node.id, frame_i);
1182 dst
1183 }
1184
1185 pub(super) fn eval_film_grain(
1186 &mut self,
1187 comp: &Comp,
1188 node: &Node,
1189 time: f64,
1190 frame_i: i64,
1191 enc: &mut wgpu::CommandEncoder,
1192 visiting: &mut HashSet<(NodeId, i64)>,
1193 stats: &mut EvalStats,
1194 ) -> CachedTexture {
1195 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1196 return self.dummy.clone();
1197 };
1198 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1199 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1200 let strength = comp.eval_number(node, "MasterStrength", time, 0.1, &self.expr) as f32;
1201 let proc_zero = comp.eval_number(node, "ProcessWhenBlendIs00", time, 0.0, &self.expr) > 0.5;
1202 let mbm_flag = self.multiplies_by_mask(comp, node, time);
1203 if (blend <= 1e-6 && !proc_zero && !mbm_flag) || (strength.abs() <= 1e-6 && !mbm_flag) {
1204 return src;
1205 }
1206 let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src };
1207 let x_size = comp.eval_number(node, "MasterXSize", time, 1.0, &self.expr) as f32;
1208 let lock_size = comp.eval_number(node, "LockSizeXY", time, 1.0, &self.expr) > 0.5;
1209 let y_size = if lock_size {
1210 x_size
1211 } else {
1212 comp.eval_number(node, "MasterYSize", time, x_size as f64, &self.expr) as f32
1213 };
1214 let rough = comp.eval_number(node, "MasterRoughness", time, 0.15, &self.expr) as f32;
1215 let master_off = comp.eval_number(node, "MasterOffset", time, 0.01, &self.expr) as f32;
1216 let log_proc = comp.eval_number(node, "LogProcessing", time, 1.0, &self.expr) as f32;
1217 let alpha_mult = comp.eval_number(node, "AlphaMultiply", time, 1.0, &self.expr) as f32;
1218 let color_str = comp.eval_number(node, "ColorStrength", time, 1.0, &self.expr) as f32;
1219 let time_lock = comp.eval_number(node, "TimeLockSeed", time, 0.0, &self.expr) > 0.5;
1220 let base_seed = comp.eval_number(node, "Seed", time, 0.0, &self.expr).round() as i32;
1221 let seed = if time_lock { base_seed } else { base_seed.wrapping_add(frame_i as i32) };
1222 let r_str = comp.eval_number(node, "RedStrength", time, 1.0, &self.expr) as f32;
1223 let g_str = comp.eval_number(node, "GreenStrength", time, 1.0, &self.expr) as f32;
1224 let b_str = comp.eval_number(node, "BlueStrength", time, 1.0, &self.expr) as f32;
1225 let r_x = comp.eval_number(node, "RedXSize", time, 1.0, &self.expr) as f32;
1226 let r_y = if lock_size { r_x } else { comp.eval_number(node, "RedYSize", time, r_x as f64, &self.expr) as f32 };
1227 let g_x = comp.eval_number(node, "GreenXSize", time, 1.0, &self.expr) as f32;
1228 let g_y = if lock_size { g_x } else { comp.eval_number(node, "GreenYSize", time, g_x as f64, &self.expr) as f32 };
1229 let b_x = comp.eval_number(node, "BlueXSize", time, 1.0, &self.expr) as f32;
1230 let b_y = if lock_size { b_x } else { comp.eval_number(node, "BlueYSize", time, b_x as f64, &self.expr) as f32 };
1231 let r_rough = comp.eval_number(node, "RedRoughness", time, 1.0, &self.expr) as f32;
1232 let g_rough = comp.eval_number(node, "GreenRoughness", time, 1.0, &self.expr) as f32;
1233 let b_rough = comp.eval_number(node, "BlueRoughness", time, 1.0, &self.expr) as f32;
1234 let r_off = comp.eval_number(node, "RedOffset", time, 0.0, &self.expr) as f32;
1235 let g_off = comp.eval_number(node, "GreenOffset", time, 0.0, &self.expr) as f32;
1236 let b_off = comp.eval_number(node, "BlueOffset", time, 0.0, &self.expr) as f32;
1237 let mono = comp.eval_number(node, "Monochrome", time, 1.0, &self.expr) as f32;
1238 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1239 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1240 let mbm = mask.is_some() && mbm_flag;
1241 let skip = self.process_skip(comp, node, time);
1242
1243 let mut u = UniformParams::default();
1244 u.p[0] = [strength, x_size, y_size, rough];
1245 u.p[1] = [seed as f32, log_proc, blend, if mask.is_some() { 1.0 } else { 0.0 }];
1246 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, r_str, g_str, b_str];
1247 u.p[3] = [mono, alpha_mult, master_off, color_str];
1248 u.p[4] = [r_x, r_y, r_rough, r_off];
1249 u.p[5] = [g_x, g_y, g_rough, g_off];
1250 u.p[6] = [b_x, b_y, b_rough, b_off];
1251 u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1252 u.p[8] = skip;
1253 let key = self.make_key(node, "FilmGrain", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..9]));
1254 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1255 stats.cache_hits += 1;
1256 return hit;
1257 }
1258 stats.cache_misses += 1;
1259 stats.nodes_evaluated += 1;
1260 let clear_skip = mbm && skip.iter().any(|&s| s > 0.5);
1261 if clear_skip {
1262 u.p[8] = [0.0; 4];
1263 }
1264 let dst_raw = self.alloc_tex_like(&src, src.depth, if clear_skip { 0 } else { key });
1265 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1266 self.dispatch_op(enc, ShaderOp::FilmGrain, &src.view, &self.dummy.view, mv, &dst_raw, &u);
1267 let dst = if clear_skip {
1268 self.clear_skipped_channels(enc, &dst_raw, skip, key)
1269 } else {
1270 dst_raw
1271 };
1272 self.cache.insert(key, dst.clone(), node.id, frame_i);
1273 dst
1274 }
1275
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280 use super::{Comp, Engine};
1281
1282 fn eval_node_px(comp_src: &str, node_name: &str) -> [u8; 4] {
1283 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1284 let id = comp.find_node(node_name).expect("find node");
1285 let mut engine = Engine::new_headless().expect("headless engine");
1286 let (tex, _) = engine.evaluate(&comp, id, 0.0);
1287 let px = engine.readback_rgba(&tex).expect("readback");
1288 let w = tex.size[0];
1289 let i = ((tex.size[1] / 2 * w + w / 2) * 4) as usize;
1290 [px[i], px[i + 1], px[i + 2], px[i + 3]]
1291 }
1292
1293 #[test]
1294 fn color_corrector_wheel_hue_and_tint_length_blend_linearly() {
1295 // Pure gray (0.5, 0.5, 0.5) with WheelHue1=0.25 and WheelTintLength1=0.5 (TintMode=0):
1296 // rgb_hue is neutral (0.5, 0.5, 0.5); TM0 tilt at angle 0.25*2pi + 27deg and length 0.5
1297 // shifts toward warm green/yellow, blended linearly with mix(..., 0.5).
1298 let comp = r#"{
1299 Tools = ordered() {
1300 Bg = Background {
1301 Inputs = {
1302 Width = Input { Value = 16, },
1303 Height = Input { Value = 16, },
1304 TopLeftRed = Input { Value = 0.5, },
1305 TopLeftGreen = Input { Value = 0.5, },
1306 TopLeftBlue = Input { Value = 0.5, },
1307 },
1308 },
1309 CC = ColorCorrector {
1310 Inputs = {
1311 Input = Input { SourceOp = "Bg", Source = "Output", },
1312 WheelHue1 = Input { Value = 0.25, },
1313 WheelTintLength1 = Input { Value = 0.5, },
1314 },
1315 },
1316 }
1317 }"#;
1318 let p = eval_node_px(comp, "CC");
1319 // Distinctly red-shifted from neutral gray (128,128,128) at WheelHue1=0.25 with
1320 // TintMode=0 linear mix(rgb_hue, rgb_tilt, 0.5) (~[217, 90, 90, 255]).
1321 assert!(p[0] > 200 && p[1] == p[2] && p[1] < 100, "expected red-shifted tint, got {p:?}");
1322 assert!((p[0] as i32 - 217).abs() <= 5 && (p[1] as i32 - 90).abs() <= 5, "p={p:?}");
1323 }
1324
1325 #[test]
1326 fn color_gain_lock_rgb_and_saturation_red() {
1327 // With LockRGB = 1, GainRed=0.5 and SaturationRed=0.0 broadcast to all 3 channels.
1328 let lock_on = r#"{
1329 Tools = ordered() {
1330 Bg = Background {
1331 Inputs = {
1332 Width = Input { Value = 16, },
1333 Height = Input { Value = 16, },
1334 TopLeftRed = Input { Value = 0.8, },
1335 TopLeftGreen = Input { Value = 0.4, },
1336 TopLeftBlue = Input { Value = 0.2, },
1337 },
1338 },
1339 CG = ColorGain {
1340 Inputs = {
1341 Input = Input { SourceOp = "Bg", Source = "Output", },
1342 LockRGB = Input { Value = 1, },
1343 GainRed = Input { Value = 0.5, },
1344 SaturationRed = Input { Value = 0.0, },
1345 },
1346 },
1347 }
1348 }"#;
1349 let p_on = eval_node_px(lock_on, "CG");
1350 // All channels scaled by 0.5 -> (0.4, 0.2, 0.1), then desaturated with Sat=0 -> uniform gray.
1351 assert_eq!(p_on[0], p_on[1]);
1352 assert_eq!(p_on[1], p_on[2]);
1353
1354 // With LockRGB omitted (defaults to 0 matching Render Node), GainRed=0.5 only scales Red,
1355 // and SaturationRed=0.0 only desaturates Red toward Rec.601 luma.
1356 let lock_off = r#"{
1357 Tools = ordered() {
1358 Bg = Background {
1359 Inputs = {
1360 Width = Input { Value = 16, },
1361 Height = Input { Value = 16, },
1362 TopLeftRed = Input { Value = 0.8, },
1363 TopLeftGreen = Input { Value = 0.4, },
1364 TopLeftBlue = Input { Value = 0.2, },
1365 },
1366 },
1367 CG = ColorGain {
1368 Inputs = {
1369 Input = Input { SourceOp = "Bg", Source = "Output", },
1370 GainRed = Input { Value = 0.5, },
1371 SaturationRed = Input { Value = 0.0, },
1372 },
1373 },
1374 }
1375 }"#;
1376 let p_off = eval_node_px(lock_off, "CG");
1377 // After GainRed=0.5: (0.4, 0.4, 0.2), luma = 0.299*0.4 + 0.587*0.4 + 0.114*0.2 = 0.3772
1378 // Red desaturated -> ~96, Green stays 0.4 -> ~102, Blue stays 0.2 -> ~51.
1379 assert!((p_off[0] as i32 - 96).abs() <= 2, "p_off={p_off:?}");
1380 assert!((p_off[1] as i32 - 102).abs() <= 2, "p_off={p_off:?}");
1381 assert!((p_off[2] as i32 - 51).abs() <= 2, "p_off={p_off:?}");
1382 }
1383
1384 #[test]
1385 fn color_gain_quadratic_dark_and_high_hue_weights() {
1386 // Pure red with Value=0.25 (u_dark = 1 - 0.25*2 = 0.5) and DarkHue=1/3 (+120 deg toward green):
1387 // quadratic weight w_dark = 0.5^2 = 0.25 -> (0.1875, 0.0625, 0) ~ (48, 16, 0),
1388 // rather than linear w = 0.5 -> (32, 32, 0).
1389 let comp = r#"{
1390 Tools = ordered() {
1391 Bg = Background {
1392 Inputs = {
1393 Width = Input { Value = 16, },
1394 Height = Input { Value = 16, },
1395 TopLeftRed = Input { Value = 0.25, },
1396 TopLeftGreen = Input { Value = 0.0, },
1397 TopLeftBlue = Input { Value = 0.0, },
1398 },
1399 },
1400 CG = ColorGain {
1401 Inputs = {
1402 Input = Input { SourceOp = "Bg", Source = "Output", },
1403 DarkHue = Input { Value = 0.3333333, },
1404 },
1405 },
1406 }
1407 }"#;
1408 let p = eval_node_px(comp, "CG");
1409 assert!((p[0] as i32 - 48).abs() <= 2 && (p[1] as i32 - 16).abs() <= 2 && p[2] == 0, "p={p:?}");
1410 }
1411
1412 #[test]
1413 fn color_corrector_multiply_by_mask_int8_clamps_before_mask_scale() {
1414 // Int8 ColorCorrector with Gain=1.7 and MultiplyByMask=1 clamps adjusted RGBA to [0,1]
1415 // before multiplying by mask*blend, whereas Float32 preserves HDR headroom before scaling.
1416 let make_comp = |depth: i32, blend: f32| format!(
1417 r#"{{
1418 Tools = ordered() {{
1419 Bg = Background {{
1420 Inputs = {{
1421 Width = Input {{ Value = 16, }},
1422 Height = Input {{ Value = 16, }},
1423 TopLeftRed = Input {{ Value = 1.0, }},
1424 TopLeftGreen = Input {{ Value = 1.0, }},
1425 TopLeftBlue = Input {{ Value = 1.0, }},
1426 TopLeftAlpha = Input {{ Value = 1.0, }},
1427 Depth = Input {{ Value = {depth}, }},
1428 }},
1429 }},
1430 M = RectangleMask {{
1431 Inputs = {{
1432 MaskWidth = Input {{ Value = 16, }},
1433 MaskHeight = Input {{ Value = 16, }},
1434 Width = Input {{ Value = 1.0, }},
1435 Height = Input {{ Value = 1.0, }},
1436 Level = Input {{ Value = 0.6, }},
1437 }},
1438 }},
1439 CC = ColorCorrector {{
1440 Inputs = {{
1441 Input = Input {{ SourceOp = "Bg", Source = "Output", }},
1442 EffectMask = Input {{ SourceOp = "M", Source = "Mask", }},
1443 MultiplyByMask = Input {{ Value = 1, }},
1444 MasterRGBGain = Input {{ Value = 1.7, }},
1445 Blend = Input {{ Value = {blend}, }},
1446 }},
1447 }},
1448 }}
1449 }}"#
1450 );
1451 // Int8 (Depth=1): clamp(1.7, 0, 1) * (0.6 * 1.0) = 0.6 -> ~153
1452 let p8 = eval_node_px(&make_comp(1, 1.0), "CC");
1453 assert!((p8[0] as i32 - 153).abs() <= 2 && p8[0] == p8[1] && p8[1] == p8[2] && (p8[3] as i32 - 153).abs() <= 2, "p8={p8:?}");
1454
1455 // Int8 with Blend=0.8: clamp(1.7, 0, 1) * (0.6 * 0.8) = 0.48 -> ~122
1456 let p8_blend = eval_node_px(&make_comp(1, 0.8), "CC");
1457 assert!((p8_blend[0] as i32 - 122).abs() <= 2 && (p8_blend[3] as i32 - 122).abs() <= 2, "p8_blend={p8_blend:?}");
1458
1459 // Float32 (Depth=3): 1.7 * (0.6 * 1.0) = 1.02 -> clamped on 8-bit readback to 255, alpha=153
1460 let p32 = eval_node_px(&make_comp(3, 1.0), "CC");
1461 assert_eq!(p32[0], 255, "expected HDR RGB > 1.0 after mask scale, got {p32:?}");
1462 assert!((p32[3] as i32 - 153).abs() <= 2, "expected alpha scaled by mask, got {p32:?}");
1463 }
1464
1465 #[test]
1466 fn color_corrector_smh_weights_use_input_luma_before_master_lgg() {
1467 // HDR input (0.6, 1.2, 1.8) has input luma y0 = 1.089 >= 1.0 (pure Highlights, w_h = 1.0).
1468 // MasterRGBGain=0.5 drops post-master luma to ~0.544, but Fusion evaluates SMH range
1469 // weights on input luma y0 before Master LGG -> 0.5 * 0.5 * (0.6, 1.2, 1.8) = (0.15, 0.30, 0.45).
1470 let comp = r#"{
1471 Tools = ordered() {
1472 Bg = Background {
1473 Inputs = {
1474 Width = Input { Value = 16, },
1475 Height = Input { Value = 16, },
1476 TopLeftRed = Input { Value = 0.2, },
1477 TopLeftGreen = Input { Value = 0.4, },
1478 TopLeftBlue = Input { Value = 0.6, },
1479 Depth = Input { Value = 3, },
1480 },
1481 },
1482 Up = BrightnessContrast {
1483 Inputs = {
1484 Input = Input { SourceOp = "Bg", Source = "Output", },
1485 Gain = Input { Value = 3.0, },
1486 },
1487 },
1488 CC = ColorCorrector {
1489 Inputs = {
1490 Input = Input { SourceOp = "Up", Source = "Output", },
1491 MasterRGBGain = Input { Value = 0.5, },
1492 ShadowsRGBGain = Input { Value = 0.5, },
1493 HighlightsRGBGain = Input { Value = 0.5, },
1494 },
1495 },
1496 }
1497 }"#;
1498 let p = eval_node_px(comp, "CC");
1499 assert!((p[0] as i32 - 38).abs() <= 2 && (p[1] as i32 - 76).abs() <= 2 && (p[2] as i32 - 115).abs() <= 2, "p={p:?}");
1500 }
1501
1502 #[test]
1503 fn gamut_convert_srgb_to_no_change_removes_gamma_only() {
1504 // SourceSpace="sRGB", OutputSpace="NoChange", RemoveGamma=1, AddGamma=1 removes sRGB gamma
1505 // and keeps linear output when OutputSpace is NoChange.
1506 let comp = r#"{
1507 Tools = ordered() {
1508 Bg = Background {
1509 Inputs = {
1510 Width = Input { Value = 16, },
1511 Height = Input { Value = 16, },
1512 TopLeftRed = Input { Value = 0.5, },
1513 TopLeftGreen = Input { Value = 0.5, },
1514 TopLeftBlue = Input { Value = 0.5, },
1515 Depth = Input { Value = 3, },
1516 },
1517 },
1518 GC = GamutConvert {
1519 Inputs = {
1520 Input = Input { SourceOp = "Bg", Source = "Output", },
1521 SourceSpace = Input { Value = FuID { "sRGB" }, },
1522 OutputSpace = Input { Value = FuID { "NoChange" }, },
1523 RemoveGamma = Input { Value = 1, },
1524 AddGamma = Input { Value = 1, },
1525 },
1526 },
1527 }
1528 }"#;
1529 let p = eval_node_px(comp, "GC");
1530 // srgb_to_linear(0.5) = 0.21404 -> ~55
1531 assert!((p[0] as i32 - 55).abs() <= 2 && p[0] == p[1] && p[1] == p[2], "p={p:?}");
1532 }
1533
1534 #[test]
1535 fn brightness_contrast_negative_gamma_preserves_transparent_zero() {
1536 // Gain=0.8, Lift=-1.0, Gamma=2.71, Contrast=-0.37 on transparent black (0,0,0,0):
1537 // v = -1.0 must NOT be clamped to 0.0 before Contrast, or it turns into +0.185 (47/255) gray.
1538 let comp = r#"{
1539 Tools = ordered() {
1540 Bg = Background {
1541 Inputs = {
1542 Width = Input { Value = 16, },
1543 Height = Input { Value = 16, },
1544 TopLeftRed = Input { Value = 0.0, },
1545 TopLeftGreen = Input { Value = 0.0, },
1546 TopLeftBlue = Input { Value = 0.0, },
1547 TopLeftAlpha = Input { Value = 0.0, },
1548 },
1549 },
1550 BC = BrightnessContrast {
1551 Inputs = {
1552 Input = Input { SourceOp = "Bg", Source = "Output", },
1553 Gain = Input { Value = 0.8, },
1554 Lift = Input { Value = -1.0, },
1555 Gamma = Input { Value = 2.71, },
1556 Contrast = Input { Value = -0.37, },
1557 },
1558 },
1559 }
1560 }"#;
1561 let p = eval_node_px(comp, "BC");
1562 assert_eq!(p, [0, 0, 0, 0], "transparent black must stay [0,0,0,0], got {p:?}");
1563 }
1564
1565 #[test]
1566 fn color_curves_identity_f16_lut_error_below_1e3() {
1567 let comp_src = r#"{
1568 Tools = ordered() {
1569 Bg = Background {
1570 Inputs = {
1571 Width = Input { Value = 16, },
1572 Height = Input { Value = 16, },
1573 TopLeftRed = Input { Value = 0.1, },
1574 TopLeftGreen = Input { Value = 0.25, },
1575 TopLeftBlue = Input { Value = 0.73, },
1576 TopLeftAlpha = Input { Value = 1.0, },
1577 Depth = Input { Value = 2, },
1578 },
1579 },
1580 CC = ColorCurves {
1581 Inputs = {
1582 Input = Input { SourceOp = "Bg", Source = "Output", },
1583 },
1584 },
1585 }
1586 }"#;
1587 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1588 let id = comp.find_node("CC").expect("CC");
1589 let Ok(mut eng) = Engine::new_headless() else {
1590 return;
1591 };
1592 let (tex, _) = eng.evaluate(&comp, id, 0.0);
1593 assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float);
1594 let [w, h] = tex.size;
1595 let unpadded_bpr = w * 8;
1596 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1597 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
1598 let buf = eng.device().create_buffer(&wgpu::BufferDescriptor {
1599 label: Some("cc-f16-readback"),
1600 size: u64::from(padded_bpr) * u64::from(h),
1601 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1602 mapped_at_creation: false,
1603 });
1604 let mut enc = eng.device().create_command_encoder(&Default::default());
1605 enc.copy_texture_to_buffer(
1606 tex.texture.as_image_copy(),
1607 wgpu::TexelCopyBufferInfo {
1608 buffer: &buf,
1609 layout: wgpu::TexelCopyBufferLayout {
1610 offset: 0,
1611 bytes_per_row: Some(padded_bpr),
1612 rows_per_image: Some(h),
1613 },
1614 },
1615 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
1616 );
1617 eng.queue().submit(Some(enc.finish()));
1618 let slice = buf.slice(..);
1619 let (tx, rx) = std::sync::mpsc::channel();
1620 slice.map_async(wgpu::MapMode::Read, move |res| {
1621 let _ = tx.send(res);
1622 });
1623 let _ = eng.device().poll(wgpu::PollType::Wait {
1624 submission_index: None,
1625 timeout: Some(std::time::Duration::from_secs(10)),
1626 });
1627 rx.recv().unwrap().unwrap();
1628 let data = slice.get_mapped_range().unwrap();
1629 let row = ((h / 2) * padded_bpr) as usize;
1630 let col = ((w / 2) * 8) as usize;
1631 let px_bytes = &data[row + col..row + col + 8];
1632 let f16_to_f32 = |lo: u8, hi: u8| -> f32 {
1633 let h = u16::from_le_bytes([lo, hi]);
1634 let sign = u32::from(h >> 15) << 31;
1635 let exp = u32::from((h >> 10) & 0x1f);
1636 let frac = u32::from(h & 0x3ff);
1637 let bits = if exp == 0 {
1638 if frac == 0 {
1639 sign
1640 } else {
1641 let mut e = 127 - 14;
1642 let mut m = frac;
1643 while (m & 0x400) == 0 {
1644 m <<= 1;
1645 e -= 1;
1646 }
1647 sign | (e << 23) | ((m & 0x3ff) << 13)
1648 }
1649 } else if exp == 0x1f {
1650 sign | (0xff << 23) | (frac << 13)
1651 } else {
1652 sign | ((exp + 112) << 23) | (frac << 13)
1653 };
1654 f32::from_bits(bits)
1655 };
1656 let r = f16_to_f32(px_bytes[0], px_bytes[1]);
1657 let g = f16_to_f32(px_bytes[2], px_bytes[3]);
1658 let b = f16_to_f32(px_bytes[4], px_bytes[5]);
1659 assert!((r - 0.1).abs() < 1e-3, "identity ColorCurves red={r}, expected 0.1");
1660 assert!((g - 0.25).abs() < 1e-3, "identity ColorCurves green={g}, expected 0.25");
1661 assert!((b - 0.73).abs() < 1e-3, "identity ColorCurves blue={b}, expected 0.73");
1662 }
1663
1664 #[test]
1665 fn colorize_and_film_grain_dod_effect_mask_align_to_canvas() {
1666 // Transform shifts a 64x64 image left by 0.25 (creates DoD origin_x < 0, width > 64).
1667 // EffectMask covers only the right quarter (x in [48, 64)) in canvas coordinates.
1668 let comp_src = r#"{
1669 Tools = ordered() {
1670 Bg = Background {
1671 Inputs = {
1672 Width = Input { Value = 64, },
1673 Height = Input { Value = 64, },
1674 TopLeftRed = Input { Value = 0.5, },
1675 TopLeftGreen = Input { Value = 0.5, },
1676 TopLeftBlue = Input { Value = 0.5, },
1677 TopLeftAlpha = Input { Value = 1.0, },
1678 },
1679 },
1680 XF = DVE {
1681 Inputs = {
1682 Input = Input { SourceOp = "Bg", Source = "Output", },
1683 Center = Input { Value = { 0.25, 0.5 }, },
1684 },
1685 },
1686 Mask = RectangleMask {
1687 Inputs = {
1688 MaskWidth = Input { Value = 64, },
1689 MaskHeight = Input { Value = 64, },
1690 Center = Input { Value = { 0.875, 0.5 }, },
1691 Width = Input { Value = 0.25, },
1692 Height = Input { Value = 1.0, },
1693 },
1694 },
1695 CZ = Fuse.Colorize {
1696 Inputs = {
1697 Image = Input { SourceOp = "XF", Source = "Output", },
1698 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1699 R2 = Input { Value = 1.0, },
1700 G2 = Input { Value = 0.0, },
1701 B2 = Input { Value = 0.0, },
1702 A2 = Input { Value = 1.0, },
1703 },
1704 },
1705 FG = FilmGrain {
1706 Inputs = {
1707 Input = Input { SourceOp = "XF", Source = "Output", },
1708 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1709 MasterStrength = Input { Value = 1.0, },
1710 Seed = Input { Value = 7, },
1711 },
1712 },
1713 }
1714 }"#;
1715 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1716 let Ok(mut eng) = Engine::new_headless() else {
1717 return;
1718 };
1719 let (cz_tex, _) = eng.evaluate(&comp, comp.find_node("CZ").unwrap(), 0.0);
1720 let cz_px = eng.readback_rgba(&cz_tex).unwrap();
1721 let at = |buf: &[u8], x: usize, y: usize| -> [u8; 4] {
1722 let i = (y * 64 + x) * 4;
1723 [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
1724 };
1725 // 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)
1726 let inside_xf_outside_mask = at(&cz_px, 32, 32);
1727 assert_eq!(inside_xf_outside_mask[0], inside_xf_outside_mask[1], "x=32 must be unmasked gray: {inside_xf_outside_mask:?}");
1728 // 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]),
1729 // whereas if mask was misplaced onto DoD texel coords it would colorize x < 48!
1730 for x in 0..46 {
1731 let p = at(&cz_px, x, 32);
1732 assert!((p[0] as i32 - p[1] as i32).abs() <= 1, "mask leaked onto x={x}: {p:?}");
1733 }
1734
1735 let (fg_tex, _) = eng.evaluate(&comp, comp.find_node("FG").unwrap(), 0.0);
1736 let fg_px = eng.readback_rgba(&fg_tex).unwrap();
1737 // Outside mask [0..46), FilmGrain must leave XF untouched (gray ~128).
1738 for x in 0..46 {
1739 let p = at(&fg_px, x, 32);
1740 assert!((p[0] as i32 - 128).abs() <= 1, "FilmGrain leaked outside mask at x={x}: {p:?}");
1741 }
1742 }
1743
1744 #[test]
1745 fn tex_scale_preserved_through_color_gain_transform_blur() {
1746 let comp_src = r#"{
1747 Tools = ordered() {
1748 FN = FastNoise {
1749 Inputs = {
1750 Width = Input { Value = 8192, },
1751 Height = Input { Value = 128, },
1752 },
1753 },
1754 CG = ColorGain {
1755 Inputs = {
1756 Input = Input { SourceOp = "FN", Source = "Output", },
1757 GainRed = Input { Value = 1.5, },
1758 },
1759 },
1760 XF = Transform {
1761 Inputs = {
1762 Input = Input { SourceOp = "CG", Source = "Output", },
1763 Center = Input { Value = { 0.52, 0.5 }, },
1764 },
1765 },
1766 BL = Blur {
1767 Inputs = {
1768 Input = Input { SourceOp = "XF", Source = "Output", },
1769 XBlurSize = Input { Value = 2.0, },
1770 },
1771 },
1772 BG = Background {
1773 Inputs = {
1774 Width = Input { Value = 128, },
1775 Height = Input { Value = 128, },
1776 },
1777 },
1778 M = Merge {
1779 Inputs = {
1780 Background = Input { SourceOp = "BG", Source = "Output", },
1781 Foreground = Input { SourceOp = "BL", Source = "Output", },
1782 },
1783 },
1784 }
1785 }"#;
1786 let comp = Comp::from_fusion_str(comp_src).expect("parse tex_scale comp");
1787 let Ok(mut eng) = Engine::new_headless() else {
1788 return;
1789 };
1790 eng.hiq = false; // caps FastNoise at 4096 -> tex_scale = 0.5
1791 let (fn_tex, _) = eng.evaluate(&comp, comp.find_node("FN").unwrap(), 0.0);
1792 assert!((fn_tex.tex_scale - 0.5).abs() < 1e-4, "expected FastNoise tex_scale=0.5, got {}", fn_tex.tex_scale);
1793 let (cg_tex, _) = eng.evaluate(&comp, comp.find_node("CG").unwrap(), 0.0);
1794 assert!((cg_tex.tex_scale - fn_tex.tex_scale).abs() < 1e-4, "ColorGain dropped tex_scale: {}", cg_tex.tex_scale);
1795 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
1796 assert!((xf_tex.tex_scale - fn_tex.tex_scale).abs() < 1e-4, "Transform dropped tex_scale: {}", xf_tex.tex_scale);
1797 let (bl_tex, _) = eng.evaluate(&comp, comp.find_node("BL").unwrap(), 0.0);
1798 assert!((bl_tex.tex_scale - fn_tex.tex_scale).abs() < 1e-4, "Blur dropped tex_scale: {}", bl_tex.tex_scale);
1799 let (m_tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
1800 assert!((m_tex.tex_scale - 1.0).abs() < 1e-4, "Merge over 128x128 BG should stay 1.0");
1801 }
1802
1803 #[test]
1804 fn color_curves_hdr_tangent_extrapolation_and_prediv() {
1805 // Probe HDR > 1.0 and < 0.0 on Float32:
1806 // 1) Identity preserves -0.5 and 2.5
1807 // 2) Linear LUT (0, 0.2) -> (1, 0.8) extrapolates to 0.2 + 0.6*(-0.5) = -0.1 and 0.2 + 0.6*2.5 = 1.7
1808 // 3) PreDividePostMultiply=1 unpremultiplies rgb/alpha > 1.0 without clamping
1809 let comp_src = r#"{
1810 Tools = ordered() {
1811 LutLin = LUTBezier {
1812 KeyColorSplines = {
1813 [0] = {
1814 [0] = { 0.2, Flags = { Linear = true } },
1815 [1] = { 0.8, Flags = { Linear = true } },
1816 },
1817 },
1818 },
1819 HdrNeg = Background {
1820 Inputs = {
1821 Width = Input { Value = 16, },
1822 Height = Input { Value = 16, },
1823 Depth = Input { Value = 4, },
1824 TopLeftRed = Input { Value = -0.5, },
1825 TopLeftGreen = Input { Value = 2.5, },
1826 TopLeftBlue = Input { Value = 1.0, },
1827 TopLeftAlpha = Input { Value = 0.5, },
1828 },
1829 },
1830 CcId = ColorCurves {
1831 Inputs = {
1832 Input = Input { SourceOp = "HdrNeg", Source = "Output", },
1833 },
1834 },
1835 EncodeId = BrightnessContrast {
1836 Inputs = {
1837 Gain = Input { Value = 0.2, },
1838 Brightness = Input { Value = 0.2, },
1839 Input = Input { SourceOp = "CcId", Source = "Output", },
1840 },
1841 },
1842 CcLin = ColorCurves {
1843 Inputs = {
1844 Red = Input { SourceOp = "LutLin", Source = "Value", },
1845 Green = Input { SourceOp = "LutLin", Source = "Value", },
1846 Input = Input { SourceOp = "HdrNeg", Source = "Output", },
1847 },
1848 },
1849 EncodeLin = BrightnessContrast {
1850 Inputs = {
1851 Gain = Input { Value = 0.2, },
1852 Brightness = Input { Value = 0.2, },
1853 Input = Input { SourceOp = "CcLin", Source = "Output", },
1854 },
1855 },
1856 CcPreDiv = ColorCurves {
1857 Inputs = {
1858 PreDividePostMultiply = Input { Value = 1, },
1859 Green = Input { SourceOp = "LutLin", Source = "Value", },
1860 Input = Input { SourceOp = "HdrNeg", Source = "Output", },
1861 },
1862 },
1863 EncodePreDiv = BrightnessContrast {
1864 Inputs = {
1865 Gain = Input { Value = 0.2, },
1866 Brightness = Input { Value = 0.2, },
1867 Input = Input { SourceOp = "CcPreDiv", Source = "Output", },
1868 },
1869 },
1870 }
1871 }"#;
1872 // Encoded as v * 0.2 + 0.2:
1873 // Id: R=-0.5 -> 0.1 (26), G=2.5 -> 0.7 (179)
1874 let pid = eval_node_px(comp_src, "EncodeId");
1875 assert!((pid[0] as i32 - 26).abs() <= 2, "Id HDR neg R={pid:?}");
1876 assert!((pid[1] as i32 - 179).abs() <= 2, "Id HDR >1 G={pid:?}");
1877 // Lin: R=-0.1 -> 0.18 (46), G=1.7 -> 0.54 (138)
1878 let plin = eval_node_px(comp_src, "EncodeLin");
1879 assert!((plin[0] as i32 - 46).abs() <= 2, "Lin HDR neg R={plin:?}");
1880 assert!((plin[1] as i32 - 138).abs() <= 2, "Lin HDR >1 G={plin:?}");
1881 // PreDiv: G_straight = 2.5 / 0.5 = 5.0 -> 0.2 + 0.6*5.0 = 3.2 -> * 0.5 = 1.6 -> enc 0.52 (133)
1882 let ppd = eval_node_px(comp_src, "EncodePreDiv");
1883 assert!((ppd[1] as i32 - 133).abs() <= 2, "PreDiv HDR >1 G={ppd:?}");
1884 }
1885
1886 #[test]
1887 fn color_curves_step_slope_guard_and_prediv_alpha_zero_and_bc_smaller_input() {
1888 let comp_src = r#"{
1889 Tools = ordered() {
1890 LutStep = LUTBezier {
1891 KeyColorSplines = {
1892 [0] = {
1893 [0] = { 0.0, Flags = { Linear = true, StepOut = true } },
1894 [0.0001] = { 1.0, Flags = { Linear = true } },
1895 [1] = { 1.0, Flags = { Linear = true } },
1896 },
1897 },
1898 },
1899 LutLift = LUTBezier {
1900 KeyColorSplines = {
1901 [0] = {
1902 [0] = { 0.6, Flags = { Linear = true } },
1903 [1] = { 1.0, Flags = { Linear = true } },
1904 },
1905 },
1906 },
1907 AdditiveA0 = Background {
1908 Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.0, }, },
1909 },
1910 CcStep = ColorCurves {
1911 Inputs = {
1912 Red = Input { SourceOp = "LutStep", Source = "Value", },
1913 Input = Input { SourceOp = "AdditiveA0", Source = "Output", },
1914 },
1915 },
1916 CcPreDivA0 = ColorCurves {
1917 Inputs = {
1918 PreDividePostMultiply = Input { Value = 1, },
1919 IgnoreTransparent = Input { Value = 1, },
1920 Green = Input { SourceOp = "LutLift", Source = "Value", },
1921 Input = Input { SourceOp = "AdditiveA0", Source = "Output", },
1922 },
1923 },
1924 CcNoPreDivA0 = ColorCurves {
1925 Inputs = {
1926 PreDividePostMultiply = Input { Value = 0, },
1927 IgnoreTransparent = Input { Value = 1, },
1928 Green = Input { SourceOp = "LutLift", Source = "Value", },
1929 Input = Input { SourceOp = "AdditiveA0", Source = "Output", },
1930 },
1931 },
1932 SmallPlate = Background {
1933 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftAlpha = Input { Value = 0.0, }, },
1934 },
1935 BigBg = Background {
1936 Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1.0, }, },
1937 },
1938 BcSmall = BrightnessContrast {
1939 Inputs = { Brightness = Input { Value = 0.25, }, Input = Input { SourceOp = "SmallPlate", Source = "Output", }, },
1940 },
1941 MSmall = Merge {
1942 Inputs = { Background = Input { SourceOp = "BigBg", Source = "Output", }, Foreground = Input { SourceOp = "BcSmall", Source = "Output", }, },
1943 },
1944 }
1945 }"#;
1946 let comp = Comp::from_fusion_str(comp_src).expect("parse color test comp");
1947 let cc_step = comp.node(comp.find_node("CcStep").unwrap());
1948 let (y0, y1, s0, s1) = Engine::color_curves_extrap_params(&comp, cc_step);
1949 for v in y0.into_iter().chain(y1).chain(s0).chain(s1) {
1950 assert!(v.is_finite() && v.abs() <= 1e3, "extrap param out of bounds: {v}");
1951 }
1952 assert!(s0[0].abs() < 1e-3, "StepOut should produce flat 0 entry slope, got {}", s0[0]);
1953
1954 let pa0_pd = eval_node_px(comp_src, "CcPreDivA0");
1955 // PreDivide=1 + IgnoreTransparent=1 does NOT short-circuit alpha=0 additive pixels:
1956 // unpremultiply zeroes RGB when alpha=0 and post-multiply returns [0, 0, 0, 0].
1957 assert_eq!(pa0_pd, [0, 0, 0, 0], "PreDiv+IgnoreTransparent alpha=0={pa0_pd:?}");
1958 let pa0_nopd = eval_node_px(comp_src, "CcNoPreDivA0");
1959 // PreDivide=0 + IgnoreTransparent=1 skips alpha=0 pixels, leaving green at 0.5 (128).
1960 assert!((pa0_nopd[1] as i32 - 128).abs() <= 2, "NoPreDiv+IgnoreTransparent alpha=0 green={pa0_nopd:?}");
1961
1962 let pstep = eval_node_px(comp_src, "CcStep");
1963 assert_eq!(pstep[0], 255);
1964
1965 // BrightnessContrast over 32x32 transparent plate covers entire 64x64 frame in Merge.
1966 let Ok(mut eng) = Engine::new_headless() else {
1967 return;
1968 };
1969 let (m_tex, _) = eng.evaluate(&comp, comp.find_node("MSmall").unwrap(), 0.0);
1970 assert_eq!(m_tex.size, [64, 64]);
1971 let m_px = eng.readback_rgba(&m_tex).unwrap();
1972 assert!((m_px[0] as i32 - 64).abs() <= 2, "corner (0,0) outside 32x32 should also receive +0.25 lift, got {:?}", &m_px[0..4]);
1973 }
1974
1975 #[test]
1976 fn gamut_convert_wide_gamut_custom_gamma_and_process_skip_mask() {
1977 let comp_src = r#"Composition {
1978 Tools = ordered() {
1979 Src = Background {
1980 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
1981 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.6, }, TopLeftAlpha = Input { Value = 1.0, }, },
1982 },
1983 Mask = RectangleMask {
1984 Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, },
1985 Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 1.0, }, },
1986 },
1987 GC = GamutConvert {
1988 Inputs = {
1989 Input = Input { SourceOp = "Src", Source = "Output", },
1990 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
1991 SourceSpace = Input { Value = FuID { "sRGB" }, },
1992 OutputSpace = Input { Value = FuID { "WideGamut" }, },
1993 CustomOutputGamma = Input { Value = 3.0, },
1994 MultiplyByMask = Input { Value = 1, },
1995 ProcessBlue = Input { Value = 0, },
1996 },
1997 },
1998 }
1999 }"#;
2000 let px = eval_node_px(comp_src, "GC");
2001 assert!(px[0] > 0 && px[1] > 0, "R/G should convert to WideGamut, got {px:?}");
2002 assert_eq!(px[2], 0, "MultiplyByMask=1 & ProcessBlue=0 clears unprocessed blue to 0, got {px:?}");
2003 assert_eq!(px[3], 255);
2004 }
2005
2006 #[test]
2007 fn film_grain_alpha_multiply_and_monochrome_and_lock_size_xy() {
2008 let comp_src = r#"Composition {
2009 Tools = ordered() {
2010 SrcA0 = Background {
2011 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
2012 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.0, }, },
2013 },
2014 SrcA1 = Background {
2015 Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
2016 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1.0, }, },
2017 },
2018 FgMult1 = FilmGrain {
2019 Inputs = { Input = Input { SourceOp = "SrcA0", Source = "Output", }, MasterStrength = Input { Value = 0.3, }, LogProcessing = Input { Value = 0, }, AlphaMultiply = Input { Value = 1, }, },
2020 },
2021 FgMult0 = FilmGrain {
2022 Inputs = { Input = Input { SourceOp = "SrcA0", Source = "Output", }, MasterStrength = Input { Value = 0.3, }, LogProcessing = Input { Value = 0, }, AlphaMultiply = Input { Value = 0, }, },
2023 },
2024 FgColor = FilmGrain {
2025 Inputs = { Input = Input { SourceOp = "SrcA1", Source = "Output", }, MasterStrength = Input { Value = 0.3, }, Monochrome = Input { Value = 0, }, },
2026 },
2027 FgAniso = FilmGrain {
2028 Inputs = { Input = Input { SourceOp = "SrcA1", Source = "Output", }, MasterStrength = Input { Value = 0.3, }, LockSizeXY = Input { Value = 0, }, MasterXSize = Input { Value = 5.0, }, MasterYSize = Input { Value = 1.0, }, },
2029 },
2030 }
2031 }"#;
2032 let comp = Comp::from_fusion_str(comp_src).expect("parse FilmGrain test comp");
2033 let Ok(mut eng) = Engine::new_headless() else {
2034 return;
2035 };
2036 let (t1, _) = eng.evaluate(&comp, comp.find_node("FgMult1").unwrap(), 0.0);
2037 let p1 = eng.readback_rgba(&t1).unwrap();
2038 // AlphaMultiply=1 on alpha=0 preserves original RGB (128,128,128,0) everywhere.
2039 assert!(p1.chunks_exact(4).all(|p| p[0] == 128 && p[3] == 0), "AlphaMultiply=1 must leave alpha=0 RGB untouched");
2040
2041 let (t0, _) = eng.evaluate(&comp, comp.find_node("FgMult0").unwrap(), 0.0);
2042 let p0 = eng.readback_rgba(&t0).unwrap();
2043 assert!(p0.chunks_exact(4).any(|p| p[0] != 128 && p[3] == 0), "AlphaMultiply=0 must grain alpha=0 RGB");
2044
2045 let (tc, _) = eng.evaluate(&comp, comp.find_node("FgColor").unwrap(), 0.0);
2046 let pc = eng.readback_rgba(&tc).unwrap();
2047 assert!(pc.chunks_exact(4).any(|p| p[0] != p[1] || p[1] != p[2]), "Monochrome=0 must produce chromatic grain");
2048
2049 let (ta, _) = eng.evaluate(&comp, comp.find_node("FgAniso").unwrap(), 0.0);
2050 let pa = eng.readback_rgba(&ta).unwrap();
2051 let dx: u32 = (0..32).flat_map(|y| (0..31).map(move |x| (x, y)))
2052 .map(|(x, y)| pa[(y * 32 + x) * 4].abs_diff(pa[(y * 32 + x + 1) * 4]) as u32)
2053 .sum();
2054 let dy: u32 = (0..31).flat_map(|y| (0..32).map(move |x| (x, y)))
2055 .map(|(x, y)| pa[(y * 32 + x) * 4].abs_diff(pa[((y + 1) * 32 + x) * 4]) as u32)
2056 .sum();
2057 assert!(dy > dx * 2, "LockSizeXY=0 with MasterXSize=5, MasterYSize=1 must vary faster in Y ({dy}) than X ({dx})");
2058 }
2059
2060 #[test]
2061 fn lut_and_curve_texture_cache_hits_on_repeat_evals() {
2062 let comp_src = r#"Composition {
2063 CurrentTime = 0,
2064 RenderRange = { 0, 1 },
2065 GlobalRange = { 0, 1 },
2066 Tools = ordered() {
2067 Src = Background {
2068 Inputs = {
2069 Width = Input { Value = 16, },
2070 Height = Input { Value = 16, },
2071 TopLeftRed = Input { Value = 0.5, },
2072 TopLeftGreen = Input { Value = 0.25, },
2073 TopLeftBlue = Input { Value = 0.75, },
2074 TopLeftAlpha = Input { Value = 1.0, },
2075 },
2076 },
2077 CC = ColorCorrector {
2078 Inputs = {
2079 Input = Input { SourceOp = "Src", Source = "Output", },
2080 MasterRGBGamma = Input { Value = 1.4, },
2081 },
2082 },
2083 LutR = LUTBezier {
2084 KeyColorSplines = { [0] = { 0, RH = { 0.33, 0.5 } }, [1] = { 1, LH = { 0.66, 0.9 } } },
2085 },
2086 Curves = ColorCurves {
2087 Inputs = {
2088 Input = Input { SourceOp = "CC", Source = "Output", },
2089 Red = Input { SourceOp = "LutR", Source = "Value", },
2090 },
2091 },
2092 HueC = HueCurves {
2093 Inputs = {
2094 Input = Input { SourceOp = "Curves", Source = "Output", },
2095 },
2096 },
2097 }
2098 }"#;
2099 let comp = Comp::from_fusion_str(comp_src).expect("parse LUT cache comp");
2100 let Ok(mut eng) = Engine::new_headless() else {
2101 return;
2102 };
2103 let target = comp.find_node("HueC").unwrap();
2104
2105 eng.evaluate(&comp, target, 0.0);
2106 let (hits_1, misses_1) = {
2107 let reg = eng.pipelines.borrow();
2108 (reg.lut_hits, reg.lut_misses)
2109 };
2110 assert_eq!(misses_1, 3, "CC + ColorCurves + HueCurves should upload 3 LUTs on cold eval");
2111 assert_eq!(hits_1, 0);
2112
2113 // Bust node/output cache and re-evaluate: LUT textures should all hit in ShaderRegistry cache.
2114 eng.bust_gpu_cache();
2115 eng.evaluate(&comp, target, 0.0);
2116 let (hits_2, misses_2) = {
2117 let reg = eng.pipelines.borrow();
2118 (reg.lut_hits, reg.lut_misses)
2119 };
2120 assert_eq!(misses_2, misses_1, "repeat eval must not allocate new LUT textures");
2121 assert_eq!(hits_2, 3, "CC + ColorCurves + HueCurves should all hit LUT cache on repeat eval");
2122
2123 // Verify bounded 64-entry LRU eviction.
2124 for i in 0..80u8 {
2125 let bytes = [i; 12 * 3 * 8];
2126 let _ = eng.pipelines.borrow_mut().get_or_upload_lut_tex(
2127 &eng.device,
2128 &eng.queue,
2129 [12, 3],
2130 model::BitDepth::Float16,
2131 wgpu::TextureFormat::Rgba16Float,
2132 12 * 8,
2133 &bytes,
2134 );
2135 }
2136 assert!(eng.pipelines.borrow().lut_misses <= 83);
2137 }
2138
2139 #[test]
2140 fn color_corrector_inverted_low_high_levels_does_not_overflow_f16() {
2141 // When MasterGreenLow (0.675) > MasterGreenHigh (0.08), span collapses without overflowing
2142 // Rgba16Float curve storage: green above Low maps to 255, green below Low maps to 0.
2143 let comp_src = r#"{
2144 Tools = ordered() {
2145 Bright = Background {
2146 Inputs = {
2147 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2148 TopLeftRed = Input { Value = 0.8, },
2149 TopLeftGreen = Input { Value = 0.85, },
2150 TopLeftBlue = Input { Value = 0.8, },
2151 TopLeftAlpha = Input { Value = 1.0, },
2152 },
2153 },
2154 Dark = Background {
2155 Inputs = {
2156 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2157 TopLeftRed = Input { Value = 0.8, },
2158 TopLeftGreen = Input { Value = 0.25, },
2159 TopLeftBlue = Input { Value = 0.8, },
2160 TopLeftAlpha = Input { Value = 1.0, },
2161 },
2162 },
2163 CCBright = ColorCorrector {
2164 Inputs = {
2165 Input = Input { SourceOp = "Bright", Source = "Output", },
2166 MasterGreenLow = Input { Value = 0.67557, },
2167 MasterGreenHigh = Input { Value = 0.0827, },
2168 MasterBlueOutputHigh = Input { Value = 0.5, },
2169 },
2170 },
2171 CCDark = ColorCorrector {
2172 Inputs = {
2173 Input = Input { SourceOp = "Dark", Source = "Output", },
2174 MasterGreenLow = Input { Value = 0.67557, },
2175 MasterGreenHigh = Input { Value = 0.0827, },
2176 MasterBlueOutputHigh = Input { Value = 0.5, },
2177 },
2178 },
2179 }
2180 }"#;
2181 let comp = Comp::from_fusion_str(comp_src).expect("parse CC inverted levels comp");
2182 let Ok(mut eng) = Engine::new_headless() else { return };
2183 let (tb, _) = eng.evaluate(&comp, comp.find_node("CCBright").unwrap(), 0.0);
2184 let pb = eng.readback_rgba(&tb).unwrap();
2185 assert_eq!(pb[1], 255, "green above MasterGreenLow must saturate to 255, not NaN->0: {:?}", &pb[..4]);
2186 assert!((pb[2] as i32 - 102).abs() <= 2, "MasterBlueOutputHigh=0.5 scales 0.8->0.4 (~102), got {}", pb[2]);
2187
2188 let (td, _) = eng.evaluate(&comp, comp.find_node("CCDark").unwrap(), 0.0);
2189 let pd = eng.readback_rgba(&td).unwrap();
2190 assert_eq!(pd[1], 0, "green below MasterGreenLow must map to 0: {:?}", &pd[..4]);
2191 }
2192
2193 #[test]
2194 fn color_gain_balance_before_additive_tonal_hue_and_process_channels() {
2195 // Matches Fusion ColorGain f11 behavior: MidRedCyan balance runs before additive tonal
2196 // DarkHue/MidHue/HighHue shifts, while ProcessRed=0 and ProcessBlue=0 keep source R/B.
2197 let comp_src = r#"{
2198 Tools = ordered() {
2199 Src = Background {
2200 Inputs = {
2201 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2202 TopLeftRed = Input { Value = 0.6157, },
2203 TopLeftGreen = Input { Value = 0.902, },
2204 TopLeftBlue = Input { Value = 0.3373, },
2205 TopLeftAlpha = Input { Value = 1.0, },
2206 },
2207 },
2208 CG = ColorGain {
2209 Inputs = {
2210 Input = Input { SourceOp = "Src", Source = "Output", },
2211 ProcessRed = Input { Value = 0, },
2212 ProcessBlue = Input { Value = 0, },
2213 GainGreen = Input { Value = 3.26722, },
2214 GammaGreen = Input { Value = 4.43987, },
2215 LiftRed = Input { Value = -0.26756, },
2216 MidRedCyan = Input { Value = -0.6691, },
2217 DarkHue = Input { Value = 0.70687, },
2218 MidHue = Input { Value = -0.5539, },
2219 HighHue = Input { Value = -0.51854, },
2220 },
2221 },
2222 }
2223 }"#;
2224 let comp = Comp::from_fusion_str(comp_src).expect("parse ColorGain balance+hue comp");
2225 let Ok(mut eng) = Engine::new_headless() else { return };
2226 let (t, _) = eng.evaluate(&comp, comp.find_node("CG").unwrap(), 0.0);
2227 let px = eng.readback_rgba(&t).unwrap();
2228 assert_eq!(px[0], 157, "ProcessRed=0 keeps source R=157");
2229 assert_eq!(px[2], 86, "ProcessBlue=0 keeps source B=86");
2230 // Fusion 21.1 GT at PlateA (64,64) = (157,230,86) gives G=46 (vs old broken G=105).
2231 assert_eq!(px[1], 46, "exact Fusion ColorGain G=46 after !HDR_FLOAT quantization, got {}", px[1]);
2232 }
2233}
2234