Skip to main content

kallo_core/
model.rs

1//! The spectral model, flattened into numbers another backend can replay.
2//!
3//! The scalar path was easy to hand over: six numbers per layer and the
4//! enlarger's four, all of them the *answers* to the model. The spectral path
5//! integrates over wavelength, so there is no answer to hand over — only the
6//! tables the integration runs on. That is what lives here.
7//!
8//! Three things are deliberately **not** re-derived on the other side:
9//!
10//! - the **polynomial basis**, because it is the only thing between a camera's
11//!   three numbers and a spectrum;
12//! - the **three 3×3 systems** (the exposure reconstruction, the print's
13//!   status-to-analytical unmixing and the scan's), because they are inverted
14//!   here by the same Gaussian elimination the CPU solves with, so the shader
15//!   does a matrix multiply and cannot drift in pivot order;
16//! - the **grey-balance anchors**, which are themselves integrals and would
17//!   otherwise have to be recomputed per render on the device.
18//!
19//! Everything else is a measured or fitted curve, copied verbatim.
20//!
21//! ## What is here, and what is not
22//!
23//! The exposure is only the *closed-form* one. A dictionary prior solves a
24//! non-negative least squares per pixel, and a baked table samples a cube; both
25//! are their own models, and neither is expressible as a constant matrix.
26//! [`PreparedRender::spectral_model`](crate::PreparedRender::spectral_model)
27//! therefore declines them rather than rendering something adjacent.
28
29use kallo_spectral::Spectrum;
30
31use crate::scan::solve3;
32use crate::spectral::GRID_LEN;
33
34/// The exposure: camera triple to per-layer log exposure.
35#[derive(Debug, Clone, PartialEq)]
36pub struct ExposureModel {
37    /// Row-major inverse of the system [`PolynomialUpsampler::system`] builds.
38    /// Coefficients are `reconstruct · rgb`.
39    ///
40    /// The zero matrix and the CPU's own fallback agree: when the system is
41    /// singular the upsampler returns zero coefficients, and a zero matrix is
42    /// exactly that for every input.
43    ///
44    /// [`PolynomialUpsampler::system`]: kallo_spectral::PolynomialUpsampler::system
45    pub reconstruct: [[f64; 3]; 3],
46    /// The three basis terms, one row each.
47    pub basis: [[f64; GRID_LEN]; 3],
48    /// The film's layer sensitivities, one row each.
49    pub film: [[f64; GRID_LEN]; 3],
50    /// The film's response to a reconstructed 18 % grey, per layer.
51    pub reference: [f64; 3],
52}
53
54/// The enlarger and the paper: negative density to paper layer exposure.
55#[derive(Debug, Clone, PartialEq)]
56pub struct PrintModel {
57    /// Row-major inverse of the status-to-analytical unmixing.
58    pub analytical: [[f64; 3]; 3],
59    /// Whether the CPU clamps the unmixed densities to zero.
60    ///
61    /// It does whenever the system solved, and does not when it fell back to
62    /// the identity. Carrying the flag is cheaper than pretending a fallback
63    /// cannot happen.
64    pub clamped: bool,
65    /// The negative's dye absorption, peak-normalised, one row per dye.
66    pub dye: [[f64; GRID_LEN]; 3],
67    /// The paper's layer sensitivities.
68    pub paper: [[f64; GRID_LEN]; 3],
69    /// The enlarger's light source.
70    pub illuminant: [f64; GRID_LEN],
71    /// The film's minimum density — base, fog and the orange mask. All zeros
72    /// when the context has none, which is the same thing the CPU does when
73    /// `base_density` is `None`.
74    pub mask: [f64; GRID_LEN],
75    /// Fraction of the mask each layer destroys at `masking_reference`.
76    ///
77    /// All zeros when masking is off: the surviving fraction is then one, so
78    /// the mask is constant, which is what no masking means.
79    pub masking: [f64; 3],
80    /// Density at which a layer has destroyed all the mask it can.
81    pub masking_reference: f64,
82    /// The enlarger's filter pack, in colour-correction units.
83    pub filters: [f64; 3],
84    /// The three filter absorption bands.
85    pub filter_bands: [[f64; GRID_LEN]; 3],
86    /// The grey balance at the reference density, per layer.
87    pub reference: [f64; 3],
88}
89
90/// The scan: print density to linear-light RGB.
91#[derive(Debug, Clone, PartialEq)]
92pub struct ScanModel {
93    /// Row-major inverse of the status-to-analytical unmixing.
94    pub analytical: [[f64; 3]; 3],
95    /// Whether the CPU clamps the unmixed densities to zero.
96    pub clamped: bool,
97    /// The paper's image dyes.
98    pub dye: [[f64; GRID_LEN]; 3],
99    /// The viewing illuminant.
100    pub illuminant: [f64; GRID_LEN],
101    /// The colour matching functions, one row per axis.
102    pub cmf: [[f64; GRID_LEN]; 3],
103    /// Row-major XYZ to linear sRGB matrix.
104    pub matrix: [[f64; 3]; 3],
105    /// XYZ of paper white.
106    pub white_xyz: [f64; 3],
107    /// RGB of paper white.
108    pub white_rgb: [f64; 3],
109    /// RGB along the neutral axis, evenly spaced in density.
110    pub neutral: [[f64; 3]; NEUTRAL_ENTRIES],
111    /// Density covered by `neutral`.
112    pub neutral_max_density: f64,
113    /// Base density of the unexposed paper.
114    pub base_density: f64,
115}
116
117/// Entries in [`ScanModel::neutral`]: `NEUTRAL_STEPS + 1`.
118pub const NEUTRAL_ENTRIES: usize = crate::scan::NEUTRAL_ENTRIES;
119
120/// Every constant a spectral render integrates with.
121#[derive(Debug, Clone, PartialEq)]
122pub struct SpectralModel {
123    /// The curve, the paper and the enlarger, which are the scalar model's
124    /// numbers and are applied identically here.
125    pub scalar: crate::pipeline::ScalarModel,
126    /// Wavelength step of every table below.
127    ///
128    /// One number for the whole model, not one per stage: all three integrate on
129    /// the same grid, and a stage that carried its own copy could be zero while
130    /// another was not — which multiplies that stage's integral by zero and
131    /// looks like a dark frame.
132    pub step_nm: f64,
133    /// The exposure, when it is the closed-form reconstruction.
134    pub exposure: Option<ExposureModel>,
135    /// The print, when it goes through dye absorption.
136    pub enlarger: Option<PrintModel>,
137    /// The scan, when it goes through reflectance.
138    pub scan: Option<ScanModel>,
139}
140
141impl SpectralModel {
142    /// Whether any stage integrates over wavelength.
143    ///
144    /// A model where this is false is the scalar path, and
145    /// [`PreparedRender::scalar_model`](crate::PreparedRender::scalar_model)
146    /// describes it with four numbers per layer instead.
147    #[must_use]
148    pub fn is_spectral(&self) -> bool {
149        self.exposure.is_some() || self.enlarger.is_some() || self.scan.is_some()
150    }
151}
152
153/// The inverse of a 3×3 matrix, or `None` when it is singular.
154///
155/// Inverting once per render rather than solving per pixel: the three systems
156/// are built from cameras, dyes and observers, none of which depend on the
157/// pixel, so a shader that solved them would be doing the same work sixty
158/// million times.
159pub(crate) fn inverse3(matrix: [[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
160    let mut inverse = [[0.0_f64; 3]; 3];
161    for column in 0..3 {
162        let mut unit = [0.0_f64; 3];
163        unit[column] = 1.0;
164        let solved = solve3(matrix, unit)?;
165        for (row, entries) in inverse.iter_mut().enumerate() {
166            entries[column] = solved[row];
167        }
168    }
169    Some(inverse)
170}
171
172/// A spectrum's samples as a fixed-size table, or `None` if it is not on the
173/// model's grid.
174pub(crate) fn table(spectrum: &Spectrum) -> Option<[f64; GRID_LEN]> {
175    spectrum.values().try_into().ok()
176}
177
178/// Three spectra as three fixed-size tables.
179pub(crate) fn tables(spectra: &[Spectrum; 3]) -> Option<[[f64; GRID_LEN]; 3]> {
180    Some([
181        table(&spectra[0])?,
182        table(&spectra[1])?,
183        table(&spectra[2])?,
184    ])
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn an_inverse_multiplies_back_to_the_identity() {
193        let matrix = [[2.0, -1.0, 0.5], [0.0, 3.0, -2.0], [1.0, 1.0, 1.0]];
194        let inverse = inverse3(matrix).expect("the test matrix is invertible");
195        for (row, products) in matrix.iter().enumerate() {
196            for (column, inverse_column) in [0, 1, 2].iter().enumerate() {
197                let sum: f64 = products
198                    .iter()
199                    .zip(&inverse)
200                    .map(|(left, right)| left * right[*inverse_column])
201                    .sum();
202                let expected = if row == column { 1.0 } else { 0.0 };
203                assert!((sum - expected).abs() < 1e-12, "{row},{column}: {sum}");
204            }
205        }
206    }
207
208    #[test]
209    fn a_singular_matrix_has_no_inverse() {
210        let matrix = [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.0, 1.0, 1.0]];
211        assert!(inverse3(matrix).is_none());
212    }
213
214    /// A render with no spectral stage is the scalar path, and must say so:
215    /// the two descriptions have to be mutually exclusive or a backend would
216    /// have to choose between them.
217    #[test]
218    fn a_plain_render_has_a_scalar_model_and_no_spectral_one() {
219        let prepared = crate::pipeline::RenderParams::default().prepare();
220        assert!(prepared.scalar_model().is_some());
221        assert!(prepared.spectral_model().is_none());
222    }
223}