1//! Wave 36 — Color Science, `MatteControl` & `MultiMerge` GPU pipelines and evaluators:
2//! - `AcesTransform` (ACES 1.3 IDT/ODT: AP0, AP1/ACEScg, ACEScct, ACEScc, Linear sRGB, sRGB, Rec.709)
3//! - `ColorSpace` (RGB <-> BW, YUV, YIQ, CMY, HLS/HSL, HSV, XYZ, CIE-LAB, YCbCr)
4//! - `ColorMatrix` (5x4 RGBA color matrix + offset)
5//! - `WhiteBalance` (Kelvin temperature, tint, sampled white-point neutralization)
6//! - `MatteControl` (matte combine, contract/expand, blur, threshold, gamma, invert, garbage/solid, spill suppress, post-multiply)
7//! - `MultiMerge` & `Fuse.MultiMerge` (N-layer transform + blend composite reusing `ShaderOp::Merge`)
8//!
9//! WebGPU safety: all texture inputs use `TextureSampleType::Float { filterable: false }`
10//! (sampled via `textureLoad` / manual bilinear), outputs are `WriteOnly` storage textures,
11//! and uniform slots grow in 512-slot chunks reset via `Engine::reset_uniform_cursors()`.
12
13mod matte_merge;
14mod params;
15#[cfg(test)]
16mod tests;
17
18use super::*;
19use params::*;
20use std::num::NonZeroU64;
21
22const COLOR_SCIENCE_WGSL: &str = include_str!("../shaders/color_science.wgsl");
23const CS_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
24
25#[derive(Clone, Copy)]
26pub(self) enum ColorScienceOp {
27 AcesTransform,
28 ColorSpace,
29 ColorMatrix,
30 WhiteBalance,
31 MatteCombine,
32 MatteFinish,
33 BlendMask,
34}
35
36struct ColorScienceFormatPipelines {
37 bgl: wgpu::BindGroupLayout,
38 aces_transform: wgpu::ComputePipeline,
39 color_space: wgpu::ComputePipeline,
40 color_matrix: wgpu::ComputePipeline,
41 white_balance: wgpu::ComputePipeline,
42 matte_combine: wgpu::ComputePipeline,
43 matte_finish: wgpu::ComputePipeline,
44 blend_mask: wgpu::ComputePipeline,
45}
46
47impl ColorScienceFormatPipelines {
48 fn pipeline(&self, op: ColorScienceOp) -> &wgpu::ComputePipeline {
49 match op {
50 ColorScienceOp::AcesTransform => &self.aces_transform,
51 ColorScienceOp::ColorSpace => &self.color_space,
52 ColorScienceOp::ColorMatrix => &self.color_matrix,
53 ColorScienceOp::WhiteBalance => &self.white_balance,
54 ColorScienceOp::MatteCombine => &self.matte_combine,
55 ColorScienceOp::MatteFinish => &self.matte_finish,
56 ColorScienceOp::BlendMask => &self.blend_mask,
57 }
58 }
59}
60
61pub(super) struct ColorSciencePipelines {
62 uniform_stride: u32,
63 uniform_chunks: Vec<wgpu::Buffer>,
64 uniform_cursor: u32,
65 formats: HashMap<(wgpu::TextureFormat, bool), ColorScienceFormatPipelines>,
66}
67
68fn build_cs_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String {
69 let mut src = COLOR_SCIENCE_WGSL.to_owned();
70 let storage_fmt = match format {
71 wgpu::TextureFormat::Rgba16Float => "rgba16float",
72 wgpu::TextureFormat::Rgba32Float => "rgba32float",
73 _ => "rgba8unorm",
74 };
75 if storage_fmt != "rgba8unorm" {
76 src = src.replace(
77 "texture_storage_2d<rgba8unorm, write>",
78 &format!("texture_storage_2d<{storage_fmt}, write>"),
79 );
80 }
81 if hdr_float {
82 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
83 }
84 src
85}
86
87fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
88 wgpu::BindGroupLayoutEntry {
89 binding,
90 visibility: wgpu::ShaderStages::COMPUTE,
91 ty: wgpu::BindingType::Texture {
92 sample_type: wgpu::TextureSampleType::Float { filterable: false },
93 view_dimension: wgpu::TextureViewDimension::D2,
94 multisampled: false,
95 },
96 count: None,
97 }
98}
99
100impl ColorSciencePipelines {
101 pub(super) fn new(device: &wgpu::Device) -> Self {
102 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
103 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
104 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
105 Self {
106 uniform_stride,
107 uniform_chunks: Vec::new(),
108 uniform_cursor: 0,
109 formats: HashMap::new(),
110 }
111 }
112
113 pub(super) fn reset_uniform_cursor(&mut self) {
114 self.uniform_cursor = 0;
115 }
116
117 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
118 self.uniform_cursor = 0;
119 if self.uniform_chunks.len() > max_chunks {
120 self.uniform_chunks.truncate(max_chunks);
121 }
122 }
123
124 fn alloc_uniform_slot(
125 &mut self,
126 device: &wgpu::Device,
127 queue: &wgpu::Queue,
128 params: &UniformParams,
129 ) -> (usize, u32) {
130 let slot_global = self.uniform_cursor;
131 let chunk_idx = (slot_global / CS_UNIFORM_SLOTS_PER_CHUNK) as usize;
132 let slot_in_chunk = slot_global % CS_UNIFORM_SLOTS_PER_CHUNK;
133 while chunk_idx >= self.uniform_chunks.len() {
134 let size = u64::from(CS_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
135 let buf = device.create_buffer(&wgpu::BufferDescriptor {
136 label: Some("color-science-params-ring"),
137 size,
138 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
139 mapped_at_creation: false,
140 });
141 self.uniform_chunks.push(buf);
142 }
143 let offset = slot_in_chunk * self.uniform_stride;
144 queue.write_buffer(
145 &self.uniform_chunks[chunk_idx],
146 u64::from(offset),
147 bytemuck::bytes_of(params),
148 );
149 self.uniform_cursor = slot_global + 1;
150 (chunk_idx, offset)
151 }
152
153 fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
154 if self.formats.contains_key(&(format, hdr_float)) {
155 return;
156 }
157 let u_size = std::mem::size_of::<UniformParams>() as u64;
158 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
159 label: Some("color-science-bgl"),
160 entries: &[
161 unfilterable_tex_entry(0),
162 unfilterable_tex_entry(1),
163 unfilterable_tex_entry(2),
164 unfilterable_tex_entry(3),
165 wgpu::BindGroupLayoutEntry {
166 binding: 4,
167 visibility: wgpu::ShaderStages::COMPUTE,
168 ty: wgpu::BindingType::StorageTexture {
169 access: wgpu::StorageTextureAccess::WriteOnly,
170 format,
171 view_dimension: wgpu::TextureViewDimension::D2,
172 },
173 count: None,
174 },
175 wgpu::BindGroupLayoutEntry {
176 binding: 5,
177 visibility: wgpu::ShaderStages::COMPUTE,
178 ty: wgpu::BindingType::Buffer {
179 ty: wgpu::BufferBindingType::Uniform,
180 has_dynamic_offset: true,
181 min_binding_size: NonZeroU64::new(u_size),
182 },
183 count: None,
184 },
185 ],
186 });
187 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
188 label: Some("color-science-pl"),
189 bind_group_layouts: &[Some(&bgl)],
190 immediate_size: 0,
191 });
192 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
193 label: Some("color-science-wgsl"),
194 source: wgpu::ShaderSource::Wgsl(build_cs_wgsl(format, hdr_float).into()),
195 });
196 let mk = |entry: &str| {
197 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
198 label: Some(entry),
199 layout: Some(&pl),
200 module: &module,
201 entry_point: Some(entry),
202 compilation_options: Default::default(),
203 cache: None,
204 })
205 };
206 self.formats.insert(
207 (format, hdr_float),
208 ColorScienceFormatPipelines {
209 bgl,
210 aces_transform: mk("aces_transform_op"),
211 color_space: mk("color_space_op"),
212 color_matrix: mk("color_matrix_op"),
213 white_balance: mk("white_balance_op"),
214 matte_combine: mk("matte_combine_op"),
215 matte_finish: mk("matte_finish_op"),
216 blend_mask: mk("blend_mask_op"),
217 },
218 );
219 }
220
221 #[allow(clippy::too_many_arguments)]
222 fn dispatch(
223 &mut self,
224 device: &wgpu::Device,
225 queue: &wgpu::Queue,
226 enc: &mut wgpu::CommandEncoder,
227 op: ColorScienceOp,
228 views: [&wgpu::TextureView; 4],
229 dst: &CachedTexture,
230 params: &UniformParams,
231 ) {
232 let hdr_float = dst.depth.is_float();
233 self.ensure_format(device, dst.format, hdr_float);
234 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
235 let entry = &self.formats[&(dst.format, hdr_float)];
236 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
237 label: Some("color-science-bg"),
238 layout: &entry.bgl,
239 entries: &[
240 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(views[0]) },
241 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(views[1]) },
242 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(views[2]) },
243 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(views[3]) },
244 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) },
245 wgpu::BindGroupEntry {
246 binding: 5,
247 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
248 buffer: &self.uniform_chunks[chunk_idx],
249 offset: 0,
250 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
251 }),
252 },
253 ],
254 });
255 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
256 label: Some("color-science-pass"),
257 timestamp_writes: None,
258 });
259 pass.set_pipeline(entry.pipeline(op));
260 pass.set_bind_group(0, &bg, &[offset]);
261 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
262 }
263}
264
265impl Engine {
266 pub(super) fn color_science_pipelines(&self) -> &RefCell<ColorSciencePipelines> {
267 self.color_science_pipelines
268 .get_or_init(|| RefCell::new(ColorSciencePipelines::new(&self.device)))
269 }
270
271 #[allow(clippy::too_many_arguments)]
272 pub(self) fn dispatch_cs(
273 &self,
274 enc: &mut wgpu::CommandEncoder,
275 op: ColorScienceOp,
276 views: [&wgpu::TextureView; 4],
277 dst: &CachedTexture,
278 params: &UniformParams,
279 ) {
280 self.color_science_pipelines()
281 .borrow_mut()
282 .dispatch(&self.device, &self.queue, enc, op, views, dst, params);
283 }
284
285 /// 1. `AcesTransform` — ACES 1.3 IDT/ODT color transform with Bradford D60<->D65,
286 /// Reference Gamut Compression, and RRT+ODT display tone mapping.
287 #[allow(clippy::too_many_arguments)]
288 pub(super) fn eval_aces_transform(
289 &mut self,
290 comp: &Comp,
291 node: &Node,
292 time: f64,
293 frame_i: i64,
294 enc: &mut wgpu::CommandEncoder,
295 visiting: &mut HashSet<(NodeId, i64)>,
296 stats: &mut EvalStats,
297 ) -> CachedTexture {
298 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
299 return self.dummy.clone();
300 };
301 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
302 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
303 let mbm = self.multiplies_by_mask(comp, node, time);
304 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
305 if blend <= 1e-6 && !(mbm && has_mask) {
306 return src;
307 }
308 let in_space = parse_aces_space(comp, node, "InputTransform", time, &self.expr);
309 let out_space = parse_aces_space(comp, node, "OutputTransform", time, &self.expr);
310 let use_rgc = comp.eval_number(node, "ReferenceGamutCompress", time, 0.0, &self.expr) > 0.5;
311 let luminance = comp.eval_number(node, "Luminance", time, 100.0, &self.expr).clamp(10.0, 10000.0) as f32;
312
313 if in_space == AcesSpace::None && out_space == AcesSpace::None && !use_rgc && !(mbm && has_mask) {
314 return src;
315 }
316
317 let eff_in = if in_space == AcesSpace::None { AcesSpace::Aces2065_1 } else { in_space };
318 let eff_out = if out_space == AcesSpace::None { AcesSpace::Aces2065_1 } else { out_space };
319 let use_rrt = matches!(out_space, AcesSpace::Srgb | AcesSpace::Rec709);
320
321 let (m1, m2) = if use_rgc || use_rrt {
322 (
323 rgb_to_rgb_bradford(eff_in.primaries(), AP1_P),
324 rgb_to_rgb_bradford(AP1_P, eff_out.primaries()),
325 )
326 } else {
327 (
328 rgb_to_rgb_bradford(eff_in.primaries(), eff_out.primaries()),
329 [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
330 )
331 };
332
333 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
334 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
335 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
336 let skip = self.process_skip(comp, node, time);
337
338 let mut u = UniformParams::default();
339 u.p[0] = [
340 eff_in.transfer_id(),
341 eff_out.transfer_id(),
342 if use_rgc { 1.0 } else { 0.0 },
343 if use_rrt { 1.0 } else { 0.0 },
344 ];
345 u.p[1] = [100.0 / luminance, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
346 u.p[2] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
347 u.p[3] = skip;
348 u.p[4] = [m1[0][0], m1[0][1], m1[0][2], 0.0];
349 u.p[5] = [m1[1][0], m1[1][1], m1[1][2], 0.0];
350 u.p[6] = [m1[2][0], m1[2][1], m1[2][2], 0.0];
351 u.p[7] = [m2[0][0], m2[0][1], m2[0][2], 0.0];
352 u.p[8] = [m2[1][0], m2[1][1], m2[1][2], 0.0];
353 u.p[9] = [m2[2][0], m2[2][1], m2[2][2], 0.0];
354
355 let key = self.make_key(node, "AcesTransform", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10]));
356 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
357 stats.cache_hits += 1;
358 return hit;
359 }
360 stats.cache_misses += 1;
361 stats.nodes_evaluated += 1;
362
363 let mut dst = self.alloc_tex_like(&src, src.depth, key);
364 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
365 self.dispatch_cs(enc, ColorScienceOp::AcesTransform, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u);
366 if src.aux.is_some() {
367 dst.set_aux(src.aux.clone());
368 }
369 self.cache.insert(key, dst.clone(), node.id, frame_i);
370 dst
371 }
372
373 /// 2. `ColorSpace` — RGB <-> BW / YUV / YIQ / CMY / HLS / HSV / XYZ / CIE-LAB / YCbCr.
374 #[allow(clippy::too_many_arguments)]
375 pub(super) fn eval_color_space(
376 &mut self,
377 comp: &Comp,
378 node: &Node,
379 time: f64,
380 frame_i: i64,
381 enc: &mut wgpu::CommandEncoder,
382 visiting: &mut HashSet<(NodeId, i64)>,
383 stats: &mut EvalStats,
384 ) -> CachedTexture {
385 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
386 return self.dummy.clone();
387 };
388 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
389 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
390 let mbm = self.multiplies_by_mask(comp, node, time);
391 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
392 let conv_dir = parse_color_space_dir(comp, node, time, &self.expr);
393 let color_type = parse_color_type(comp, node, time, &self.expr);
394 let dst_depth = self.node_depth(comp, node, time, Some(src.depth));
395
396 if (blend <= 1e-6 || conv_dir == 0) && dst_depth == src.depth && !(mbm && has_mask) {
397 return src;
398 }
399
400 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
401 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
402 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
403 let skip = self.process_skip(comp, node, time);
404
405 let mut u = UniformParams::default();
406 u.p[0] = [conv_dir as f32, color_type as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }];
407 u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, dst_depth as u32 as f32, 0.0];
408 u.p[2] = skip;
409
410 let key = self.make_key(node, "ColorSpace", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
411 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
412 stats.cache_hits += 1;
413 return hit;
414 }
415 stats.cache_misses += 1;
416 stats.nodes_evaluated += 1;
417
418 let mut dst = self.alloc_tex_like(&src, dst_depth, key);
419 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
420 self.dispatch_cs(enc, ColorScienceOp::ColorSpace, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u);
421 if src.aux.is_some() {
422 dst.set_aux(src.aux.clone());
423 }
424 self.cache.insert(key, dst.clone(), node.id, frame_i);
425 dst
426 }
427
428 /// 3. `ColorMatrix` — 5x4 RGBA color matrix + offset.
429 #[allow(clippy::too_many_arguments)]
430 pub(super) fn eval_color_matrix(
431 &mut self,
432 comp: &Comp,
433 node: &Node,
434 time: f64,
435 frame_i: i64,
436 enc: &mut wgpu::CommandEncoder,
437 visiting: &mut HashSet<(NodeId, i64)>,
438 stats: &mut EvalStats,
439 ) -> CachedTexture {
440 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
441 return self.dummy.clone();
442 };
443 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
444 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
445 let mbm = self.multiplies_by_mask(comp, node, time);
446 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
447 if blend <= 1e-6 && !(mbm && has_mask) {
448 return src;
449 }
450
451 let (mat, off) = read_color_matrix(comp, node, time, &self.expr);
452 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
453 let clip_b = comp.eval_number(node, "ClipBlack", time, 0.0, &self.expr) as f32;
454 let clip_w = comp.eval_number(node, "ClipWhite", time, 0.0, &self.expr) as f32;
455
456 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
457 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
458 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
459 let skip = self.process_skip(comp, node, time);
460
461 let mut u = UniformParams::default();
462 u.p[0] = mat[0];
463 u.p[1] = mat[1];
464 u.p[2] = mat[2];
465 u.p[3] = mat[3];
466 u.p[4] = off;
467 u.p[5] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
468 u.p[6] = [if mbm { 1.0 } else { 0.0 }, clip_b, clip_w, 0.0];
469 u.p[7] = skip;
470
471 let key = self.make_key(node, "ColorMatrix", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..8]));
472 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
473 stats.cache_hits += 1;
474 return hit;
475 }
476 stats.cache_misses += 1;
477 stats.nodes_evaluated += 1;
478
479 let mut dst = self.alloc_tex_like(&src, src.depth, key);
480 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
481 self.dispatch_cs(enc, ColorScienceOp::ColorMatrix, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u);
482 if src.aux.is_some() {
483 dst.set_aux(src.aux.clone());
484 }
485 self.cache.insert(key, dst.clone(), node.id, frame_i);
486 dst
487 }
488
489 /// 4. `WhiteBalance` — Kelvin / relative temperature, tint, and sampled white-point gains.
490 #[allow(clippy::too_many_arguments)]
491 pub(super) fn eval_white_balance(
492 &mut self,
493 comp: &Comp,
494 node: &Node,
495 time: f64,
496 frame_i: i64,
497 enc: &mut wgpu::CommandEncoder,
498 visiting: &mut HashSet<(NodeId, i64)>,
499 stats: &mut EvalStats,
500 ) -> CachedTexture {
501 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
502 return self.dummy.clone();
503 };
504 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
505 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
506 let mbm = self.multiplies_by_mask(comp, node, time);
507 let has_mask = Self::resolve_effect_mask_id(comp, node).is_some();
508 if blend <= 1e-6 && !(mbm && has_mask) {
509 return src;
510 }
511
512 let temp_raw = if node.inputs.contains_key("Temperature") {
513 comp.eval_number(node, "Temperature", time, 0.0, &self.expr)
514 } else {
515 comp.eval_number(node, "ColorTemperature", time, 0.0, &self.expr)
516 };
517 let kelvin = if temp_raw > 100.0 {
518 temp_raw.clamp(1667.0, 25000.0)
519 } else {
520 6500.0 * 2.0_f64.powf(temp_raw.clamp(-2.5, 2.5))
521 };
522 let w_ref = kelvin_to_srgb_white(6500.0);
523 let w_cur = kelvin_to_srgb_white(kelvin);
524 let tint = comp.eval_number(node, "Tint", time, 0.0, &self.expr).clamp(-2.0, 2.0);
525 let tint_g = 2.0_f64.powf(-tint * 0.5);
526
527 let mut gain = [w_ref[0] / w_cur[0], (w_ref[1] / w_cur[1]) * tint_g, w_ref[2] / w_cur[2]];
528 let read_opt = |keys: &[&str], def: f64| -> f64 {
529 for &k in keys {
530 if node.inputs.contains_key(k) {
531 return comp.eval_number(node, k, time, def, &self.expr);
532 }
533 }
534 def
535 };
536 let lock_ref = comp.eval_number(node, "LockReference", time, 1.0, &self.expr) > 0.5;
537 let rr = read_opt(&["ReferenceRed", "RefRed", "BalanceRed"], 1.0).max(1e-4);
538 let rg = read_opt(&["ReferenceGreen", "RefGreen", "BalanceGreen"], 1.0).max(1e-4);
539 let rb = read_opt(&["ReferenceBlue", "RefBlue", "BalanceBlue"], 1.0).max(1e-4);
540
541 const LUMA: [f64; 3] = [0.2126, 0.7152, 0.0722];
542 let ref_luma = rr * LUMA[0] + rg * LUMA[1] + rb * LUMA[2];
543 if lock_ref {
544 gain[0] *= ref_luma / rr;
545 gain[1] *= ref_luma / rg;
546 gain[2] *= ref_luma / rb;
547 } else {
548 let tr = read_opt(&["TargetRed", "WhiteRed"], 1.0).max(1e-4);
549 let tg = read_opt(&["TargetGreen", "WhiteGreen"], 1.0).max(1e-4);
550 let tb = read_opt(&["TargetBlue", "WhiteBlue"], 1.0).max(1e-4);
551 gain[0] *= tr / rr;
552 gain[1] *= tg / rg;
553 gain[2] *= tb / rb;
554 }
555 let g_luma = (gain[0] * LUMA[0] + gain[1] * LUMA[1] + gain[2] * LUMA[2]).max(1e-5);
556 let gain_f32 = [(gain[0] / g_luma) as f32, (gain[1] / g_luma) as f32, (gain[2] / g_luma) as f32];
557
558 let gamut_str = node.static_str("Gamut").or_else(|| node.static_str("ColorSpace")).unwrap_or("");
559 let gamma_mode = match gamut_str.to_ascii_lowercase().replace(['.', ' ', '_'], "").as_str() {
560 "srgb" => 1.0_f32,
561 "rec709" => 2.0_f32,
562 _ => 0.0_f32,
563 };
564 let prediv = comp.eval_number(node, "PreDividePostMultiply", time, 0.0, &self.expr) as f32;
565
566 let src = if has_mask { self.crop_to_canvas(enc, src) } else { src };
567 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
568 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
569 let skip = self.process_skip(comp, node, time);
570
571 let mut u = UniformParams::default();
572 u.p[0] = [gain_f32[0], gain_f32[1], gain_f32[2], gamma_mode];
573 u.p[1] = [prediv, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
574 u.p[2] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
575 u.p[3] = skip;
576
577 let key = self.make_key(node, "WhiteBalance", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
578 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
579 stats.cache_hits += 1;
580 return hit;
581 }
582 stats.cache_misses += 1;
583 stats.nodes_evaluated += 1;
584
585 let mut dst = self.alloc_tex_like(&src, src.depth, key);
586 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
587 self.dispatch_cs(enc, ColorScienceOp::WhiteBalance, [&src.view, &self.dummy.view, &self.dummy.view, mv], &dst, &u);
588 if src.aux.is_some() {
589 dst.set_aux(src.aux.clone());
590 }
591 self.cache.insert(key, dst.clone(), node.id, frame_i);
592 dst
593 }
594}