Skip to main content

kallo_core/
print.rs

1//! Spectral printing: dye densities to paper layer exposures.
2//!
3//! Phase 0 printed by treating each channel's density as that channel's light
4//! loss. That misses the reason colour negatives have orange masks and couplers:
5//! a dye does not absorb in one channel, it absorbs over a band, and the paper's
6//! three layers overlap as well.
7//!
8//! The chain is short and physical:
9//!
10//! ```text
11//! D_cmy ──► T(λ) = 10^(-Σ d · absorption) ──► ∫ L(λ)·T(λ)·S_layer(λ) dλ ──► logE
12//! ```
13//!
14//! The mask is the part that is not a constant. An unexposed colour negative is
15//! orange because the cyan layer carries a coloured coupler that absorbs blue;
16//! that coupler is consumed wherever cyan dye is made, so the mask and the dye's
17//! unwanted absorption cancel. [`PrintContext::with_masking`] is that term — see
18//! [`Masking`].
19//!
20//! Everything here is a **placeholder**: the dye and layer spectra are broad
21//! Gaussians with plausible widths, not measurements. They are parameterised in
22//! one place so phase 4 can replace them with digitised curves without touching
23//! the arithmetic. The mask is the exception: `with_base_density` takes the
24//! measured one, which is why masking couplers could be modelled before the dyes
25//! they compensate.
26
27use kallo_spectral::Spectrum;
28
29use crate::model::{PrintModel, inverse3, table, tables};
30use crate::scan::solve3;
31
32use crate::spectral::{GRID_LEN, GRID_START_NM, GRID_STEP_NM};
33
34/// One dye's absorption, or one paper layer's sensitivity, as a Gaussian band.
35#[derive(Debug, Clone, Copy)]
36struct Band {
37    peak_nm: f64,
38    width_nm: f64,
39}
40
41/// Cyan absorbs red, magenta absorbs green, yellow absorbs blue. The widths are
42/// wide on purpose: that overlap *is* the crosstalk the scalar model lacks.
43const DYE_BANDS: [Band; 3] = [
44    Band {
45        peak_nm: 650.0,
46        width_nm: 55.0,
47    },
48    Band {
49        peak_nm: 550.0,
50        width_nm: 50.0,
51    },
52    Band {
53        peak_nm: 450.0,
54        width_nm: 55.0,
55    },
56];
57
58/// Filter pack bands: yellow removes blue, magenta removes green, cyan removes
59/// red. Wider than a real dichroic filter, and a placeholder.
60const FILTER_BANDS: [Band; 3] = [
61    Band {
62        peak_nm: 450.0,
63        width_nm: 55.0,
64    },
65    Band {
66        peak_nm: 550.0,
67        width_nm: 50.0,
68    },
69    Band {
70        peak_nm: 650.0,
71        width_nm: 55.0,
72    },
73];
74
75/// The paper's three layers sit under the same three bands, for the same reason.
76const PAPER_BANDS: [Band; 3] = [
77    Band {
78        peak_nm: 650.0,
79        width_nm: 45.0,
80    },
81    Band {
82        peak_nm: 550.0,
83        width_nm: 40.0,
84    },
85    Band {
86        peak_nm: 450.0,
87        width_nm: 45.0,
88    },
89];
90
91/// Masking couplers: the coloured coupler that is destroyed as the dye forms.
92///
93/// A colour negative is not three independent layers. The cyan dye absorbs some
94/// blue and green that it should not, so the cyan layer carries a **coloured
95/// coupler** — an orange mask — that absorbs blue and is consumed wherever cyan
96/// dye is made. The two errors then subtract: where the cyan dye is dense the
97/// mask is gone, and where it is thin the mask is there to take its place.
98///
99/// That is why an unexposed colour negative is orange, and why the orange goes
100/// away as the frame is exposed. [`PrintContext::with_base_density`] adds the
101/// mask as a constant; this is the term that makes it behave.
102///
103/// The strength is per layer because the mask does not have to belong to the
104/// cyan one alone — in practice the orange mask does, which is the default.
105#[derive(Debug, Clone, Copy)]
106pub struct Masking {
107    /// Fraction of the base density each layer destroys at its reference density.
108    pub strength: [f64; 3],
109    /// Density at which a layer has destroyed all the mask it can.
110    pub reference_density: f64,
111}
112
113impl Default for Masking {
114    fn default() -> Self {
115        Self {
116            strength: [1.0, 0.0, 0.0],
117            reference_density: 2.0,
118        }
119    }
120}
121
122impl Masking {
123    /// How much of the mask survives, given the three analytical densities.
124    #[must_use]
125    pub fn surviving(&self, density_cmy: [f64; 3]) -> f64 {
126        let reference = self.reference_density.max(1e-9);
127        let removed: f64 = density_cmy
128            .iter()
129            .zip(&self.strength)
130            .map(|(density, strength)| strength * (density / reference).clamp(0.0, 1.0))
131            .sum();
132        (1.0 - removed).clamp(0.0, 1.0)
133    }
134}
135
136/// The spectral model of the enlarger and the paper.
137#[derive(Debug, Clone)]
138pub struct PrintContext {
139    grid: Spectrum,
140    dye: [Spectrum; 3],
141    paper: [Spectrum; 3],
142    reference: [f64; 3],
143    /// The density the print balance is anchored on, kept so that replacing the
144    /// spectra can recompute the anchor.
145    reference_density: [f64; 3],
146    /// Enlarger filter pack, in Kodak colour-correction units for yellow, magenta
147    /// and cyan. Cyan is almost always zero in a colour head.
148    filters: [f64; 3],
149    /// The three filter absorption bands: yellow removes blue, magenta removes
150    /// green, cyan removes red. Placeholders, like the dyes.
151    filter_bands: [Spectrum; 3],
152    /// The enlarger's light source. Equal-energy until a real one is measured.
153    illuminant: Spectrum,
154    /// Density of the unexposed, processed film: base, fog and the colour mask.
155    /// Added to the dye densities before the transmittance is computed.
156    base_density: Option<Spectrum>,
157    /// How much of that base density the couplers destroy as dye forms.
158    masking: Option<Masking>,
159}
160
161impl PrintContext {
162    /// Build the context, anchoring the output on a reference negative density.
163    ///
164    /// The anchor is what makes the print balance solvable: everything is
165    /// reported relative to the light the reference negative passes, so a
166    /// mid-grey negative lands at log exposure 0 on every layer.
167    ///
168    /// # Panics
169    ///
170    /// Cannot panic: the grid is a valid constant.
171    #[must_use]
172    pub fn new(reference_density: [f64; 3]) -> Self {
173        let grid = Spectrum::uniform(GRID_START_NM, GRID_STEP_NM, GRID_LEN)
174            .expect("the internal grid is a valid constant");
175
176        let dye: [Spectrum; 3] = DYE_BANDS.map(|band| gaussian(&grid, band));
177        // Unit area, so the response to white light is 1.0 per layer.
178        let paper: [Spectrum; 3] = PAPER_BANDS.map(|band| normalised(gaussian(&grid, band)));
179        // Built before the struct literal, because `grid` is moved into it.
180        let filter_bands: [Spectrum; 3] = FILTER_BANDS.map(|band| gaussian(&grid, band));
181        let illuminant = Spectrum::filled(grid.clone(), 1.0);
182
183        let mut context = Self {
184            grid,
185            dye,
186            paper,
187            reference: [1.0; 3],
188            reference_density,
189            filters: [0.0; 3],
190            filter_bands,
191            illuminant,
192            base_density: None,
193            masking: None,
194        };
195        // Anchor on the *neutral* density at the reference level, so that grey
196        // stays grey across the scale. The pipeline compensates for the small
197        // residual at the actual (near-neutral) mid-grey density.
198        let neutral_level =
199            (reference_density[0] + reference_density[1] + reference_density[2]) / 3.0;
200        context.reference = context.balanced([neutral_level; 3]);
201        context
202    }
203
204    /// Replace only the dye spectra, keeping the paper layers.
205    #[must_use]
206    pub fn with_dyes(mut self, dye: [Spectrum; 3]) -> Self {
207        self.dye = dye.map(|spectrum| spectrum.resampled(&self.grid));
208        self.reference = self.balanced(self.reference_density);
209        self
210    }
211
212    /// The gain the grey balance applies at a neutral density, per layer.
213    ///
214    /// A diagnostic: if real dyes are neutral by design, these gains should be
215    /// close to 1 and the numerical balance is doing nothing.
216    #[must_use]
217    pub fn balance_gain(&self, neutral_density: f64) -> [f64; 3] {
218        let response = self.response([neutral_density; 3]);
219        let target = (response[0] * response[1] * response[2]).cbrt();
220        std::array::from_fn(|layer| target / response[layer].max(1e-12))
221    }
222
223    /// The enlarger, from measured spectra instead of the placeholder bands.
224    ///
225    /// The three Gaussian `filter_bands` and the equal-energy `illuminant` are
226    /// the model from before the data existed. This replaces the illuminant with
227    /// lamp × heat glass × pack, in that order, normalised to its own peak — the
228    /// print's exposure is solved, so a common factor is an exposure time and not
229    /// a measurement.
230    ///
231    /// The reference is **not** recomputed, and that is the modelling choice:
232    /// the grey balance stands in for dye and coupler design (see `balanced`),
233    /// so it is computed for the print as the film and paper make it, without
234    /// the enlarger. A pack therefore arrives as an *imbalance* — the cast a
235    /// printer sees and dials away — instead of being absorbed into the
236    /// material's own correction. Zero pack and no glass leave the model exactly
237    /// as it was, equal-energy light included.
238    #[must_use]
239    pub fn with_enlarger(
240        mut self,
241        pack: crate::filters::FilterPack,
242        glass: Option<crate::filters::HeatGlass>,
243    ) -> Self {
244        if pack.is_empty() && glass.is_none() {
245            return self;
246        }
247        let lamp = crate::filters::lamp(3200.0);
248        let pack_transmission = pack.transmittance();
249        let glass_transmission = glass.map(|heat| heat.transmittance(2.0));
250        let mut transmission = [0.0_f64; GRID_LEN];
251        for (index, value) in transmission.iter_mut().enumerate() {
252            let heat = glass_transmission.map_or(1.0, |values| values[index]);
253            *value = lamp[index] * pack_transmission[index] * heat;
254        }
255        let peak = transmission
256            .iter()
257            .copied()
258            .fold(0.0_f64, f64::max)
259            .max(1e-12);
260        for (value, sample) in self.illuminant.values_mut().iter_mut().zip(transmission) {
261            *value = sample / peak;
262        }
263        // The bands were a placeholder for absorption that is now in the
264        // spectrum; leaving them on would charge the light twice.
265        self.filters = [0.0, 0.0, 0.0];
266        self
267    }
268
269    /// Set the enlarger filter pack, in Kodak colour-correction units.
270    #[must_use]
271    pub fn with_filters(mut self, filters: [f64; 3]) -> Self {
272        self.filters = filters;
273        self.reference = self.balanced(self.reference_density);
274        self
275    }
276
277    /// Solve for the filter pack that makes a neutral negative print neutral.
278    ///
279    /// The filters change the ratio of the three layer responses, which is exactly
280    /// what a printer adjusts with test strips. Two unknowns, two ratios, so a
281    /// coarse grid followed by a refinement is enough and is easier to trust than
282    /// a gradient step on a function with clamps in it.
283    #[must_use]
284    pub fn solve_filters(&self, density: f64) -> [f64; 3] {
285        let spread = |candidate: Self| {
286            let response = candidate.response([density; 3]);
287            let target = (response[0] * response[1] * response[2]).cbrt();
288            let gains: [f64; 3] = std::array::from_fn(|i| target / response[i].max(1e-12));
289            gains.iter().copied().fold(f64::NEG_INFINITY, f64::max)
290                - gains.iter().copied().fold(f64::INFINITY, f64::min)
291        };
292
293        let mut best = (f64::INFINITY, [0.0; 3]);
294        let mut step = 10.0_f64;
295        let mut centre = [0.0_f64; 3];
296        for _ in 0..4 {
297            for yellow in 0..=20 {
298                for magenta in 0..=20 {
299                    let candidate = [
300                        centre[0] + (f64::from(yellow) - 10.0) * step,
301                        centre[1] + (f64::from(magenta) - 10.0) * step,
302                        0.0,
303                    ]
304                    .map(|value| value.max(0.0));
305                    let value = spread(self.clone().with_filters(candidate));
306                    if value < best.0 {
307                        best = (value, candidate);
308                    }
309                }
310            }
311            centre = best.1;
312            step /= 5.0;
313        }
314        best.1
315    }
316
317    /// Build the context the renderer uses: every spectrum measured.
318    ///
319    /// The dyes, the paper's layers and the mask are the digitised curves from
320    /// `crate::measured`; the mask is coupled, so it is consumed where the cyan
321    /// dye forms. This is the model, and [`Self::new`] is what it is compared
322    /// against.
323    ///
324    /// # Panics
325    ///
326    /// Cannot panic: the tables are compile-time constants on the internal grid.
327    #[must_use]
328    pub fn measured(reference_density: [f64; 3]) -> Self {
329        Self::measured_with(
330            reference_density,
331            &crate::measured::FILM_DYES,
332            &crate::measured::FILM_MASK,
333            &crate::measured::PAPER_LAYERS,
334        )
335    }
336
337    /// As [`Self::measured`], on one film's spectra and one paper's layers.
338    ///
339    /// Both are properties of the stock — the dye set and the layer speeds
340    /// differ between products — so the caller passes them rather than this
341    /// taking whichever sheet was digitised first. The film's dyes are what the
342    /// print sees; the paper's layers are what it responds with.
343    #[must_use]
344    pub fn measured_with(
345        reference_density: [f64; 3],
346        film_dyes: &[[f64; crate::spectral::GRID_LEN]; 3],
347        film_mask: &[f64; crate::spectral::GRID_LEN],
348        paper_layers: &[[f64; crate::spectral::GRID_LEN]; 3],
349    ) -> Self {
350        Self::new(reference_density)
351            .with_spectra(
352                film_dyes.map(|table| crate::measured::spectrum(&table)),
353                paper_layers.map(|table| crate::measured::spectrum(&table)),
354            )
355            .with_base_density(crate::measured::spectrum(film_mask))
356            .with_masking(Masking::default())
357    }
358
359    /// Add the film's minimum density: base, fog and the orange mask.
360    ///
361    /// The published dye curves have D-min subtracted, so the mask is not in
362    /// them. Without it a neutral negative does not print neutral, and the grey
363    /// balance is left compensating for a physical layer that was removed from
364    /// the data.
365    #[must_use]
366    pub fn with_base_density(mut self, base: Spectrum) -> Self {
367        let base = base.resampled(&self.grid);
368        self.base_density = Some(base);
369        self.reference = self.balanced(self.reference_density);
370        self
371    }
372
373    /// Let the base density be destroyed as the dyes form.
374    ///
375    /// Without this the mask is a constant, which is what an unexposed frame
376    /// looks like and not what an exposed one does.
377    #[must_use]
378    pub fn with_masking(mut self, masking: Masking) -> Self {
379        self.masking = Some(masking);
380        self.reference = self.balanced(self.reference_density);
381        self
382    }
383
384    /// Replace the placeholder bands with measured spectra.
385    ///
386    /// The spectra are resampled onto the internal grid, so anything digitised
387    /// on a uniform grid can be passed in. The reference response is recomputed,
388    /// because the anchor depends on the dyes.
389    #[must_use]
390    pub fn with_spectra(mut self, dye: [Spectrum; 3], paper: [Spectrum; 3]) -> Self {
391        self.dye = dye.map(|spectrum| spectrum.resampled(&self.grid));
392        self.paper = paper.map(|spectrum| spectrum.resampled(&self.grid));
393        self.reference = self.balanced(self.reference_density);
394        self
395    }
396
397    /// The wavelength grid.
398    #[must_use]
399    pub fn grid(&self) -> &Spectrum {
400        &self.grid
401    }
402
403    /// log10 of the paper's layer response, relative to the reference negative.
404    #[must_use]
405    pub fn expose(&self, density_cmy: [f64; 3]) -> [f64; 3] {
406        let response = self.balanced(density_cmy);
407        std::array::from_fn(|layer| {
408            let ratio = response[layer] / self.reference[layer].max(1e-12);
409            ratio.max(1e-10).log10()
410        })
411    }
412
413    /// Grey balance.
414    ///
415    /// Overlapping dye bands make a neutral negative transmit a coloured
416    /// spectrum, and the paper's own overlapping sensitivities do not cancel it.
417    /// Real products solve this with dye and coupler design; a placeholder model
418    /// has to solve it numerically, or every neutral prints green.
419    ///
420    /// The correction is defined on the neutral axis only: scale each layer so
421    /// that a density triple equal on all three channels responds equally on all
422    /// three layers. Colour casts caused by *unequal* densities survive, because
423    /// that is the crosstalk the model is here to express.
424    fn balanced(&self, density_cmy: [f64; 3]) -> [f64; 3] {
425        let response = self.response(density_cmy);
426        let mean = (density_cmy[0] + density_cmy[1] + density_cmy[2]) / 3.0;
427        let neutral = self.response([mean; 3]);
428        let target = (neutral[0] * neutral[1] * neutral[2]).cbrt();
429
430        std::array::from_fn(|layer| {
431            let scale = target / neutral[layer].max(1e-12);
432            response[layer] * scale
433        })
434    }
435
436    /// Status density to analytical density.
437    ///
438    /// The characteristic curves are measured through status filters, so each
439    /// channel already contains all three dyes. The dye curves are per-dye
440    /// shapes. Feeding one into the other double-counts the overlap; the same
441    /// correction the scan needed applies here.
442    ///
443    /// The system depends only on the dyes, so it is built once per call and
444    /// inverted once per render — see [`Self::model`].
445    fn analytical_matrix(&self) -> [[f64; 3]; 3] {
446        let probes = [650.0, 550.0, 450.0];
447        let mut matrix = [[0.0_f64; 3]; 3];
448        for (row, wavelength) in probes.iter().enumerate() {
449            for (column, dye) in self.dye.iter().enumerate() {
450                matrix[row][column] = dye.interpolate(*wavelength);
451            }
452        }
453        matrix
454    }
455
456    fn analytical(&self, status: [f64; 3]) -> [f64; 3] {
457        solve3(self.analytical_matrix(), status)
458            .map(|values| values.map(|value| value.max(0.0)))
459            .unwrap_or(status)
460    }
461
462    /// The constants this context integrates with, flattened for another backend.
463    ///
464    /// `None` when a table is not on the model's grid, which
465    /// [`Self::new`] rules out but [`Self::with_spectra`] does not have to.
466    #[must_use]
467    pub fn model(&self) -> Option<PrintModel> {
468        let inverse = inverse3(self.analytical_matrix());
469        // No base density prints as a zero mask, and no masking prints as zero
470        // strengths: the surviving fraction is then one, so the mask is a
471        // constant, which is what masking off means.
472        Some(PrintModel {
473            analytical: inverse.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
474            clamped: inverse.is_some(),
475            dye: tables(&self.dye)?,
476            paper: tables(&self.paper)?,
477            illuminant: table(&self.illuminant)?,
478            mask: match &self.base_density {
479                Some(base) => table(base)?,
480                None => [0.0; GRID_LEN],
481            },
482            masking: self.masking.map_or([0.0; 3], |masking| masking.strength),
483            masking_reference: self
484                .masking
485                .map_or(1.0, |masking| masking.reference_density),
486            filters: self.filters,
487            filter_bands: tables(&self.filter_bands)?,
488            reference: self.reference,
489        })
490    }
491
492    fn response(&self, status_density: [f64; 3]) -> [f64; 3] {
493        let density_cmy = self.analytical(status_density);
494        // Allocation-free on purpose: this runs once per pixel, and cloning a
495        // spectrum here measured 20x slower than the rest of the render.
496        let step = self.grid.step_nm();
497        let mut response = [0.0_f64; 3];
498        for wavelength_index in 0..self.grid.len() {
499            // The mask is present in the unexposed film and consumed where the
500            // dyes form, which is the masking coupler doing its job.
501            let mask = match (&self.base_density, &self.masking) {
502                (Some(base), Some(masking)) => {
503                    base.values()[wavelength_index] * masking.surviving(density_cmy)
504                }
505                (Some(base), None) => base.values()[wavelength_index],
506                (None, _) => 0.0,
507            };
508            let mut density: f64 = mask;
509            density += density_cmy
510                .iter()
511                .zip(&self.dye)
512                .map(|(value, dye)| value * dye.values()[wavelength_index])
513                .sum::<f64>();
514            // exp2 is markedly cheaper than powf and this runs per wavelength
515            // per pixel: 10^-d = 2^(-d * log2 10).
516            let mut filter = 0.0;
517            for (cc, band) in self.filters.iter().zip(&self.filter_bands) {
518                filter += cc * band.values()[wavelength_index] / 100.0;
519            }
520            let light = self.illuminant.values()[wavelength_index];
521            let transmitted = (-(density + filter) * std::f64::consts::LOG2_10).exp2() * light;
522            for (value, paper) in response.iter_mut().zip(&self.paper) {
523                *value += paper.values()[wavelength_index] * transmitted;
524            }
525        }
526        for value in &mut response {
527            *value *= step;
528        }
529        response
530    }
531}
532
533fn gaussian(grid: &Spectrum, band: Band) -> Spectrum {
534    let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
535    for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
536        let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
537        let z = (wavelength - band.peak_nm) / band.width_nm;
538        *value = (-0.5 * z * z).exp();
539    }
540    spectrum
541}
542
543fn normalised(mut spectrum: Spectrum) -> Spectrum {
544    let area: f64 = spectrum.values().iter().sum::<f64>() * spectrum.step_nm();
545    if area > 0.0 {
546        for value in spectrum.values_mut() {
547            *value /= area;
548        }
549    }
550    spectrum
551}
552
553/// With no coupling the base density is a constant: an unexposed frame and a
554/// fully exposed one wear the same mask.
555#[test]
556fn without_masking_the_base_density_is_constant() {
557    let masking = Masking::default();
558    assert!((masking.surviving([0.0; 3]) - 1.0).abs() < 1e-12);
559    assert!((masking.surviving([2.0, 0.0, 0.0]) - 0.0).abs() < 1e-12);
560    assert!((masking.surviving([1.0, 0.0, 0.0]) - 0.5).abs() < 1e-12);
561}
562
563/// The mask belongs to the cyan layer by default: developing the magenta or
564/// the yellow layer must leave it alone.
565#[test]
566fn only_the_layer_that_owns_the_mask_destroys_it() {
567    let masking = Masking::default();
568    assert!((masking.surviving([0.0, 2.0, 0.0]) - 1.0).abs() < 1e-12);
569    assert!((masking.surviving([0.0, 0.0, 2.0]) - 1.0).abs() < 1e-12);
570}
571
572/// The point of the model: as cyan dye forms, the mask releases the blue it
573/// was absorbing, so the layer's blue absorption stops growing.
574#[test]
575fn the_mask_gives_blue_back_as_cyan_forms() {
576    let grid = Spectrum::uniform(380.0, 5.0, 71).unwrap();
577    // A mask that absorbs blue only.
578    let mut base = Spectrum::filled(grid.clone(), 0.0);
579    for (index, value) in base.values_mut().iter_mut().enumerate() {
580        let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
581        *value = 0.6 * (-0.5 * ((wavelength - 450.0) / 25.0).powi(2)).exp();
582    }
583    let context = PrintContext::new([1.0; 3]).with_base_density(base);
584    let masked = context.clone().with_masking(Masking::default());
585    // Blue is channel 2 of the scan, but `expose` returns paper response;
586    // compare the plain context with the masked one at the same density.
587    // `with_masking` re-anchors on the reference density, so the absolute
588    // values move; what must not move is the *gain* from forming cyan dye.
589    let plain_gain = context.expose([2.0, 0.0, 0.0])[2] - context.expose([0.0; 3])[2];
590    let masked_gain = masked.expose([2.0, 0.0, 0.0])[2] - masked.expose([0.0; 3])[2];
591    assert!(
592        masked_gain > plain_gain,
593        "the mask must give blue back: {masked_gain} vs {plain_gain}"
594    );
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    fn reference_density() -> [f64; 3] {
602        [1.2, 1.1, 1.0]
603    }
604
605    /// The film's dyes are what the print sees, so a different dye set prints a
606    /// neutral negative differently. Swapping cyan and yellow is the cheapest
607    /// stand-in for "another manufacturer's film": same densities, different
608    /// absorbed wavelengths.
609    #[test]
610    fn another_films_dyes_print_another_colour() {
611        let density = [0.9, 0.9, 0.9];
612        let vision = PrintContext::measured_with(
613            reference_density(),
614            &crate::measured::FILM_DYES,
615            &crate::measured::FILM_MASK,
616            &crate::measured::PAPER_LAYERS,
617        )
618        .expose(density);
619
620        let mut swapped = crate::measured::FILM_DYES;
621        swapped.swap(0, 2);
622        let other = PrintContext::measured_with(
623            reference_density(),
624            &swapped,
625            &crate::measured::FILM_MASK,
626            &crate::measured::PAPER_LAYERS,
627        )
628        .expose(density);
629
630        // A third of a stop between two dye sets at one density: that is the
631        // difference the user sees when they change film, and it comes from the
632        // spectra rather than from the curve.
633        let shift = (0..3)
634            .map(|channel| (other[channel] - vision[channel]).abs())
635            .fold(0.0_f64, f64::max);
636        assert!(
637            shift > 0.05,
638            "swapping the dyes should move the print: {vision:?} vs {other:?}"
639        );
640    }
641
642    #[test]
643    fn the_neutral_reference_lands_at_zero() {
644        let context = PrintContext::new(reference_density());
645        let level =
646            (reference_density()[0] + reference_density()[1] + reference_density()[2]) / 3.0;
647        for log_e in context.expose([level; 3]) {
648            assert!(log_e.abs() < 1e-9, "{log_e}");
649        }
650    }
651
652    #[test]
653    fn the_reference_negative_is_near_zero() {
654        let context = PrintContext::new(reference_density());
655        // The anchor is neutral grey, so the slightly non-neutral reference
656        // negative sits within a fraction of a stop. The pipeline subtracts the
657        // remainder when it solves the print balance.
658        for log_e in context.expose(reference_density()) {
659            assert!(log_e.abs() < 0.15, "{log_e}");
660        }
661    }
662
663    #[test]
664    fn more_density_means_less_light_on_every_layer() {
665        let context = PrintContext::new(reference_density());
666        let base = context.expose(reference_density());
667        let denser = context.expose([1.6, 1.1, 1.0]);
668        assert!(denser[0] < base[0], "{denser:?}");
669    }
670
671    #[test]
672    fn measured_spectra_replace_the_placeholders() {
673        let context = PrintContext::new(reference_density());
674        let baseline = context.expose([1.0, 0.5, 0.2]);
675
676        // Narrow bands are a different physical world: less overlap, less
677        // crosstalk, so the numbers must move.
678        let grid = context.grid().clone();
679        let narrow: [Spectrum; 3] = [450.0, 550.0, 650.0].map(|peak| {
680            let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
681            for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
682                let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
683                *value = (-0.5 * ((wavelength - peak) / 12.0).powi(2)).exp();
684            }
685            spectrum
686        });
687        let replaced = PrintContext::new(reference_density()).with_spectra(narrow.clone(), narrow);
688        let moved = replaced.expose([1.0, 0.5, 0.2]);
689        let difference: f64 = baseline
690            .iter()
691            .zip(&moved)
692            .map(|(a, b)| (a - b).abs())
693            .sum();
694        assert!(difference > 1e-3, "replacing the spectra changed nothing");
695    }
696
697    #[test]
698    fn neutral_densities_stay_neutral() {
699        let context = PrintContext::new(reference_density());
700        // A grey scale across the useful density range.
701        for step in 0..=12 {
702            let density = 0.2 + 0.15 * f64::from(step);
703            let log_e = context.expose([density; 3]);
704            let spread = log_e.iter().copied().fold(f64::NEG_INFINITY, f64::max)
705                - log_e.iter().copied().fold(f64::INFINITY, f64::min);
706            assert!(
707                spread < 1e-9,
708                "grey {density} drifts by {spread}: {log_e:?}"
709            );
710        }
711    }
712
713    #[test]
714    fn dyes_leak_into_neighbouring_layers() {
715        let context = PrintContext::new(reference_density());
716        let base = context.expose(reference_density());
717
718        // Pure cyan: it should darken the red layer most...
719        let cyan = context.expose([1.7, 1.1, 1.0]);
720        let red_drop = base[0] - cyan[0];
721        let green_drop = base[1] - cyan[1];
722        assert!(
723            red_drop > green_drop,
724            "red {red_drop} vs green {green_drop}"
725        );
726
727        // ...but it must also move the other layers. That coupling is exactly
728        // what the scalar print model could not express.
729        assert!(green_drop.abs() > 1e-4, "no crosstalk: {green_drop}");
730    }
731}