craft-develop: extract colorops and light_v3 stages (#587) (#3000)

* craft-develop: extract colorops and light_v3 stages (#587)

* craft-develop: fix colorops imports against craft-color-transform

* develop: preserve calibrated color and RAW stage parity
This commit is contained in:
Dylan M. Taylor
2026-11-22 01:18:12 -05:00
committed by GitHub
parent 34129bac99
commit b67df8175c
7 changed files with 1423 additions and 0 deletions
Generated
+1
View File
@@ -1809,6 +1809,7 @@ dependencies = [
name = "craft-develop"
version = "0.1.0"
dependencies = [
"craft-color",
"craft-color-transform",
"craft-develop-model",
"craft-render-parity",
+1
View File
@@ -11,6 +11,7 @@ repository.workspace = true
workspace = true
[dependencies]
craft-color = { workspace = true }
craft-color-transform = { workspace = true }
craft-develop-model = { workspace = true }
serde = { workspace = true }
+2
View File
@@ -13,8 +13,10 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "<commi
| Module | From LightCraft (`a75497d6`) | Contents |
|---|---|---|
| `color::spline` | `crates/color/src/spline.rs` | Re-exports `craft_color_transform::curve` (`MonotoneCurve`, `Lut1`). |
| `colorops` | `crates/pipeline` | OkLCh colour tools (`ColorOps`, `WheelK`, `PointK`, `band_hues`, `band_weights`, `calibration_matrix`, `calibrate`). |
| `curve` | `crates/pipeline` | The parametric tone curve and its regions. |
| `finish` | `crates/pipeline` | Pure-Rust finishing helpers: sharpening masks/limits, vignette parameters, value grain, gamut mapping, and curve saturation refinement. |
| `light_v3` / `light_v3_params` | `crates/pipeline` | Process V4+ calibrated Contrast and Blacks operators (`LightOps`, `PreviewOps`, `Operator`, `Fit`, `Mode`). |
| `lut` | `crates/pipeline` | 3D lookup tables and the `.cube` reader. |
| `tone` | `crates/pipeline` | Global tone mapping (`ToneMap` and `CameraTone`) from scene luminance to display-linear luminance, SDR and HDR. |
| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. |
+530
View File
@@ -0,0 +1,530 @@
//! Colour tools in OkLCh on display-linear Rec.2020 values: vibrance, saturation, the 8-band colour
//! mixer, B&W mix, and 3-way colour grading; plus the camera-calibration matrix (scene linear).
use std::f32::consts::{PI, TAU};
use std::sync::OnceLock;
use craft_color::srgb_to_linear;
use craft_color_transform::oklab::{OkLab, lab_to_lch, lch_to_lab};
use craft_color_transform::{Mat3, REC2020, SRGB};
use craft_develop_model::{Calibration, DevelopSettings, MAX_POINT_COLORS, MIXER_HUES, PointColor, Treatment, Wheel};
fn oklab_2020() -> &'static OkLab {
static M: OnceLock<OkLab> = OnceLock::new();
M.get_or_init(|| OkLab::for_space(&REC2020))
}
#[inline]
fn oklab_from_2020(rgb: [f32; 3]) -> [f32; 3] {
oklab_2020().from_rgb(rgb)
}
#[inline]
fn oklab_to_2020(lab: [f32; 3]) -> [f32; 3] {
oklab_2020().to_rgb(lab)
}
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
let c = v * s;
let hp = h.rem_euclid(360.0) / 60.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let (r, g, b) = match hp as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
[r + m, g + m, b + m]
}
/// Whether `s` renders in black and white (B&W treatment or monochrome profile).
#[inline]
pub fn is_bw(s: &DevelopSettings) -> bool {
s.treatment == Treatment::Bw || s.profile.id == "lc.mono" || s.profile.id.starts_with("lc.bw.")
}
/// Linear Rec.2020 luminance.
#[inline]
pub fn luminance_2020(c: [f32; 3]) -> f32 {
c[0] * 0.2627 + c[1] * 0.6780 + c[2] * 0.0593
}
/// OkLCh hue angle (radians) of a pure sRGB colour with HSV hue `deg`.
pub fn oklch_hue_of_srgb_hue(deg: f64) -> f32 {
let c = hsv_to_rgb(deg as f32, 1.0, 1.0);
let lin = c.map(srgb_to_linear);
// Match LightCraft's matrix precision: round only after the full transform.
let rec = SRGB.to_space(&REC2020).apply(lin.map(f64::from)).map(|v| v as f32);
lab_to_lch(oklab_from_2020(rec))[2]
}
/// OkLCh hue (radians) of each colour-mixer band centre.
pub fn band_hues() -> &'static [f32; 8] {
static H: OnceLock<[f32; 8]> = OnceLock::new();
H.get_or_init(|| MIXER_HUES.map(oklch_hue_of_srgb_hue))
}
#[inline]
fn wrap(a: f32) -> f32 {
(a + PI).rem_euclid(TAU) - PI
}
/// Partition-of-unity weights of hue `h` over the 8 bands (raised cosine between neighbours).
#[inline]
pub fn band_weights(h: f32) -> [f32; 8] {
let hues = band_hues();
let mut w = [0.0f32; 8];
for i in 0..8 {
let a = hues[i];
let b = hues[(i + 1) % 8];
let span = wrap(b - a).rem_euclid(TAU);
let d = wrap(h - a).rem_euclid(TAU);
if d <= span {
let t = d / span;
let s = 0.5 - 0.5 * (t * PI).cos();
w[i] += 1.0 - s;
w[(i + 1) % 8] += s;
break;
}
}
w
}
/// A colour-grading wheel as an OkLab offset (a, b) and a lightness shift.
#[derive(Clone, Copy, Debug)]
pub struct WheelK {
pub a: f32,
pub b: f32,
pub lum: f32,
}
/// Number of `f32`s per Point Color sample in [`PointK::words`] (the GPU parameter layout).
pub const POINT_WORDS: usize = 10;
/// A Point Color sample resolved for the per-pixel stage: the sample (OkLab lightness, chroma, hue
/// in radians), the adjustment (hue rotation in radians, chroma scale − 1, lightness shift,
/// variance factor − 1) and the half-widths of the range box (hue radians, chroma, lightness).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PointK {
pub l: f32,
pub c: f32,
pub h: f32,
pub dh: f32,
pub sat: f32,
pub dl: f32,
pub var: f32,
pub wh: f32,
pub wc: f32,
pub wl: f32,
}
impl PointK {
pub fn new(p: &PointColor) -> PointK {
let k = (p.range.clamp(0.0, 100.0) / 50.0).max(0.05) as f32;
let f = |v: f64| (v.clamp(0.0, 100.0) / 100.0) as f32;
PointK {
l: p.lum as f32,
c: p.chroma.max(0.0) as f32,
h: (p.hue as f32).to_radians(),
dh: (p.hue_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.5,
sat: (p.sat_shift.clamp(-100.0, 100.0) / 100.0) as f32,
dl: (p.lum_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.2,
var: (p.variance.clamp(-100.0, 100.0) / 100.0) as f32 * 0.8,
wh: (0.1 + 0.6 * f(p.hue_range)) * k,
wc: (0.02 + 0.12 * f(p.sat_range)) * k,
wl: (0.05 + 0.4 * f(p.lum_range)) * k,
}
}
pub fn words(&self) -> [f32; POINT_WORDS] {
[self.l, self.c, self.h, self.dh, self.sat, self.dl, self.var, self.wh, self.wc, self.wl]
}
/// How much an OkLCh colour belongs to this sample's range (0..1, soft edges).
#[inline]
pub fn weight(&self, l: f32, c: f32, h: f32) -> f32 {
// hue is meaningless for near-neutral colours: a chromatic sample ignores them, a
// near-neutral sample selects by chroma and lightness only
let wh = if self.c < 0.02 { 1.0 } else { (1.0 - smooth(0.5 * self.wh, self.wh, wrap(h - self.h).abs())) * smooth(0.005, 0.025, c) };
if wh <= 0.0 {
return 0.0;
}
let wc = 1.0 - smooth(0.5 * self.wc, self.wc, (c - self.c).abs());
let wl = 1.0 - smooth(0.5 * self.wl, self.wl, (l - self.l).abs());
wh * wc * wl
}
/// Apply this sample's adjustment to an OkLCh colour.
#[inline]
pub fn apply(&self, lch: [f32; 3]) -> [f32; 3] {
let [mut l, mut c, mut h] = lch;
let w = self.weight(l, c, h);
if w <= 0.0 {
return lch;
}
h += w * (self.var * wrap(h - self.h) + self.dh);
c += w * self.var * (c - self.c);
c = (c * (1.0 + w * self.sat)).max(0.0);
l += w * (self.var * (l - self.l) + self.dl);
[l, c, h]
}
}
/// The colour tools' parameters, resolved once per render (fields are read by the GPU kernel).
#[derive(Clone, Debug)]
pub struct ColorOps {
pub vibrance: f32,
pub saturation: f32,
pub hue: [f32; 8],
pub sat: [f32; 8],
pub lum: [f32; 8],
pub mixer: bool,
/// Point Color samples that change something (applied after the mixer).
pub points: Vec<PointK>,
pub bw: Option<[f32; 8]>,
/// Wheels (shadows, midtones, highlights, global), blending, balance.
pub grading: Option<([WheelK; 4], f32, f32)>,
/// OkLCh hue of skin tones (protected by vibrance).
pub skin: f32,
}
fn wheel(w: &Wheel) -> WheelK {
let h = oklch_hue_of_srgb_hue(w.hue);
let s = (w.sat / 100.0) as f32 * 0.09;
WheelK { a: s * h.cos(), b: s * h.sin(), lum: (w.lum / 100.0) as f32 * 0.12 }
}
impl ColorOps {
pub fn new(s: &DevelopSettings) -> ColorOps {
let bands = s.mixer.bands();
let g = &s.grading;
ColorOps {
vibrance: (s.color.vibrance / 100.0) as f32,
saturation: (s.color.saturation / 100.0) as f32,
hue: bands.map(|b| (b.hue / 100.0) as f32 * 0.5),
sat: bands.map(|b| (b.sat / 100.0) as f32),
lum: bands.map(|b| (b.lum / 100.0) as f32 * 0.18),
mixer: !s.mixer.is_neutral(),
points: if is_bw(s) {
Vec::new()
} else {
s.point_colors.iter().take(MAX_POINT_COLORS).filter(|p| !p.is_neutral()).map(PointK::new).collect()
},
bw: is_bw(s).then(|| s.bw_mix.bands().map(|v| (v / 100.0) as f32)),
grading: (!g.is_neutral()).then(|| {
(
[wheel(&g.shadows), wheel(&g.midtones), wheel(&g.highlights), wheel(&g.global)],
(g.blending / 100.0) as f32,
(g.balance / 100.0) as f32,
)
}),
skin: oklch_hue_of_srgb_hue(25.0),
}
}
pub fn is_identity(&self) -> bool {
self.vibrance == 0.0 && self.saturation == 0.0 && !self.mixer && self.points.is_empty() && self.bw.is_none() && self.grading.is_none()
}
/// `local_sat` (−1..1) and `local_hue` (radians) come from masks.
#[inline]
pub fn apply(&self, rgb: [f32; 3], local_sat: f32, local_hue: f32) -> [f32; 3] {
if self.is_identity() && local_sat == 0.0 && local_hue == 0.0 {
return rgb;
}
let lab = oklab_from_2020(rgb);
// only chroma changes (vibrance / saturation, maybe grading): scale a, b directly — the same
// result as the OkLCh round trip without its sin / cos (and atan2 unless vibrance needs the hue)
if !self.mixer && self.points.is_empty() && self.bw.is_none() && local_hue == 0.0 {
let mut lab = lab;
let c0 = (lab[1] * lab[1] + lab[2] * lab[2]).sqrt();
let mut c = c0;
if self.vibrance != 0.0 {
let low = 1.0 - (c / 0.22).clamp(0.0, 1.0);
let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(lab[2].atan2(lab[1]) - self.skin) / 0.35).powi(2)).exp() } else { 1.0 };
c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0);
}
if self.saturation != 0.0 || local_sat != 0.0 {
c *= (1.0 + self.saturation + local_sat).max(0.0);
}
if c0 > 0.0 {
let k = c / c0;
lab[1] *= k;
lab[2] *= k;
}
return self.grade(lab);
}
let [mut l, mut c, mut h] = lab_to_lch(lab);
if self.mixer {
let w = band_weights(h);
let (mut dh, mut ds, mut dl) = (0.0, 0.0, 0.0);
for i in 0..8 {
dh += w[i] * self.hue[i];
ds += w[i] * self.sat[i];
dl += w[i] * self.lum[i];
}
let chroma_w = (c / 0.12).min(1.0);
h += dh * chroma_w;
c *= (1.0 + ds).max(0.0);
l += dl * chroma_w * l.max(0.05).sqrt();
}
for p in &self.points {
[l, c, h] = p.apply([l, c, h]);
}
if self.vibrance != 0.0 {
let low = 1.0 - (c / 0.22).clamp(0.0, 1.0);
let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(h - self.skin) / 0.35).powi(2)).exp() } else { 1.0 };
c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0);
}
if self.saturation != 0.0 || local_sat != 0.0 {
c *= (1.0 + self.saturation + local_sat).max(0.0);
}
h += local_hue;
if let Some(bw) = &self.bw {
let w = band_weights(h);
let mix: f32 = (0..8).map(|i| w[i] * bw[i]).sum();
l = (l + mix * (c / 0.2).min(1.0) * 0.25).max(0.0);
c = 0.0;
}
self.grade(lch_to_lab([l, c, h]))
}
/// Colour grading on OkLab, then back to linear Rec.2020.
#[inline]
fn grade(&self, mut lab: [f32; 3]) -> [f32; 3] {
if let Some((wheels, blending, balance)) = &self.grading {
let m = 0.5 - balance * 0.25;
let width = 0.15 + blending * 0.5;
let ws = 1.0 - smooth(m - width, m + width * 0.25, lab[0]);
let wh = smooth(m - width * 0.25, m + width, lab[0]);
let wm = (1.0 - ws - wh).max(0.0);
for (k, wt) in wheels.iter().zip([ws, wm, wh, 1.0]) {
lab[1] += k.a * wt;
lab[2] += k.b * wt;
lab[0] += k.lum * wt;
}
}
oklab_to_2020(lab)
}
}
/// Hue rotation (OkLCh radians) of a calibration primary at ±100.
pub const CALIB_HUE: f32 = 0.5;
/// Chroma scale of a calibration primary at ±100 (`1 ± CALIB_SAT`).
pub const CALIB_SAT: f32 = 0.6;
/// The calibration panel's primaries as a white-preserving 3×3 matrix on linear Rec.2020 (row-major):
/// each primary is rotated in OkLCh hue and scaled in chroma at constant OkLab lightness, then the
/// columns are rescaled so that neutral (1, 1, 1) maps to itself. `None` when neutral.
pub fn calibration_matrix(c: &Calibration) -> Option<[[f32; 3]; 3]> {
let prim = c.primaries();
if prim.iter().all(|(h, s)| *h == 0.0 && *s == 0.0) {
return None;
}
let mut p = [[0.0f64; 3]; 3];
for (i, (hue, sat)) in prim.iter().enumerate() {
let mut e = [0.0f32; 3];
e[i] = 1.0;
let [l, ch, h] = lab_to_lch(oklab_from_2020(e));
let h2 = h + (hue.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_HUE;
let c2 = ch * (1.0 + (sat.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_SAT);
let q = oklab_to_2020(lch_to_lab([l, c2, h2]));
for (r, row) in p.iter_mut().enumerate() {
row[i] = q[r] as f64;
}
}
let m = Mat3(p);
let k = m.inverse()?.apply([1.0, 1.0, 1.0]);
Some(std::array::from_fn(|r| std::array::from_fn(|col| (p[r][col] * k[col]) as f32)))
}
/// Shadows-tint strength at ±100: the green channel's relative change in deep shadows.
pub const SHADOW_TINT: f32 = 0.3;
/// Calibration in scene-linear light (before tone mapping): the primaries matrix, then the shadows
/// tint (green ↔ magenta, weighted towards dark tones, luminance kept). Skip tint when either
/// luminance is nonpositive so negative scene-linear samples cannot be inverted or amplified.
#[inline]
pub fn calibrate(c: [f32; 3], m: Option<&[[f32; 3]; 3]>, shadow_tint: f32) -> [f32; 3] {
let mut c = c;
if let Some(m) = m {
c = std::array::from_fn(|r| (m[r][0] * c[0] + m[r][1] * c[1] + m[r][2] * c[2]).max(0.0));
}
if shadow_tint != 0.0 {
let y0 = luminance_2020(c);
if y0 > 0.0 {
let w = 1.0 - smooth(-5.0, -0.5, (y0.max(1e-7) / 0.18).log2());
let tinted = [c[0], c[1] * (1.0 - SHADOW_TINT * shadow_tint * w).max(0.0), c[2]];
let y1 = luminance_2020(tinted);
if y1 > 0.0 {
c = tinted.map(|v| v * y0 / y1.max(1e-9));
}
}
}
c
}
#[inline]
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
#[cfg(test)]
mod tests {
use super::*;
use craft_color_transform::oklab::lab_to_lch;
#[test]
fn weights_partition_unity() {
for i in 0..360 {
let h = (i as f32).to_radians() - PI;
let w = band_weights(h);
let s: f32 = w.iter().sum();
assert!((s - 1.0).abs() < 1e-4, "{i}: {s}");
}
// at a band centre, that band dominates
let w = band_weights(band_hues()[5]);
assert!(w[5] > 0.99);
}
#[test]
fn neutral_is_identity() {
let ops = ColorOps::new(&DevelopSettings::default());
assert!(ops.is_identity());
assert_eq!(ops.apply([0.2, 0.3, 0.4], 0.0, 0.0), [0.2, 0.3, 0.4]);
}
#[test]
fn saturation_and_bw() {
let mut s = DevelopSettings::default();
s.color.saturation = -100.0;
let g = ColorOps::new(&s).apply([0.4, 0.1, 0.05], 0.0, 0.0);
assert!((g[0] - g[1]).abs() < 1e-3 && (g[1] - g[2]).abs() < 1e-3, "{g:?}");
let mut s = DevelopSettings { treatment: Treatment::Bw, ..Default::default() };
let ops = ColorOps::new(&s);
let b = ops.apply([0.05, 0.1, 0.5], 0.0, 0.0);
assert!((b[0] - b[2]).abs() < 1e-3);
// raising blue in the B&W mix brightens blue things
s.bw_mix.blue = 80.0;
let b2 = ColorOps::new(&s).apply([0.05, 0.1, 0.5], 0.0, 0.0);
assert!(b2[1] > b[1]);
}
#[test]
fn mixer_targets_its_band() {
let mut s = DevelopSettings::default();
s.mixer.blue.sat = -100.0;
let ops = ColorOps::new(&s);
let blue = [0.02, 0.05, 0.4];
let red = [0.4, 0.03, 0.02];
let cb = lab_to_lch(oklab_from_2020(ops.apply(blue, 0.0, 0.0)))[1];
let cr0 = lab_to_lch(oklab_from_2020(red))[1];
let cr = lab_to_lch(oklab_from_2020(ops.apply(red, 0.0, 0.0)))[1];
assert!(cb < 0.02, "{cb}");
assert!((cr - cr0).abs() < 0.01);
}
#[test]
fn calibration_keeps_white_and_moves_primaries() {
assert!(calibration_matrix(&Calibration::default()).is_none());
let cal = Calibration { red_hue: 60.0, blue_sat: -50.0, ..Default::default() };
let m = calibration_matrix(&cal).unwrap();
let grey = calibrate([0.3, 0.3, 0.3], Some(&m), 0.0);
assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-4), "{grey:?}");
// red rotates in hue, blue loses chroma
let red = [0.4, 0.05, 0.03];
let h0 = lab_to_lch(oklab_from_2020(red))[2];
let h1 = lab_to_lch(oklab_from_2020(calibrate(red, Some(&m), 0.0)))[2];
assert!(h1 - h0 > 0.05, "{h0} -> {h1}");
let blue = [0.03, 0.05, 0.4];
let c0 = lab_to_lch(oklab_from_2020(blue))[1];
let c1 = lab_to_lch(oklab_from_2020(calibrate(blue, Some(&m), 0.0)))[1];
assert!(c1 < c0 * 0.97, "{c0} -> {c1}");
}
#[test]
fn shadow_tint_targets_shadows() {
let dark = calibrate([0.01, 0.01, 0.01], None, 1.0);
let bright = calibrate([0.8, 0.8, 0.8], None, 1.0);
assert!(dark[1] < dark[0] * 0.85, "magenta shadows: {dark:?}");
assert!((bright[1] - bright[0]).abs() < 1e-3, "{bright:?}");
let y = |c: [f32; 3]| luminance_2020(c);
assert!((y(dark) - 0.01).abs() < 1e-5);
let green = calibrate([0.01, 0.01, 0.01], None, -1.0);
assert!(green[1] > green[0]);
}
#[test]
fn shadow_tint_skips_nonpositive_luminance_before_or_after_tint() {
let negative = [-0.01; 3];
assert_eq!(calibrate(negative, None, 1.0), negative);
// Positive before adjustment, negative after a full green reduction.
let mixed = [-0.006, 0.003, 0.0];
assert!(luminance_2020(mixed) > 0.0);
assert!(luminance_2020([mixed[0], mixed[1] * 0.7, mixed[2]]) < 0.0);
assert_eq!(calibrate(mixed, None, 1.0), mixed);
}
#[test]
fn hue_anchors_match_f64_matrix_accumulation() {
let matrix = SRGB.to_space(&REC2020).0;
for deg in (0..360).map(f64::from).chain(MIXER_HUES) {
let lin = hsv_to_rgb(deg as f32, 1.0, 1.0).map(srgb_to_linear).map(f64::from);
let rec = matrix.map(|r| (r[0] * lin[0] + r[1] * lin[1] + r[2] * lin[2]) as f32);
assert_eq!(oklch_hue_of_srgb_hue(deg), lab_to_lch(oklab_from_2020(rec))[2], "hue {deg}");
}
}
#[test]
fn point_color_targets_its_range() {
let skin = [0.35, 0.16, 0.09];
let [l, c, h] = lab_to_lch(oklab_from_2020(skin));
let sample =
PointColor { lum: l as f64, chroma: c as f64, hue: (h as f64).to_degrees(), hue_shift: 60.0, sat_shift: -50.0, ..Default::default() };
let mut s = DevelopSettings::default();
s.point_colors.push(sample);
let ops = ColorOps::new(&s);
let out = lab_to_lch(oklab_from_2020(ops.apply(skin, 0.0, 0.0)));
assert!(out[1] < c * 0.7, "chroma {c} -> {}", out[1]);
assert!(wrap(out[2] - h) > 0.2, "hue {h} -> {}", out[2]);
// far colours are untouched
for far in [[0.02, 0.05, 0.4], [0.05, 0.3, 0.05], [0.3, 0.3, 0.3]] {
let o = ops.apply(far, 0.0, 0.0);
assert!(far.iter().zip(&o).all(|(a, b)| (a - b).abs() < 1e-4), "{far:?} -> {o:?}");
}
// weight: 1 at the sample, falling to 0 outside the range; a wider range reaches further
let k = PointK::new(&sample);
assert!((k.weight(l, c, h) - 1.0).abs() < 1e-6);
assert_eq!(k.weight(l, c, h + 1.0), 0.0);
let wide = PointK::new(&PointColor { range: 100.0, ..sample });
assert!(wide.weight(l, c, h + 0.45) > k.weight(l, c, h + 0.45));
}
#[test]
fn point_color_variance_compresses_towards_the_sample() {
let p = PointColor { lum: 0.6, chroma: 0.1, hue: 40.0, variance: -100.0, range: 100.0, ..Default::default() };
let k = PointK::new(&p);
let (h0, near) = (40f32.to_radians(), 40f32.to_radians() + 0.1);
let o = k.apply([0.62, 0.11, near]);
assert!((o[2] - h0).abs() < 0.1 && (o[1] - 0.1).abs() < 0.01 && (o[0] - 0.6).abs() < 0.02, "{o:?}");
let k = PointK::new(&PointColor { variance: 100.0, ..p });
let o = k.apply([0.62, 0.11, near]);
assert!(o[2] - h0 > 0.1, "{o:?}");
}
#[test]
fn grading_tints_shadows_only() {
let mut s = DevelopSettings::default();
s.grading.shadows = Wheel { hue: 220.0, sat: 60.0, lum: 0.0 };
let ops = ColorOps::new(&s);
let dark = ops.apply([0.01, 0.01, 0.01], 0.0, 0.0);
let bright = ops.apply([0.8, 0.8, 0.8], 0.0, 0.0);
assert!(dark[2] > dark[0]);
assert!((bright[2] - bright[0]).abs() < 0.02);
}
}
+5
View File
@@ -4,8 +4,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod color;
pub mod colorops;
pub mod curve;
pub mod finish;
pub mod inpaint;
pub mod light_v3;
// generated (`light_v3_params.rs`), kept in its own compact layout
#[rustfmt::skip]
pub mod light_v3_params;
pub mod lut;
pub mod tone;
+565
View File
@@ -0,0 +1,565 @@
//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone
//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied
//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance:
//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated).
//!
//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from
//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity:
//!
//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise
//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law
//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign;
//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB
//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light
//! ([`Mode::Mix`], one weight per sign).
//!
//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of
//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each
//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated
//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU
//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations
//! retain the original evaluation, including any preceding per-channel operation.
use craft_color_transform::{Mat3, PROPHOTO, REC2020};
use craft_develop_model::{DevelopSettings, Process};
use crate::light_v3_params as fitted;
/// Entries of an operator's table over encoded `v` in 0..=1.
pub const LUT_N: usize = 1024;
/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it.
pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7];
/// How an operator is applied to a pixel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// To each encoded ProPhoto channel.
PerChannel,
/// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio.
Luminance,
/// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign.
Mix,
}
impl Mode {
/// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`).
pub fn code(self) -> u32 {
match self {
Mode::PerChannel => 0,
Mode::Luminance => 1,
Mode::Mix => 2,
}
}
}
/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at
/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix
/// logits (positive, negative amounts) in [`Mode::Mix`].
#[derive(Clone, Copy, Debug)]
pub struct Fit {
pub mode: Mode,
/// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`).
pub signed: bool,
pub params: &'static [f64],
}
const KNOTS_N: usize = fitted::KNOTS.len();
/// A [`Fit`] unpacked (`Family.unpack`).
#[derive(Clone, Copy, Debug)]
pub struct Unpacked {
pub d_pos: [f64; KNOTS_N],
pub d_neg: [f64; KNOTS_N],
/// `(τ, q)` of the amount law, positive and negative amounts.
pub law_pos: (f64, f64),
pub law_neg: (f64, f64),
/// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]).
pub weights: (f64, f64),
}
fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
impl Fit {
/// The parameters unpacked; `None` when their number doesn't fit the layout.
pub fn unpack(&self) -> Option<Unpacked> {
let n = KNOTS_N - 1;
let p = self.params;
let mix = self.mode == Mode::Mix;
let len = 2 * n + 4 + if mix { 2 } else { 0 };
if p.len() != len {
return None;
}
// D(1) = 0 is appended (the last knot stays 0)
let shape = |off: usize| -> Option<[f64; KNOTS_N]> {
let mut d = [0.0; KNOTS_N];
for (k, slot) in d.iter_mut().take(n).enumerate() {
*slot = *p.get(off + k)?;
}
Some(d)
};
let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?);
if self.signed {
d_pos[0] = 0.0;
d_neg[0] = 0.0;
}
let at = |i: usize| p.get(i).copied();
let i = 2 * n;
let law_pos = (at(i)?.exp(), at(i + 1)?.exp());
let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp());
let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) };
Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights })
}
}
/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it
/// shrinks.
pub fn law((tau, q): (f64, f64), a: f64) -> f64 {
let t = (a.abs() / 100.0).min(1.0);
let tau = tau.clamp(1e-3, 1e3);
((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q)
}
/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends.
fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 {
let k = &fitted::KNOTS;
if v <= k[0] {
return d[0];
}
for i in 1..KNOTS_N {
if v <= k[i] {
let t = (v - k[i - 1]) / (k[i] - k[i - 1]);
return d[i - 1] + t * (d[i] - d[i - 1]);
}
}
d[KNOTS_N - 1]
}
impl Unpacked {
/// `F_a(v)` on an encoded value (`Family.curve`).
pub fn curve(&self, a: f64, v: f64) -> f64 {
if a == 0.0 {
return v;
}
if a > 0.0 {
return v + law(self.law_pos, a) * interp(v, &self.d_pos);
}
(v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0)
}
}
/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of
/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]).
#[derive(Clone, Debug)]
pub struct Operator {
pub mode: Mode,
/// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance).
pub weight: f32,
pub lut: Box<[f32; LUT_N]>,
}
impl Operator {
/// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack.
///
/// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising
/// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds.
/// The fitting tool inverts `F` the same way.
pub fn new(fit: &Fit, amount: f64) -> Option<Operator> {
let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 };
if a == 0.0 {
return None;
}
let u = fit.unpack()?;
let weight = match fit.mode {
Mode::PerChannel => 1.0,
Mode::Luminance => 0.0,
Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32,
};
let mut lut = Box::new([0.0f32; LUT_N]);
let mut top = 0.0f64;
for (i, slot) in lut.iter_mut().enumerate() {
let v = i as f64 / (LUT_N - 1) as f64;
top = top.max(u.curve(a, v));
*slot = srgb_decode(top) as f32;
}
// The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance
// result that contributes nothing, on both CPU and GPU.
let mode = if weight == 1.0 {
Mode::PerChannel
} else if weight == 0.0 {
Mode::Luminance
} else {
Mode::Mix
};
Some(Operator { mode, weight, lut })
}
/// The table at encoded `v` (clamped to 0..=1), interpolated: linear output.
#[inline]
pub fn eval(&self, v: f32) -> f32 {
let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32;
let i = (f as usize).min(LUT_N - 2);
let t = f - i as f32;
self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t
}
/// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which
/// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their
/// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the
/// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its
/// pixel unless the pixel's luminance is above 1.
#[inline]
pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 {
if x > 1.0 {
x
} else if x < 0.0 {
self.lut[0] + x
} else {
self.eval(encode(x))
}
}
/// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance
/// (unchanged when the luminance is at most 1e-6, or above 1).
#[inline]
fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2];
if y.is_nan() || y <= 1e-6 || y > 1.0 {
return p;
}
let r = self.channel(y, encode) / y;
p.map(|c| c * r)
}
/// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes
/// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled
/// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y`
/// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR
/// component of a pixel with `Y ≤ 1` moves by the luminance part's share.
#[inline]
pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
match self.mode {
Mode::PerChannel => p.map(|c| self.channel(c, encode)),
Mode::Luminance => self.luminance(p, encode),
Mode::Mix => {
let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode));
let w = self.weight;
std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k])
}
}
}
}
/// sRGB decoding in f64 (the tables are built in f64, like the fit).
fn srgb_decode(e: f64) -> f64 {
if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) }
}
/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back.
pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) {
let to = REC2020.to_space(&PROPHOTO);
let from = to.inverse().unwrap_or(Mat3::IDENTITY);
(to.to_f32(), from.to_f32())
}
/// The active operators of a render, in order (Contrast, Blacks), and the conversions to
/// and from the space they work in. Applied after the tone map, chroma scaling and highlight
/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`).
#[derive(Clone, Debug)]
pub struct LightOps {
pub ops: Vec<Operator>,
pub to_pro: [[f32; 3]; 3],
pub from_pro: [[f32; 3]; 3],
}
/// The fits of Contrast and Blacks, in the order they apply.
pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS];
/// Whether `s` renders with the V4 operators: process V4 or later, a raw source, and its camera tone
/// curve. Other sources keep the tone map's own Contrast and Blacks.
pub fn applies(s: &DevelopSettings, is_raw: bool, has_camera_tone: bool) -> bool {
is_raw && has_camera_tone && s.process.process() >= Process::V4
}
impl LightOps {
/// The operators of `s` (see [`applies`]); `None` when they don't apply or every
/// slider is at 0.
pub fn new(s: &DevelopSettings, is_raw: bool, has_camera_tone: bool) -> Option<LightOps> {
if !applies(s, is_raw, has_camera_tone) {
return None;
}
let l = &s.light;
let ops: Vec<Operator> = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect();
if ops.is_empty() {
return None;
}
let (to_pro, from_pro) = prophoto_matrices();
Some(LightOps { ops, to_pro, from_pro })
}
/// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the
/// exact curve or the shared table, as the render encodes).
#[inline]
pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
let mut p = mul3(&self.to_pro, d);
for op in &self.ops {
p = op.apply(p, encode);
}
mul3(&self.from_pro, p)
}
}
/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`]
/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples.
const PREVIEW_INTERVALS: usize = 16_384;
/// An operator with its sRGB encoding and decoding included in one linear-input table.
struct LinearOperator {
black: f32,
white: f32,
// Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float
// conversion or subtraction of neighbouring samples in the pixel loop.
segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>,
}
impl LinearOperator {
fn new(channel: impl Fn(f32) -> f32) -> Self {
let black = channel(0.0);
let mut previous = black;
let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]);
for (i, segment) in segments.iter_mut().enumerate() {
let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32);
let slope = (next - previous) * PREVIEW_INTERVALS as f32;
let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32;
*segment = [intercept, slope];
previous = next;
}
Self { black, white: previous, segments }
}
#[inline(always)]
fn channel(&self, x: f32) -> f32 {
if x >= 1.0 {
if x == 1.0 { self.white } else { x }
} else if x < 0.0 {
self.black + x
} else {
let f = x * PREVIEW_INTERVALS as f32;
let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize;
let [intercept, slope] = self.segments[i];
intercept + slope * x
}
}
}
/// CPU preview tables for per-channel operations, built once per render. Luminance operations
/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum.
pub struct PreviewOps {
ops: PreviewOperators,
to_pro: [[f32; 4]; 3],
from_pro: [[f32; 4]; 3],
}
enum PreviewOperators {
PerChannel(LinearOperator),
Separate(Vec<LinearOperator>),
}
impl PreviewOps {
pub fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option<Self> {
let ops = &exact.ops;
// Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified
// by F(Y) / Y. Keep every preceding operation exact too, including Contrast.
if ops.iter().any(|o| o.mode != Mode::PerChannel) {
return None;
}
// A preceding black lift could carry a negative input across zero. Only fuse when
// preceding operators fix zero, so the composed negative extension remains F(0) + x.
// Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses.
let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0);
let ops = if fuse {
PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode))))
} else {
PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect())
};
let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]);
Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) })
}
// Keep the single-table path in the finish loop. An out-of-line call per pixel saves
// little code here but adds register spills to this otherwise small operation.
#[inline(always)]
pub fn apply(&self, d: [f32; 3]) -> [f32; 3] {
let mut p = mul_preview(&self.to_pro, d);
match &self.ops {
PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])],
PreviewOperators::Separate(ops) => {
for op in ops {
p = p.map(|c| op.channel(c));
}
}
}
mul_preview(&self.from_pro, p)
}
}
/// Padded columns let the compiler multiply the RGB rows together in vector registers.
/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`.
#[inline(always)]
fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] {
let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]);
[out[0], out[1], out[2]]
}
#[inline]
fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] {
[
m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2],
m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2],
m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2],
]
}
/// `fit_pointwise.py`'s own values for one fit at one amount (generated into
/// [`crate::light_v3_params`]; the tests check the port against them).
#[cfg(test)]
pub struct Reference {
pub amount: f64,
/// `Family.curve` at `light_v3_params::REF_V`.
pub curve: &'static [f64],
/// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases.
pub apply: Option<&'static [[f64; 3]]>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::light_v3_params as fitted;
use craft_color::linear_to_srgb;
use craft_develop_model::Process;
fn srgb_to_linear(v: f32) -> f32 {
craft_color::srgb_to_linear(v)
}
fn fits() -> [(&'static str, &'static Fit, &'static [Reference]); 2] {
[("contrast", &fitted::CONTRAST, fitted::CONTRAST_REFERENCE), ("blacks", &fitted::BLACKS, fitted::BLACKS_REFERENCE)]
}
#[test]
fn applies_respects_process_raw_source_and_camera_tone() {
let v3 = DevelopSettings { process: Process::V3.version(), ..Default::default() };
let v4 = DevelopSettings { process: Process::V4.version(), ..Default::default() };
let v8 = DevelopSettings { process: Process::V8.version(), ..Default::default() };
assert!(!applies(&v3, true, true));
assert!(!applies(&v4, true, false));
assert!(!applies(&v4, false, true));
assert!(applies(&v4, true, true));
assert!(applies(&v8, true, true));
}
#[test]
fn the_shipped_fits_unpack_as_the_family_lays_them_out() {
assert!(std::ptr::eq(FITS[0], &fitted::CONTRAST) && std::ptr::eq(FITS[1], &fitted::BLACKS));
for (name, fit, _) in fits() {
let u = fit.unpack().unwrap_or_else(|| panic!("{name} doesn't unpack"));
assert_eq!((u.d_pos[11], u.d_neg[11]), (0.0, 0.0), "{name}");
assert_eq!(fit.signed, name == "contrast");
if fit.signed {
assert_eq!((u.d_pos[0], u.d_neg[0]), (0.0, 0.0));
}
assert!([u.law_pos, u.law_neg].iter().all(|(t, q)| t.is_finite() && q.is_finite() && *t > 0.0 && *q > 0.0), "{name}");
let (w0, w1) = u.weights;
assert!((0.0..=1.0).contains(&w0) && (0.0..=1.0).contains(&w1), "{name}");
}
assert_eq!(fitted::CONTRAST.mode, Mode::PerChannel);
assert_eq!(fitted::BLACKS.mode, Mode::Mix);
let short = Fit { params: &fitted::CONTRAST.params[..20], ..fitted::CONTRAST };
assert!(short.unpack().is_none());
assert!(Operator::new(&short, 50.0).is_none());
}
#[test]
fn exact_mix_endpoints_select_only_the_contributing_mode() {
assert_eq!(Operator::new(&fitted::BLACKS, -30.0).unwrap().mode, Mode::PerChannel);
assert_eq!(Operator::new(&fitted::BLACKS, 30.0).unwrap().mode, Mode::Mix);
let mut params = fitted::BLACKS.params.to_vec();
*params.last_mut().unwrap() = -1000.0;
let fit = Fit { params: Box::leak(params.into_boxed_slice()), ..fitted::BLACKS };
assert_eq!(Operator::new(&fit, -30.0).unwrap().mode, Mode::Luminance);
}
#[test]
fn preview_tables_match_exact_operators_over_combined_amounts() {
let mut worst = 0.0f32;
for contrast in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] {
for blacks in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] {
let mut s = DevelopSettings::default();
s.light.contrast = contrast;
s.light.blacks = blacks;
let Some(exact) = LightOps::new(&s, true, true) else { continue };
let preview = PreviewOps::new(&exact, &linear_to_srgb);
assert_eq!(preview.is_some(), blacks <= 0.0);
for i in 0..=8192 {
let v = i as f32 / 8192.0;
for p in [[v; 3], [v, v * 0.1, v * 0.02], [v * 0.04, v, v * 0.2], [v * 0.1, v * 0.03, v], [v * 3.0, -v * 0.2, v]] {
let a = exact.apply(p, &linear_to_srgb);
let b = preview.as_ref().map_or_else(|| exact.apply(p, &linear_to_srgb), |preview| preview.apply(p));
for (a, b) in a.into_iter().zip(b) {
let error = (linear_to_srgb(a.clamp(0.0, 1.0)) - linear_to_srgb(b.clamp(0.0, 1.0))).abs() * 255.0;
worst = worst.max(error);
assert!(error <= 1.0, "Contrast {contrast}, Blacks {blacks}, input {p:?}: {error} levels");
}
}
}
}
}
assert!(worst <= 1.0);
}
#[test]
fn the_operators_are_fit_pointwise_family() {
for (name, fit, refs) in fits() {
let u = fit.unpack().unwrap();
assert!(!refs.is_empty());
let mut worst = 0.0f64;
for r in refs {
for (v, want) in fitted::REF_V.iter().zip(r.curve) {
let got = u.curve(r.amount, *v);
assert!((got - want).abs() < 1e-11, "{name} {} at {v}: {got} vs {want}", r.amount);
}
let Some(apply) = r.apply else { continue };
let op = Operator::new(fit, r.amount).unwrap();
for (px, want) in fitted::REF_PIX.iter().zip(apply) {
let lin = px.map(|v| srgb_to_linear(v as f32));
let got = op.apply(lin, &linear_to_srgb).map(linear_to_srgb);
for k in 0..3 {
worst = worst.max((got[k] as f64 - want[k]).abs());
}
}
}
assert!(worst < 1e-3, "{name}: {worst}");
}
}
#[test]
fn every_operator_is_monotone_and_keeps_white() {
for (name, fit, _) in fits() {
for a in (-100..=100).filter(|a| *a != 0) {
let op = Operator::new(fit, a as f64).unwrap();
assert!(op.lut[0] >= 0.0, "{name} {a}: F(0) = {}", op.lut[0]);
assert!((op.lut[LUT_N - 1] - 1.0).abs() < 1e-6, "{name} {a}: F(1) = {}", op.lut[LUT_N - 1]);
assert!(op.lut.windows(2).all(|w| w[1] >= w[0]), "{name} {a} decreases");
let mut prev = f32::MIN;
for i in -50..=1100 {
let x = i as f32 / 1000.0;
let y = op.channel(x, &linear_to_srgb);
assert!(y >= prev, "{name} {a} at {x}: {y} < {prev}");
prev = y;
}
}
}
}
}
+319
View File
@@ -0,0 +1,319 @@
//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]).
//!
//! GENERATED from [LightCraft at 08179b9b](https://github.com/storytold/lightcraft/tree/08179b9bc3f75dc54134b1ce402cfd2d0a841b38).
//! In that checkout, run `python3 tools/light_v3_constants.py rust --check` against the upstream file.
//! The [generator](https://github.com/storytold/lightcraft/blob/08179b9bc3f75dc54134b1ce402cfd2d0a841b38/tools/light_v3_constants.py)
//! uses the [committed fits](https://github.com/storytold/lightcraft/tree/08179b9bc3f75dc54134b1ce402cfd2d0a841b38/tools/light_v3_fits)
//! named below and writes `crates/pipeline/src/light_v3_params.rs`. The shared copy only changes this
//! provenance note; keep the generated constants unchanged.
//!
//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports'
//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another
//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are
//! private; errors are published only with at least three contributing photos. These are our operator family's
//! parameters (`docs/light-v3.md`), not Lightroom's.
//!
//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos;
//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`.
//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos;
//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`.
use crate::light_v3::{Fit, Mode};
#[cfg(test)]
use crate::light_v3::Reference;
/// The family's knots: the displacement shapes are piecewise linear on them.
pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0];
/// `tools/light_v3_fits/contrast.json`.
pub const CONTRAST: Fit = Fit {
mode: Mode::PerChannel,
signed: true,
params: &[
9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477,
-0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389,
0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336,
-0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873,
0.10657448975892592, -0.13962415708911588, 0.37724097657204825,
],
};
/// `tools/light_v3_fits/blacks.json`.
pub const BLACKS: Fit = Fit {
mode: Mode::Mix,
signed: false,
params: &[
0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743,
0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467,
0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734,
0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452,
6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333,
],
};
/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto).
#[cfg(test)]
pub const REF_V: [f64; 16] = [
0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0,
];
#[cfg(test)]
pub const REF_PIX: [[f64; 3]; 6] = [
[0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99],
];
/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant
/// digits).
#[cfg(test)]
pub const CONTRAST_REFERENCE: &[Reference] = &[
Reference {
amount: -100.0,
curve: &[
0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301,
0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0,
],
apply: Some(&[
[0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543],
[0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115],
[0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898],
]),
},
Reference {
amount: -63.0,
curve: &[
0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955,
0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0,
],
apply: Some(&[
[0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571],
[0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223],
[0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598],
]),
},
Reference {
amount: -25.0,
curve: &[
0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431,
0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0,
],
apply: Some(&[
[0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337],
[0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008],
[0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309],
]),
},
Reference {
amount: -4.0,
curve: &[
0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729,
0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0,
],
apply: Some(&[
[0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611],
[0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259],
[0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171],
]),
},
Reference {
amount: -1.0,
curve: &[
0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153,
0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0,
],
apply: Some(&[
[0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843],
[0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971],
[0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711],
]),
},
Reference {
amount: 1.0,
curve: &[
0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771,
0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0,
],
apply: Some(&[
[0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167],
[0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104],
[0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974],
]),
},
Reference {
amount: 4.0,
curve: &[
0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504,
0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0,
],
apply: Some(&[
[0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007],
[0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501],
[0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716],
]),
},
Reference {
amount: 25.0,
curve: &[
0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954,
0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0,
],
apply: Some(&[
[0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294],
[0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036],
[0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695],
]),
},
Reference {
amount: 63.0,
curve: &[
0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043,
0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0,
],
apply: Some(&[
[0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671],
[0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214],
[0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887],
]),
},
Reference {
amount: 100.0,
curve: &[
0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783,
0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0,
],
apply: Some(&[
[0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348],
[0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828],
[0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878],
]),
},
];
/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant
/// digits).
#[cfg(test)]
pub const BLACKS_REFERENCE: &[Reference] = &[
Reference {
amount: -100.0,
curve: &[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601,
0.771963089505, 0.880557079195, 0.964167123758, 1.0,
],
apply: Some(&[
[0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414],
[0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981],
[0.693725171247, 0.964167123755, 0.988055707915],
]),
},
Reference {
amount: -63.0,
curve: &[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807,
0.793543473258, 0.891588093197, 0.967476427959, 1.0,
],
apply: Some(&[
[0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728],
[0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935],
[0.72565290629, 0.967476427958, 0.989158809318],
]),
},
Reference {
amount: -25.0,
curve: &[
0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796,
0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0,
],
apply: Some(&[
[1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846],
[0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568],
[0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823],
]),
},
Reference {
amount: -4.0,
curve: &[
0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769,
0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0,
],
apply: Some(&[
[0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317],
[0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259],
[0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179],
]),
},
Reference {
amount: -1.0,
curve: &[
0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029,
0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0,
],
apply: Some(&[
[0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032],
[0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235],
[0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963],
]),
},
Reference {
amount: 1.0,
curve: &[
9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943,
0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604,
1.0,
],
apply: Some(&[
[0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538],
[0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162],
[0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688],
]),
},
Reference {
amount: 4.0,
curve: &[
4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135,
0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656,
1.0,
],
apply: Some(&[
[0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491],
[0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096],
[0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658],
]),
},
Reference {
amount: 25.0,
curve: &[
0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592,
0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944,
1.0,
],
apply: Some(&[
[0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382],
[0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074],
[0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456],
]),
},
Reference {
amount: 63.0,
curve: &[
0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214,
0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744,
1.0,
],
apply: Some(&[
[0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691],
[0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489],
[0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794],
]),
},
Reference {
amount: 100.0,
curve: &[
0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079,
0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372,
1.0,
],
apply: Some(&[
[0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953],
[0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499],
[0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831],
]),
},
];