authoravatarclover caruso<git@paperclover.net>2026-12-02 14:00:48-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-02 15:22:33-08:00
log15015e645a39282908398af9f08617c77deddbd6
tree39246ea5ae1f05f15c6763a42180872529c7ca1a
parent6bd39bafcfd2edfffc5eda4bddcc14cc6382ca92
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(engine): implement 14 OCIO, Layer, Metadata, MultiText & Utility built-ins

Assisted-by: claude-sonnet-5.5

15 files changed, 2295 insertions(+), 49 deletions(-)

crates/engine/src/eval/color_lut.rs+5-5
...@@ -6,8 +6,8 @@...@@ -6,8 +6,8 @@
6//! `textureLoad`, outputs are `WriteOnly` storage textures, and 3D LUTs are packed6//! `textureLoad`, outputs are `WriteOnly` storage textures, and 3D LUTs are packed
7//! into 2D `Rgba32Float` textures for 100% WebGPU / `wasm32` parity.7//! into 2D `Rgba32Float` textures for 100% WebGPU / `wasm32` parity.
88
9mod color_fx;9pub(in crate::eval) mod color_fx;
10mod colorimetry;10pub(in crate::eval) mod colorimetry;
11mod cst_gamut;11mod cst_gamut;
12mod film_look;12mod film_look;
13pub mod lut_io;13pub mod lut_io;
...@@ -23,7 +23,7 @@ const COLOR_LUT_WGSL: &str = include_str!("../shaders/color_lut.wgsl");...@@ -23,7 +23,7 @@ const COLOR_LUT_WGSL: &str = include_str!("../shaders/color_lut.wgsl");
23const CL_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;23const CL_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
2424
25#[derive(Clone, Copy)]25#[derive(Clone, Copy)]
26pub(self) enum ColorLutOp {26pub(in crate::eval) enum ColorLutOp {
27 ColorMatrix,27 ColorMatrix,
28 SetCanvasColor,28 SetCanvasColor,
29 ChromaticAdaptation,29 ChromaticAdaptation,
...@@ -182,7 +182,7 @@ impl ColorLutPipelines {...@@ -182,7 +182,7 @@ impl ColorLutPipelines {
182 (chunk_idx, offset)182 (chunk_idx, offset)
183 }183 }
184184
185 pub(self) fn get_or_upload_lut_rgba32f(185 pub(in crate::eval) fn get_or_upload_lut_rgba32f(
186 &mut self,186 &mut self,
187 device: &wgpu::Device,187 device: &wgpu::Device,
188 queue: &wgpu::Queue,188 queue: &wgpu::Queue,
...@@ -355,7 +355,7 @@ impl Engine {...@@ -355,7 +355,7 @@ impl Engine {
355 }355 }
356356
357 #[allow(clippy::too_many_arguments)]357 #[allow(clippy::too_many_arguments)]
358 pub(self) fn dispatch_cl(358 pub(in crate::eval) fn dispatch_cl(
359 &self,359 &self,
360 enc: &mut wgpu::CommandEncoder,360 enc: &mut wgpu::CommandEncoder,
361 op: ColorLutOp,361 op: ColorLutOp,
crates/engine/src/eval/color_lut/color_fx.rs+1-1
...@@ -196,7 +196,7 @@ fn parse_cdl_triplet(s: &str, def: [f32; 3]) -> [f32; 3] {...@@ -196,7 +196,7 @@ fn parse_cdl_triplet(s: &str, def: [f32; 3]) -> [f32; 3] {
196 }196 }
197}197}
198198
199pub(super) fn parse_cdl_xml(199pub(in crate::eval) fn parse_cdl_xml(
200 text: &str,200 text: &str,
201 ccc_id: &str,201 ccc_id: &str,
202) -> Option<([f32; 3], [f32; 3], [f32; 3], f32)> {202) -> Option<([f32; 3], [f32; 3], [f32; 3], f32)> {
crates/engine/src/eval/color_lut/colorimetry.rs+39-39
...@@ -3,33 +3,33 @@...@@ -3,33 +3,33 @@
33
4use model::{Comp, ExprEngine, Node};4use model::{Comp, ExprEngine, Node};
55
6pub(super) const D60: [f64; 2] = [0.32168, 0.33767];6pub(in crate::eval) const D60: [f64; 2] = [0.32168, 0.33767];
7pub(super) const D65: [f64; 2] = [0.3127, 0.3290];7pub(in crate::eval) const D65: [f64; 2] = [0.3127, 0.3290];
8pub(super) const D50: [f64; 2] = [0.34567, 0.35850];8pub(in crate::eval) const D50: [f64; 2] = [0.34567, 0.35850];
9pub(super) const DCI_W: [f64; 2] = [0.3140, 0.3510];9pub(in crate::eval) const DCI_W: [f64; 2] = [0.3140, 0.3510];
1010
11pub(super) type Primaries = [[f64; 2]; 4];11pub(in crate::eval) type Primaries = [[f64; 2]; 4];
1212
13pub(super) const P_REC709: Primaries = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65];13pub(in crate::eval) const P_REC709: Primaries = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65];
14pub(super) const P_REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65];14pub(in crate::eval) const P_REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65];
15pub(super) const P_P3_D65: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65];15pub(in crate::eval) const P_P3_D65: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65];
16pub(super) const P_P3_D60: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D60];16pub(in crate::eval) const P_P3_D60: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D60];
17pub(super) const P_P3_DCI: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], DCI_W];17pub(in crate::eval) const P_P3_DCI: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], DCI_W];
18pub(super) const P_AP0: Primaries = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], D60];18pub(in crate::eval) const P_AP0: Primaries = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], D60];
19pub(super) const P_AP1: Primaries = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60];19pub(in crate::eval) const P_AP1: Primaries = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60];
20pub(super) const P_DWG: Primaries = [[0.8000, 0.3130], [0.1682, 0.9877], [0.0790, -0.1155], D65];20pub(in crate::eval) const P_DWG: Primaries = [[0.8000, 0.3130], [0.1682, 0.9877], [0.0790, -0.1155], D65];
21pub(super) const P_AWG3: Primaries = [[0.6840, 0.3130], [0.2210, 0.8480], [0.0861, -0.1020], D65];21pub(in crate::eval) const P_AWG3: Primaries = [[0.6840, 0.3130], [0.2210, 0.8480], [0.0861, -0.1020], D65];
22pub(super) const P_AWG4: Primaries = [[0.7347, 0.2653], [0.1424, 0.8576], [0.0991, -0.0308], D65];22pub(in crate::eval) const P_AWG4: Primaries = [[0.7347, 0.2653], [0.1424, 0.8576], [0.0991, -0.0308], D65];
23pub(super) const P_SGAMUT3: Primaries = [[0.730, 0.280], [0.140, 0.855], [0.100, -0.050], D65];23pub(in crate::eval) const P_SGAMUT3: Primaries = [[0.730, 0.280], [0.140, 0.855], [0.100, -0.050], D65];
24pub(super) const P_SGAMUT3_CINE: Primaries = [[0.766, 0.275], [0.225, 0.800], [0.089, -0.087], D65];24pub(in crate::eval) const P_SGAMUT3_CINE: Primaries = [[0.766, 0.275], [0.225, 0.800], [0.089, -0.087], D65];
25pub(super) const P_RWG: Primaries = [[0.780308, 0.304253], [0.121595, 1.493994], [0.095612, -0.084589], D65];25pub(in crate::eval) const P_RWG: Primaries = [[0.780308, 0.304253], [0.121595, 1.493994], [0.095612, -0.084589], D65];
26pub(super) const P_ADOBE: Primaries = [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06], D65];26pub(in crate::eval) const P_ADOBE: Primaries = [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06], D65];
27pub(super) const P_VGAMUT: Primaries = [[0.730, 0.280], [0.165, 0.840], [0.100, -0.030], D65];27pub(in crate::eval) const P_VGAMUT: Primaries = [[0.730, 0.280], [0.165, 0.840], [0.100, -0.030], D65];
28pub(super) const P_CGAMUT: Primaries = [[0.740, 0.270], [0.170, 1.140], [0.080, -0.100], D65];28pub(in crate::eval) const P_CGAMUT: Primaries = [[0.740, 0.270], [0.170, 1.140], [0.080, -0.100], D65];
29pub(super) const P_BMDWG5: Primaries = [[0.7177215, 0.3171181], [0.2280410, 0.8615690], [0.1005841, -0.0820452], D65];29pub(in crate::eval) const P_BMDWG5: Primaries = [[0.7177215, 0.3171181], [0.2280410, 0.8615690], [0.1005841, -0.0820452], D65];
3030
31#[derive(Clone, Copy, PartialEq, Eq)]31#[derive(Clone, Copy, PartialEq, Eq)]
32pub(super) enum CatMethod {32pub(in crate::eval) enum CatMethod {
33 Bradford,33 Bradford,
34 Cat02,34 Cat02,
35 VonKries,35 VonKries,
...@@ -39,7 +39,7 @@ pub(super) enum CatMethod {...@@ -39,7 +39,7 @@ pub(super) enum CatMethod {
39}39}
4040
41impl CatMethod {41impl CatMethod {
42 pub(super) fn matrix(self) -> [[f64; 3]; 3] {42 pub(in crate::eval) fn matrix(self) -> [[f64; 3]; 3] {
43 match self {43 match self {
44 Self::Bradford => [44 Self::Bradford => [
45 [0.8951, 0.2664, -0.1614],45 [0.8951, 0.2664, -0.1614],
...@@ -71,7 +71,7 @@ impl CatMethod {...@@ -71,7 +71,7 @@ impl CatMethod {
71 }71 }
72}72}
7373
74pub(super) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {74pub(in crate::eval) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
75 let [a, b, c] = m[0];75 let [a, b, c] = m[0];
76 let [d, e, f] = m[1];76 let [d, e, f] = m[1];
77 let [g, h, i] = m[2];77 let [g, h, i] = m[2];
...@@ -84,15 +84,15 @@ pub(super) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {...@@ -84,15 +84,15 @@ pub(super) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
84 ]84 ]
85}85}
8686
87pub(super) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {87pub(in crate::eval) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
88 std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum()))88 std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum()))
89}89}
9090
91pub(super) fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {91pub(in crate::eval) fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] {
92 std::array::from_fn(|r| (0..3).map(|c| m[r][c] * v[c]).sum())92 std::array::from_fn(|r| (0..3).map(|c| m[r][c] * v[c]).sum())
93}93}
9494
95pub(super) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> {95pub(in crate::eval) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> {
96 let mut a = [[0.0_f64; 8]; 4];96 let mut a = [[0.0_f64; 8]; 4];
97 for r in 0..4 {97 for r in 0..4 {
98 for c in 0..4 {98 for c in 0..4 {
...@@ -127,19 +127,19 @@ pub(super) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> {...@@ -127,19 +127,19 @@ pub(super) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> {
127 Some(std::array::from_fn(|r| std::array::from_fn(|c| a[r][4 + c])))127 Some(std::array::from_fn(|r| std::array::from_fn(|c| a[r][4 + c])))
128}128}
129129
130pub(super) fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] {130pub(in crate::eval) fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] {
131 let y = xy[1].max(1e-6);131 let y = xy[1].max(1e-6);
132 [xy[0] / y, 1.0, (1.0 - xy[0] - xy[1]) / y]132 [xy[0] / y, 1.0, (1.0 - xy[0] - xy[1]) / y]
133}133}
134134
135pub(super) fn primaries_to_xyz(p: Primaries) -> [[f64; 3]; 3] {135pub(in crate::eval) fn primaries_to_xyz(p: Primaries) -> [[f64; 3]; 3] {
136 let [xr, xg, xb, xw] = [xy_to_xyz(p[0]), xy_to_xyz(p[1]), xy_to_xyz(p[2]), xy_to_xyz(p[3])];136 let [xr, xg, xb, xw] = [xy_to_xyz(p[0]), xy_to_xyz(p[1]), xy_to_xyz(p[2]), xy_to_xyz(p[3])];
137 let base = [[xr[0], xg[0], xb[0]], [xr[1], xg[1], xb[1]], [xr[2], xg[2], xb[2]]];137 let base = [[xr[0], xg[0], xb[0]], [xr[1], xg[1], xb[1]], [xr[2], xg[2], xb[2]]];
138 let s = mat3_vec(mat3_inv(base), xw);138 let s = mat3_vec(mat3_inv(base), xw);
139 std::array::from_fn(|r| std::array::from_fn(|c| base[r][c] * s[c]))139 std::array::from_fn(|r| std::array::from_fn(|c| base[r][c] * s[c]))
140}140}
141141
142pub(super) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMethod) -> [[f64; 3]; 3] {142pub(in crate::eval) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMethod) -> [[f64; 3]; 3] {
143 if (src_wp[0] - dst_wp[0]).abs() <= 1e-7 && (src_wp[1] - dst_wp[1]).abs() <= 1e-7 {143 if (src_wp[0] - dst_wp[0]).abs() <= 1e-7 && (src_wp[1] - dst_wp[1]).abs() <= 1e-7 {
144 return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];144 return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
145 }145 }
...@@ -154,7 +154,7 @@ pub(super) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMeth...@@ -154,7 +154,7 @@ pub(super) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMeth
154 mat3_mul(mat3_inv(m_cat), mat3_mul(diag, m_cat))154 mat3_mul(mat3_inv(m_cat), mat3_mul(diag, m_cat))
155}155}
156156
157pub(super) fn rgb_to_rgb_matrix(157pub(in crate::eval) fn rgb_to_rgb_matrix(
158 src: Option<Primaries>,158 src: Option<Primaries>,
159 dst: Option<Primaries>,159 dst: Option<Primaries>,
160 white_adapt: bool,160 white_adapt: bool,
...@@ -183,7 +183,7 @@ pub(super) fn rgb_to_rgb_matrix(...@@ -183,7 +183,7 @@ pub(super) fn rgb_to_rgb_matrix(
183}183}
184184
185/// Kang et al. (2002) Planckian locus chromaticity `xy(T)` for `1667K..50000K` + green-magenta tint.185/// Kang et al. (2002) Planckian locus chromaticity `xy(T)` for `1667K..50000K` + green-magenta tint.
186pub(super) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] {186pub(in crate::eval) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] {
187 let t = kelvin.clamp(1667.0, 25000.0);187 let t = kelvin.clamp(1667.0, 25000.0);
188 let x = if t <= 4000.0 {188 let x = if t <= 4000.0 {
189 -0.2661239e9 / (t * t * t) - 0.2343589e6 / (t * t) + 0.8776956e3 / t + 0.179910189 -0.2661239e9 / (t * t * t) - 0.2343589e6 / (t * t) + 0.8776956e3 / t + 0.179910
...@@ -202,7 +202,7 @@ pub(super) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] {...@@ -202,7 +202,7 @@ pub(super) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] {
202 [x.clamp(0.05, 0.75), (y + duv).clamp(0.05, 0.75)]202 [x.clamp(0.05, 0.75), (y + duv).clamp(0.05, 0.75)]
203}203}
204204
205pub(super) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> {205pub(in crate::eval) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> {
206 let s: String = raw206 let s: String = raw
207 .to_ascii_lowercase()207 .to_ascii_lowercase()
208 .chars()208 .chars()
...@@ -236,7 +236,7 @@ pub(super) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> {...@@ -236,7 +236,7 @@ pub(super) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> {
236 }236 }
237}237}
238238
239pub(super) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> CatMethod {239pub(in crate::eval) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> CatMethod {
240 if let Some(raw) = node.static_str("CATMethod").or_else(|| node.static_str("Method")) {240 if let Some(raw) = node.static_str("CATMethod").or_else(|| node.static_str("Method")) {
241 let s: String = raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();241 let s: String = raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
242 if s.contains("bradford") { return CatMethod::Bradford; }242 if s.contains("bradford") { return CatMethod::Bradford; }
...@@ -258,7 +258,7 @@ pub(super) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprE...@@ -258,7 +258,7 @@ pub(super) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprE
258}258}
259259
260/// Returns `Some(Primaries)` for RGB spaces, or `None` for CIE XYZ.260/// Returns `Some(Primaries)` for RGB spaces, or `None` for CIE XYZ.
261pub(super) fn parse_color_space(raw: Option<&str>) -> Option<Primaries> {261pub(in crate::eval) fn parse_color_space(raw: Option<&str>) -> Option<Primaries> {
262 let s_raw = raw.unwrap_or("REC709_COLORSPACE");262 let s_raw = raw.unwrap_or("REC709_COLORSPACE");
263 let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();263 let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
264 let s = s.strip_suffix("colorspace").unwrap_or(&s);264 let s = s.strip_suffix("colorspace").unwrap_or(&s);
...@@ -319,7 +319,7 @@ pub(super) fn parse_color_space(raw: Option<&str>) -> Option<Primaries> {...@@ -319,7 +319,7 @@ pub(super) fn parse_color_space(raw: Option<&str>) -> Option<Primaries> {
319 Some(P_REC709)319 Some(P_REC709)
320}320}
321321
322pub(super) fn parse_gamma_id(raw: Option<&str>) -> i32 {322pub(in crate::eval) fn parse_gamma_id(raw: Option<&str>) -> i32 {
323 let s_raw = raw.unwrap_or("LINEAR_GAMMA");323 let s_raw = raw.unwrap_or("LINEAR_GAMMA");
324 let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();324 let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
325 let s = s.strip_suffix("gamma").unwrap_or(&s);325 let s = s.strip_suffix("gamma").unwrap_or(&s);
...@@ -392,7 +392,7 @@ pub(super) fn parse_gamma_id(raw: Option<&str>) -> i32 {...@@ -392,7 +392,7 @@ pub(super) fn parse_gamma_id(raw: Option<&str>) -> i32 {
392 0392 0
393}393}
394394
395pub(super) fn parse_tm_mode(raw: Option<&str>) -> i32 {395pub(in crate::eval) fn parse_tm_mode(raw: Option<&str>) -> i32 {
396 let s: String = raw.unwrap_or("TM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();396 let s: String = raw.unwrap_or("TM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
397 match s.as_str() {397 match s.as_str() {
398 "tmclip" | "clip" => 1,398 "tmclip" | "clip" => 1,
...@@ -403,7 +403,7 @@ pub(super) fn parse_tm_mode(raw: Option<&str>) -> i32 {...@@ -403,7 +403,7 @@ pub(super) fn parse_tm_mode(raw: Option<&str>) -> i32 {
403 }403 }
404}404}
405405
406pub(super) fn parse_gm_mode(raw: Option<&str>) -> i32 {406pub(in crate::eval) fn parse_gm_mode(raw: Option<&str>) -> i32 {
407 let s: String = raw.unwrap_or("GM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();407 let s: String = raw.unwrap_or("GM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
408 match s.as_str() {408 match s.as_str() {
409 "gmrcm1" | "saturationcompression" | "compress" | "aces" => 1,409 "gmrcm1" | "saturationcompression" | "compress" | "aces" => 1,
crates/engine/src/eval/color_lut/lut_io.rs+1-1
...@@ -17,7 +17,7 @@ pub struct ParsedLut {...@@ -17,7 +17,7 @@ pub struct ParsedLut {
17 pub content_hash: u64,17 pub content_hash: u64,
18}18}
1919
20fn hash_lut_data(is_3d: bool, size: u32, dmin: [f32; 3], dmax: [f32; 3], rgba: &[f32]) -> u64 {20pub(in crate::eval) fn hash_lut_data(is_3d: bool, size: u32, dmin: [f32; 3], dmax: [f32; 3], rgba: &[f32]) -> u64 {
21 let mut h = DefaultHasher::new();21 let mut h = DefaultHasher::new();
22 "ParsedLut".hash(&mut h);22 "ParsedLut".hash(&mut h);
23 is_3d.hash(&mut h);23 is_3d.hash(&mut h);
crates/engine/src/eval/layer_ocio.rs created+318
...@@ -0,0 +1,318 @@
1//! OCIO, Layer, Metadata, Generator & Utility built-ins:
2//! - `OCIOColorSpace`, `OCIODisplay`, `OCIOFileTransform`
3//! - `LayerMuxer`, `LayerRegex`, `LayerRemover`, `Swizzler`
4//! - `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC`, `Dummy`
5//! - `MultiText`, `Fields`, `KeyStretcher`, `ChromaticAberrationRemoval`
6//!
7//! Colour tools reuse the `color_lut` colorimetry, transfer-curve and LUT/CDL pipelines; the ops
8//! with no existing equivalent live in `layer_ocio.wgsl` (`filterable: false` + `textureLoad`,
9//! WriteOnly storage output patched per format, no `read_write` storage textures).
10
11mod file_transform;
12mod layers;
13mod ocio;
14mod pattern;
15mod swizzle_fields;
16#[cfg(test)]
17mod tests;
18mod utility;
19
20use super::*;
21use std::num::NonZeroU64;
22
23const LAYER_OCIO_WGSL: &str = include_str!("../shaders/layer_ocio.wgsl");
24const LO_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
25const ENTRY_POINTS: [&str; 4] = ["ocio_display_op", "swizzler_op", "fields_op", "chroma_aberration_op"];
26
27#[derive(Clone, Copy)]
28enum LayerOcioOp {
29 OcioDisplay,
30 Swizzler,
31 Fields,
32 ChromaAberration,
33}
34
35struct LayerOcioFormatPipelines {
36 bgl: wgpu::BindGroupLayout,
37 ops: [wgpu::ComputePipeline; ENTRY_POINTS.len()],
38}
39
40pub(crate) struct LayerOcioPipelines {
41 uniform_stride: u32,
42 uniform_chunks: Vec<wgpu::Buffer>,
43 uniform_cursor: u32,
44 by_format: HashMap<(wgpu::TextureFormat, bool), LayerOcioFormatPipelines>,
45}
46
47fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
48 wgpu::BindGroupLayoutEntry {
49 binding,
50 visibility: wgpu::ShaderStages::COMPUTE,
51 ty: wgpu::BindingType::Texture {
52 sample_type: wgpu::TextureSampleType::Float { filterable: false },
53 view_dimension: wgpu::TextureViewDimension::D2,
54 multisampled: false,
55 },
56 count: None,
57 }
58}
59
60fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String {
61 let storage_fmt = match format {
62 wgpu::TextureFormat::Rgba16Float => "rgba16float",
63 wgpu::TextureFormat::Rgba32Float => "rgba32float",
64 _ => "rgba8unorm",
65 };
66 let mut src = LAYER_OCIO_WGSL.replace(
67 "texture_storage_2d<rgba8unorm, write>",
68 &format!("texture_storage_2d<{storage_fmt}, write>"),
69 );
70 if hdr_float {
71 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
72 }
73 src
74}
75
76impl LayerOcioPipelines {
77 pub(super) fn new(device: &wgpu::Device) -> Self {
78 let uniform_size = std::mem::size_of::<UniformParams>() as u32;
79 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
80 Self {
81 uniform_stride: uniform_size.div_ceil(min_align) * min_align,
82 uniform_chunks: Vec::new(),
83 uniform_cursor: 0,
84 by_format: HashMap::new(),
85 }
86 }
87
88 pub(super) fn reset_uniform_cursor(&mut self) {
89 self.uniform_cursor = 0;
90 }
91
92 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
93 self.uniform_cursor = 0;
94 self.uniform_chunks.truncate(max_chunks);
95 }
96
97 fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) {
98 let slot = self.uniform_cursor;
99 let chunk_idx = (slot / LO_UNIFORM_SLOTS_PER_CHUNK) as usize;
100 while chunk_idx >= self.uniform_chunks.len() {
101 self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor {
102 label: Some("layer-ocio-params-ring"),
103 size: u64::from(LO_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride),
104 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
105 mapped_at_creation: false,
106 }));
107 }
108 let offset = (slot % LO_UNIFORM_SLOTS_PER_CHUNK) * self.uniform_stride;
109 queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params));
110 self.uniform_cursor = slot + 1;
111 (chunk_idx, offset)
112 }
113
114 fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) {
115 if self.by_format.contains_key(&(format, hdr_float)) {
116 return;
117 }
118 let u_size = std::mem::size_of::<UniformParams>() as u64;
119 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
120 label: Some("layer-ocio-bgl"),
121 entries: &[
122 unfilterable_tex_entry(0),
123 unfilterable_tex_entry(1),
124 unfilterable_tex_entry(2),
125 unfilterable_tex_entry(3),
126 wgpu::BindGroupLayoutEntry {
127 binding: 4,
128 visibility: wgpu::ShaderStages::COMPUTE,
129 ty: wgpu::BindingType::StorageTexture {
130 access: wgpu::StorageTextureAccess::WriteOnly,
131 format,
132 view_dimension: wgpu::TextureViewDimension::D2,
133 },
134 count: None,
135 },
136 wgpu::BindGroupLayoutEntry {
137 binding: 5,
138 visibility: wgpu::ShaderStages::COMPUTE,
139 ty: wgpu::BindingType::Buffer {
140 ty: wgpu::BufferBindingType::Uniform,
141 has_dynamic_offset: true,
142 min_binding_size: NonZeroU64::new(u_size),
143 },
144 count: None,
145 },
146 ],
147 });
148 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
149 label: Some("layer-ocio-pl"),
150 bind_group_layouts: &[Some(&bgl)],
151 immediate_size: 0,
152 });
153 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
154 label: Some("layer-ocio-wgsl"),
155 source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()),
156 });
157 let ops = ENTRY_POINTS.map(|entry| {
158 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
159 label: Some(entry),
160 layout: Some(&pl),
161 module: &module,
162 entry_point: Some(entry),
163 compilation_options: Default::default(),
164 cache: None,
165 })
166 });
167 self.by_format.insert((format, hdr_float), LayerOcioFormatPipelines { bgl, ops });
168 }
169
170 #[allow(clippy::too_many_arguments)]
171 fn dispatch(
172 &mut self,
173 device: &wgpu::Device,
174 queue: &wgpu::Queue,
175 enc: &mut wgpu::CommandEncoder,
176 op: LayerOcioOp,
177 views: [&wgpu::TextureView; 4],
178 dst: &CachedTexture,
179 params: &UniformParams,
180 ) {
181 let hdr_float = dst.depth.is_float();
182 self.ensure_format(device, dst.format, hdr_float);
183 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
184 let fp = &self.by_format[&(dst.format, hdr_float)];
185 let mut entries: Vec<wgpu::BindGroupEntry> = views
186 .iter()
187 .enumerate()
188 .map(|(i, v)| wgpu::BindGroupEntry { binding: i as u32, resource: wgpu::BindingResource::TextureView(v) })
189 .collect();
190 entries.push(wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) });
191 entries.push(wgpu::BindGroupEntry {
192 binding: 5,
193 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
194 buffer: &self.uniform_chunks[chunk_idx],
195 offset: 0,
196 size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64),
197 }),
198 });
199 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
200 label: Some("layer-ocio-bg"),
201 layout: &fp.bgl,
202 entries: &entries,
203 });
204 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
205 label: Some("layer-ocio-pass"),
206 timestamp_writes: None,
207 });
208 pass.set_pipeline(&fp.ops[op as usize]);
209 pass.set_bind_group(0, &bg, &[offset]);
210 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
211 }
212}
213
214/// Blend / EffectMask / Process* state shared by every colour or spatial filter.
215struct Effect {
216 blend: f32,
217 mbm: bool,
218 mask: Option<CachedTexture>,
219 mask_inv: bool,
220 skip: [f32; 4],
221}
222
223fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 {
224 keys.iter()
225 .find(|&&k| node.inputs.contains_key(k))
226 .map_or(default, |&k| comp.eval_number(node, k, time, default, expr))
227}
228
229fn str_any<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> {
230 keys.iter().find_map(|k| node.static_str(k))
231}
232
233fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> {
234 ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s)))
235}
236
237/// Lowercased alphanumerics only, so `"Rec.709 (sRGB)"` matches `"rec709srgb"`.
238fn squash(s: &str) -> String {
239 s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect()
240}
241
242impl Engine {
243 fn layer_ocio_pipelines(&self) -> &RefCell<LayerOcioPipelines> {
244 self.layer_ocio.get_or_init(|| RefCell::new(LayerOcioPipelines::new(&self.device)))
245 }
246
247 /// Resolves `Blend` and the EffectMask for `src`; `Err(src)` when the effect is an identity
248 /// (`Blend == 0` without `MultiplyByMask`). A masked source is cropped to the canvas so mask UVs line up.
249 #[allow(clippy::too_many_arguments)]
250 fn effect_prologue(
251 &mut self,
252 comp: &Comp,
253 node: &Node,
254 time: f64,
255 src: CachedTexture,
256 enc: &mut wgpu::CommandEncoder,
257 visiting: &mut HashSet<(NodeId, i64)>,
258 stats: &mut EvalStats,
259 ) -> Result<(CachedTexture, Effect), CachedTexture> {
260 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
261 let mbm = self.multiplies_by_mask(comp, node, time);
262 if blend <= 1e-6 && !mbm {
263 return Err(src);
264 }
265 let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src };
266 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
267 let skip = self.process_skip(comp, node, time);
268 Ok((src, Effect { blend, mbm, mask, mask_inv, skip }))
269 }
270
271 /// Dispatches one `layer_ocio.wgsl` op over `src` (binding 0) with `b` (binding 1, `src` when `None`)
272 /// and `z` (binding 2, a dummy when `None`); the result keeps `src`'s DoD and aux channels.
273 #[allow(clippy::too_many_arguments)]
274 fn run_lo_filter(
275 &mut self,
276 node: &Node,
277 tag: &'static str,
278 op: LayerOcioOp,
279 src: &CachedTexture,
280 b: Option<&CachedTexture>,
281 z: Option<&wgpu::TextureView>,
282 fx: &Effect,
283 depth: BitDepth,
284 mut u: UniformParams,
285 frame_i: i64,
286 enc: &mut wgpu::CommandEncoder,
287 stats: &mut EvalStats,
288 ) -> CachedTexture {
289 u.p[14] = [fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)];
290 u.p[15] = fx.skip;
291 let b_hash = b.map_or(0, |t| t.content_hash);
292 let mask_hash = fx.mask.as_ref().map_or(0, |m| m.content_hash);
293 let key = self.make_key(node, tag, src.size, &[src.content_hash, b_hash, mask_hash, depth as u64], bytemuck::cast_slice(&u.p));
294 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
295 stats.cache_hits += 1;
296 return hit;
297 }
298 stats.cache_misses += 1;
299 stats.nodes_evaluated += 1;
300 let mut dst = self.alloc_tex_like(src, depth, key);
301 let views = [
302 &src.view,
303 b.map_or(&src.view, |t| &t.view),
304 z.unwrap_or(&self.dummy.view),
305 fx.mask.as_ref().map_or(&self.dummy.view, |m| &m.view),
306 ];
307 self.layer_ocio_pipelines()
308 .borrow_mut()
309 .dispatch(&self.device, &self.queue, enc, op, views, &dst, &u);
310 dst.set_aux(src.aux.clone());
311 self.cache.insert(key, dst.clone(), node.id, frame_i);
312 dst
313 }
314}
315
316fn b2f(v: bool) -> f32 {
317 if v { 1.0 } else { 0.0 }
318}
crates/engine/src/eval/layer_ocio/file_transform.rs created+287
...@@ -0,0 +1,287 @@
1//! `OCIOFileTransform` — `.cube` / `.3dl` LUTs, `.clf` (first `ASC_CDL`, `LUT3D` or `LUT1D` node) and
2//! `.cc` / `.ccc` / `.cdl` CDL files, applied through the `FileLUT` and `OCIOCDLTransform` GPU ops.
3
4use super::*;
5use crate::eval::color_lut::ColorLutOp;
6use crate::eval::color_lut::color_fx::parse_cdl_xml;
7use crate::eval::color_lut::lut_io::{ParsedLut, hash_lut_data, load_lut_from_spec, pack_3d_lut_rgba};
8
9const INVERSE_ITERATIONS: usize = 12;
10
11enum FileTransform {
12 Lut(ParsedLut),
13 Cdl { slope: [f32; 3], offset: [f32; 3], power: [f32; 3], sat: f32, reverse: bool },
14}
15
16fn xml_attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
17 let rest = &tag[tag.find(&format!("{name}=\""))? + name.len() + 2..];
18 Some(&rest[..rest.find('"')?])
19}
20
21/// Scale taking a CLF integer bit-depth attribute (`"10i"`) to normalized floats; float depths are 1.
22fn bit_depth_scale(depth: Option<&str>) -> f32 {
23 match depth.and_then(|d| d.strip_suffix('i')).and_then(|d| d.parse::<u32>().ok()) {
24 Some(bits) => 1.0 / ((1_u64 << bits.min(32)) - 1) as f32,
25 None => 1.0,
26 }
27}
28
29fn clf_lut(text: &str) -> Option<ParsedLut> {
30 let (is_3d, open) = match (text.find("<LUT3D"), text.find("<LUT1D")) {
31 (Some(i), _) => (true, i),
32 (None, Some(i)) => (false, i),
33 _ => return None,
34 };
35 let node = &text[open..];
36 let tag = &node[..node.find('>')?];
37 let array = &node[node.find("<Array")?..];
38 let array_tag = &array[..array.find('>')?];
39 let body = &array[array_tag.len() + 1..array.find("</Array>")?];
40 let scale = bit_depth_scale(xml_attr(tag, "outBitDepth"));
41 let values: Vec<f32> = body.split_whitespace().filter_map(|t| t.parse::<f32>().ok()).map(|v| v * scale).collect();
42 let dim: Vec<usize> = xml_attr(array_tag, "dim")?.split_whitespace().filter_map(|t| t.parse().ok()).collect();
43 if is_3d {
44 let n = *dim.first()?;
45 if dim.len() < 4 || values.len() != n * n * n * 3 {
46 return None;
47 }
48 // CLF varies B fastest; the packed layout varies R fastest.
49 let mut entries = vec![[0.0_f32; 3]; n * n * n];
50 for (i, rgb) in values.chunks_exact(3).enumerate() {
51 let (r, g, b) = (i / (n * n), (i / n) % n, i % n);
52 entries[r + n * (g + n * b)] = [rgb[0], rgb[1], rgb[2]];
53 }
54 lut_3d(n as u32, [0.0; 3], [1.0; 3], &entries)
55 } else {
56 let n = *dim.first()?;
57 let channels = *dim.get(1)?;
58 if n < 2 || (channels != 1 && channels != 3) || values.len() != n * channels {
59 return None;
60 }
61 let rows: Vec<[f32; 3]> = values
62 .chunks_exact(channels)
63 .map(|v| if channels == 1 { [v[0]; 3] } else { [v[0], v[1], v[2]] })
64 .collect();
65 Some(lut_1d([0.0; 3], [1.0; 3], &rows))
66 }
67}
68
69fn lut_3d(n: u32, dmin: [f32; 3], dmax: [f32; 3], entries: &[[f32; 3]]) -> Option<ParsedLut> {
70 let (tiles_x, tex_size, rgba_f32) = pack_3d_lut_rgba(n, entries).ok()?;
71 let content_hash = hash_lut_data(true, n, dmin, dmax, &rgba_f32);
72 Some(ParsedLut { is_3d: true, size: n, tiles_x, tex_size, domain_min: dmin, domain_max: dmax, rgba_f32, content_hash })
73}
74
75fn lut_1d(dmin: [f32; 3], dmax: [f32; 3], rows: &[[f32; 3]]) -> ParsedLut {
76 let n = rows.len() as u32;
77 let rgba_f32: Vec<f32> = rows.iter().flat_map(|[r, g, b]| [*r, *g, *b, 1.0]).collect();
78 let content_hash = hash_lut_data(false, n, dmin, dmax, &rgba_f32);
79 ParsedLut { is_3d: false, size: n, tiles_x: 1, tex_size: [n, 1], domain_min: dmin, domain_max: dmax, rgba_f32, content_hash }
80}
81
82fn cdl_from_xml(text: &str, ccc_id: &str) -> Option<FileTransform> {
83 let (slope, offset, power, sat) = parse_cdl_xml(text, ccc_id)?;
84 let reverse = text.find("<ASC_CDL").is_some_and(|i| {
85 let tag = &text[i..i + text[i..].find('>').unwrap_or(0)];
86 xml_attr(tag, "style").is_some_and(|s| s.to_ascii_lowercase().starts_with("rev"))
87 });
88 Some(FileTransform::Cdl { slope, offset, power, sat, reverse })
89}
90
91/// Loads `spec` as inline text or a file path; `None` when empty, unreadable or unsupported.
92fn load_file_transform(spec: &str, ccc_id: &str) -> Option<FileTransform> {
93 let spec = spec.trim();
94 let lower = spec.to_ascii_lowercase();
95 let xml_ext = [".clf", ".ctf", ".cc", ".ccc", ".cdl"].iter().any(|e| lower.ends_with(e));
96 if !xml_ext && !spec.starts_with('<') {
97 return load_lut_from_spec(spec).map(FileTransform::Lut);
98 }
99 let text = if spec.starts_with('<') {
100 spec.to_owned()
101 } else {
102 #[cfg(not(target_arch = "wasm32"))]
103 {
104 std::fs::read_to_string(spec).ok()?
105 }
106 #[cfg(target_arch = "wasm32")]
107 {
108 return None;
109 }
110 };
111 if text.contains("<ASC_CDL") || text.contains("<Slope>") {
112 return cdl_from_xml(&text, ccc_id);
113 }
114 clf_lut(&text).map(FileTransform::Lut)
115}
116
117fn sample_lut_3d(l: &ParsedLut, rgb: [f32; 3]) -> [f32; 3] {
118 let n = l.size as usize;
119 let at = |r: usize, g: usize, b: usize| {
120 let (tx, ty) = (b % l.tiles_x as usize, b / l.tiles_x as usize);
121 let i = ((ty * n + g) * l.tex_size[0] as usize + tx * n + r) * 4;
122 [l.rgba_f32[i], l.rgba_f32[i + 1], l.rgba_f32[i + 2]]
123 };
124 let pos: [f32; 3] = std::array::from_fn(|c| {
125 ((rgb[c] - l.domain_min[c]) / (l.domain_max[c] - l.domain_min[c]).max(1e-6)).clamp(0.0, 1.0) * (n - 1) as f32
126 });
127 let i0: [usize; 3] = pos.map(|p| (p.floor() as usize).min(n - 2));
128 let f: [f32; 3] = std::array::from_fn(|c| pos[c] - i0[c] as f32);
129 let mut out = [0.0_f32; 3];
130 for corner in 0..8 {
131 let (dr, dg, db) = (corner & 1, (corner >> 1) & 1, corner >> 2);
132 let w = [dr, dg, db].iter().zip(f).map(|(&d, f)| if d == 1 { f } else { 1.0 - f }).product::<f32>();
133 let v = at(i0[0] + dr, i0[1] + dg, i0[2] + db);
134 for c in 0..3 {
135 out[c] += w * v[c];
136 }
137 }
138 out
139}
140
141/// Inverts `l` over its own domain: 3D by fixed-point iteration on the forward lookup, 1D by a
142/// monotone (non-decreasing) per-channel search. `None` for degenerate LUTs.
143fn invert_lut(l: &ParsedLut) -> Option<ParsedLut> {
144 let n = l.size as usize;
145 if n < 2 {
146 return None;
147 }
148 let (dmin, dmax) = (l.domain_min, l.domain_max);
149 let node = |i: usize, c: usize| dmin[c] + i as f32 / (n - 1) as f32 * (dmax[c] - dmin[c]);
150 if l.is_3d {
151 let mut entries = vec![[0.0_f32; 3]; n * n * n];
152 for (idx, entry) in entries.iter_mut().enumerate() {
153 let target = [node(idx % n, 0), node((idx / n) % n, 1), node(idx / (n * n), 2)];
154 let mut x = target;
155 for _ in 0..INVERSE_ITERATIONS {
156 let fx = sample_lut_3d(l, x);
157 x = std::array::from_fn(|c| (x[c] + target[c] - fx[c]).clamp(dmin[c], dmax[c]));
158 }
159 *entry = x;
160 }
161 return lut_3d(l.size, dmin, dmax, &entries);
162 }
163 let mut rows = vec![[0.0_f32; 3]; n];
164 for c in 0..3 {
165 let forward: Vec<f32> = (0..n).map(|i| l.rgba_f32[i * 4 + c]).collect();
166 for (j, row) in rows.iter_mut().enumerate() {
167 let y = node(j, c);
168 let hi = forward.partition_point(|&v| v < y).clamp(1, n - 1);
169 let (a, b) = (forward[hi - 1], forward[hi]);
170 let t = if (b - a).abs() > 1e-9 { ((y - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 };
171 row[c] = node(hi - 1, c) + t * (node(hi, c) - node(hi - 1, c));
172 }
173 }
174 Some(lut_1d(dmin, dmax, &rows))
175}
176
177fn parse_interpolation(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 {
178 match str_any(node, &["Interpolation"]).map(squash).as_deref() {
179 Some("nearest") => 2.0,
180 Some("linear" | "trilinear") => 1.0,
181 Some(_) => 0.0,
182 None if node.inputs.contains_key("Interpolation") => {
183 match comp.eval_number(node, "Interpolation", time, 1.0, expr).round() as i32 {
184 0 => 1.0,
185 2 => 2.0,
186 _ => 0.0,
187 }
188 }
189 None => 0.0,
190 }
191}
192
193impl Engine {
194 /// `OCIOFileTransform` — applies `File` (`Direction` Forward/Inverse, `Interpolation` Linear/Tetrahedral/Nearest).
195 #[allow(clippy::too_many_arguments)]
196 pub(in crate::eval) fn eval_ocio_file_transform(
197 &mut self,
198 comp: &Comp,
199 node: &Node,
200 time: f64,
201 frame_i: i64,
202 enc: &mut wgpu::CommandEncoder,
203 visiting: &mut HashSet<(NodeId, i64)>,
204 stats: &mut EvalStats,
205 ) -> CachedTexture {
206 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
207 return self.dummy.clone();
208 };
209 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
210 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
211 Ok(v) => v,
212 Err(src) => return src,
213 };
214 let masked = fx.mbm && fx.mask.is_some();
215 let file_key = ["File", "FileName", "LUTFile"].into_iter().find(|k| node.inputs.contains_key(*k)).unwrap_or("File");
216 let spec = comp.eval_text(node, file_key, time, "", &self.expr);
217 let ccc_id = comp.eval_text(node, "CCCID", time, "", &self.expr);
218 let inverse = match str_any(node, &["Direction"]).map(squash).as_deref() {
219 Some(d) => matches!(d, "inverse" | "reverse" | "backward"),
220 None => comp.eval_number(node, "Direction", time, 0.0, &self.expr) > 0.5,
221 };
222 let Some(transform) = load_file_transform(&spec, &ccc_id) else {
223 return if masked { self.mask_only(node, &src, &fx, frame_i, enc, stats) } else { src };
224 };
225 let mask_flags = [b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)];
226
227 match transform {
228 FileTransform::Cdl { slope, offset, power, sat, reverse } => {
229 let mut u = UniformParams::default();
230 u.p[0] = [slope[0], slope[1], slope[2], sat];
231 u.p[1] = [offset[0], offset[1], offset[2], b2f(inverse != reverse)];
232 u.p[2] = [power[0], power[1], power[2], fx.blend];
233 u.p[3] = [mask_flags[0], mask_flags[1], mask_flags[2], 0.0];
234 u.p[4] = fx.skip;
235 self.run_cl_filter(node, "OCIOFileCDL", ColorLutOp::OcioCdl, &src, None, fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats)
236 }
237 FileTransform::Lut(lut) => {
238 let Some(lut) = (if inverse { invert_lut(&lut) } else { Some(lut) }) else {
239 return src;
240 };
241 let mut u = UniformParams::default();
242 u.p[0] = [lut.domain_min[0], lut.domain_min[1], lut.domain_min[2], if lut.is_3d { 3.0 } else { 1.0 }];
243 u.p[1] = [lut.domain_max[0], lut.domain_max[1], lut.domain_max[2], lut.size as f32];
244 u.p[2] = [lut.tiles_x as f32, 1.0, 1.0, 1.0];
245 u.p[4] = [fx.blend, mask_flags[0], mask_flags[1], mask_flags[2]];
246 u.p[5] = fx.skip;
247 u.p[6] = [0.0, parse_interpolation(comp, node, time, &self.expr), 0.0, 0.0];
248 let view = self
249 .color_lut_pipelines()
250 .borrow_mut()
251 .get_or_upload_lut_rgba32f(&self.device, &self.queue, lut.content_hash, lut.tex_size, &lut.rgba_f32);
252 self.run_cl_filter(node, "OCIOFileLUT", ColorLutOp::FileLut, &src, Some((&view, lut.content_hash)), fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats)
253 }
254 }
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
263 fn invert_lut_undoes_3d_and_1d_tables() {
264 let n = 5;
265 let node = |i: usize| i as f32 / (n - 1) as f32;
266 let entries: Vec<[f32; 3]> = (0..n * n * n)
267 .map(|i| [i % n, (i / n) % n, i / (n * n)].map(|c| 0.5 * node(c) + 0.1))
268 .collect();
269 let forward = lut_3d(n as u32, [0.0; 3], [1.0; 3], &entries).unwrap();
270 let inverse = invert_lut(&forward).unwrap();
271 for x in [0.4_f32, 0.6] {
272 let back = sample_lut_3d(&inverse, sample_lut_3d(&forward, [x, x, x]));
273 assert!(back.iter().all(|b| (b - x).abs() < 0.01), "3D inverse of {x}: {back:?}");
274 }
275
276 let squares: Vec<[f32; 3]> = (0..n).map(|i| [node(i) * node(i); 3]).collect();
277 let inverse_1d = invert_lut(&lut_1d([0.0; 3], [1.0; 3], &squares)).unwrap();
278 assert!((inverse_1d.rgba_f32[4] - 0.5).abs() < 1e-6, "1D inverse of 0.25 is 0.5");
279 }
280
281 #[test]
282 fn clf_attrs_and_bit_depths() {
283 assert_eq!(xml_attr("<LUT1D outBitDepth=\"10i\" x=\"1\">", "outBitDepth"), Some("10i"));
284 assert_eq!(bit_depth_scale(Some("10i")), 1.0 / 1023.0);
285 assert_eq!(bit_depth_scale(Some("32f")), 1.0);
286 }
287}
crates/engine/src/eval/layer_ocio/layers.rs created+135
...@@ -0,0 +1,135 @@
1//! `LayerMuxer`, `LayerRegex`, `LayerRemover` and the lossless passthroughs `Dummy`,
2//! `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC` (textures carry no metadata, so RGBA, DoD and aux pass through).
3
4use super::pattern::is_match;
5use super::*;
6use crate::cache::AuxChannels;
7use std::sync::Arc;
8
9/// Aux channel names as matched by `LayerRegex` / `LayerRemover` patterns, with their `Kill*` input.
10const AUX_LAYERS: [(&str, &str); 4] = [("Z", "KillZ"), ("Normal", "KillNormal"), ("Vector", "KillVector"), ("BackVector", "KillBackVector")];
11
12fn aux_slots(aux: &mut AuxChannels) -> [&mut Option<crate::cache::AuxChannelTex>; 4] {
13 [&mut aux.z, &mut aux.normal, &mut aux.vector, &mut aux.back_vector]
14}
15
16/// `tex` with `aux` swapped in under a content hash that reflects the change.
17fn with_aux(tex: &CachedTexture, aux: AuxChannels, salt: &impl Hash) -> CachedTexture {
18 let mut out = tex.clone();
19 out.set_aux(Some(Arc::new(aux)));
20 let mut h = DefaultHasher::new();
21 tex.content_hash.hash(&mut h);
22 salt.hash(&mut h);
23 out.content_hash = h.finish();
24 out
25}
26
27fn mux_ports() -> impl Iterator<Item = String> {
28 ["Background", "Input"]
29 .into_iter()
30 .map(str::to_owned)
31 .chain((1..=16).flat_map(|n| [format!("Input{n}"), format!("Foreground{n}")]))
32 .chain(std::iter::once("Foreground".to_owned()))
33}
34
35impl Engine {
36 /// `Dummy`, `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC`: the first connected input unchanged (a transparent
37 /// canvas when none is). `MetadataInput` and the timecode fields are not evaluated.
38 pub(in crate::eval) fn eval_passthrough(
39 &mut self,
40 comp: &Comp,
41 node: &Node,
42 time: f64,
43 enc: &mut wgpu::CommandEncoder,
44 visiting: &mut HashSet<(NodeId, i64)>,
45 stats: &mut EvalStats,
46 ) -> CachedTexture {
47 match conn_any(comp, node, &["Input", "Image", "Background", "Source"]) {
48 Some(id) => self.eval_node(comp, id, time, enc, visiting, stats),
49 None => self.dummy.clone(),
50 }
51 }
52
53 /// `LayerMuxer` — RGBA from the first connected input (`Background`, `Input1..`, `Foreground1..`);
54 /// each aux channel the main input lacks comes from the first later input of identical DoD that has it.
55 pub(in crate::eval) fn eval_layer_muxer(
56 &mut self,
57 comp: &Comp,
58 node: &Node,
59 time: f64,
60 enc: &mut wgpu::CommandEncoder,
61 visiting: &mut HashSet<(NodeId, i64)>,
62 stats: &mut EvalStats,
63 ) -> CachedTexture {
64 let mut inputs = mux_ports()
65 .filter_map(|p| node.connected_node(&p).and_then(|s| comp.find_node(s)))
66 .collect::<Vec<_>>();
67 inputs.dedup();
68 let mut layers = inputs.into_iter().map(|id| self.eval_node(comp, id, time, enc, visiting, stats));
69 let Some(main) = layers.next() else {
70 return self.dummy.clone();
71 };
72 let mut aux = main.aux_cloned();
73 let mut donors = Vec::new();
74 for layer in layers.filter(|l| l.size == main.size && l.origin == main.origin) {
75 let Some(other) = layer.aux.as_deref() else { continue };
76 let mut other = other.clone();
77 let mut taken = false;
78 for (slot, donor) in aux_slots(&mut aux).into_iter().zip(aux_slots(&mut other)) {
79 if slot.is_none() && donor.is_some() {
80 *slot = donor.take();
81 taken = true;
82 }
83 }
84 if taken {
85 donors.push(layer.content_hash);
86 }
87 }
88 if donors.is_empty() {
89 return main;
90 }
91 with_aux(&main, aux, &("LayerMuxer", donors))
92 }
93
94 /// `LayerRegex` keeps the aux channels whose name matches `Pattern` (all when empty; `Invert` flips the
95 /// selection); `LayerRemover` drops those matching `Layers` plus any `Kill*` toggle. RGBA is never touched.
96 #[allow(clippy::too_many_arguments)]
97 pub(in crate::eval) fn eval_layer_filter(
98 &mut self,
99 comp: &Comp,
100 node: &Node,
101 time: f64,
102 remove: bool,
103 enc: &mut wgpu::CommandEncoder,
104 visiting: &mut HashSet<(NodeId, i64)>,
105 stats: &mut EvalStats,
106 ) -> CachedTexture {
107 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
108 return self.dummy.clone();
109 };
110 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
111 let Some(src_aux) = src.aux.as_deref() else {
112 return src;
113 };
114 let pattern = if remove {
115 comp.eval_text(node, "Layers", time, "", &self.expr)
116 } else {
117 comp.eval_text(node, "Pattern", time, ".*", &self.expr)
118 };
119 let invert = !remove && comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;
120 let mut aux = src_aux.clone();
121 let mut dropped = Vec::new();
122 for ((name, kill), slot) in AUX_LAYERS.into_iter().zip(aux_slots(&mut aux)) {
123 let matched = !pattern.is_empty() && is_match(&pattern, name);
124 let killed = remove && (matched || comp.eval_number(node, kill, time, 0.0, &self.expr) > 0.5);
125 let keep = if remove { !killed } else { (pattern.is_empty() || matched) != invert };
126 if !keep && slot.take().is_some() {
127 dropped.push(name);
128 }
129 }
130 if dropped.is_empty() {
131 return src;
132 }
133 with_aux(&src, aux, &(&node.kind, dropped))
134 }
135}
crates/engine/src/eval/layer_ocio/ocio.rs created+247
...@@ -0,0 +1,247 @@
1//! `OCIOColorSpace` and `OCIODisplay`, built on the `ColorSpaceTransform` colorimetry and transfer curves.
2
3use super::*;
4use crate::eval::color_lut::ColorLutOp;
5use crate::eval::color_lut::colorimetry::{
6 CatMethod, P_AP0, P_AP1, P_AWG3, P_AWG4, P_DWG, P_P3_D60, P_P3_D65, P_P3_DCI, P_REC709, P_REC2020, P_RWG,
7 P_SGAMUT3, P_SGAMUT3_CINE, Primaries, parse_color_space, parse_gamma_id, rgb_to_rgb_matrix,
8};
9use std::sync::Arc;
10
11/// An OCIO color space as `(gamut, transfer id)`; `gamut == None` is CIE XYZ.
12type SpaceDef = (Option<Primaries>, i32);
13
14/// Resolves an OCIO space name onto the `ColorSpaceTransform` vocabulary; `None` for `Raw`/data spaces.
15fn ocio_space(name: &str) -> Option<SpaceDef> {
16 let s = squash(name);
17 if s == "raw" || s.contains("data") || s.contains("passthrough") {
18 return None;
19 }
20 let gamut = if s.contains("acescc") || s.contains("acescg") || s.contains("ap1") {
21 Some(P_AP1)
22 } else if s.contains("aces") || s.contains("ap0") {
23 Some(P_AP0)
24 } else if s.contains("logc4") || s.contains("awg4") {
25 Some(P_AWG4)
26 } else if s.contains("logc") || s.contains("alexa") || s.contains("awg") {
27 Some(P_AWG3)
28 } else if s.contains("slog") || s.contains("sgamut") {
29 Some(if s.contains("cine") { P_SGAMUT3_CINE } else { P_SGAMUT3 })
30 } else if s.contains("log3g10") || s.contains("rwg") || s.contains("redwidegamut") {
31 Some(P_RWG)
32 } else if s.contains("davinci") || s.contains("dwg") {
33 Some(P_DWG)
34 } else {
35 parse_color_space(Some(name))
36 };
37 let xfer = if s.starts_with("linear") || s == "lin" {
38 0
39 } else if s.contains("intermediate") {
40 15
41 } else if s.contains("displayp3") || s.contains("srgb") {
42 1
43 } else {
44 parse_gamma_id(Some(&s))
45 };
46 Some((gamut, xfer))
47}
48
49/// `ColorSpaceTransform` shader parameters taking `from`-encoded RGB to `to`-encoded RGB.
50struct Cst {
51 m: [[f32; 3]; 3],
52 in_xfer: i32,
53 out_xfer: i32,
54}
55
56impl Cst {
57 /// `None` when the conversion is an identity.
58 fn between(from: SpaceDef, to: SpaceDef) -> Option<Self> {
59 let m = rgb_to_rgb_matrix(from.0, to.0, true, CatMethod::Bradford);
60 let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
61 (m != identity || from.1 != to.1).then_some(Self { m, in_xfer: from.1, out_xfer: to.1 })
62 }
63
64 fn uniforms(&self, fx: Option<&Effect>) -> UniformParams {
65 let mut u = UniformParams::default();
66 for (row, m) in u.p.iter_mut().zip(&self.m) {
67 *row = [m[0], m[1], m[2], 0.0];
68 }
69 u.p[3] = [self.in_xfer as f32, self.out_xfer as f32, 0.0, 0.0];
70 u.p[4] = [100.0, 100.0, 0.9, 1.0];
71 u.p[5] = [1.0, 1.0, 0.0, 0.0];
72 if let Some(fx) = fx {
73 u.p[5] = [1.0, fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv)];
74 u.p[6] = [b2f(fx.mbm), 0.0, 0.0, 0.0];
75 u.p[7] = fx.skip;
76 }
77 u
78 }
79}
80
81/// Display gamut and curve id (see `ocio_display_op`) plus whether the device implies an ACES view.
82fn parse_display_device(device: &str) -> (Primaries, i32, bool) {
83 let s = squash(device);
84 let aces = s.contains("aces");
85 let (gamut, curve) = if s.contains("2100") && s.contains("hlg") {
86 (P_REC2020, 6)
87 } else if s.contains("2100") || s.contains("pq") {
88 (P_REC2020, 5)
89 } else if s.contains("displayp3") {
90 (P_P3_D65, 1)
91 } else if s.contains("p3") {
92 let gamut = if s.contains("dci") {
93 P_P3_DCI
94 } else if s.contains("d60") {
95 P_P3_D60
96 } else {
97 P_P3_D65
98 };
99 (gamut, 4)
100 } else if s.contains("2020") {
101 (P_REC2020, 3)
102 } else if s.contains("709") || s.contains("1886") {
103 (P_REC709, 3)
104 } else {
105 (P_REC709, 1)
106 };
107 (gamut, curve, aces)
108}
109
110fn parse_view_transform(view: Option<&str>, aces_device: bool) -> i32 {
111 match view.map(squash).as_deref() {
112 Some(v) if v.contains("aces") || v.contains("filmic") => 1,
113 Some(v) if v.contains("reinhard") => 2,
114 Some(v) if !v.is_empty() => 0,
115 _ => i32::from(aces_device),
116 }
117}
118
119impl Engine {
120 /// Dispatches one `color_lut` op over `src` with an optional packed LUT texture (binding 1),
121 /// caching the result under a key of its inputs; the result keeps `src`'s DoD and aux channels.
122 #[allow(clippy::too_many_arguments)]
123 pub(super) fn run_cl_filter(
124 &mut self,
125 node: &Node,
126 tag: &'static str,
127 op: ColorLutOp,
128 src: &CachedTexture,
129 lut: Option<(&Arc<wgpu::TextureView>, u64)>,
130 mask: Option<&CachedTexture>,
131 u: &UniformParams,
132 depth: BitDepth,
133 frame_i: i64,
134 enc: &mut wgpu::CommandEncoder,
135 stats: &mut EvalStats,
136 ) -> CachedTexture {
137 let lut_hash = lut.map_or(0, |l| l.1);
138 let mask_hash = mask.map_or(0, |m| m.content_hash);
139 let key = self.make_key(node, tag, src.size, &[src.content_hash, mask_hash, lut_hash, depth as u64], bytemuck::cast_slice(&u.p));
140 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
141 stats.cache_hits += 1;
142 return hit;
143 }
144 stats.cache_misses += 1;
145 stats.nodes_evaluated += 1;
146 let mut dst = self.alloc_tex_like(src, depth, key);
147 let views = [
148 &*src.view,
149 lut.map_or(&*self.dummy.view, |l| &**l.0),
150 &*self.dummy.view,
151 mask.map_or(&*self.dummy.view, |m| &*m.view),
152 ];
153 self.dispatch_cl(enc, op, views, &dst, u);
154 dst.set_aux(src.aux.clone());
155 self.cache.insert(key, dst.clone(), node.id, frame_i);
156 dst
157 }
158
159 /// `OCIOColorSpace` — converts between named OCIO color spaces (`SourceSpace` -> `OutputSpace`).
160 #[allow(clippy::too_many_arguments)]
161 pub(in crate::eval) fn eval_ocio_color_space(
162 &mut self,
163 comp: &Comp,
164 node: &Node,
165 time: f64,
166 frame_i: i64,
167 enc: &mut wgpu::CommandEncoder,
168 visiting: &mut HashSet<(NodeId, i64)>,
169 stats: &mut EvalStats,
170 ) -> CachedTexture {
171 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
172 return self.dummy.clone();
173 };
174 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
175 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
176 Ok(v) => v,
177 Err(src) => return src,
178 };
179 let from = ocio_space(str_any(node, &["SourceSpace", "InputSpace"]).unwrap_or("scene_linear"));
180 let to = ocio_space(str_any(node, &["OutputSpace", "DestSpace"]).unwrap_or("scene_linear"));
181 let cst = from.zip(to).and_then(|(from, to)| Cst::between(from, to));
182 let Some(cst) = cst else {
183 return if fx.mbm && fx.mask.is_some() { self.mask_only(node, &src, &fx, frame_i, enc, stats) } else { src };
184 };
185 let depth = self.node_depth(comp, node, time, Some(src.depth));
186 let u = cst.uniforms(Some(&fx));
187 self.run_cl_filter(node, "OCIOColorSpace", ColorLutOp::ColorSpaceTransform, &src, None, fx.mask.as_ref(), &u, depth, frame_i, enc, stats)
188 }
189
190 /// `MultiplyByMask` on an identity transform: zeroes outside the EffectMask via the `FileLUT` identity path.
191 pub(super) fn mask_only(
192 &mut self,
193 node: &Node,
194 src: &CachedTexture,
195 fx: &Effect,
196 frame_i: i64,
197 enc: &mut wgpu::CommandEncoder,
198 stats: &mut EvalStats,
199 ) -> CachedTexture {
200 let mut u = UniformParams::default();
201 u.p[2] = [1.0, 1.0, 1.0, 1.0];
202 u.p[4] = [fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)];
203 u.p[5] = fx.skip;
204 self.run_cl_filter(node, "OCIOIdentityMask", ColorLutOp::FileLut, src, None, fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats)
205 }
206
207 /// `OCIODisplay` — `InputSpace` -> display gamut, then exposure, view transform, display curve and post gamma.
208 #[allow(clippy::too_many_arguments)]
209 pub(in crate::eval) fn eval_ocio_display(
210 &mut self,
211 comp: &Comp,
212 node: &Node,
213 time: f64,
214 frame_i: i64,
215 enc: &mut wgpu::CommandEncoder,
216 visiting: &mut HashSet<(NodeId, i64)>,
217 stats: &mut EvalStats,
218 ) -> CachedTexture {
219 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
220 return self.dummy.clone();
221 };
222 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
223 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
224 Ok(v) => v,
225 Err(src) => return src,
226 };
227 let (gamut, curve, aces_device) = parse_display_device(str_any(node, &["DisplayDevice", "Display"]).unwrap_or("sRGB"));
228 let view = parse_view_transform(str_any(node, &["ViewTransform", "View"]), aces_device);
229 let exposure = comp.eval_number(node, "Exposure", time, 0.0, &self.expr);
230 let gamma = comp.eval_number(node, "Gamma", time, 1.0, &self.expr).max(1e-3);
231 let depth = self.node_depth(comp, node, time, Some(src.depth));
232
233 let from = ocio_space(str_any(node, &["InputSpace", "SourceSpace"]).unwrap_or("scene_linear"));
234 let linear_depth = if depth.is_float() { depth } else { BitDepth::Float16 };
235 let lin = match from.and_then(|from| Cst::between(from, (Some(gamut), 0))) {
236 Some(cst) => {
237 self.run_cl_filter(node, "OCIODisplayInput", ColorLutOp::ColorSpaceTransform, &src, None, None, &cst.uniforms(None), linear_depth, frame_i, enc, stats)
238 }
239 None => src.clone(),
240 };
241
242 let mut u = UniformParams::default();
243 u.p[0] = [2f64.powf(exposure) as f32, (1.0 / gamma) as f32, curve as f32, view as f32];
244 let tex_b = &src;
245 self.run_lo_filter(node, "OCIODisplay", LayerOcioOp::OcioDisplay, &lin, Some(tex_b), None, &fx, depth, u, frame_i, enc, stats)
246 }
247}
crates/engine/src/eval/layer_ocio/pattern.rs created+139
...@@ -0,0 +1,139 @@
1//! Minimal case-insensitive regex subset for layer names: literals, `.`, `[...]` classes (ranges, `^`
2//! negation), `\` escapes, `*` `+` `?` quantifiers, top-level `|`, and `^` / `$` anchors.
3//! Unanchored patterns match anywhere in the name.
4
5enum Atom {
6 Any,
7 Lit(char),
8 Class { ranges: Vec<(char, char)>, negated: bool },
9}
10
11struct Token {
12 atom: Atom,
13 min: usize,
14 max: usize,
15}
16
17struct Branch {
18 start_anchored: bool,
19 end_anchored: bool,
20 tokens: Vec<Token>,
21}
22
23impl Atom {
24 fn matches(&self, c: char) -> bool {
25 match self {
26 Atom::Any => true,
27 Atom::Lit(l) => *l == c,
28 Atom::Class { ranges, negated } => ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c)) != *negated,
29 }
30 }
31}
32
33fn parse_branch(pattern: &str) -> Branch {
34 let chars: Vec<char> = pattern.to_lowercase().chars().collect();
35 let (mut i, mut tokens) = (0, Vec::new());
36 let start_anchored = chars.first() == Some(&'^');
37 i += usize::from(start_anchored);
38 let escaped_dollar = chars.len() >= 2 && chars[chars.len() - 2] == '\\';
39 let end_anchored = chars.len() > i && chars.last() == Some(&'$') && !escaped_dollar;
40 let end = chars.len() - usize::from(end_anchored);
41 while i < end {
42 let atom = match chars[i] {
43 '.' => Atom::Any,
44 '\\' if i + 1 < end => {
45 i += 1;
46 Atom::Lit(chars[i])
47 }
48 '[' => {
49 let mut j = i + 1;
50 let negated = chars.get(j) == Some(&'^');
51 j += usize::from(negated);
52 let mut ranges = Vec::new();
53 while j < end && chars[j] != ']' {
54 let lo = chars[j];
55 if chars.get(j + 1) == Some(&'-') && j + 2 < end && chars[j + 2] != ']' {
56 ranges.push((lo, chars[j + 2]));
57 j += 3;
58 } else {
59 ranges.push((lo, lo));
60 j += 1;
61 }
62 }
63 i = j;
64 Atom::Class { ranges, negated }
65 }
66 c => Atom::Lit(c),
67 };
68 i += 1;
69 let (min, max) = match chars.get(i).filter(|_| i < end) {
70 Some('*') => (0, usize::MAX),
71 Some('+') => (1, usize::MAX),
72 Some('?') => (0, 1),
73 _ => (1, 1),
74 };
75 if (min, max) != (1, 1) {
76 i += 1;
77 }
78 tokens.push(Token { atom, min, max });
79 }
80 Branch { start_anchored, end_anchored, tokens }
81}
82
83fn match_from(tokens: &[Token], text: &[char], end_anchored: bool) -> bool {
84 let Some((tok, rest)) = tokens.split_first() else {
85 return !end_anchored || text.is_empty();
86 };
87 let available = text.iter().take(tok.max).take_while(|&&c| tok.atom.matches(c)).count();
88 (tok.min..=available).rev().any(|n| match_from(rest, &text[n..], end_anchored))
89}
90
91/// True when any `|` alternative of `pattern` matches `text`.
92pub(super) fn is_match(pattern: &str, text: &str) -> bool {
93 let text: Vec<char> = text.to_lowercase().chars().collect();
94 split_alternatives(pattern).into_iter().any(|alt| {
95 let branch = parse_branch(alt);
96 let last_start = if branch.start_anchored { 0 } else { text.len() };
97 (0..=last_start).any(|s| match_from(&branch.tokens, &text[s..], branch.end_anchored))
98 })
99}
100
101fn split_alternatives(pattern: &str) -> Vec<&str> {
102 let (mut parts, mut start, mut escaped, mut in_class) = (Vec::new(), 0, false, false);
103 for (i, c) in pattern.char_indices() {
104 match c {
105 _ if escaped => escaped = false,
106 '\\' => escaped = true,
107 '[' => in_class = true,
108 ']' => in_class = false,
109 '|' if !in_class => {
110 parts.push(&pattern[start..i]);
111 start = i + 1;
112 }
113 _ => {}
114 }
115 }
116 parts.push(&pattern[start..]);
117 parts
118}
119
120#[cfg(test)]
121mod tests {
122 use super::is_match;
123
124 #[test]
125 fn subset_semantics() {
126 assert!(is_match(".*", "Normal"));
127 assert!(is_match("^z$", "Z"));
128 assert!(!is_match("^z$", "BackZ"));
129 assert!(is_match("vec", "BackVector"));
130 assert!(!is_match("^vec", "BackVector"));
131 assert!(is_match("^vector$", "Vector"));
132 assert!(is_match("^z$|^normal$", "Normal"));
133 assert!(!is_match("^z$|^normal$", "Vector"));
134 assert!(is_match("^[a-c]+x$", "abcx"));
135 assert!(!is_match("^[^a-c]+x$", "abcx"));
136 assert!(is_match("^back?vector$", "BackVector"));
137 assert!(is_match("^ba?ck?vector$", "bcvector"));
138 }
139}
crates/engine/src/eval/layer_ocio/swizzle_fields.rs created+162
...@@ -0,0 +1,162 @@
1//! `Swizzler`, `Fields` and `ChromaticAberrationRemoval` — the `layer_ocio.wgsl` spatial/channel filters.
2
3use super::*;
4
5/// Swizzler channel selector id (see `swizzle_channel` in the shader): `Red`..`Alpha`, `Zero`, `One`,
6/// `Luminance`, `Z`; a `Secondary` prefix reads the second input, `Inverted` flips the result (ids 12+).
7fn swizzle_source(node: &Node, comp: &Comp, key: &str, default: f64, time: f64, expr: &ExprEngine) -> f32 {
8 let Some(name) = str_any(node, &[key]) else {
9 return comp.eval_number(node, key, time, default, expr).round().clamp(0.0, 23.0) as f32;
10 };
11 let mut s = squash(name);
12 let mut offset = 0;
13 if let Some(rest) = ["inverted", "invert", "inv"].iter().find_map(|p| s.strip_prefix(p)) {
14 s = rest.to_owned();
15 offset = 12;
16 }
17 let secondary = ["secondary", "background", "input2", "bg"].iter().find_map(|p| s.strip_prefix(p).map(str::to_owned));
18 let channel = secondary.as_deref().unwrap_or(&s);
19 let id = match channel {
20 "red" | "r" => 0,
21 "green" | "g" => 1,
22 "blue" | "b" => 2,
23 "alpha" | "a" => 3,
24 "zero" | "0" | "black" => 4,
25 "one" | "1" | "white" => 5,
26 "luminance" | "luma" | "y" => 6,
27 "z" | "depth" => 7,
28 _ => default as i32,
29 };
30 // Secondary-input channels only exist for R, G, B, A (ids 8..=11).
31 let id = if secondary.is_some() && id <= 3 { id + 8 } else { id };
32 (id + offset) as f32
33}
34
35fn enum_id(comp: &Comp, node: &Node, key: &str, names: &[&str], default: f64, time: f64, expr: &ExprEngine) -> i32 {
36 match str_any(node, &[key]).map(squash) {
37 Some(s) => names.iter().position(|n| s.contains(n)).unwrap_or(0) as i32,
38 None => comp.eval_number(node, key, time, default, expr).round().clamp(0.0, (names.len() - 1) as f64) as i32,
39 }
40}
41
42impl Engine {
43 /// `Swizzler` — each output channel picks a source channel (`Red`/`Green`/`Blue`/`Alpha` inputs).
44 #[allow(clippy::too_many_arguments)]
45 pub(in crate::eval) fn eval_swizzler(
46 &mut self,
47 comp: &Comp,
48 node: &Node,
49 time: f64,
50 frame_i: i64,
51 enc: &mut wgpu::CommandEncoder,
52 visiting: &mut HashSet<(NodeId, i64)>,
53 stats: &mut EvalStats,
54 ) -> CachedTexture {
55 let Some(src_id) = conn_any(comp, node, &["Input", "Image"]) else {
56 return self.dummy.clone();
57 };
58 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
59 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
60 Ok(v) => v,
61 Err(src) => return src,
62 };
63 let sources = [("Red", 0.0), ("Green", 1.0), ("Blue", 2.0), ("Alpha", 3.0)]
64 .map(|(key, default)| swizzle_source(node, comp, key, default, time, &self.expr));
65 if sources == [0.0, 1.0, 2.0, 3.0] && !(fx.mbm && fx.mask.is_some()) {
66 return src;
67 }
68 let second = conn_any(comp, node, &["Input2", "Secondary", "Background", "Foreground"])
69 .map(|id| self.eval_node(comp, id, time, enc, visiting, stats));
70 let z = src.aux.as_ref().and_then(|a| a.z.as_ref()).map(|z| z.view.clone());
71 let depth = self.node_depth(comp, node, time, Some(src.depth));
72 let mut u = UniformParams::default();
73 u.p[0] = sources;
74 u.p[1][0] = b2f(z.is_some());
75 self.run_lo_filter(node, "Swizzler", LayerOcioOp::Swizzler, &src, second.as_ref(), z.as_deref(), &fx, depth, u, frame_i, enc, stats)
76 }
77
78 /// `Fields` — `Operation` Deinterlace / Interlace / SwapFields / StripFields over `FieldOrder` line parity.
79 /// `Interlace` weaves in `Input2` (or `Input` at the next frame) as the second field.
80 #[allow(clippy::too_many_arguments)]
81 pub(in crate::eval) fn eval_fields(
82 &mut self,
83 comp: &Comp,
84 node: &Node,
85 time: f64,
86 frame_i: i64,
87 enc: &mut wgpu::CommandEncoder,
88 visiting: &mut HashSet<(NodeId, i64)>,
89 stats: &mut EvalStats,
90 ) -> CachedTexture {
91 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
92 return self.dummy.clone();
93 };
94 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
95 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
96 Ok(v) => v,
97 Err(src) => return src,
98 };
99 let e = &self.expr;
100 // `deint` precedes `interlace` so "Deinterlace" is not read as "Interlace".
101 let operation = match str_any(node, &["Operation"]).map(squash) {
102 Some(s) => ["deint", "interlace", "swap", "strip"].iter().position(|n| s.contains(n)).unwrap_or(0) as i32,
103 None => comp.eval_number(node, "Operation", time, 0.0, e).round().clamp(0.0, 3.0) as i32,
104 };
105 let method = enum_id(comp, node, "Method", &["blend", "interp", "dup"], 0.0, time, e);
106 let parity = enum_id(comp, node, "FieldOrder", &["odd", "even"], 0.0, time, e);
107 let second = if operation == 1 {
108 Some(match conn_any(comp, node, &["Input2", "Foreground"]) {
109 Some(id) => self.eval_node(comp, id, time, enc, visiting, stats),
110 None => {
111 let next = (time + 1.0).min(comp.global_range[1].max(comp.global_range[0]) as f64).max(time);
112 self.eval_node(comp, src_id, next, enc, visiting, stats)
113 }
114 })
115 } else {
116 None
117 };
118 let second = second.map(|s| self.crop_to_canvas(enc, s));
119 let depth = self.node_depth(comp, node, time, Some(src.depth));
120 let mut u = UniformParams::default();
121 u.p[0] = [operation as f32, method as f32, parity as f32, b2f(second.is_some())];
122 self.run_lo_filter(node, "Fields", LayerOcioOp::Fields, &src, second.as_ref(), None, &fx, depth, u, frame_i, enc, stats)
123 }
124
125 /// `ChromaticAberrationRemoval` — radially rescales R/G/B about `Center` (scale = `*Scale` + 0.01 * `RedCyan`
126 /// / `GreenMagenta` / `BlueYellow`) and desaturates colour fringes by `Defringe`.
127 #[allow(clippy::too_many_arguments)]
128 pub(in crate::eval) fn eval_chromatic_aberration_removal(
129 &mut self,
130 comp: &Comp,
131 node: &Node,
132 time: f64,
133 frame_i: i64,
134 enc: &mut wgpu::CommandEncoder,
135 visiting: &mut HashSet<(NodeId, i64)>,
136 stats: &mut EvalStats,
137 ) -> CachedTexture {
138 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
139 return self.dummy.clone();
140 };
141 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
142 let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) {
143 Ok(v) => v,
144 Err(src) => return src,
145 };
146 let e = &self.expr;
147 let channel = |shift: &str, scale: &str| {
148 (num_any(comp, node, &[scale], time, 1.0, e) + 0.01 * num_any(comp, node, &[shift], time, 0.0, e)) as f32
149 };
150 let scales = [channel("RedCyan", "RedScale"), channel("GreenMagenta", "GreenScale"), channel("BlueYellow", "BlueScale")];
151 let defringe = comp.eval_number(node, "Defringe", time, 0.0, e).max(0.0) as f32;
152 if scales.iter().all(|s| (s - 1.0).abs() < 1e-7) && defringe <= 1e-6 && !(fx.mbm && fx.mask.is_some()) {
153 return src;
154 }
155 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], e);
156 let depth = self.node_depth(comp, node, time, Some(src.depth));
157 let mut u = UniformParams::default();
158 u.p[0] = [scales[0], scales[1], scales[2], defringe];
159 u.p[1] = [center[0] as f32, 1.0 - center[1] as f32, 0.0, 0.0];
160 self.run_lo_filter(node, "ChromaticAberrationRemoval", LayerOcioOp::ChromaAberration, &src, None, None, &fx, depth, u, frame_i, enc, stats)
161 }
162}
crates/engine/src/eval/layer_ocio/tests.rs created+432
...@@ -0,0 +1,432 @@
1//! GPU unit tests for the 14 OCIO / Layer / Metadata / Generator / Utility built-ins.
2
3use super::*;
4
5fn comp(tools: &str) -> Comp {
6 let src = format!(
7 "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}"
8 );
9 Comp::from_fusion_str(&src).expect("parse comp")
10}
11
12/// Float32 solid-colour `Background` named `name`.
13fn solid(name: &str, w: u32, h: u32, [r, g, b, a]: [f32; 4]) -> String {
14 format!(
15 "{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, \
16 TopLeftRed = Input {{ Value = {r}, }}, TopLeftGreen = Input {{ Value = {g}, }}, TopLeftBlue = Input {{ Value = {b}, }}, TopLeftAlpha = Input {{ Value = {a}, }}, }}, }},"
17 )
18}
19
20/// `name = <kind> { Inputs = { Input = <src>, <extra> } }`.
21fn tool(name: &str, kind: &str, src: &str, extra: &str) -> String {
22 format!("{name} = {kind} {{ Inputs = {{ Input = Input {{ SourceOp = \"{src}\", Source = \"Output\", }}, {extra} }}, }},")
23}
24
25fn with_z(name: &str, src: &str) -> String {
26 tool(name, "Dimension.CopyAux", src, "Channel = Input { Value = FuID { \"Z\" }, }, Mode = Input { Value = 1, },")
27}
28
29fn render(c: &Comp, name: &str, time: f64) -> Option<(CachedTexture, Vec<f32>)> {
30 let mut eng = Engine::new_headless().ok()?;
31 let (tex, stats) = eng.evaluate(c, c.find_node(name).expect("find node"), time);
32 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
33 let px = eng.readback_rgba_f32(&tex).unwrap();
34 Some((tex, px))
35}
36
37fn px(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] {
38 let i = ((y * w + x) * 4) as usize;
39 buf[i..i + 4].try_into().unwrap()
40}
41
42fn near(got: f32, want: f32, tol: f32, what: &str) {
43 assert!((got - want).abs() <= tol, "{what}: got {got}, want {want} (±{tol})");
44}
45
46fn srgb_oetf(x: f32) -> f32 {
47 if x <= 0.0031308 { x * 12.92 } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 }
48}
49
50fn left_half_mask() -> &'static str {
51 "M = RectangleMask { Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, \
52 Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, },"
53}
54
55#[test]
56fn ocio_color_space_converts_transfer_gamut_and_preserves_hdr() {
57 let c = comp(&[
58 solid("Mid", 16, 16, [0.5, 0.5, 0.5, 1.0]),
59 solid("Red", 16, 16, [1.0, 0.0, 0.0, 1.0]),
60 solid("Hdr", 16, 16, [2.5, 2.5, 2.5, 1.0]),
61 solid("Gray", 16, 16, [0.18, 0.18, 0.18, 1.0]),
62 tool("Lin", "OCIOColorSpace", "Mid", "SourceSpace = Input { Value = \"sRGB - Texture\", }, OutputSpace = Input { Value = \"Linear Rec.709 (sRGB)\", },"),
63 tool("Ap1", "OCIOColorSpace", "Red", "SourceSpace = Input { Value = \"Linear Rec.709 (sRGB)\", }, OutputSpace = Input { Value = \"ACEScg\", },"),
64 tool("Log", "OCIOColorSpace", "Gray", "SourceSpace = Input { Value = \"Linear\", }, OutputSpace = Input { Value = \"ARRI LogC3\", },"),
65 tool("Back", "OCIOColorSpace", "Log", "SourceSpace = Input { Value = \"ARRI LogC3\", }, OutputSpace = Input { Value = \"Linear\", },"),
66 tool("Id", "OCIOColorSpace", "Hdr", "SourceSpace = Input { Value = \"ACEScg\", }, OutputSpace = Input { Value = \"ACEScg\", },"),
67 tool("Hdr2", "OCIOColorSpace", "Hdr", "SourceSpace = Input { Value = \"Linear\", }, OutputSpace = Input { Value = \"ACEScct\", },"),
68 tool("Off", "OCIOColorSpace", "Mid", "SourceSpace = Input { Value = \"sRGB\", }, Blend = Input { Value = 0, },"),
69 solid("Lft", 32, 16, [0.5, 0.5, 0.5, 1.0]),
70 left_half_mask().to_owned(),
71 tool("Masked", "OCIOColorSpace", "Lft", "SourceSpace = Input { Value = \"sRGB\", }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"),
72 tool("MaskedInv", "OCIOColorSpace", "Lft", "SourceSpace = Input { Value = \"sRGB\", }, ApplyMaskInverted = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"),
73 ].concat());
74 let Some((_, lin)) = render(&c, "Lin", 0.0) else { return };
75 near(px(&lin, 16, 3, 3)[0], 0.21404, 2e-3, "sRGB 0.5 -> linear");
76 let (_, ap1) = render(&c, "Ap1", 0.0).unwrap();
77 let p = px(&ap1, 16, 3, 3);
78 near(p[0], 0.6131, 0.01, "Rec.709 red -> ACEScg R");
79 near(p[1], 0.0702, 0.01, "Rec.709 red -> ACEScg G");
80 near(p[2], 0.0206, 0.01, "Rec.709 red -> ACEScg B");
81 let (_, log) = render(&c, "Log", 0.0).unwrap();
82 near(px(&log, 16, 3, 3)[0], 0.391, 0.01, "LogC3 of 18% gray");
83 let (_, back) = render(&c, "Back", 0.0).unwrap();
84 near(px(&back, 16, 3, 3)[0], 0.18, 2e-3, "LogC3 round trip");
85 let (_, id) = render(&c, "Id", 0.0).unwrap();
86 assert_eq!(px(&id, 16, 3, 3), [2.5, 2.5, 2.5, 1.0], "identity keeps HDR exactly");
87 let (_, cct) = render(&c, "Hdr2", 0.0).unwrap();
88 assert!(px(&cct, 16, 3, 3)[0] > 0.5, "ACEScct encodes HDR without clamping");
89 let (_, off) = render(&c, "Off", 0.0).unwrap();
90 assert_eq!(px(&off, 16, 3, 3), [0.5, 0.5, 0.5, 1.0], "Blend=0 passes through");
91 let (_, masked) = render(&c, "Masked", 0.0).unwrap();
92 near(px(&masked, 32, 4, 8)[0], 0.21404, 2e-3, "inside mask converted");
93 near(px(&masked, 32, 28, 8)[0], 0.5, 1e-4, "outside mask untouched");
94 let (_, inv) = render(&c, "MaskedInv", 0.0).unwrap();
95 near(px(&inv, 32, 4, 8)[0], 0.5, 1e-4, "ApplyMaskInverted keeps inside");
96 near(px(&inv, 32, 28, 8)[0], 0.21404, 2e-3, "ApplyMaskInverted converts outside");
97}
98
99#[test]
100fn ocio_display_applies_exposure_curve_gamma_and_view() {
101 let c = comp(&[
102 solid("Gray", 16, 16, [0.18, 0.18, 0.18, 1.0]),
103 solid("Hdr", 16, 16, [4.0, 4.0, 4.0, 1.0]),
104 tool("Def", "OCIODisplay", "Gray", ""),
105 tool("Ev1", "OCIODisplay", "Gray", "Exposure = Input { Value = 1, },"),
106 tool("G2", "OCIODisplay", "Gray", "Gamma = Input { Value = 2, },"),
107 tool("P2", "OCIODisplay", "Gray", "DisplayDevice = Input { Value = \"Rec.709\", },"),
108 tool("Raw", "OCIODisplay", "Hdr", ""),
109 tool("Aces", "OCIODisplay", "Hdr", "ViewTransform = Input { Value = \"ACES\", },"),
110 tool("Srgb", "OCIODisplay", "Gray", "InputSpace = Input { Value = \"sRGB\", },"),
111 tool("Off", "OCIODisplay", "Gray", "Blend = Input { Value = 0, },"),
112 ].concat());
113 let Some((_, def)) = render(&c, "Def", 0.0) else { return };
114 near(px(&def, 16, 4, 4)[0], srgb_oetf(0.18), 2e-3, "sRGB display of 18% gray");
115 let (_, ev) = render(&c, "Ev1", 0.0).unwrap();
116 near(px(&ev, 16, 4, 4)[0], srgb_oetf(0.36), 2e-3, "+1 stop doubles linear before the curve");
117 let (_, g2) = render(&c, "G2", 0.0).unwrap();
118 near(px(&g2, 16, 4, 4)[0], srgb_oetf(0.18).sqrt(), 2e-3, "post gamma");
119 let (_, p2) = render(&c, "P2", 0.0).unwrap();
120 near(px(&p2, 16, 4, 4)[0], 0.18_f32.powf(1.0 / 2.4), 2e-3, "Rec.709 display uses gamma 2.4");
121 let (_, raw) = render(&c, "Raw", 0.0).unwrap();
122 assert!(px(&raw, 16, 4, 4)[0] > 1.0, "no view transform keeps HDR above 1");
123 let (_, aces) = render(&c, "Aces", 0.0).unwrap();
124 let a = px(&aces, 16, 4, 4)[0];
125 assert!(a > 0.5 && a < 1.0, "ACES view rolls HDR into range: {a}");
126 let (_, srgb_in) = render(&c, "Srgb", 0.0).unwrap();
127 assert!(px(&srgb_in, 16, 4, 4)[0] < px(&def, 16, 4, 4)[0], "sRGB-encoded input decodes before the display curve");
128 let (_, off) = render(&c, "Off", 0.0).unwrap();
129 assert_eq!(px(&off, 16, 4, 4)[0], 0.18);
130}
131
132const POW2_LUT: &str = "LUT_1D_SIZE 5\\n0 0 0\\n0.0625 0.0625 0.0625\\n0.25 0.25 0.25\\n0.5625 0.5625 0.5625\\n1 1 1\\n";
133const SWAP_RB_CLF: &str = "<ProcessList><LUT3D inBitDepth=\\\"32f\\\" outBitDepth=\\\"32f\\\"><Array dim=\\\"2 2 2 3\\\">\
134 0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1</Array></LUT3D></ProcessList>";
135const DOUBLE_CDL: &str = "<ASC_CDL id=\\\"a\\\"><SOPNode><Slope>2 2 2</Slope><Offset>0 0 0</Offset><Power>1 1 1</Power></SOPNode>\
136 <SATNode><Saturation>1</Saturation></SATNode></ASC_CDL>";
137
138#[test]
139fn ocio_file_transform_luts_cdl_clf_direction_and_interpolation() {
140 let file = |spec: &str, extra: &str| format!("File = Input {{ Value = \"{spec}\", }}, {extra}");
141 let c = comp(&[
142 solid("Src", 16, 16, [0.5, 0.5, 0.5, 1.0]),
143 solid("Low", 16, 16, [0.3, 0.3, 0.3, 1.0]),
144 solid("Rgb", 16, 16, [0.2, 0.4, 0.6, 1.0]),
145 tool("Fwd", "OCIOFileTransform", "Src", &file(POW2_LUT, "")),
146 tool("Inv", "OCIOFileTransform", "Fwd", &file(POW2_LUT, "Direction = Input { Value = \"Inverse\", },")),
147 tool("Lin", "OCIOFileTransform", "Low", &file(POW2_LUT, "Interpolation = Input { Value = \"Linear\", },")),
148 tool("Near", "OCIOFileTransform", "Low", &file(POW2_LUT, "Interpolation = Input { Value = \"Nearest\", },")),
149 tool("Clf", "OCIOFileTransform", "Rgb", &file(SWAP_RB_CLF, "")),
150 tool("Cdl", "OCIOFileTransform", "Low", &file(DOUBLE_CDL, "")),
151 tool("CdlInv", "OCIOFileTransform", "Low", &file(DOUBLE_CDL, "Direction = Input { Value = \"Inverse\", },")),
152 tool("Empty", "OCIOFileTransform", "Rgb", &file("", "")),
153 tool("Missing", "OCIOFileTransform", "Rgb", &file("/nonexistent/grade.cube", "")),
154 tool("Off", "OCIOFileTransform", "Src", &file(POW2_LUT, "Blend = Input { Value = 0, },")),
155 ].concat());
156 let Some((_, fwd)) = render(&c, "Fwd", 0.0) else { return };
157 near(px(&fwd, 16, 3, 3)[0], 0.25, 2e-3, "1D .cube forward");
158 let (_, inv) = render(&c, "Inv", 0.0).unwrap();
159 near(px(&inv, 16, 3, 3)[0], 0.5, 5e-3, "Inverse undoes the forward LUT");
160 let (_, lin) = render(&c, "Lin", 0.0).unwrap();
161 near(px(&lin, 16, 3, 3)[0], 0.1, 2e-3, "Linear interpolation between nodes");
162 let (_, near_px) = render(&c, "Near", 0.0).unwrap();
163 near(px(&near_px, 16, 3, 3)[0], 0.0625, 2e-3, "Nearest snaps to the closest node");
164 let (_, clf) = render(&c, "Clf", 0.0).unwrap();
165 let p = px(&clf, 16, 3, 3);
166 near(p[0], 0.6, 2e-3, "CLF LUT3D B-fastest order: R<-B");
167 near(p[1], 0.4, 2e-3, "CLF LUT3D G");
168 near(p[2], 0.2, 2e-3, "CLF LUT3D B<-R");
169 let (_, cdl) = render(&c, "Cdl", 0.0).unwrap();
170 near(px(&cdl, 16, 3, 3)[0], 0.6, 2e-3, "CDL slope 2");
171 let (_, cdl_inv) = render(&c, "CdlInv", 0.0).unwrap();
172 near(px(&cdl_inv, 16, 3, 3)[0], 0.15, 2e-3, "CDL inverse");
173 for name in ["Empty", "Missing"] {
174 let (_, same) = render(&c, name, 0.0).unwrap();
175 assert_eq!(px(&same, 16, 3, 3), [0.2, 0.4, 0.6, 1.0], "{name} passes through");
176 }
177 let (_, off) = render(&c, "Off", 0.0).unwrap();
178 assert_eq!(px(&off, 16, 3, 3)[0], 0.5);
179}
180
181#[test]
182fn layer_muxer_regex_and_remover_route_aux_without_touching_rgba() {
183 let c = comp(&[
184 solid("Plain", 16, 16, [0.2, 0.4, 0.6, 1.0]),
185 solid("Other", 16, 16, [0.9, 0.1, 0.1, 1.0]),
186 with_z("Deep", "Other"),
187 "Mux = LayerMuxer { Inputs = { Background = Input { SourceOp = \"Plain\", Source = \"Output\", }, Foreground1 = Input { SourceOp = \"Deep\", Source = \"Output\", }, }, },".to_owned(),
188 "MuxMain = LayerMuxer { Inputs = { Background = Input { SourceOp = \"Deep\", Source = \"Output\", }, Input1 = Input { SourceOp = \"Plain\", Source = \"Output\", }, }, },".to_owned(),
189 "MuxEmpty = LayerMuxer { },".to_owned(),
190 tool("KeepAll", "LayerRegex", "Deep", ""),
191 tool("KeepZ", "LayerRegex", "Deep", "Pattern = Input { Value = \"^z$\", },"),
192 tool("KeepNormal", "LayerRegex", "Deep", "Pattern = Input { Value = \"^normal$\", },"),
193 tool("InvZ", "LayerRegex", "Deep", "Pattern = Input { Value = \"^z$\", }, Invert = Input { Value = 1, },"),
194 tool("KillZ", "LayerRemover", "Deep", "KillZ = Input { Value = 1, },"),
195 tool("KillByName", "LayerRemover", "Deep", "Layers = Input { Value = \"^z$|^normal$\", },"),
196 tool("KillNormal", "LayerRemover", "Deep", "KillNormal = Input { Value = 1, },"),
197 ].concat());
198 let has_z = |t: &CachedTexture| t.aux.as_ref().is_some_and(|a| a.z.is_some());
199 let Some((plain, plain_px)) = render(&c, "Plain", 0.0) else { return };
200 assert!(!has_z(&plain));
201
202 let (mux, mux_px) = render(&c, "Mux", 0.0).unwrap();
203 assert!(has_z(&mux), "Background lacks Z so the foreground's Z is routed in");
204 assert_eq!(mux_px, plain_px, "main RGBA comes from the Background");
205 let (mux_main, mux_main_px) = render(&c, "MuxMain", 0.0).unwrap();
206 let (deep, deep_px) = render(&c, "Deep", 0.0).unwrap();
207 assert!(has_z(&mux_main) && mux_main.content_hash == deep.content_hash, "nothing to route: input returned untouched");
208 assert_eq!(mux_main_px, deep_px);
209 assert_eq!(render(&c, "MuxEmpty", 0.0).unwrap().0.size, [1, 1]);
210
211 for (name, expect_z) in [("KeepAll", true), ("KeepZ", true), ("KeepNormal", false), ("InvZ", false), ("KillZ", false), ("KillByName", false), ("KillNormal", true)] {
212 let (t, p) = render(&c, name, 0.0).unwrap();
213 assert_eq!(has_z(&t), expect_z, "{name} Z presence");
214 assert_eq!(p, deep_px, "{name} leaves RGBA lossless");
215 }
216}
217
218#[test]
219fn swizzler_remaps_channels_secondary_luminance_z_and_mask() {
220 let c = comp(&[
221 solid("Src", 32, 16, [0.2, 0.4, 0.6, 0.5]),
222 solid("Sec", 32, 16, [0.9, 0.8, 0.7, 0.1]),
223 solid("Hdr", 32, 16, [2.5, 2.5, 2.5, 1.0]),
224 with_z("Deep", "Src"),
225 left_half_mask().to_owned(),
226 tool("Swap", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, Green = Input { Value = \"Zero\", }, Alpha = Input { Value = \"One\", },"),
227 tool("Id", "Swizzler", "Src", ""),
228 tool("Inv", "Swizzler", "Src", "Red = Input { Value = \"InvertedRed\", },"),
229 tool("Luma", "Swizzler", "Hdr", "Red = Input { Value = \"Luminance\", },"),
230 tool("Z", "Swizzler", "Deep", "Green = Input { Value = \"Z\", },"),
231 "Sw2 = Swizzler { Inputs = { Input = Input { SourceOp = \"Src\", Source = \"Output\", }, Input2 = Input { SourceOp = \"Sec\", Source = \"Output\", }, \
232 Red = Input { Value = \"SecondaryRed\", }, Alpha = Input { Value = \"SecondaryAlpha\", }, }, },".to_owned(),
233 tool("Masked", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"),
234 tool("MaskedInv", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, ApplyMaskInverted = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"),
235 tool("Mult", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, MultiplyByMask = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"),
236 ].concat());
237 let Some((_, swap)) = render(&c, "Swap", 0.0) else { return };
238 assert_eq!(px(&swap, 32, 5, 5), [0.6, 0.0, 0.2, 1.0]);
239 let (_, id) = render(&c, "Id", 0.0).unwrap();
240 assert_eq!(px(&id, 32, 5, 5), [0.2, 0.4, 0.6, 0.5], "default selectors are identity");
241 let (_, inv) = render(&c, "Inv", 0.0).unwrap();
242 near(px(&inv, 32, 5, 5)[0], 0.8, 1e-6, "inverted red");
243 let (_, luma) = render(&c, "Luma", 0.0).unwrap();
244 near(px(&luma, 32, 5, 5)[0], 2.5, 1e-3, "luminance of HDR gray stays above 1");
245 let (_, z) = render(&c, "Z", 0.0).unwrap();
246 assert!(px(&z, 32, 5, 5)[1] != 0.4, "Z aux replaces green");
247 let (_, sw2) = render(&c, "Sw2", 0.0).unwrap();
248 let p = px(&sw2, 32, 5, 5);
249 near(p[0], 0.9, 1e-5, "secondary red");
250 near(p[3], 0.1, 1e-5, "secondary alpha");
251 near(p[1], 0.4, 1e-6, "untouched green");
252 let (_, masked) = render(&c, "Masked", 0.0).unwrap();
253 assert_eq!(px(&masked, 32, 4, 8)[0], 0.6, "inside mask swapped");
254 assert_eq!(px(&masked, 32, 28, 8)[0], 0.2, "outside mask untouched");
255 let (_, inverted) = render(&c, "MaskedInv", 0.0).unwrap();
256 assert_eq!(px(&inverted, 32, 4, 8)[0], 0.2);
257 assert_eq!(px(&inverted, 32, 28, 8)[0], 0.6);
258 let (_, mult) = render(&c, "Mult", 0.0).unwrap();
259 assert_eq!(px(&mult, 32, 28, 8), [0.0; 4], "MultiplyByMask zeroes outside the mask");
260}
261
262#[test]
263fn metadata_tools_and_dummy_are_lossless_passthroughs() {
264 let c = comp(&[
265 solid("Src", 16, 16, [0.2, 0.4, 0.6, 1.0]),
266 with_z("Deep", "Src"),
267 tool("Copy", "Fuse.FLS_CopyMetadata", "Deep", ""),
268 tool("Tc", "Fuse.SetMetaDataTC", "Deep", "TimeCode = Input { Value = \"01:00:00:00\", }, FPS = Input { Value = 24, }, DropFrame = Input { Value = 0, },"),
269 tool("Dum", "Dummy", "Deep", ""),
270 "Free = Dummy { }, FreeCopy = Fuse.FLS_CopyMetadata { }, FreeTc = Fuse.SetMetaDataTC { },".to_owned(),
271 ].concat());
272 let Some((deep, deep_px)) = render(&c, "Deep", 0.0) else { return };
273 for name in ["Copy", "Tc", "Dum"] {
274 let (t, p) = render(&c, name, 0.0).unwrap();
275 assert_eq!(p, deep_px, "{name} pixels");
276 assert_eq!((t.origin, t.canvas_size, t.depth), (deep.origin, deep.canvas_size, deep.depth), "{name} DoD/depth");
277 assert!(t.aux.as_ref().is_some_and(|a| a.z.is_some()), "{name} keeps aux.z");
278 }
279 for name in ["Free", "FreeCopy", "FreeTc"] {
280 assert_eq!(render(&c, name, 0.0).unwrap().0.size, [1, 1], "{name} disconnected");
281 }
282}
283
284#[test]
285fn multi_text_renders_each_layer_and_matches_text_plus_for_one() {
286 let c = comp(r#"
287 Mt = MultiText { Inputs = {
288 Width = Input { Value = 128, }, Height = Input { Value = 64, },
289 StyledText1 = Input { Value = "II", }, Center1 = Input { Value = { 0.25, 0.5 }, }, Size1 = Input { Value = 0.4, },
290 Red1 = Input { Value = 1, }, Green1 = Input { Value = 0, }, Blue1 = Input { Value = 0, },
291 Text2 = Input { Value = "II", }, Center2 = Input { Value = { 0.75, 0.5 }, }, Size2 = Input { Value = 0.4, },
292 Red2 = Input { Value = 0, }, Green2 = Input { Value = 1, }, Blue2 = Input { Value = 0, },
293 }, },
294 One = MultiText { Inputs = {
295 Width = Input { Value = 128, }, Height = Input { Value = 64, },
296 StyledText = Input { Value = "HI", }, Size = Input { Value = 0.25, },
297 }, },
298 Tp = TextPlus { Inputs = {
299 Width = Input { Value = 128, }, Height = Input { Value = 64, },
300 StyledText = Input { Value = "HI", }, Size = Input { Value = 0.25, },
301 }, },
302 Empty = MultiText { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, }, },
303 "#);
304 let Some((mt, mt_px)) = render(&c, "Mt", 0.0) else { return };
305 assert_eq!(mt.canvas_size, [128, 64]);
306 let count = |range: std::ops::Range<u32>, pred: &dyn Fn([f32; 4]) -> bool| {
307 range.flat_map(|x| (0..64).map(move |y| (x, y))).filter(|&(x, y)| pred(px(&mt_px, mt.size[0], x, y))).count()
308 };
309 assert!(count(0..64, &|p| p[0] > 0.8 && p[1] < 0.2 && p[3] > 0.8) > 10, "layer 1 renders red text on the left");
310 assert!(count(64..128, &|p| p[1] > 0.8 && p[0] < 0.2 && p[3] > 0.8) > 10, "layer 2 renders green text on the right");
311 assert_eq!(count(0..64, &|p| p[1] > 0.5 && p[3] > 0.5), 0, "layers stay on their own side");
312 let (one, one_px) = render(&c, "One", 0.0).unwrap();
313 let (tp, tp_px) = render(&c, "Tp", 0.0).unwrap();
314 assert_eq!((one.size, one.origin), (tp.size, tp.origin));
315 assert_eq!(one_px, tp_px, "a single layer is exactly TextPlus");
316 let (_, empty_px) = render(&c, "Empty", 0.0).unwrap();
317 assert!(empty_px.iter().all(|&v| v == 0.0), "no text renders transparent");
318}
319
320fn row_ramp() -> String {
321 "Ramp = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \
322 Type = Input { Value = FuID { \"Vertical\" }, }, TopLeftRed = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, \
323 BottomLeftRed = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, }, }, },"
324 .to_owned()
325}
326
327#[test]
328fn fields_deinterlace_interlace_swap_and_strip() {
329 let fields = |name: &str, extra: &str| tool(name, "Fields", "Ramp", extra);
330 let c = comp(&[
331 row_ramp(),
332 solid("Second", 16, 16, [0.0, 1.0, 0.0, 1.0]),
333 fields("Dup", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Duplicate\", },"),
334 fields("Interp", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Interpolate\", },"),
335 fields("Blend", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Blend\", },"),
336 fields("Even", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Duplicate\", }, FieldOrder = Input { Value = \"Even\", },"),
337 fields("Swap", "Operation = Input { Value = \"SwapFields\", },"),
338 fields("Strip", "Operation = Input { Value = \"StripFields\", }, Method = Input { Value = \"Blend\", },"),
339 "Weave = Fields { Inputs = { Input = Input { SourceOp = \"Ramp\", Source = \"Output\", }, Input2 = Input { SourceOp = \"Second\", Source = \"Output\", }, \
340 Operation = Input { Value = \"Interlace\", }, }, },".to_owned(),
341 fields("Off", "Operation = Input { Value = \"SwapFields\", }, Blend = Input { Value = 0, },"),
342 ].concat());
343 let Some((_, ramp)) = render(&c, "Ramp", 0.0) else { return };
344 let r = |buf: &[f32], y: u32| px(buf, 16, 2, y)[0];
345 assert!(r(&ramp, 3) > r(&ramp, 2) + 0.01, "the ramp must vary per row for the parity checks to mean anything");
346 let (_, dup) = render(&c, "Dup", 0.0).unwrap();
347 near(r(&dup, 2), r(&ramp, 2), 1e-6, "dominant (odd) lines kept");
348 near(r(&dup, 3), r(&ramp, 2), 1e-6, "Duplicate copies the dominant line above");
349 let (_, interp) = render(&c, "Interp", 0.0).unwrap();
350 near(r(&interp, 3), (r(&ramp, 2) + r(&ramp, 4)) / 2.0, 1e-6, "Interpolate averages neighbours");
351 let (_, blend) = render(&c, "Blend", 0.0).unwrap();
352 near(r(&blend, 3), (r(&ramp, 3) + (r(&ramp, 2) + r(&ramp, 4)) / 2.0) / 2.0, 1e-6, "Blend mixes with the interpolation");
353 let (_, even) = render(&c, "Even", 0.0).unwrap();
354 near(r(&even, 2), r(&ramp, 1), 1e-6, "Even field order keeps odd rows and rebuilds even ones");
355 let (_, swap) = render(&c, "Swap", 0.0).unwrap();
356 near(r(&swap, 2), r(&ramp, 3), 1e-6, "SwapFields exchanges line pairs");
357 near(r(&swap, 3), r(&ramp, 2), 1e-6, "SwapFields exchanges line pairs");
358 let (_, strip) = render(&c, "Strip", 0.0).unwrap();
359 near(r(&strip, 3), r(&ramp, 2), 1e-6, "StripFields drops the second field");
360 let (_, weave) = render(&c, "Weave", 0.0).unwrap();
361 near(r(&weave, 2), r(&ramp, 2), 1e-6, "Interlace keeps the dominant line from Input");
362 assert_eq!(px(&weave, 16, 2, 3), [0.0, 1.0, 0.0, 1.0], "Interlace takes the other lines from Input2");
363 let (_, off) = render(&c, "Off", 0.0).unwrap();
364 assert_eq!(off, ramp);
365}
366
367#[test]
368fn chromatic_aberration_removal_rescales_channels_radially() {
369 let c = comp(&[
370 "Ramp = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \
371 Type = Input { Value = FuID { \"Horizontal\" }, }, TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, \
372 TopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, }, },".to_owned(),
373 "Edge = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \
374 TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, }, },".to_owned(),
375 tool("Def", "ChromaticAberrationRemoval", "Ramp", ""),
376 tool("Red", "ChromaticAberrationRemoval", "Ramp", "RedScale = Input { Value = 1.1, },"),
377 tool("Blue", "ChromaticAberrationRemoval", "Ramp", "BlueYellow = Input { Value = 10, },"),
378 tool("Off", "ChromaticAberrationRemoval", "Ramp", "RedScale = Input { Value = 1.1, }, Blend = Input { Value = 0, },"),
379 tool("Defr", "ChromaticAberrationRemoval", "Edge", "Defringe = Input { Value = 1, },"),
380 ].concat());
381 let Some((_, ramp)) = render(&c, "Ramp", 0.0) else { return };
382 let (_, def) = render(&c, "Def", 0.0).unwrap();
383 assert_eq!(def, ramp, "default is identity");
384 let (_, red) = render(&c, "Red", 0.0).unwrap();
385 let (a, b) = (px(&ramp, 64, 48, 8), px(&red, 64, 48, 8));
386 assert!(b[0] > a[0] + 0.01, "red sampled farther from the centre: {} vs {}", b[0], a[0]);
387 near(b[1], a[1], 1e-5, "green untouched");
388 near(px(&red, 64, 32, 8)[0], px(&ramp, 64, 32, 8)[0], 0.02, "centre pixel stays put");
389 let (_, blue) = render(&c, "Blue", 0.0).unwrap();
390 assert!(px(&blue, 64, 48, 8)[2] > a[2] + 0.01, "BlueYellow shifts blue");
391 let (_, off) = render(&c, "Off", 0.0).unwrap();
392 assert_eq!(off, ramp);
393 let (_, defr) = render(&c, "Defr", 0.0).unwrap();
394 assert_eq!(px(&defr, 16, 8, 8), [1.0, 0.0, 0.0, 1.0], "defringe leaves flat colour alone");
395}
396
397#[test]
398fn key_stretcher_keeps_intro_and_outro_and_stretches_the_middle() {
399 let keys = (0..=10).map(|f| format!("[{f}] = {{ {}, Flags = {{ StepIn = true }} }},", f as f32 / 10.0)).collect::<String>();
400 let stretch = |name: &str, mode: &str| {
401 format!(
402 "{name} = KeyStretcher {{ Inputs = {{ Input = Input {{ SourceOp = \"Clip\", Source = \"Output\", }}, \
403 SourceStart = Input {{ Value = 2, }}, SourceEnd = Input {{ Value = 4, }}, StretchStart = Input {{ Value = 2, }}, \
404 StretchEnd = Input {{ Value = 6, }}, StretchMode = Input {{ Value = \"{mode}\", }}, }}, }},"
405 )
406 };
407 let c = comp(&[
408 "Clip = Background { Inputs = { Width = Input { Value = 4, }, Height = Input { Value = 4, }, Depth = Input { Value = 4, }, \
409 TopLeftRed = Input { SourceOp = \"Ramp\", Source = \"Value\", }, TopLeftAlpha = Input { Value = 1, }, }, },".to_owned(),
410 format!("Ramp = BezierSpline {{ KeyFrames = {{ {keys} }} }},"),
411 stretch("Loop", "Loop"),
412 stretch("Hold", "Hold"),
413 stretch("Ping", "PingPong"),
414 stretch("Scale", "Scale"),
415 "Ident = KeyStretcher { Inputs = { Input = Input { SourceOp = \"Clip\", Source = \"Output\", }, }, },".to_owned(),
416 "Cycle = KeyStretcher { Inputs = { Input = Input { SourceOp = \"Cycle\", Source = \"Output\", }, }, },".to_owned(),
417 "Free = KeyStretcher { },".to_owned(),
418 ].concat());
419 let value = |name: &str, t: f64| render(&c, name, t).map(|(_, p)| px(&p, 4, 1, 1)[0]);
420 let Some(intro) = value("Loop", 1.0) else { return };
421 near(intro, 0.1, 1e-3, "intro plays unstretched");
422 near(value("Loop", 5.0).unwrap(), 0.3, 1e-3, "Loop wraps the middle over the source range");
423 near(value("Loop", 8.0).unwrap(), 0.6, 1e-3, "outro continues from SourceEnd");
424 near(value("Hold", 5.0).unwrap(), 0.4, 1e-3, "Hold clamps at SourceEnd");
425 near(value("Ping", 5.0).unwrap(), 0.3, 1e-3, "PingPong folds back");
426 near(value("Scale", 4.0).unwrap(), 0.3, 1e-3, "Scale maps linearly");
427 for t in [0.0, 3.0, 10.0] {
428 near(value("Ident", t).unwrap(), t as f32 / 10.0, 1e-3, "defaults are the identity");
429 }
430 assert_eq!(render(&c, "Cycle", 3.0).unwrap().0.size, [1, 1], "self-referencing input terminates");
431 assert_eq!(render(&c, "Free", 0.0).unwrap().0.size, [1, 1]);
432}
crates/engine/src/eval/layer_ocio/utility.rs created+215
...@@ -0,0 +1,215 @@
1//! `KeyStretcher` and `MultiText`.
2
3use super::*;
4use model::InputBinding;
5
6const MAX_TEXT_LAYERS: usize = 16;
7
8/// How the middle segment maps onto `[SourceStart, SourceEnd]`.
9#[derive(Clone, Copy, PartialEq, Debug)]
10enum StretchMode {
11 Hold,
12 Loop,
13 PingPong,
14 Scale,
15}
16
17struct Stretch {
18 source: [f64; 2],
19 stretch: [f64; 2],
20 mode: StretchMode,
21}
22
23impl Stretch {
24 /// Source time for output time `t`: the intro before `stretch[0]` and outro after `stretch[1]` play
25 /// unstretched, continuous with the middle segment's ends.
26 fn source_time(&self, t: f64) -> f64 {
27 let [src_start, src_end] = self.source;
28 let [st_start, st_end] = self.stretch;
29 if t < st_start {
30 return t + (src_start - st_start);
31 }
32 if t > st_end {
33 return src_end + (t - st_end);
34 }
35 let dt = t - st_start;
36 let src_span = src_end - src_start;
37 let out_span = st_end - st_start;
38 if src_span <= 0.0 {
39 return src_start;
40 }
41 src_start
42 + match self.mode {
43 StretchMode::Scale if out_span > 0.0 => dt / out_span * src_span,
44 StretchMode::Scale => 0.0,
45 StretchMode::Hold => dt.min(src_span),
46 StretchMode::Loop => dt.rem_euclid(src_span),
47 StretchMode::PingPong => {
48 let p = dt.rem_euclid(2.0 * src_span);
49 if p <= src_span { p } else { 2.0 * src_span - p }
50 }
51 }
52 }
53}
54
55/// Re-keys `node`'s inputs for text layer `layer` (`0` = the shared inputs only): `Layer{n}Foo`, `Layer{n}.Foo`
56/// and `Foo{n}` override `Foo`, then MultiText names map onto `TextPlus` inputs.
57fn text_layer_inputs(node: &Node, layer: usize) -> HashMap<String, InputBinding> {
58 const ALIASES: [(&str, &str); 5] =
59 [("Text", "StyledText"), ("Red", "Red1"), ("Green", "Green1"), ("Blue", "Blue1"), ("Alpha", "Alpha1")];
60 let alias = |name: &str| ALIASES.iter().find(|(from, _)| *from == name).map_or(name, |(_, to)| *to).to_owned();
61 let layer_name = |key: &str| -> Option<String> {
62 let n = layer.to_string();
63 let rest = key
64 .strip_prefix(&format!("Layer{n}"))
65 .filter(|r| !r.starts_with(|c: char| c.is_ascii_digit()))
66 .map(|r| r.trim_start_matches('.'));
67 let rest = rest.or_else(|| key.strip_suffix(&n).filter(|r| !r.is_empty() && !r.ends_with(|c: char| c.is_ascii_digit())));
68 rest.map(|r| if r.is_empty() { "StyledText".to_owned() } else { alias(r) })
69 };
70 let shared = node
71 .inputs
72 .iter()
73 .filter(|(k, _)| !k.starts_with("Layer") && !k.ends_with(|c: char| c.is_ascii_digit()))
74 .map(|(k, b)| (alias(k), b.clone()));
75 let own = node.inputs.iter().filter_map(|(k, b)| Some((layer_name(k).filter(|_| layer > 0)?, b.clone())));
76 shared.chain(own).collect()
77}
78
79fn text_layers(node: &Node) -> Vec<usize> {
80 (1..=MAX_TEXT_LAYERS)
81 .filter(|&n| {
82 ["Layer{}", "Layer{}StyledText", "Layer{}.StyledText", "Layer{}Text", "Layer{}.Text", "StyledText{}", "Text{}"]
83 .iter()
84 .any(|pat| node.inputs.contains_key(&pat.replace("{}", &n.to_string())))
85 })
86 .collect()
87}
88
89impl Engine {
90 /// `KeyStretcher` — retimes `Input` so the intro and outro play unstretched around a stretched middle segment.
91 #[allow(clippy::too_many_arguments)]
92 pub(in crate::eval) fn eval_key_stretcher(
93 &mut self,
94 comp: &Comp,
95 node: &Node,
96 time: f64,
97 frame_i: i64,
98 enc: &mut wgpu::CommandEncoder,
99 visiting: &mut HashSet<(NodeId, i64)>,
100 stats: &mut EvalStats,
101 ) -> CachedTexture {
102 let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else {
103 return self.dummy.clone();
104 };
105 let [g_start, g_end] = comp.global_range.map(|f| f as f64);
106 let read = |keys: &[&str], default: f64| num_any(comp, node, keys, time, default, &self.expr);
107 let mode = match str_any(node, &["StretchMode", "Mode"]).map(squash).as_deref() {
108 Some("hold") => StretchMode::Hold,
109 Some("loop") => StretchMode::Loop,
110 Some("pingpong") => StretchMode::PingPong,
111 Some(_) => StretchMode::Scale,
112 None => match read(&["StretchMode", "Mode"], 3.0).round() as i32 {
113 0 => StretchMode::Hold,
114 1 => StretchMode::Loop,
115 2 => StretchMode::PingPong,
116 _ => StretchMode::Scale,
117 },
118 };
119 let stretch = Stretch {
120 source: [read(&["SourceStart"], g_start), read(&["SourceEnd"], g_end)],
121 stretch: [read(&["StretchStart", "KeyFrames"], g_start), read(&["StretchEnd"], g_end)],
122 mode,
123 };
124 let remapped = stretch.source_time(time).clamp(g_start, g_end.max(g_start));
125 if (remapped - time).abs() < 1e-9 {
126 return self.eval_node(comp, src_id, time, enc, visiting, stats);
127 }
128 self.eval_time_remapped(comp, node, time, frame_i, remapped, enc, visiting, stats)
129 }
130
131 /// `MultiText` — one `TextPlus` render per layer (`Layer{n}` / `Text{n}` / `StyledText{n}` with per-layer
132 /// overrides of the shared inputs), composited over each other in layer order on the shared canvas.
133 #[allow(clippy::too_many_arguments)]
134 pub(in crate::eval) fn eval_multi_text(
135 &mut self,
136 comp: &Comp,
137 node: &Node,
138 time: f64,
139 frame_i: i64,
140 comp_dims: [u32; 2],
141 enc: &mut wgpu::CommandEncoder,
142 stats: &mut EvalStats,
143 ) -> CachedTexture {
144 let layers = text_layers(node);
145 let mut acc: Option<CachedTexture> = None;
146 for layer in if layers.is_empty() { vec![0] } else { layers } {
147 let mut text_node = node.clone();
148 text_node.kind = "TextPlus".to_owned();
149 text_node.inputs = text_layer_inputs(node, layer);
150 let rendered = self.eval_text_plus(comp, &text_node, time, frame_i, comp_dims, enc, stats);
151 acc = Some(match acc {
152 None => rendered,
153 Some(bg) => {
154 let bg = self.crop_to_canvas(enc, bg);
155 let fg = self.crop_to_canvas(enc, rendered);
156 self.merge_text_layer(node, bg, fg, frame_i, enc, stats)
157 }
158 });
159 }
160 acc.unwrap_or_else(|| self.dummy.clone())
161 }
162
163 /// Straight `Merge` of canvas-sized `fg` over `bg`.
164 fn merge_text_layer(
165 &mut self,
166 node: &Node,
167 bg: CachedTexture,
168 fg: CachedTexture,
169 frame_i: i64,
170 enc: &mut wgpu::CommandEncoder,
171 stats: &mut EvalStats,
172 ) -> CachedTexture {
173 let key = self.make_key(node, "MultiTextMerge", bg.size, &[bg.content_hash, fg.content_hash], &[]);
174 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
175 stats.cache_hits += 1;
176 return hit;
177 }
178 stats.cache_misses += 1;
179 stats.nodes_evaluated += 1;
180 let mut u = UniformParams::default();
181 u.p[0] = [0.5, 0.5, 1.0, 0.0];
182 u.p[1] = [1.0, 1.0, 0.0, 0.0];
183 u.p[2] = [0.0, 0.0, 1.0, 0.0];
184 u.p[3] = [0.0, 0.0, fg.size[0] as f32, fg.size[1] as f32];
185 u.p[6] = [0.0, 1.0, 0.0, 0.0];
186 let dst = self.alloc_tex_like(&bg, bg.depth.max(fg.depth), key);
187 self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, &self.dummy.view, &dst, &u);
188 self.cache.insert(key, dst.clone(), node.id, frame_i);
189 dst
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 fn stretch(mode: StretchMode) -> Stretch {
198 Stretch { source: [10.0, 14.0], stretch: [10.0, 18.0], mode }
199 }
200
201 #[test]
202 fn middle_modes_map_into_source_range() {
203 assert_eq!(stretch(StretchMode::Scale).source_time(14.0), 12.0);
204 assert_eq!(stretch(StretchMode::Hold).source_time(17.0), 14.0);
205 assert_eq!(stretch(StretchMode::Loop).source_time(15.0), 11.0);
206 assert_eq!(stretch(StretchMode::PingPong).source_time(15.0), 13.0);
207 }
208
209 #[test]
210 fn intro_and_outro_stay_unstretched() {
211 let s = stretch(StretchMode::Loop);
212 assert_eq!(s.source_time(4.0), 4.0);
213 assert_eq!(s.source_time(20.0), 16.0);
214 }
215}
crates/engine/src/eval/mod.rs+21
...@@ -33,6 +33,7 @@ mod warps_masks;...@@ -33,6 +33,7 @@ mod warps_masks;
33mod fx_fuses;33mod fx_fuses;
34mod archive_fx2;34mod archive_fx2;
35mod surface_fx;35mod surface_fx;
36mod layer_ocio;
36mod text_3d;37mod text_3d;
37mod registry;38mod registry;
38mod dispatch;39mod dispatch;
...@@ -87,6 +88,7 @@ pub struct Engine {...@@ -87,6 +88,7 @@ pub struct Engine {
87 fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>,88 fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>,
88 archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>,89 archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>,
89 pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>,90 pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>,
91 pub(crate) layer_ocio: OnceCell<RefCell<layer_ocio::LayerOcioPipelines>>,
90 auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>,92 auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>,
91 pub auto_matte_cache: crate::auto_matte::AutoMatteCache,93 pub auto_matte_cache: crate::auto_matte::AutoMatteCache,
92 motion_blur: crate::motion_blur::MotionBlurPipelines,94 motion_blur: crate::motion_blur::MotionBlurPipelines,
...@@ -204,6 +206,7 @@ impl Engine {...@@ -204,6 +206,7 @@ impl Engine {
204 fx_fuses_pipelines: OnceCell::new(),206 fx_fuses_pipelines: OnceCell::new(),
205 archive_fx2_pipelines: OnceCell::new(),207 archive_fx2_pipelines: OnceCell::new(),
206 surface_fx: OnceCell::new(),208 surface_fx: OnceCell::new(),
209 layer_ocio: OnceCell::new(),
207 auto_matte_pipelines: OnceCell::new(),210 auto_matte_pipelines: OnceCell::new(),
208 auto_matte_cache: crate::auto_matte::AutoMatteCache::new(),211 auto_matte_cache: crate::auto_matte::AutoMatteCache::new(),
209 motion_blur: crate::motion_blur::MotionBlurPipelines::default(),212 motion_blur: crate::motion_blur::MotionBlurPipelines::default(),
...@@ -373,6 +376,9 @@ impl Engine {...@@ -373,6 +376,9 @@ impl Engine {
373 if let Some(sfx) = self.surface_fx.get() {376 if let Some(sfx) = self.surface_fx.get() {
374 sfx.borrow_mut().reset_uniform_cursor();377 sfx.borrow_mut().reset_uniform_cursor();
375 }378 }
379 if let Some(lo) = self.layer_ocio.get() {
380 lo.borrow_mut().reset_uniform_cursor();
381 }
376 if let Some(am) = self.auto_matte_pipelines.get() {382 if let Some(am) = self.auto_matte_pipelines.get() {
377 am.borrow_mut().reset_uniform_cursor();383 am.borrow_mut().reset_uniform_cursor();
378 }384 }
...@@ -411,6 +417,9 @@ impl Engine {...@@ -411,6 +417,9 @@ impl Engine {
411 if let Some(sfx) = self.surface_fx.get() {417 if let Some(sfx) = self.surface_fx.get() {
412 sfx.borrow_mut().trim_uniform_chunks(2);418 sfx.borrow_mut().trim_uniform_chunks(2);
413 }419 }
420 if let Some(lo) = self.layer_ocio.get() {
421 lo.borrow_mut().trim_uniform_chunks(2);
422 }
414 if let Some(am) = self.auto_matte_pipelines.get() {423 if let Some(am) = self.auto_matte_pipelines.get() {
415 am.borrow_mut().trim_uniform_chunks(2);424 am.borrow_mut().trim_uniform_chunks(2);
416 }425 }
...@@ -1063,6 +1072,18 @@ impl Engine {...@@ -1063,6 +1072,18 @@ impl Engine {
1063 "TV" => self.eval_tv(comp, node, time, frame_i, enc, visiting, stats),1072 "TV" => self.eval_tv(comp, node, time, frame_i, enc, visiting, stats),
1064 "AutoDomain" => self.eval_auto_domain(comp, node, time, frame_i, enc, visiting, stats),1073 "AutoDomain" => self.eval_auto_domain(comp, node, time, frame_i, enc, visiting, stats),
1065 "Fuse.FrameAverage" => self.eval_fuse_frame_average(comp, node, time, frame_i, enc, visiting, stats),1074 "Fuse.FrameAverage" => self.eval_fuse_frame_average(comp, node, time, frame_i, enc, visiting, stats),
1075 "OCIOColorSpace" => self.eval_ocio_color_space(comp, node, time, frame_i, enc, visiting, stats),
1076 "OCIODisplay" => self.eval_ocio_display(comp, node, time, frame_i, enc, visiting, stats),
1077 "OCIOFileTransform" => self.eval_ocio_file_transform(comp, node, time, frame_i, enc, visiting, stats),
1078 "LayerMuxer" => self.eval_layer_muxer(comp, node, time, enc, visiting, stats),
1079 "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats),
1080 "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats),
1081 "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats),
1082 "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" => self.eval_passthrough(comp, node, time, enc, visiting, stats),
1083 "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats),
1084 "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats),
1085 "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats),
1086 "ChromaticAberrationRemoval" => self.eval_chromatic_aberration_removal(comp, node, time, frame_i, enc, visiting, stats),
1066 "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats),1087 "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
1067 "sNGon"1088 "sNGon"
1068 | "sRectangle"1089 | "sRectangle"
crates/engine/src/shaders/color_lut.wgsl+24-3
...@@ -905,6 +905,18 @@ fn sample_lut3d_tetrahedral(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32, t...@@ -905,6 +905,18 @@ fn sample_lut3d_tetrahedral(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32, t
905 }905 }
906}906}
907907
908fn sample_lut3d_trilinear(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32, tiles_x: i32) -> vec3<f32> {
909 let pos = clamp(rgb_norm, vec3<f32>(0.0), vec3<f32>(1.0)) * f32(n - 1);
910 let i0 = min(vec3<i32>(floor(pos)), vec3<i32>(max(n - 2, 0)));
911 let i1 = min(i0 + vec3<i32>(1), vec3<i32>(n - 1));
912 let f = pos - vec3<f32>(i0);
913 let c00 = mix(fetch_lut3d_texel(lut, i0.r, i0.g, i0.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i0.g, i0.b, n, tiles_x, false), f.r);
914 let c10 = mix(fetch_lut3d_texel(lut, i0.r, i1.g, i0.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i1.g, i0.b, n, tiles_x, false), f.r);
915 let c01 = mix(fetch_lut3d_texel(lut, i0.r, i0.g, i1.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i0.g, i1.b, n, tiles_x, false), f.r);
916 let c11 = mix(fetch_lut3d_texel(lut, i0.r, i1.g, i1.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i1.g, i1.b, n, tiles_x, false), f.r);
917 return mix(mix(c00, c10, f.g), mix(c01, c11, f.g), f.b);
918}
919
908fn sample_lut1d(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32) -> vec3<f32> {920fn sample_lut1d(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32) -> vec3<f32> {
909 let max_i = f32(n - 1);921 let max_i = f32(n - 1);
910 let pr = clamp(rgb_norm.r, 0.0, 1.0) * max_i;922 let pr = clamp(rgb_norm.r, 0.0, 1.0) * max_i;
...@@ -930,7 +942,7 @@ fn sample_lut1d(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32) -> vec3<f32>...@@ -930,7 +942,7 @@ fn sample_lut1d(lut: texture_2d<f32>, rgb_norm: vec3<f32>, n: i32) -> vec3<f32>
930// p[3] = (offset, clip_black, clip_white, prediv)942// p[3] = (offset, clip_black, clip_white, prediv)
931// p[4] = (blend, has_mask, mask_inv, mbm)943// p[4] = (blend, has_mask, mask_inv, mbm)
932// p[5] = skip944// p[5] = skip
933// p[6] = (color_space: 0=RGB, 1=YUV, 2=HLS, 3=YIQ, 4=CMY, 0, 0, 0)945// p[6] = (color_space: 0=RGB, 1=YUV, 2=HLS, 3=YIQ, 4=CMY, interp: 0=tetrahedral 1=trilinear 2=nearest, 0, 0)
934// ============================================================================946// ============================================================================
935fn lut_rgb_to_cs(rgb: vec3<f32>, cs: i32) -> vec3<f32> {947fn lut_rgb_to_cs(rgb: vec3<f32>, cs: i32) -> vec3<f32> {
936 if (cs == 1) {948 if (cs == 1) {
...@@ -993,10 +1005,19 @@ fn file_lut_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -993,10 +1005,19 @@ fn file_lut_op(@builtin(global_invocation_id) gid: vec3<u32>) {
9931005
994 let dmin = u.p[0].xyz;1006 let dmin = u.p[0].xyz;
995 let dmax = u.p[1].xyz;1007 let dmax = u.p[1].xyz;
996 let norm_rgb = (rgb - dmin) / max(dmax - dmin, vec3<f32>(1e-6));1008 var norm_rgb = (rgb - dmin) / max(dmax - dmin, vec3<f32>(1e-6));
1009 let interp = i32(round(u.p[6].y));
1010 if (interp == 2 && lut_size >= 2) {
1011 let last = f32(lut_size - 1);
1012 norm_rgb = round(clamp(norm_rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * last) / last;
1013 }
9971014
998 if (lut_kind == 3 && lut_size >= 2) {1015 if (lut_kind == 3 && lut_size >= 2) {
999 rgb = sample_lut3d_tetrahedral(tex_b, norm_rgb, lut_size, tiles_x, false);1016 if (interp == 1) {
1017 rgb = sample_lut3d_trilinear(tex_b, norm_rgb, lut_size, tiles_x);
1018 } else {
1019 rgb = sample_lut3d_tetrahedral(tex_b, norm_rgb, lut_size, tiles_x, false);
1020 }
1000 } else if (lut_kind == 1 && lut_size >= 2) {1021 } else if (lut_kind == 1 && lut_size >= 2) {
1001 rgb = sample_lut1d(tex_b, norm_rgb, lut_size);1022 rgb = sample_lut1d(tex_b, norm_rgb, lut_size);
1002 }1023 }
crates/engine/src/shaders/layer_ocio.wgsl created+269
...@@ -0,0 +1,269 @@
1// OCIODisplay, Swizzler, Fields & ChromaticAberrationRemoval compute shaders.
2//
3// WebGPU-safe (`wasm32` compatible): every texture input is `filterable: false` and read via
4// `textureLoad`; the output is a WriteOnly storage texture (format patched at pipeline build);
5// no `read_write` storage textures.
6//
7// Shared tail params for every op: p[14] = (blend, has_mask, mask_inv, mbm), p[15] = skip (1 = keep source).
8// Bindings: tex_a = main source, tex_b = secondary, tex_c = Z aux (Swizzler) / unused, mask_tex = EffectMask.
9
10@group(0) @binding(0) var tex_a: texture_2d<f32>;
11@group(0) @binding(1) var tex_b: texture_2d<f32>;
12@group(0) @binding(2) var tex_c: texture_2d<f32>;
13@group(0) @binding(3) var mask_tex: texture_2d<f32>;
14@group(0) @binding(4) var dst_tex: texture_storage_2d<rgba8unorm, write>;
15
16struct Params {
17 p: array<vec4<f32>, 16>,
18};
19@group(0) @binding(5) var<uniform> u: Params;
20
21const HDR_FLOAT: bool = false;
22const LUMA_709: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
23
24fn store_dst(p: vec2<i32>, col: vec4<f32>) {
25 if (HDR_FLOAT) {
26 textureStore(dst_tex, p, col);
27 } else {
28 textureStore(dst_tex, p, clamp(col, vec4<f32>(0.0), vec4<f32>(1.0)));
29 }
30}
31
32fn load_clamped(tex: texture_2d<f32>, p: vec2<i32>) -> vec4<f32> {
33 let dims = vec2<i32>(textureDimensions(tex));
34 return textureLoad(tex, clamp(p, vec2<i32>(0), max(dims - vec2<i32>(1), vec2<i32>(0))), 0);
35}
36
37fn sample_bilinear(tex: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> {
38 let dims = vec2<i32>(textureDimensions(tex));
39 let max_c = max(dims - vec2<i32>(1), vec2<i32>(0));
40 let f = clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)) * vec2<f32>(dims) - vec2<f32>(0.5);
41 let i0 = clamp(vec2<i32>(floor(f)), vec2<i32>(0), max_c);
42 let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), max_c);
43 let t = clamp(f - floor(f), vec2<f32>(0.0), vec2<f32>(1.0));
44 let c00 = textureLoad(tex, i0, 0);
45 let c10 = textureLoad(tex, vec2<i32>(i1.x, i0.y), 0);
46 let c01 = textureLoad(tex, vec2<i32>(i0.x, i1.y), 0);
47 let c11 = textureLoad(tex, i1, 0);
48 return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y);
49}
50
51fn read_mask(gid: vec2<u32>, dims: vec2<u32>) -> f32 {
52 if (u.p[14].y < 0.5) {
53 return 1.0;
54 }
55 let uv = (vec2<f32>(gid) + vec2<f32>(0.5)) / vec2<f32>(dims);
56 let m = sample_bilinear(mask_tex, uv).a;
57 return select(m, 1.0 - m, u.p[14].z > 0.5);
58}
59
60/// Blend `res` over `src` by `Blend * EffectMask`; `MultiplyByMask` zeroes outside the mask.
61fn finish(src: vec4<f32>, res: vec4<f32>, gid: vec2<u32>, dims: vec2<u32>) -> vec4<f32> {
62 let m = clamp(read_mask(gid, dims) * u.p[14].x, 0.0, 1.0);
63 let use_mbm = u.p[14].y > 0.5 && u.p[14].w > 0.5;
64 var out_col = select(mix(src, res, m), res * m, use_mbm);
65 let unproc = select(src, vec4<f32>(0.0), use_mbm);
66 return select(out_col, unproc, u.p[15] > vec4<f32>(0.5));
67}
68
69// ============================================================================
70// OCIODisplay — exposure -> view transform -> display curve -> post gamma
71// tex_a = premultiplied linear image in display primaries, tex_b = original source (blend base)
72// p[0] = (exposure_gain, inv_post_gamma, display_curve, view_transform)
73// display_curve: 0=linear 1=sRGB 2=g2.2 3=g2.4 4=g2.6 5=PQ 6=HLG
74// view_transform: 0=none 1=ACES filmic fit 2=Reinhard
75// ============================================================================
76fn pow_signed(c: f32, e: f32) -> f32 {
77 return sign(c) * pow(abs(c), e);
78}
79
80fn encode_display(c: f32, curve: i32) -> f32 {
81 switch curve {
82 case 1: {
83 let a = abs(c);
84 let v = select(1.055 * pow(a, 1.0 / 2.4) - 0.055, a * 12.92, a <= 0.0031308);
85 return sign(c) * v;
86 }
87 case 2: { return pow_signed(c, 1.0 / 2.2); }
88 case 3: { return pow_signed(c, 1.0 / 2.4); }
89 case 4: { return pow_signed(c, 1.0 / 2.6); }
90 case 5: {
91 let y = pow(clamp(c, 0.0, 1.0e4) * 100.0 / 10000.0, 0.1593017578125);
92 return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), 78.84375);
93 }
94 case 6: {
95 let e = max(c, 0.0);
96 return select(0.17883277 * log(12.0 * e - 0.28466892) + 0.55991073, sqrt(3.0 * e), e <= 1.0 / 12.0);
97 }
98 default: { return c; }
99 }
100}
101
102fn view_tonemap(x: vec3<f32>, mode: i32) -> vec3<f32> {
103 if (mode == 1) {
104 let v = max(x, vec3<f32>(0.0));
105 return clamp((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
106 }
107 if (mode == 2) {
108 let v = max(x, vec3<f32>(0.0));
109 return v / (vec3<f32>(1.0) + v);
110 }
111 return x;
112}
113
114@compute @workgroup_size(8, 8)
115fn ocio_display_op(@builtin(global_invocation_id) gid: vec3<u32>) {
116 let dims = textureDimensions(dst_tex);
117 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
118 let p = vec2<i32>(gid.xy);
119 let lin = textureLoad(tex_a, p, 0);
120 let orig = textureLoad(tex_b, p, 0);
121 let curve = i32(round(u.p[0].z));
122 let straight = select(lin.rgb, lin.rgb / lin.a, lin.a > 1e-6);
123 var rgb = view_tonemap(straight * u.p[0].x, i32(round(u.p[0].w)));
124 rgb = vec3<f32>(encode_display(rgb.r, curve), encode_display(rgb.g, curve), encode_display(rgb.b, curve));
125 if (abs(u.p[0].y - 1.0) > 1e-6) {
126 rgb = vec3<f32>(pow_signed(rgb.r, u.p[0].y), pow_signed(rgb.g, u.p[0].y), pow_signed(rgb.b, u.p[0].y));
127 }
128 store_dst(p, finish(orig, vec4<f32>(rgb * lin.a, lin.a), gid.xy, dims));
129}
130
131// ============================================================================
132// Swizzler — per-channel source selection
133// p[0] = (src_r, src_g, src_b, src_a), p[1] = (has_z, 0, 0, 0)
134// selector: 0..3 = R,G,B,A of Input, 4 = 0, 5 = 1, 6 = luminance, 7 = Z aux,
135// 8..11 = R,G,B,A of the secondary input (tex_b, UV-mapped), 12..15 = inverted 0..3
136// ============================================================================
137fn pick_channel(sel: i32, a: vec4<f32>, b: vec4<f32>, z: f32) -> f32 {
138 switch sel {
139 case 0: { return a.r; }
140 case 1: { return a.g; }
141 case 2: { return a.b; }
142 case 3: { return a.a; }
143 case 4: { return 0.0; }
144 case 5: { return 1.0; }
145 case 6: { return dot(a.rgb, LUMA_709); }
146 case 7: { return z; }
147 case 8: { return b.r; }
148 case 9: { return b.g; }
149 case 10: { return b.b; }
150 default: { return b.a; }
151 }
152}
153
154fn swizzle_channel(sel: i32, a: vec4<f32>, b: vec4<f32>, z: f32) -> f32 {
155 let inverted = sel >= 12;
156 let v = pick_channel(select(sel, sel - 12, inverted), a, b, z);
157 return select(v, 1.0 - v, inverted);
158}
159
160@compute @workgroup_size(8, 8)
161fn swizzler_op(@builtin(global_invocation_id) gid: vec3<u32>) {
162 let dims = textureDimensions(dst_tex);
163 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
164 let p = vec2<i32>(gid.xy);
165 let a = textureLoad(tex_a, p, 0);
166 let uv = (vec2<f32>(gid.xy) + vec2<f32>(0.5)) / vec2<f32>(dims);
167 let b = sample_bilinear(tex_b, uv);
168 var z = 0.0;
169 if (u.p[1].x > 0.5) {
170 z = sample_bilinear(tex_c, uv).r;
171 }
172 let res = vec4<f32>(
173 swizzle_channel(i32(round(u.p[0].x)), a, b, z),
174 swizzle_channel(i32(round(u.p[0].y)), a, b, z),
175 swizzle_channel(i32(round(u.p[0].z)), a, b, z),
176 swizzle_channel(i32(round(u.p[0].w)), a, b, z),
177 );
178 store_dst(p, finish(a, res, gid.xy, dims));
179}
180
181// ============================================================================
182// Fields — line-parity processing. tex_a = Input, tex_b = second field source (Interlace)
183// p[0] = (operation, method, dominant_parity, has_b)
184// operation: 0=Deinterlace 1=Interlace 2=SwapFields 3=StripFields
185// method: 0=Blend 1=Interpolate 2=Duplicate
186// dominant_parity: row % 2 == parity rows belong to the dominant (first) field
187// ============================================================================
188@compute @workgroup_size(8, 8)
189fn fields_op(@builtin(global_invocation_id) gid: vec3<u32>) {
190 let dims = textureDimensions(dst_tex);
191 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
192 let p = vec2<i32>(gid.xy);
193 let a = textureLoad(tex_a, p, 0);
194 let op = i32(round(u.p[0].x));
195 let method = i32(round(u.p[0].y));
196 let parity = i32(round(u.p[0].z));
197 let h = i32(dims.y);
198 let dominant = (p.y % 2) == parity;
199 let up = load_clamped(tex_a, p + vec2<i32>(0, -1));
200 let down = load_clamped(tex_a, p + vec2<i32>(0, 1));
201 var res = a;
202 if (op == 1) {
203 if (!dominant && u.p[0].w > 0.5) {
204 res = load_clamped(tex_b, p);
205 }
206 } else if (op == 2) {
207 // Swap each (2k, 2k+1) line pair; an unpaired last line passes through.
208 let partner = select(p.y + 1, p.y - 1, (p.y % 2) == 1);
209 if (partner < h) {
210 res = textureLoad(tex_a, vec2<i32>(p.x, partner), 0);
211 }
212 } else if (!dominant) {
213 // Deinterlace / StripFields: rebuild the non-dominant field from the dominant one.
214 let has_up = p.y > 0;
215 let has_down = p.y + 1 < h;
216 let dup = select(down, up, has_up);
217 let interp = select(select(select(a, down, has_down), up, has_up), (up + down) * 0.5, has_up && has_down);
218 if (op == 3 || method == 2) {
219 res = dup;
220 } else if (method == 1) {
221 res = interp;
222 } else {
223 res = (a + interp) * 0.5;
224 }
225 }
226 store_dst(p, finish(a, res, gid.xy, dims));
227}
228
229// ============================================================================
230// ChromaticAberrationRemoval — per-channel radial rescale about Center + defringe
231// p[0] = (scale_r, scale_g, scale_b, defringe), p[1] = (center_u, center_v (top-down), 0, 0)
232// ============================================================================
233fn sample_channel_scaled(uv: vec2<f32>, center: vec2<f32>, scale: f32) -> vec4<f32> {
234 return sample_bilinear(tex_a, center + (uv - center) * scale);
235}
236
237@compute @workgroup_size(8, 8)
238fn chroma_aberration_op(@builtin(global_invocation_id) gid: vec3<u32>) {
239 let dims = textureDimensions(dst_tex);
240 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
241 let p = vec2<i32>(gid.xy);
242 let a = textureLoad(tex_a, p, 0);
243 let uv = (vec2<f32>(gid.xy) + vec2<f32>(0.5)) / vec2<f32>(dims);
244 let center = u.p[1].xy;
245 var rgb = vec3<f32>(
246 sample_channel_scaled(uv, center, u.p[0].x).r,
247 sample_channel_scaled(uv, center, u.p[0].y).g,
248 sample_channel_scaled(uv, center, u.p[0].z).b,
249 );
250 let defringe = u.p[0].w;
251 if (defringe > 1e-6) {
252 // Desaturate where the 3x3 neighbourhood's colour-difference signal swings hard (colour fringes).
253 var lo = vec3<f32>(1.0e9);
254 var hi = vec3<f32>(-1.0e9);
255 for (var dy = -1; dy <= 1; dy++) {
256 for (var dx = -1; dx <= 1; dx++) {
257 let n = load_clamped(tex_a, p + vec2<i32>(dx, dy)).rgb;
258 let l = dot(n, LUMA_709);
259 let d = vec3<f32>(n.r - l, n.g - l, n.b - l);
260 lo = min(lo, d);
261 hi = max(hi, d);
262 }
263 }
264 let swing = max(hi.r - lo.r, max(hi.b - lo.b, hi.g - lo.g));
265 let amount = clamp(swing * defringe * 2.0, 0.0, 1.0);
266 rgb = mix(rgb, vec3<f32>(dot(rgb, LUMA_709)), amount);
267 }
268 store_dst(p, finish(a, vec4<f32>(rgb, a.a), gid.xy, dims));
269}