From 6c034902b2bbdbd7158ab5bc50a4e08b6059829a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:30:48 -0500 Subject: [PATCH] craft-develop: extract spline, curve, and lut modules from LightCraft (#587) (#2274) Co-authored-by: texjer --- Cargo.toml | 1 + crates/develop/Cargo.toml | 18 +++ crates/develop/src/color/mod.rs | 3 + crates/develop/src/color/spline.rs | 206 +++++++++++++++++++++++++ crates/develop/src/curve.rs | 238 +++++++++++++++++++++++++++++ crates/develop/src/lib.rs | 5 + crates/develop/src/lut.rs | 164 ++++++++++++++++++++ 7 files changed, 635 insertions(+) create mode 100644 crates/develop/Cargo.toml create mode 100644 crates/develop/src/color/mod.rs create mode 100644 crates/develop/src/color/spline.rs create mode 100644 crates/develop/src/curve.rs create mode 100644 crates/develop/src/lib.rs create mode 100644 crates/develop/src/lut.rs diff --git a/Cargo.toml b/Cargo.toml index b5581ed03..3f7db3be2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -174,6 +174,7 @@ craft-quit = { path = "crates/quit" } craft-rtf = { path = "crates/rtf" } craft-raw = { path = "crates/raw" } craft-geom = { path = "crates/geom" } +craft-develop = { path = "crates/develop" } craft-develop-model = { path = "crates/develop-model" } craft-sheet = { path = "crates/sheet" } craft-sketch = { path = "crates/sketch" } diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml new file mode 100644 index 000000000..0daa6107f --- /dev/null +++ b/crates/develop/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-develop" +description = "The raw develop pipeline, CPU path: sensor data from craft-raw (or a decoded linear image) and craft-develop-model settings in, the rendered picture out." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-develop-model = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/develop/src/color/mod.rs b/crates/develop/src/color/mod.rs new file mode 100644 index 000000000..cc8b9a869 --- /dev/null +++ b/crates/develop/src/color/mod.rs @@ -0,0 +1,3 @@ +//! Colour helpers for the develop pipeline. + +pub mod spline; diff --git a/crates/develop/src/color/spline.rs b/crates/develop/src/color/spline.rs new file mode 100644 index 000000000..c2c75f305 --- /dev/null +++ b/crates/develop/src/color/spline.rs @@ -0,0 +1,206 @@ +//! Curves for tone mapping: monotone cubic Hermite splines (Fritsch–Carlson) and lookup tables. +//! +//! Monotone interpolation never overshoots between control points, so a point curve can't invert +//! tones by accident (a common complaint with natural cubic splines). + +use serde::{Deserialize, Serialize}; + +/// A curve through control points in `0..1 × 0..1` (x strictly increasing after normalization). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MonotoneCurve { + xs: Vec, + ys: Vec, + ms: Vec, +} + +impl MonotoneCurve { + /// Build from points; sorts by x, merges duplicates. Fewer than two points → identity. + pub fn new(points: &[(f64, f64)]) -> MonotoneCurve { + let mut p: Vec<(f64, f64)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); + p.sort_by(|a, b| a.0.total_cmp(&b.0)); + p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9); + if p.len() < 2 { + p = vec![(0.0, 0.0), (1.0, 1.0)]; + } + let n = p.len(); + let xs: Vec = p.iter().map(|q| q.0).collect(); + let ys: Vec = p.iter().map(|q| q.1).collect(); + let d: Vec = (0..n - 1).map(|i| (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i])).collect(); + let mut ms = vec![0.0; n]; + ms[0] = d[0]; + ms[n - 1] = d[n - 2]; + for i in 1..n - 1 { + ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 }; + } + // Fritsch–Carlson limiter where the data is monotone within a segment. + for i in 0..n - 1 { + if d[i] == 0.0 { + ms[i] = 0.0; + ms[i + 1] = 0.0; + continue; + } + let a = ms[i] / d[i]; + let b = ms[i + 1] / d[i]; + let s = a * a + b * b; + if s > 9.0 { + let t = 3.0 / s.sqrt(); + ms[i] = t * a * d[i]; + ms[i + 1] = t * b * d[i]; + } + } + MonotoneCurve { xs, ys, ms } + } + + pub fn identity() -> MonotoneCurve { + MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)]) + } + + pub fn eval(&self, x: f64) -> f64 { + // NaN passes both bound checks below and would send the search past either end + if x.is_nan() { + return x; + } + let n = self.xs.len(); + if x <= self.xs[0] { + return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0; + } + if x >= self.xs[n - 1] { + return self.ys[n - 1]; + } + let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) { + Ok(i) => return self.ys[i], + Err(i) => i - 1, + }; + let h = self.xs[i + 1] - self.xs[i]; + let t = (x - self.xs[i]) / h; + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[i] + + (t3 - 2.0 * t2 + t) * h * self.ms[i] + + (-2.0 * t3 + 3.0 * t2) * self.ys[i + 1] + + (t3 - t2) * h * self.ms[i + 1] + } + + /// Sample into a LUT of `n` entries (at least 2) over `0..1`. + pub fn to_lut(&self, n: usize) -> Lut1 { + let n = n.max(2); + Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() } + } + + pub fn points(&self) -> Vec<(f64, f64)> { + self.xs.iter().copied().zip(self.ys.iter().copied()).collect() + } +} + +/// A 1-D lookup table over `0..1` with linear interpolation; inputs outside clamp. +#[derive(Clone, Debug, PartialEq)] +pub struct Lut1 { + pub v: Vec, +} + +impl Lut1 { + /// At least 2 entries, like [`Lut1::from_fn`]. + pub fn identity(n: usize) -> Lut1 { + Lut1::from_fn(n, |x| x) + } + /// `f` sampled at `n` evenly spaced points over `0..1` (at least 2). + pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 { + let n = n.max(2); + Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() } + } + /// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0). + #[inline] + pub fn eval(&self, x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + let n = self.v.len(); + if n < 2 { + return self.v.first().copied().unwrap_or(x); + } + let f = x * (n - 1) as f32; + let i = (f as usize).min(n - 2); + let t = f - i as f32; + self.v[i] + (self.v[i + 1] - self.v[i]) * t + } + /// `self ∘ inner` (apply `inner` first). + pub fn compose(&self, inner: &Lut1) -> Lut1 { + Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() } + } + pub fn is_identity(&self) -> bool { + let n = self.v.len(); + self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identity_curve() { + let c = MonotoneCurve::identity(); + for i in 0..=10 { + let x = i as f64 / 10.0; + assert!((c.eval(x) - x).abs() < 1e-12); + } + assert!(c.to_lut(256).is_identity()); + } + + #[test] + fn passes_through_points_and_is_monotone() { + let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)]; + let c = MonotoneCurve::new(&pts); + for (x, y) in pts { + assert!((c.eval(x) - y).abs() < 1e-12); + } + let mut prev = -1.0; + for i in 0..=1000 { + let y = c.eval(i as f64 / 1000.0); + assert!(y >= prev - 1e-12); + prev = y; + } + } + + #[test] + fn no_overshoot_on_flat_segment() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]); + for i in 400..=600 { + let y = c.eval(i as f64 / 1000.0); + assert!((y - 0.5).abs() < 1e-9, "{y}"); + } + } + + #[test] + fn lut_compose() { + let a = Lut1::from_fn(1024, |x| x * x); + let b = Lut1::from_fn(1024, |x| x.sqrt()); + let c = a.compose(&b); + assert!((c.eval(0.3) - 0.3).abs() < 2e-3); + } + + #[test] + fn nan_input_and_short_luts_do_not_panic() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]); + assert!(c.eval(f64::NAN).is_nan()); + assert!(c.eval(-f64::NAN).is_nan()); + for n in [0, 1] { + assert_eq!(c.to_lut(n).v.len(), 2, "{n}"); + assert!(Lut1::identity(n).is_identity(), "{n}"); + assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}"); + } + assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3); + assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table"); + assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0); + assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7); + } + + proptest::proptest! { + #[test] + fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) { + let mut ys = ys; ys.sort_by(|a, b| a.total_cmp(b)); + let n = ys.len(); + let pts: Vec<(f64, f64)> = ys.iter().enumerate().map(|(i, y)| (i as f64 / (n - 1) as f64, *y)).collect(); + let c = MonotoneCurve::new(&pts); + let mut prev = f64::MIN; + for i in 0..=200 { let y = c.eval(i as f64 / 200.0); proptest::prop_assert!(y >= prev - 1e-9); prev = y; } + } + } +} diff --git a/crates/develop/src/curve.rs b/crates/develop/src/curve.rs new file mode 100644 index 000000000..46b0eef6a --- /dev/null +++ b/crates/develop/src/curve.rs @@ -0,0 +1,238 @@ +//! The parametric tone curve model shared by the pipeline renderer and the UI curve editor. +//! +//! Lightroom-style tone curve parametric model: four regions (shadows, darks, lights, highlights) +//! separated by three split points. Each region contributes a cosine-windowed bump, summed and +//! forced monotone. + +use crate::color::spline::Lut1; +use craft_develop_model::ToneCurve; + +/// The four shape controls of the parametric curve, in graph order: region 0 is the darkest. +pub const PARAM_AMOUNTS: [&str; 4] = ["curve.shadows", "curve.darks", "curve.lights", "curve.highlights"]; + +/// Resolution the parametric curve is sampled at, matching the renderer's LUT. +pub const PARAM_LUT: usize = 1024; + +/// The parametric (region) curve of a [`ToneCurve`]: the four region amounts, each a cosine bump +/// over its window between two splits, summed and then forced monotone. +/// +/// This is the renderer's curve, not an approximation of it — both `curve_luts` in the pipeline +/// and the curve editor in the UI use this struct so they can never disagree. +#[derive(Clone, Debug)] +pub struct ParametricCurve { + /// The curve, sampled and already forced monotone. + lut: [f32; PARAM_LUT], + /// The three region boundaries as fractions of the graph (0..1). + pub splits: [f64; 3], + /// The four region amounts, in graph order (0 = shadows, 3 = highlights). + pub amounts: [f64; 4], +} + +impl ParametricCurve { + pub fn new(c: &ToneCurve) -> ParametricCurve { + let s0 = if c.split_shadows.is_nan() { 0.25 } else { (c.split_shadows / 100.0).clamp(0.0, 1.0) as f32 }; + let s1 = if c.split_mid.is_nan() { 0.50_f32.max(s0) } else { (c.split_mid / 100.0).clamp(s0 as f64, 1.0) as f32 }; + let s2 = if c.split_highlights.is_nan() { 0.75_f32.max(s1) } else { (c.split_highlights / 100.0).clamp(s1 as f64, 1.0) as f32 }; + let clean_amt = |a: f64| if a.is_nan() { 0.0 } else { a.clamp(-100.0, 100.0) }; + let (a0, a1, a2, a3) = (clean_amt(c.shadows), clean_amt(c.darks), clean_amt(c.lights), clean_amt(c.highlights)); + let splits = [s0 as f64, s1 as f64, s2 as f64]; + let amounts = [a0, a1, a2, a3]; + let regions = [(0.0, s0, a0), (s0, s1, a1), (s1, s2, a2), (s2, 1.0, a3)]; + let mut lut = [0.0_f32; PARAM_LUT]; + let mut prev = 0.0_f32; + for (i, entry) in lut.iter_mut().enumerate() { + let x = i as f32 / (PARAM_LUT - 1) as f32; + let mut d = 0.0_f32; + for (a, b, amt) in regions { + if amt == 0.0 { + continue; + } + let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); + if half <= f32::EPSILON { + continue; + } + let t = ((x - ctr) / half).clamp(-1.0, 1.0); + d += (amt / 100.0) as f32 * 0.22 * (0.5 + 0.5 * (t * std::f32::consts::PI).cos()); + } + let y = (x + d * 4.0 * x * (1.0 - x)).clamp(0.0, 1.0); + prev = prev.max(y); + *entry = prev; + } + ParametricCurve { lut, splits, amounts } + } + + /// Convert the evaluated parametric curve into a 1024-entry [`Lut1`]. + pub fn to_lut(&self) -> Lut1 { + Lut1 { v: self.lut.to_vec() } + } + + /// The curve at `x` (0 = black, 1 = white), read off the table (so it never overshoots the ends). + pub fn at(&self, x: f64) -> f64 { + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) as f32 }; + let at = x * (PARAM_LUT - 1) as f32; + let i = at.floor().clamp(0.0, (PARAM_LUT - 1) as f32) as usize; + let cur = self.lut.get(i).copied().unwrap_or(0.0); + let next = self.lut.get(i + 1).copied().unwrap_or(cur); + let f = at - i as f32; + (cur + (next - cur) * f) as f64 + } + + /// Where region `region`'s handle sits on the input axis: the middle of its own window, so a + /// handle never has to cross a split to be grabbed. + pub fn region_x(&self, region: usize) -> f64 { + let (a, b) = self.region_window(region); + (a + b) / 2.0 + } + + /// The window (two splits, as fractions of the graph) region `region` owns. + pub fn region_window(&self, region: usize) -> (f64, f64) { + let s0 = self.split_x(0); + let s1 = self.split_x(1); + let s2 = self.split_x(2); + match region { + 0 => (0.0, s0), + 1 => (s0, s1), + 2 => (s1, s2), + _ => (s2, 1.0), + } + } + + /// The half-width of region `region`'s own bump, as fraction of the graph. + pub fn region_half(&self, region: usize) -> f64 { + let (a, b) = self.region_window(region); + (b - a) * 0.75 + 0.05 + } + + /// The cosine window region `region` applies at `x` (1 at its centre, 0 at the window edges). + pub fn region_window_at(&self, region: usize, x: f64) -> f64 { + let ctr = self.region_x(region); + let half = self.region_half(region); + if half <= f64::EPSILON { + return 0.0; + } + let t = ((x - ctr) / half).clamp(-1.0, 1.0); + 0.5 + 0.5 * (t * std::f64::consts::PI).cos() + } + + /// The region that owns graph position `x`: the one whose own window contains it. The four + /// windows tile 0..1, so this is always defined and a drag anywhere on the curve moves exactly + /// one slider — the region under the pointer. + pub fn region_at(&self, x: f64) -> usize { + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; + let s0 = self.split_x(0); + let s1 = self.split_x(1); + let s2 = self.split_x(2); + if x <= s0 { + 0 + } else if x <= s1 { + 1 + } else if x <= s2 { + 2 + } else { + 3 + } + } + + /// How much output level region `region`'s bump gains at `x` per unit of its slider: the bump is + /// linear in the amount, so this is a constant for a given `x`. A drag converts the pointer's + /// vertical motion into a slider change through it. + pub fn level_per_unit(&self, region: usize, x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + 0.22 / 100.0 * self.region_window_at(region, x) * 4.0 * x * (1.0 - x) + } + + /// The baseline level at `x` from the identity diagonal plus the contributions of all regions + /// *except* `region`. Used when inverting the model for `region` while holding the other three + /// regions fixed. + pub fn base_level_without(&self, region: usize, x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + let mut d = 0.0; + for i in 0..4 { + if i == region { + continue; + } + let amt = self.amounts.get(i).copied().unwrap_or(0.0); + if amt == 0.0 { + continue; + } + d += (amt / 100.0) * 0.22 * self.region_window_at(i, x); + } + x + d * 4.0 * x * (1.0 - x) + } + + /// The curve level region `region` sits at when its slider holds `amount`, at graph position `x`, + /// holding the other regions fixed at their current settings. + pub fn handle_level_at(&self, region: usize, amount: f64, x: f64) -> f64 { + (self.base_level_without(region, x) + amount * self.level_per_unit(region, x)).clamp(0.0, 1.0) + } + + /// The amount that puts region `region`'s curve at `level` at `x`, with the other three + /// regions held fixed — the inverse of [`Self::handle_level_at`]. A level the region cannot + /// reach saturates rather than jumping. + pub fn amount_at_level(&self, region: usize, level: f64, x: f64) -> f64 { + let per_unit = self.level_per_unit(region, x); + if per_unit.abs() <= f64::EPSILON { + return self.amounts.get(region).copied().unwrap_or(0.0); + } + let base = self.base_level_without(region, x); + ((level.clamp(0.0, 1.0) - base) / per_unit).clamp(-100.0, 100.0).round() + } + + /// The graph position split `split` (0..=2) sits at, 0..1. + pub fn split_x(&self, split: usize) -> f64 { + self.splits.get(split).copied().unwrap_or(0.5) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn non_finite_or_inverted_splits_do_not_panic_or_poison_curve() { + let c = ToneCurve { + split_shadows: 80.0, + split_mid: 20.0, + split_highlights: f64::NAN, + shadows: f64::NAN, + lights: f64::INFINITY, + ..Default::default() + }; + let model = ParametricCurve::new(&c); + assert!(model.at(0.5).is_finite()); + assert!(model.at(f64::NAN).is_finite()); + assert!(model.region_at(f64::NAN) < 4); + assert!((model.splits[0] - 0.8).abs() < 1e-6); + assert!((model.splits[1] - 0.8).abs() < 1e-6); + assert!((model.splits[2] - 0.8).abs() < 1e-6); + } + + #[test] + fn horizontal_inversion_at_x_0_51_with_darks_60_preserves_zero_lights() { + let c = ToneCurve { darks: 60.0, lights: 0.0, ..Default::default() }; + let model = ParametricCurve::new(&c); + assert_eq!(model.region_at(0.51), 2, "x=0.51 is inside the Lights region"); + let level = model.at(0.51); + assert!((level - 0.5619).abs() < 0.001, "extracted model at 0.51 is ~0.5619: {level}"); + // With other regions held fixed, inverting at level ~0.5619 must return Lights = 0, NOT 45! + let lights = model.amount_at_level(2, level, 0.51); + assert_eq!(lights, 0.0, "zero vertical delta preserves Lights=0: {lights}"); + } + + #[test] + fn a_curve_level_and_its_amount_are_inverses_with_other_regions_present() { + let c = ToneCurve { shadows: 20.0, darks: -30.0, lights: 40.0, highlights: -10.0, ..Default::default() }; + let model = ParametricCurve::new(&c); + for region in 0..4 { + let centre = model.region_x(region); + let (_, upper) = model.region_window(region); + for x in [centre, centre + (upper - centre) * 0.5] { + for amount in [-100.0, -40.0, 0.0, 30.0, 100.0] { + let level = model.handle_level_at(region, amount, x); + let back = model.amount_at_level(region, level, x); + assert!((back - amount).abs() <= 1.0, "region {region} at {x}: {amount} -> {level} -> {back}"); + } + } + } + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs new file mode 100644 index 000000000..e95ca26d7 --- /dev/null +++ b/crates/develop/src/lib.rs @@ -0,0 +1,5 @@ +//! Raw develop pipeline (CPU path), extracted from LightCraft. + +pub mod color; +pub mod curve; +pub mod lut; diff --git a/crates/develop/src/lut.rs b/crates/develop/src/lut.rs new file mode 100644 index 000000000..971599cbb --- /dev/null +++ b/crates/develop/src/lut.rs @@ -0,0 +1,164 @@ +//! 3D LUT profiles: `.cube` files (the plain-text Cube LUT format: `LUT_3D_SIZE`, optional +//! `DOMAIN_MIN` / `DOMAIN_MAX`, then size³ "r g b" lines with red changing fastest), applied to +//! the display-encoded output colour and blended by the profile amount. Profiles are registered +//! here by id (`lut:…`) and found by the finishing stage (CPU loop and GPU kernel alike). + +use std::collections::HashMap; +use std::sync::{Arc, OnceLock, RwLock}; + +/// A 3D colour lookup table. +#[derive(Clone, Debug, PartialEq)] +pub struct Lut3d { + pub size: usize, + pub data: Vec<[f32; 3]>, + pub domain_min: [f32; 3], + pub domain_max: [f32; 3], + pub title: Option, +} + +impl Lut3d { + /// Parse a `.cube` file. + pub fn parse_cube(text: &str) -> Result { + let (mut size, mut title) = (0usize, None); + let (mut min, mut max) = ([0.0f32; 3], [1.0f32; 3]); + let mut data = Vec::new(); + let three = |rest: &str| -> Option<[f32; 3]> { + let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); + (v.len() == 3 && v.iter().all(|x| x.is_finite())).then(|| [v[0], v[1], v[2]]) + }; + for line in text.lines() { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(r) = l.strip_prefix("TITLE") { + title = Some(r.trim().trim_matches('"').to_string()); + } else if let Some(r) = l.strip_prefix("LUT_3D_SIZE") { + size = r.trim().parse().map_err(|_| format!("bad LUT_3D_SIZE `{}`", r.trim()))?; + if !(2..=256).contains(&size) { + return Err(format!("LUT_3D_SIZE {size} out of range")); + } + } else if l.starts_with("LUT_1D_SIZE") { + return Err("1D LUTs are not supported (only 3D .cube files)".into()); + } else if let Some(r) = l.strip_prefix("DOMAIN_MIN") { + min = three(r).ok_or("bad DOMAIN_MIN")?; + } else if let Some(r) = l.strip_prefix("DOMAIN_MAX") { + max = three(r).ok_or("bad DOMAIN_MAX")?; + } else if l.starts_with(|c: char| c.is_ascii_alphabetic()) { + // a data line of `nan` / `inf` starts with a letter too: it is bad data, not a keyword + if l.split_whitespace().next().is_some_and(|w| w.parse::().is_ok()) { + return Err(format!("bad line `{l}`")); + } + // other keywords (LUT_IN_VIDEO_RANGE…) are ignored + } else { + data.push(three(l).ok_or_else(|| format!("bad line `{l}`"))?); + } + } + if size == 0 { + return Err("not a 3D .cube LUT (no LUT_3D_SIZE)".into()); + } + if data.len() != size * size * size { + return Err(format!("expected {} entries, found {}", size * size * size, data.len())); + } + Ok(Lut3d { size, data, domain_min: min, domain_max: max, title }) + } + + /// Look up `c` (trilinear). + pub fn apply(&self, c: [f32; 3]) -> [f32; 3] { + let n = self.size; + let s = (n - 1) as f32; + let mut idx = [0usize; 3]; + let mut frac = [0.0f32; 3]; + for k in 0..3 { + let span = (self.domain_max[k] - self.domain_min[k]).max(1e-6); + let x = (((c[k] - self.domain_min[k]) / span).clamp(0.0, 1.0)) * s; + let i = (x.floor() as usize).min(n - 2); + idx[k] = i; + frac[k] = x - i as f32; + } + let at = |r: usize, g: usize, b: usize| self.data[r + n * (g + n * b)]; + let lerp = |a: [f32; 3], b: [f32; 3], t: f32| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; + let (r, g, b) = (idx[0], idx[1], idx[2]); + let c00 = lerp(at(r, g, b), at(r + 1, g, b), frac[0]); + let c10 = lerp(at(r, g + 1, b), at(r + 1, g + 1, b), frac[0]); + let c01 = lerp(at(r, g, b + 1), at(r + 1, g, b + 1), frac[0]); + let c11 = lerp(at(r, g + 1, b + 1), at(r + 1, g + 1, b + 1), frac[0]); + lerp(lerp(c00, c10, frac[1]), lerp(c01, c11, frac[1]), frac[2]) + } +} + +fn registry() -> &'static RwLock>> { + static R: OnceLock>>> = OnceLock::new(); + R.get_or_init(Default::default) +} + +/// Make a LUT available to renders under profile id `id` (`lut:…`). +pub fn register(id: &str, lut: Lut3d) { + registry().write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), Arc::new(lut)); +} + +/// The LUT registered for profile `id`. +pub fn get(id: &str) -> Option> { + if !id.starts_with("lut:") { + return None; + } + registry().read().unwrap_or_else(|e| e.into_inner()).get(id).cloned() +} + +/// Forget a LUT profile. +pub fn unregister(id: &str) { + registry().write().unwrap_or_else(|e| e.into_inner()).remove(id); +} + +/// Profile ids that render with a LUT. +pub fn is_lut_profile(id: &str) -> bool { + id.starts_with("lut:") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cube(f: impl Fn([f32; 3]) -> [f32; 3], n: usize) -> String { + let mut s = format!("TITLE \"test\"\nLUT_3D_SIZE {n}\n"); + for b in 0..n { + for g in 0..n { + for r in 0..n { + let c = f([r as f32 / (n - 1) as f32, g as f32 / (n - 1) as f32, b as f32 / (n - 1) as f32]); + s.push_str(&format!("{} {} {}\n", c[0], c[1], c[2])); + } + } + } + s + } + + #[test] + fn identity_and_swap() { + let id = Lut3d::parse_cube(&cube(|c| c, 17)).unwrap(); + assert_eq!(id.title.as_deref(), Some("test")); + let v = id.apply([0.2, 0.55, 0.9]); + assert!(v.iter().zip([0.2, 0.55, 0.9]).all(|(a, b)| (a - b).abs() < 1e-5), "{v:?}"); + let swap = Lut3d::parse_cube(&cube(|c| [c[2], c[1], c[0]], 9)).unwrap(); + let v = swap.apply([0.1, 0.5, 0.8]); + assert!((v[0] - 0.8).abs() < 1e-5 && (v[2] - 0.1).abs() < 1e-5, "{v:?}"); + assert!(Lut3d::parse_cube("LUT_1D_SIZE 4\n0 0 0").is_err()); + assert!(Lut3d::parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err(), "too few entries"); + } + + #[test] + fn non_finite_entries_rejected() { + let bad_line = |body: &str| { + let e = Lut3d::parse_cube(body).expect_err(body); + assert!(e.starts_with("bad line"), "{e}"); + }; + bad_line(&format!("LUT_3D_SIZE 2\n{}", "-inf inf nan\n".repeat(8))); + bad_line(&format!("LUT_3D_SIZE 2\n{}", "1e39 0 0\n".repeat(8))); + bad_line(&format!("LUT_3D_SIZE 2\n-inf 0 0\n{}", "0 0 0\n".repeat(7))); + bad_line(&format!("LUT_3D_SIZE 2\nnan 0 0\n{}", "0 0 0\n".repeat(8))); + bad_line(&format!("LUT_3D_SIZE 2\ninf 0 0\n{}", "0 0 0\n".repeat(8))); + let ok = cube(|c| c, 2); + assert!(Lut3d::parse_cube(&ok).is_ok()); + assert!(Lut3d::parse_cube(&format!("DOMAIN_MIN nan 0 0\n{ok}")).is_err()); + assert!(Lut3d::parse_cube(&format!("DOMAIN_MAX inf 1 1\n{ok}")).is_err()); + } +}