Skip to main content

kallo_core/
pipeline.rs

1//! The render: a negative is exposed, developed, and printed.
2//!
3//! Phase 0 keeps a single scalar per channel. There is no spectrum yet, but
4//! the *shape* of the computation is already the final one: light becomes
5//! density on the negative, the negative becomes light again in the enlarger,
6//! and that light becomes density on the paper.
7//!
8//! ```text
9//! E ──► D_neg ──► T = 10^-D ──► D_print ──► R = 10^-D
10//!        ▲                          ▲
11//!    H&D curve                 paper curve,
12//!  (development)              balanced on 18 % grey
13//! ```
14
15use crate::curve::CharacteristicCurve;
16use crate::development::DevelopmentParams;
17use crate::emulsion::{FilmStock, PaperStock};
18use crate::lut::ExposureLut;
19use crate::model::SpectralModel;
20use crate::print::PrintContext;
21use crate::scan::ScanContext;
22use crate::spectral::{CameraProfile, SpectralContext};
23
24/// log10 of the luminance a mid-grey card reflects. The anchor everything is
25/// balanced against; 0.18 is the conventional value.
26#[must_use]
27pub fn mid_grey_log_e() -> f64 {
28    0.18_f64.log10()
29}
30
31/// Everything needed to render: which film, which paper, and how it was developed.
32#[derive(Debug, Clone)]
33pub struct RenderParams {
34    /// The negative.
35    pub film: &'static FilmStock,
36    /// The paper it is printed on.
37    pub paper: &'static PaperStock,
38    /// How the negative was developed.
39    pub development: DevelopmentParams,
40    /// Exposure offset in stops, applied before the negative is exposed.
41    pub exposure_ev: f64,
42    /// Expose through the spectral path instead of the per-channel scalar one.
43    pub spectral: bool,
44    /// Which sensor the input RGB is assumed to have come from. Ignored by the
45    /// scalar path.
46    pub camera: CameraProfile,
47    /// Bake the spectral exposure into a `size^3` table. Zero disables it.
48    pub lut_size: usize,
49    /// Print through spectral dye absorption and paper layer sensitivities.
50    ///
51    /// A non-empty colour pack or a heat glass turns this on by itself: those
52    /// are spectra in the light path, and the scalar print has no wavelength
53    /// to put them in.
54    pub spectral_print: bool,
55    /// Scan through spectral reflectance, illuminant and observer.
56    pub spectral_scan: bool,
57    /// Run the cyan-sensitive layer's inhibitor (ADR 0018).
58    ///
59    /// Off by default, and only meaningful for a stock that declares such a
60    /// layer: its strength and diffusion length are placeholders, so turning it
61    /// on is asking for a demonstration of the mechanism, not for a prediction
62    /// about the film.
63    pub interimage: bool,
64    /// How much light the enlarger puts through, in stops, on top of the
65    /// exposure solved to print a mid grey as a mid grey.
66    ///
67    /// Zero is "the test strip that came out right". Positive is more light,
68    /// which is a darker print; negative is less. This is the number a printer
69    /// dials, and the one a dodge or a burn will vary per pixel once the bench
70    /// can ask for that.
71    pub print_exposure_ev: f64,
72    /// The enlarger's colour pack in Kodak CC units, and an optional heat glass.
73    /// Empty and `None` are the model without this stage.
74    pub filters: crate::filters::FilterPack,
75    /// The heat-absorbing glass in the light path, at its 2 mm reference.
76    pub heat_glass: Option<crate::filters::HeatGlass>,
77}
78
79impl Default for RenderParams {
80    fn default() -> Self {
81        Self {
82            film: crate::emulsion::film_stock("vision3_500t").expect("built-in stock"),
83            paper: crate::emulsion::paper_stock("portra_endura").expect("built-in stock"),
84            development: DevelopmentParams::default(),
85            exposure_ev: 0.0,
86            spectral: false,
87            camera: CameraProfile::default(),
88            lut_size: 0,
89            spectral_print: false,
90            spectral_scan: false,
91            print_exposure_ev: 0.0,
92            interimage: false,
93            filters: crate::filters::FilterPack::none(),
94            heat_glass: None,
95        }
96    }
97}
98
99impl RenderParams {
100    /// Freeze the development-dependent curves and solve the print balance.
101    #[must_use]
102    pub fn prepare(&self) -> PreparedRender {
103        self.prepare_with(None)
104    }
105
106    /// Prepare with a table loaded from disk instead of baking one.
107    ///
108    /// The table was baked from some camera, film and dictionary; the caller is
109    /// responsible for it matching this render's film. The format carries no
110    /// model identity yet, which is a known gap.
111    #[must_use]
112    pub fn prepare_with_lut(&self, lut: ExposureLut) -> PreparedRender {
113        let mut prepared = Self {
114            spectral: false,
115            lut_size: 0,
116            ..self.clone()
117        }
118        .prepare_with(None);
119        prepared.lut = Some(lut);
120        prepared
121    }
122
123    /// As [`Self::prepare`], with an optional dictionary for the spectral prior.
124    ///
125    /// The atoms are what the hybrid needs; without them the spectral path uses
126    /// the polynomial prior alone.
127    #[must_use]
128    pub fn prepare_with(&self, atoms: Option<&[kallo_spectral::Spectrum]>) -> PreparedRender {
129        // A silver film has one record, so the three-channel scalar path cannot
130        // express it: it would develop each input channel separately and print a
131        // colour image from a film that has no colour. A monochrome stock is
132        // therefore always exposed through its spectrum, whatever was asked for.
133        let monochrome = self.film.process == crate::emulsion::FilmProcess::Monochrome;
134        // ADR 0017: a dye fed by two emulsions is two integrals and two curves.
135        // The scalar path has three numbers and one curve per channel, so it
136        // cannot say a fourth layer exists; such a stock is always exposed
137        // through its spectrum, exactly as a monochrome film is.
138        let extra = self
139            .film
140            .extra_cyan
141            .map(|emulsion| self.development.apply_to(emulsion.characteristic()));
142        // A CL layer is a fourth integral too, and the scalar path has three
143        // channels: it cannot even say that the layer exists.
144        let cl_layer = self.interimage && self.film.cl_layer.is_some();
145        let spectral = self.spectral || monochrome || extra.is_some() || cl_layer;
146        let channels: [CharacteristicCurve; 3] =
147            std::array::from_fn(|i| self.development.apply_to(self.film.channels[i]));
148
149        let paper = self.paper.channel;
150
151        // Solve the enlarger exposure so that a mid-grey negative prints at
152        // the paper's target reflectance. This is what an operator does with
153        // the aperture and the test strip, done in closed form: find the log
154        // exposure at which the paper reaches the target density, and shift the
155        // enlarger's exposure by however far mid grey is from it.
156        let target_density = -self.paper.target_mid_reflectance.log10();
157        let target_log_e = paper.log_exposure_at(target_density);
158
159        let mid = mid_grey_log_e();
160        let mut density_mid: [f64; 3] = std::array::from_fn(|i| channels[i].density(mid));
161        // The cyan dye's second emulsion develops at mid grey too. Leaving it
162        // out of this number would balance the enlarger on a negative the film
163        // does not make, and every four-layer stock would print a stop dark in
164        // cyan.
165        if let Some(extra) = extra {
166            density_mid[0] += extra.density(mid);
167        }
168
169        // Two ways to describe what reaches the paper. The scalar one treats each
170        // density as that channel's light loss; the spectral one integrates the
171        // dyes' absorption bands against the paper's layer sensitivities.
172        //
173        // A silver image has no dyes to integrate. Asking for the spectral print
174        // on a monochrome film would leave a constant — the image would vanish
175        // into a flat grey — so the scalar print is what those films get, and
176        // `is_spectral_print` says so.
177        //
178        // A colour pack or a heat glass is a thing in the light path, and the
179        // only model that can say what it does is the spectral one: filtering
180        // the scalar print would be a colour wheel with no spectrum behind it.
181        // Asking for either therefore turns the stage on, even when the caller
182        // did not ask for the spectral print by name.
183        let filtered = !self.filters.is_empty() || self.heat_glass.is_some();
184        let print = ((self.spectral_print || filtered) && !monochrome).then(|| {
185            PrintContext::measured_with(
186                density_mid,
187                self.film.dyes,
188                self.film.mask,
189                self.paper.layers,
190            )
191            .with_enlarger(self.filters, self.heat_glass)
192        });
193        let print_shift: [f64; 3] = match &print {
194            // The spectral model is anchored on neutral grey, so the actual
195            // mid-grey exposure is subtracted here rather than assumed to be 0.
196            Some(context) => {
197                let mid_exposure = context.expose(density_mid);
198                std::array::from_fn(|i| target_log_e - mid_exposure[i])
199            }
200            // The non-spectral print has no mask to add, so the film's base
201            // density goes into the exponent with the dye.
202            None => {
203                std::array::from_fn(|i| target_log_e + density_mid[i] + self.film.base_density[i])
204            }
205        };
206
207        // The enlarger's timer, on top of the balance solved above: one number,
208        // the same on every layer, which is what an exposure is. Everything
209        // downstream — the CPU print, the scalar model handed to the GPU, the
210        // replay — reads `print_shift`, so the timer rides there rather than
211        // in a second field that three backends would have to learn about.
212        let print_exposure = self.print_exposure_ev * 2.0_f64.log10();
213        let print_shift: [f64; 3] =
214            std::array::from_fn(|layer| print_shift[layer] + print_exposure);
215
216        PreparedRender {
217            channels,
218            base_density: self.film.base_density,
219            paper,
220            print_shift,
221            print,
222            scan: self
223                .spectral_scan
224                .then(|| ScanContext::measured_with(self.paper.dyes)),
225            extra,
226            cl_layer,
227            exposure_shift: self.exposure_ev * 2.0_f64.log10(),
228            reversal: self.film.process == crate::emulsion::FilmProcess::Reversal,
229            spectral: spectral
230                .then(|| {
231                    let context =
232                        SpectralContext::for_stock(self.film).with_camera(self.camera.clone());
233                    match atoms {
234                        Some(atoms) => context.with_atoms(atoms),
235                        None => context,
236                    }
237                })
238                .filter(|_| self.lut_size < 2),
239            lut: (spectral && self.lut_size >= 2 && extra.is_none()).then(|| {
240                let context =
241                    SpectralContext::for_stock(self.film).with_camera(self.camera.clone());
242                let context = match atoms {
243                    Some(atoms) => context.with_atoms(atoms),
244                    None => context,
245                };
246                ExposureLut::bake(self.lut_size, &context)
247            }),
248        }
249    }
250}
251
252/// The scalar model, flattened into the numbers another backend needs.
253///
254/// A GPU cannot call into this crate, and re-deriving the model from its
255/// parameters on the other side would be a second implementation that could
256/// drift. So the prepared render hands over the numbers it solved, in the shape
257/// a shader wants: per layer, a base density, a span, a slope and an inflection
258/// point; then the paper's two numbers and the enlarger's four.
259///
260/// Only the pure scalar path has one. The spectral exposure, the spectral print
261/// and the spectral scan integrate over wavelength, and a backend that wants
262/// them has to port the integration rather than the numbers.
263#[derive(Debug, Clone, Copy, PartialEq)]
264pub struct ScalarModel {
265    /// Per layer: `d_min`, `d_max`, `gamma`, `log_e0`.
266    pub curve: [[f64; 4]; 3],
267    /// The paper's `d_min`, `d_max`, `gamma` and `log_e0`.
268    pub paper: [f64; 4],
269    /// How sharply each curve's toe turns: the three layers, then the paper.
270    ///
271    /// It rides on the curve rather than on the model because it is a property
272    /// of the material — see `crate::curve`.
273    pub toe_transition: [f64; 4],
274    /// How sharply each curve's shoulder turns: the three layers, then the
275    /// paper. Equal to `toe_transition` for every material whose two corners
276    /// were measured as one.
277    pub shoulder_transition: [f64; 4],
278    /// The film's minimum density in status terms: base, fog and mask.
279    pub base_density: [f64; 3],
280    /// The enlarger's exposure shift per layer, in decades.
281    pub print_shift: [f64; 3],
282    /// Exposure offset applied before the curve, in decades.
283    pub exposure_shift: f64,
284    /// Whether the film is its own picture. A reversal keeps its density and
285    /// stops: there is no paper between the development and the eye.
286    pub reversal: bool,
287}
288
289/// The exposure, as the curve stage receives it.
290#[derive(Debug, Clone, Copy, PartialEq)]
291pub struct Exposure {
292    /// Log exposure of the three layers, in the order the film records them.
293    pub layers: [f64; 3],
294    /// Log exposure of the cyan dye's second emulsion, when the stock has one.
295    pub extra: Option<f64>,
296}
297
298/// A [`RenderParams`] with the curves already developed and the print balanced.
299#[derive(Debug, Clone)]
300pub struct PreparedRender {
301    /// Whether the film is viewed directly rather than printed.
302    pub reversal: bool,
303    channels: [CharacteristicCurve; 3],
304    base_density: [f64; 3],
305    paper: CharacteristicCurve,
306    print_shift: [f64; 3],
307    exposure_shift: f64,
308    /// The live spectral model, when no table was baked.
309    spectral: Option<SpectralContext>,
310    /// The baked table, when one was requested.
311    lut: Option<ExposureLut>,
312    /// The spectral print model, when requested.
313    print: Option<PrintContext>,
314    /// The spectral scan model, when requested.
315    scan: Option<ScanContext>,
316    /// The cyan dye's second emulsion, when the stock has one — ADR 0017.
317    ///
318    /// Only its curve lives here. The sensitivity is a table the spectral
319    /// context integrates, and the two meet in [`Self::negative_density_with`]:
320    /// the context says how much light the layer saw, this says how much dye
321    /// that made, and the cyan dye sums the two emulsions' densities.
322    extra: Option<CharacteristicCurve>,
323    /// Whether the fourth integral belongs to a cyan-sensitive inhibitor layer
324    /// rather than to a dye-forming emulsion (ADR 0018).
325    cl_layer: bool,
326}
327
328impl PreparedRender {
329    /// The enlarger's exposure, per layer, in decades: the balance solved for
330    /// a mid grey, plus the timer.
331    ///
332    /// This is what an operator dials: a colour head moves three exposure
333    /// factors against each other until a neutral negative prints neutral, and
334    /// a timer moves all three together. Both show up *here*, not in the
335    /// per-pixel exponent — see `with_enlarger` in `print.rs` for why.
336    #[must_use]
337    pub fn print_shift(&self) -> [f64; 3] {
338        self.print_shift
339    }
340
341    /// The same negative and paper, printed on another development's balance.
342    ///
343    /// A test strip is one exposure: several developments of one negative,
344    /// every print made with the enlarger where the first print set it. The
345    /// curves stay this development's — each print is a negative of its own
346    /// time — while the paper, the enlarger's balance and the scan come from
347    /// the reference. [`crate::contact::print()`] is the same idea on one
348    /// sheet; this is the same idea for prints made one at a time.
349    #[must_use]
350    pub fn printed_like(mut self, reference: &Self) -> Self {
351        self.paper = reference.paper;
352        self.print_shift = reference.print_shift;
353        self.print = reference.print.clone();
354        self.scan = reference.scan.clone();
355        self
356    }
357
358    /// The curve, the paper and the enlarger as plain numbers.
359    ///
360    /// Always available, because a spectral render runs the same three stages:
361    /// it only reaches the paper through an integration instead of through a
362    /// per-channel subtraction.
363    fn numbers(&self) -> ScalarModel {
364        ScalarModel {
365            curve: std::array::from_fn(|layer| {
366                let curve = &self.channels[layer];
367                [curve.d_min, curve.d_max, curve.gamma, curve.log_e0]
368            }),
369            paper: [
370                self.paper.d_min,
371                self.paper.d_max,
372                self.paper.gamma,
373                self.paper.log_e0,
374            ],
375            toe_transition: [
376                self.channels[0].toe_transition,
377                self.channels[1].toe_transition,
378                self.channels[2].toe_transition,
379                self.paper.toe_transition,
380            ],
381            shoulder_transition: [
382                self.channels[0].shoulder_transition,
383                self.channels[1].shoulder_transition,
384                self.channels[2].shoulder_transition,
385                self.paper.shoulder_transition,
386            ],
387            base_density: self.base_density,
388            print_shift: self.print_shift,
389            exposure_shift: self.exposure_shift,
390            reversal: self.reversal,
391        }
392    }
393
394    /// The scalar model as plain numbers, when the render uses only the scalar
395    /// path. `None` the moment any spectral stage is active.
396    #[must_use]
397    pub fn scalar_model(&self) -> Option<ScalarModel> {
398        if self.spectral.is_some()
399            || self.lut.is_some()
400            || self.print.is_some()
401            || self.scan.is_some()
402        {
403            return None;
404        }
405        Some(self.numbers())
406    }
407
408    /// The spectral model as plain numbers, when this render integrates over
409    /// wavelength and nothing in it needs a solver or a sampled cube.
410    ///
411    /// `None` in three cases, and the distinction matters to a caller that has
412    /// to choose a backend rather than to a caller that has to render:
413    ///
414    /// - nothing is spectral, so [`Self::scalar_model`] describes it;
415    /// - a baked table is in use, which is a sampled approximation rather than
416    ///   an integration;
417    /// - a dictionary prior is in use, which solves a non-negative least
418    ///   squares per pixel instead of a fixed matrix.
419    ///
420    /// The last two are their own models. A backend that implemented them would
421    /// be porting a solver, not replaying numbers, and it should say so rather
422    /// than substitute the closed form.
423    #[must_use]
424    pub fn spectral_model(&self) -> Option<SpectralModel> {
425        // ADR 0017: the fourth layer is a fourth integral and a second curve on
426        // the cyan dye. No field of the model carries it, and a backend that
427        // replayed the three layers would render a different film without
428        // saying so — so it declines, and the caller renders on the CPU.
429        if self.extra.is_some() || self.cl_layer {
430            return None;
431        }
432        if self.lut.is_some() {
433            return None;
434        }
435        // All three stages integrate on the model grid, so the first one that
436        // is present carries the step and the others cannot disagree.
437        let step_nm = self
438            .spectral
439            .as_ref()
440            .map(|context| context.grid().step_nm())
441            .or_else(|| self.print.as_ref().map(|context| context.grid().step_nm()))
442            .or_else(|| self.scan.as_ref().map(|context| context.grid().step_nm()))
443            .unwrap_or(0.0);
444        let model = SpectralModel {
445            scalar: self.numbers(),
446            step_nm,
447            exposure: match &self.spectral {
448                Some(context) => Some(context.model()?),
449                None => None,
450            },
451            enlarger: match &self.print {
452                Some(context) => Some(context.model()?),
453                None => None,
454            },
455            scan: match &self.scan {
456                Some(context) => Some(context.model()?),
457                None => None,
458            },
459        };
460        model.is_spectral().then_some(model)
461    }
462
463    /// The three negative curves after development.
464    #[must_use]
465    pub fn channels(&self) -> &[CharacteristicCurve; 3] {
466        &self.channels
467    }
468
469    /// Whether the spectral path is active, baked or live.
470    #[must_use]
471    pub fn is_spectral(&self) -> bool {
472        self.spectral.is_some() || self.lut.is_some()
473    }
474
475    /// Whether the print is going through the spectral model.
476    #[must_use]
477    pub fn is_spectral_print(&self) -> bool {
478        self.print.is_some()
479    }
480
481    /// Whether the scan is going through the spectral model.
482    #[must_use]
483    pub fn is_spectral_scan(&self) -> bool {
484        self.scan.is_some()
485    }
486
487    /// The baked table, if one was requested.
488    #[must_use]
489    pub fn lut(&self) -> Option<&ExposureLut> {
490        self.lut.as_ref()
491    }
492
493    /// Everything the curve stage needs from a pixel.
494    ///
495    /// The fourth layer rides beside the three rather than inside them: its
496    /// density lands on the cyan dye, which already has a layer, so folding it
497    /// into the blue channel's log exposure would combine the emulsions before
498    /// their curves and lose exactly what ADR 0017 added.
499    ///
500    /// `None` for the fourth layer is the ordinary case — every stock before
501    /// PRO 400H — and makes the rest of the chain the model it always was.
502    pub fn expose(&self, linear: [f64; 3]) -> Exposure {
503        let scalar = || std::array::from_fn(|channel| linear[channel].max(1e-10).log10());
504        if let Some(lut) = &self.lut {
505            // Baked: three trilinear lookups. A table cannot carry a fourth
506            // axis, which is why `prepare_with` refuses one for such a stock.
507            return Exposure {
508                layers: lut.sample(linear),
509                extra: None,
510            };
511        }
512        if let Some(context) = &self.spectral {
513            // Live: reconstruct once and integrate four times. The fallback
514            // keeps the function total; it cannot trigger with a context this
515            // module built.
516            return match context.expose_with_extra(linear) {
517                Some((layers, extra)) => Exposure { layers, extra },
518                None => Exposure {
519                    layers: scalar(),
520                    extra: None,
521                },
522            };
523        }
524        Exposure {
525            layers: scalar(),
526            extra: None,
527        }
528    }
529
530    /// The three log exposures: scalar per channel, or the film's layers
531    /// integrating a reconstructed spectrum.
532    #[must_use]
533    pub fn log_exposure(&self, linear: [f64; 3]) -> [f64; 3] {
534        self.expose(linear).layers
535    }
536
537    /// The negative's density, from log exposure.
538    ///
539    /// This is the three-layer model: one emulsion per dye. A stock with a
540    /// fourth layer wants [`Self::negative_density_with`], which is this plus
541    /// the second cyan emulsion.
542    #[must_use]
543    pub fn negative_density(&self, log_e: [f64; 3]) -> [f64; 3] {
544        self.negative_density_with(log_e, None)
545    }
546
547    /// The negative's density, with the cyan dye's second emulsion when there
548    /// is one.
549    ///
550    /// The sum is over densities: both emulsions make the same dye, and the
551    /// densitometer sees one number, so two emulsions at half a stop each are
552    /// not one at a stop. Ignoring `extra` is bit-for-bit the old model.
553    #[must_use]
554    pub fn negative_density_with(&self, log_e: [f64; 3], extra: Option<f64>) -> [f64; 3] {
555        let mut density: [f64; 3] = std::array::from_fn(|channel| {
556            self.channels[channel].density(log_e[channel] + self.exposure_shift)
557        });
558        if let (Some(curve), Some(log_e)) = (self.extra, extra) {
559            density[0] += curve.density(log_e + self.exposure_shift);
560        }
561        density
562    }
563
564    /// The print and the scan, from the negative's density.
565    #[must_use]
566    pub fn positive(&self, density_cmy: [f64; 3]) -> [f64; 3] {
567        // A reversal film is its own picture: there is no print, no paper and no
568        // enlarger between the development and the eye. What leaves is what the
569        // film transmits, and the density *is* the image.
570        if self.reversal {
571            // The film's clearest point is the projector's white: a slide's
572            // density is absolute — 0.08 for clean film, 3.3 for unexposed —
573            // and displaying it as a fraction of *clear film* rather than of
574            // nothing is what a lamp behind it does. Without that the whole
575            // image sits between two and eighty per cent and reads as a murk;
576            // a projector's white level is not a correction, it is the other
577            // half of the observation.
578            return std::array::from_fn(|channel| {
579                let white = self.channels[channel].d_max;
580                10.0_f64
581                    .powf(-(density_cmy[channel] + self.base_density[channel] - white))
582                    .clamp(0.0, 1.0)
583            });
584        }
585
586        // The spectral print does one integration for all three layers; calling
587        // it inside the channel loop made it six times more expensive per pixel.
588        let print_exposure = self
589            .print
590            .as_ref()
591            .map(|context| context.expose(density_cmy));
592
593        let mut density_print = [0.0; 3];
594        for channel in 0..3 {
595            // The enlarger sees the light the negative transmitted: per channel
596            // in the scalar model, through the dye spectra in the spectral one.
597            // The non-spectral print has no spectrum for the base, so the
598            // film's minimum density rides in the exponent with the dye. The
599            // spectral one puts the measured mask into the integral instead.
600            let log_transmittance = match &print_exposure {
601                Some(values) => values[channel],
602                None => -(density_cmy[channel] + self.base_density[channel]),
603            };
604            density_print[channel] = self
605                .paper
606                .density(log_transmittance + self.print_shift[channel]);
607        }
608
609        match &self.scan {
610            // Spectral scan: reflectance through the illuminant and the observer.
611            Some(context) => context.scan(density_print),
612            // Scalar scan: each density is that channel's light loss.
613            None => density_print.map(|density| 10.0_f64.powf(-density).clamp(0.0, 1.0)),
614        }
615    }
616
617    /// Render one linear-light pixel.
618    #[must_use]
619    pub fn render_pixel(&self, linear: [f64; 3]) -> [f64; 3] {
620        let exposure = self.expose(linear);
621        self.positive(self.negative_density_with(exposure.layers, exposure.extra))
622    }
623
624    /// Whether the render carries a fourth layer of either kind.
625    #[must_use]
626    pub fn has_extra_layer(&self) -> bool {
627        self.extra.is_some() || self.cl_layer
628    }
629
630    /// Whether the fourth layer releases inhibitor rather than forming dye.
631    #[must_use]
632    pub fn has_inhibitor_layer(&self) -> bool {
633        self.cl_layer
634    }
635}
636
637/// What happens between the exposure and the development.
638///
639/// Both are optional and independent; the model without them is the model.
640#[derive(Debug, Clone, Copy, Default)]
641pub struct Finishing<'a> {
642    /// The film's own blur: how soft the emulsion makes everything.
643    pub emulsion: Option<&'a crate::mtf::EmulsionBlur>,
644    /// Light that scatters in the emulsion and reflects off the base.
645    pub halation: Option<&'a crate::halation::Halation>,
646    /// The emulsion's grain.
647    pub grain: Option<&'a crate::grain::GrainField>,
648    /// DIR couplers, acting on the developed densities.
649    pub couplers: Option<&'a crate::couplers::Couplers>,
650    /// The cyan-sensitive layer's inhibitor, acting on the cyan dye — ADR 0018.
651    pub interimage: Option<&'a crate::interimage::InterImage>,
652}
653
654/// Run `f` over every pixel, in parallel when the `parallel` feature is on.
655///
656/// The render is embarrassingly parallel: a pixel's exposure, its density and
657/// its print depend on that pixel alone. So this is the whole of the speed-up —
658/// no tiling, no work queue, no second code path that could disagree with the
659/// serial one. The spatial stages (halation, the couplers) run before and after
660/// and stay serial, because they are the ones that genuinely look sideways.
661#[inline]
662fn each_pixel<T: Send>(data: &mut [T], width: usize, f: impl Fn(usize, usize, &mut T) + Sync) {
663    #[cfg(feature = "parallel")]
664    {
665        use rayon::prelude::*;
666        data.par_iter_mut()
667            .enumerate()
668            .for_each(|(index, slot)| f(index % width, index / width, slot));
669    }
670    #[cfg(not(feature = "parallel"))]
671    {
672        for (index, slot) in data.iter_mut().enumerate() {
673            f(index % width, index / width, slot);
674        }
675    }
676}
677
678/// [`each_pixel`], for two planes that describe the same pixel.
679///
680/// The fourth layer needs a plane of its own — it is a layer, not a fourth
681/// number in a three-channel pixel — and its exposure comes from the same
682/// reconstructed spectrum as the other three. Filling the two in separate
683/// passes would reconstruct every spectrum twice.
684#[inline]
685fn each_pixel_pair<A: Send, B: Send>(
686    first: &mut [A],
687    second: &mut [B],
688    width: usize,
689    f: impl Fn(usize, usize, &mut A, &mut B) + Sync,
690) {
691    #[cfg(feature = "parallel")]
692    {
693        use rayon::prelude::*;
694        first
695            .par_iter_mut()
696            .zip(second.par_iter_mut())
697            .enumerate()
698            .for_each(|(index, (left, right))| f(index % width, index / width, left, right));
699    }
700    #[cfg(not(feature = "parallel"))]
701    {
702        for (index, (left, right)) in first.iter_mut().zip(second.iter_mut()).enumerate() {
703            f(index % width, index / width, left, right);
704        }
705    }
706}
707
708/// Render a whole image with the finishing effects.
709///
710/// Halation runs first and needs the whole frame, because it moves light
711/// between pixels; grain runs second and is per pixel. Both are applied to the
712/// exposure — one to where the light went, one to how many grains it developed —
713/// which is why they sit before the curve rather than after the print.
714/// A developed negative: densities, and the grid they came at.
715///
716/// Densities do not depend on a paper, so one of these can be printed as many
717/// times as wanted — on as many papers, at as many print exposures — without
718/// touching the film model again. That is what a darkroom does, and it is what
719/// the bench needs in order to stay responsive while a print exposure is being
720/// dialled.
721#[derive(Debug, Clone, PartialEq)]
722pub struct Negative {
723    /// Pixels across.
724    pub width: usize,
725    /// Pixels down.
726    pub height: usize,
727    /// Per pixel, the cyan, magenta and yellow density the film developed.
728    pub densities: Vec<[f64; 3]>,
729}
730
731impl PreparedRender {
732    /// Expose and develop: everything the film and the development decide, and
733    /// nothing the paper does.
734    #[must_use]
735    pub fn develop(
736        &self,
737        pixels: &[[f64; 3]],
738        width: usize,
739        height: usize,
740        finishing: &Finishing,
741    ) -> Negative {
742        let width = width.max(1);
743        let height = height.max(1);
744
745        // Without a spatial effect there is nothing to keep a frame for, and
746        // grain is the only thing left that wants pixel coordinates.
747        if finishing.emulsion.is_none()
748            && finishing.halation.is_none()
749            && finishing.couplers.is_none()
750            && finishing.interimage.is_none()
751        {
752            let densities: Vec<[f64; 3]> = pixels
753                .iter()
754                .enumerate()
755                .map(|(index, pixel)| {
756                    let exposure = self.expose(*pixel);
757                    let mean = self.negative_density_with(exposure.layers, exposure.extra);
758                    match finishing.grain {
759                        Some(grain) => self.negative_density_with(
760                            std::array::from_fn(|channel| {
761                                exposure.layers[channel]
762                                    + grain.jitter(
763                                        index % width,
764                                        index / width,
765                                        mean[channel],
766                                        channel,
767                                    )
768                            }),
769                            exposure.extra,
770                        ),
771                        None => mean,
772                    }
773                })
774                .collect();
775            return Negative {
776                width,
777                height,
778                densities,
779            };
780        }
781
782        // Exposure first: halation moves light between pixels, before anything
783        // is developed.
784        let mut log_e: Vec<[f64; 3]> = pixels.to_vec();
785        // The fourth layer is a fourth plane, allocated only when the stock has
786        // one: a stock without it renders through exactly the vectors it used to.
787        let mut extra: Option<Vec<f64>> = self.has_extra_layer().then(|| vec![0.0; log_e.len()]);
788        match extra.as_mut() {
789            Some(plane) => each_pixel_pair(&mut log_e, plane, width, |_, _, pixel, slot| {
790                let exposure = self.expose(*pixel);
791                *pixel = exposure.layers;
792                // No integral means no exposure: the emulsion stays at its
793                // minimum density rather than at a plausible-looking zero.
794                *slot = exposure.extra.unwrap_or(f64::NEG_INFINITY);
795            }),
796            None => each_pixel(&mut log_e, width, |_, _, pixel| {
797                *pixel = self.log_exposure(*pixel);
798            }),
799        }
800        // The emulsion's own blur comes first: it is the lens's image being
801        // softened by the film, and the halo is light that entered the film and
802        // came back, so it is distributed by the same blur afterwards.
803        if let Some(emulsion) = finishing.emulsion {
804            emulsion.apply(&mut log_e, width, height);
805        }
806        if let Some(halation) = finishing.halation {
807            halation.apply(&mut log_e, width, height);
808        }
809
810        // Then the emulsion: grain on the exposure, the curve on the result.
811        let mut density: Vec<[f64; 3]> = log_e.clone();
812        each_pixel(&mut density, width, |x, y, slot| {
813            let log_e = log_e[y * width + x];
814            let extra = extra.as_ref().map(|plane| plane[y * width + x]);
815            let mean = self.negative_density_with(log_e, extra);
816            *slot = match finishing.grain {
817                Some(grain) => self.negative_density_with(
818                    std::array::from_fn(|channel| {
819                        log_e[channel] + grain.jitter(x, y, mean[channel], channel)
820                    }),
821                    extra,
822                ),
823                None => mean,
824            };
825        });
826
827        // The cyan-sensitive layer's inhibitor, before the couplers: its release
828        // is the light the layer absorbed, not the density it developed, so it
829        // is the earlier of the two development effects.
830        if let (Some(stage), Some(plane)) = (finishing.interimage, extra.as_ref()) {
831            let light: Vec<f64> = plane.iter().map(|value| 10f64.powf(*value)).collect();
832            stage.apply(&mut density, &light, width, height);
833        }
834
835        // Then the chemistry: the inhibitors act on what has already developed.
836        if let Some(couplers) = finishing.couplers {
837            couplers.apply(&mut density, width, height);
838        }
839
840        Negative {
841            width,
842            height,
843            densities: density,
844        }
845    }
846
847    /// Print a developed negative through this render's paper and enlarger.
848    #[must_use]
849    pub fn print(&self, negative: &Negative) -> Vec<[f64; 3]> {
850        negative
851            .densities
852            .iter()
853            .map(|density| self.positive(*density))
854            .collect()
855    }
856}
857
858/// Develop a whole image and print it, in place.
859///
860/// This is `develop` followed by `print`, and exists because most callers want
861/// a picture rather than a negative. A caller that wants the negative — to
862/// print it on a second paper, or at another print exposure — should take it
863/// apart the way this does.
864pub fn render_pixels_finished(
865    pixels: &mut [[f64; 3]],
866    prepared: &PreparedRender,
867    width: usize,
868    height: usize,
869    finishing: &Finishing,
870) {
871    let negative = prepared.develop(pixels, width, height, finishing);
872    for (pixel, density) in pixels.iter_mut().zip(&negative.densities) {
873        *pixel = prepared.positive(*density);
874    }
875}
876
877/// Render a whole image in place.
878pub fn render_pixels(pixels: &mut [[f64; 3]], prepared: &PreparedRender) {
879    // Width only matters to the grain, which this path has none of.
880    each_pixel(pixels, 1, |_, _, pixel| {
881        *pixel = prepared.render_pixel(*pixel);
882    });
883}
884
885/// Render a whole image with grain.
886///
887/// The grain is an exposure fluctuation, so it is applied to the log exposure
888/// and then pushed through the same curve — which is what keeps it out of a
889/// blank frame and out of the shoulder without either case being special-cased.
890pub fn render_pixels_with_grain(
891    pixels: &mut [[f64; 3]],
892    prepared: &PreparedRender,
893    grain: &crate::grain::GrainField,
894) {
895    render_pixels_finished(
896        pixels,
897        prepared,
898        grain.width,
899        grain.height,
900        &Finishing {
901            emulsion: None,
902            halation: None,
903            grain: Some(grain),
904            couplers: None,
905            interimage: None,
906        },
907    );
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913
914    /// The fourth layer's sensitivity: a straight line at 5 nm, sampled every
915    /// 10 nm. Interpolating it back onto the model grid returns the same
916    /// function, so it sees *exactly* what the blue layer sees and only the
917    /// anchor can differ.
918    const STRAIGHT: [f32; 36] = {
919        let mut table = [0.0_f32; 36];
920        let mut index = 0;
921        while index < 36 {
922            table[index] = 1.0 + 0.02 * (index as f32);
923            index += 1;
924        }
925        table
926    };
927
928    /// A four-layer stock: three identical straight-line layers and a cyan dye
929    /// fed by a second emulsion. `Box::leak` because [`RenderParams`] borrows
930    /// the stock and the test is its only owner.
931    fn four_layer(curve: [f64; 4]) -> &'static FilmStock {
932        let mut straight = [0.0; crate::spectral::GRID_LEN];
933        for (index, value) in straight.iter_mut().enumerate() {
934            *value = 1.0 + 0.01 * index as f64;
935        }
936        let layers: &'static [[f64; crate::spectral::GRID_LEN]; 3] =
937            Box::leak(Box::new([straight, straight, straight]));
938        let mut stock = *crate::emulsion::film_stock("vision3_500t").expect("built-in stock");
939        stock.id = "test_four_layer";
940        stock.layers = layers;
941        stock.extra_cyan = Some(crate::dye::Emulsion {
942            curve,
943            transition: crate::curve::TRANSITION,
944            sensitivity: &STRAIGHT,
945        });
946        Box::leak(Box::new(stock))
947    }
948
949    /// A mid grey, printed once at the solved exposure and once a stop over.
950    ///
951    /// The timer is a separate number from the balance: zero is the test strip
952    /// that came out right, and one stop is a darker print on every layer.
953    #[test]
954    fn print_exposure_darkens_the_print() {
955        let base = RenderParams::default();
956        let over = RenderParams {
957            print_exposure_ev: 1.0,
958            ..RenderParams::default()
959        };
960
961        let grey = [0.18, 0.18, 0.18];
962        let solved = base.prepare().render_pixel(grey);
963        let darker = over.prepare().render_pixel(grey);
964
965        for channel in 0..3 {
966            assert!(
967                darker[channel] < solved[channel],
968                "channel {channel}: {darker:?} should be darker than {solved:?}"
969            );
970        }
971        // A stop is a factor of two in exposure, not a factor of two in the
972        // print: the paper's curve stands between them, and it must not be
973        // bypassed.
974        assert!(darker[0] < solved[0] * 0.95);
975    }
976
977    /// A colour pack is a spectrum in the light path, so it turns on the stage
978    /// that can carry one — even when the caller did not ask for the spectral
979    /// print by name.
980    #[test]
981    fn a_colour_pack_engages_the_spectral_print() {
982        use crate::filters::{FilterPack, HeatGlass};
983
984        let plain = RenderParams::default().prepare();
985        assert!(!plain.is_spectral_print(), "no glass, no spectral print");
986
987        let filtered = RenderParams {
988            filters: FilterPack::new(0.0, 30.0, 0.0),
989            ..RenderParams::default()
990        }
991        .prepare();
992        assert!(filtered.is_spectral_print());
993
994        let glass = RenderParams {
995            heat_glass: Some(HeatGlass::Kg3),
996            ..RenderParams::default()
997        }
998        .prepare();
999        assert!(glass.is_spectral_print());
1000    }
1001
1002    /// A test strip is one exposure: every print keeps the first print's
1003    /// enlarger balance while carrying its own development.
1004    #[test]
1005    fn a_test_strip_keeps_the_first_prints_balance() {
1006        let at = |minutes: f64| {
1007            RenderParams {
1008                development: DevelopmentParams {
1009                    time_min: minutes,
1010                    ..DevelopmentParams::default()
1011                },
1012                ..RenderParams::default()
1013            }
1014            .prepare()
1015        };
1016        let first = at(3.0);
1017        let second = at(12.0);
1018        let strip = second.clone().printed_like(&first);
1019
1020        assert_eq!(strip.print_shift(), first.print_shift());
1021        assert_ne!(strip.print_shift(), second.print_shift());
1022
1023        // The negative is still the twelve-minute one: only the print is held.
1024        let log_e = [-1.0, -1.0, -1.0];
1025        assert_eq!(
1026            strip.negative_density_with(log_e, None),
1027            second.negative_density_with(log_e, None)
1028        );
1029        assert_ne!(
1030            strip.negative_density_with(log_e, None),
1031            first.negative_density_with(log_e, None)
1032        );
1033
1034        // Printed on one exposure, the longer development is the denser
1035        // negative — so it passes less light and prints lighter. That is the
1036        // comparison a test strip exists to make.
1037        let grey = [0.18, 0.18, 0.18];
1038        assert!(
1039            strip.render_pixel(grey)[0] > first.render_pixel(grey)[0],
1040            "the strip's twelve-minute print should be lighter than its three"
1041        );
1042    }
1043
1044    /// One negative, two papers.
1045    ///
1046    /// The negative is developed once and holds no paper, so the bench can try
1047    /// a second paper without re-developing the film — which is the whole point
1048    /// of the split.
1049    #[test]
1050    fn a_negative_prints_on_any_paper() {
1051        let first = RenderParams::default();
1052        let second = RenderParams {
1053            paper: crate::emulsion::paper_stock("endura_premier").expect("built-in paper"),
1054            ..RenderParams::default()
1055        };
1056
1057        let negative = first.prepare().develop(
1058            &[[0.18, 0.18, 0.18], [0.4, 0.3, 0.2]],
1059            2,
1060            1,
1061            &Finishing::default(),
1062        );
1063        assert_eq!(negative.densities.len(), 2);
1064
1065        let on_first = first.prepare().print(&negative);
1066        let on_second = second.prepare().print(&negative);
1067        assert_ne!(on_first, on_second);
1068
1069        // And the two-stage path is what the one-shot path does.
1070        let mut pixels = vec![[0.18, 0.18, 0.18], [0.4, 0.3, 0.2]];
1071        render_pixels_finished(&mut pixels, &first.prepare(), 2, 1, &Finishing::default());
1072        assert_eq!(pixels, on_first);
1073    }
1074
1075    /// The fourth layer's plane has to survive the effects path too: it is
1076    /// filled beside the three-channel exposure, developed by the same curve
1077    /// pass, and read back as the cyan dye's second density. A stock without a
1078    /// fourth layer never allocates it, which is why this is the only test that
1079    /// takes the pair path with a non-empty plane.
1080    #[test]
1081    fn a_four_layer_frame_renders_through_the_effects_path() {
1082        let prepared = RenderParams {
1083            film: four_layer([0.0, 1.0, 1.0, -0.5]),
1084            ..RenderParams::default()
1085        }
1086        .prepare();
1087        assert!(prepared.has_extra_layer());
1088
1089        let mut pixels = vec![
1090            [0.6, 0.3, 0.1],
1091            [0.1, 0.2, 0.4],
1092            [0.05, 0.05, 0.05],
1093            [0.9, 0.9, 0.9],
1094        ];
1095        let halation = crate::halation::Halation::typical(6.0);
1096        render_pixels_finished(
1097            &mut pixels,
1098            &prepared,
1099            2,
1100            2,
1101            &Finishing {
1102                emulsion: None,
1103                halation: Some(&halation),
1104                grain: None,
1105                couplers: None,
1106                interimage: None,
1107            },
1108        );
1109        assert!(
1110            pixels
1111                .iter()
1112                .all(|pixel| pixel.iter().all(|value| value.is_finite() && *value >= 0.0))
1113        );
1114
1115        // The same frame through the no-effects path: the two differ only by
1116        // the halo, which is small but not nothing on a bright edge.
1117        let mut plain = vec![
1118            [0.6, 0.3, 0.1],
1119            [0.1, 0.2, 0.4],
1120            [0.05, 0.05, 0.05],
1121            [0.9, 0.9, 0.9],
1122        ];
1123        render_pixels_finished(
1124            &mut plain,
1125            &prepared,
1126            2,
1127            2,
1128            &Finishing {
1129                emulsion: None,
1130                halation: None,
1131                grain: None,
1132                couplers: None,
1133                interimage: None,
1134            },
1135        );
1136        for (halated, plain) in pixels.iter().zip(&plain) {
1137            for (left, right) in halated.iter().zip(plain) {
1138                assert!((left - right).abs() < 0.5, "{halated:?} vs {plain:?}");
1139            }
1140        }
1141    }
1142
1143    /// The enlarger is balanced on the density the negative actually has, so a
1144    /// four-layer stock must still print mid grey as mid grey. If the balance
1145    /// ignored the second emulsion, the printed grey would come out too dark in
1146    /// cyan by exactly that density.
1147    #[test]
1148    fn a_four_layer_stock_still_prints_mid_grey_as_mid_grey() {
1149        for curve in [[0.0, 1.0, 1.0, -1.0], [0.0, 2.0, 0.7, -0.2]] {
1150            let prepared = RenderParams {
1151                film: four_layer(curve),
1152                ..RenderParams::default()
1153            }
1154            .prepare();
1155            let exposure = prepared.expose([0.18, 0.18, 0.18]);
1156            let printed =
1157                prepared.positive(prepared.negative_density_with(exposure.layers, exposure.extra));
1158            for value in printed {
1159                assert!(
1160                    (value - 0.18).abs() < 0.02,
1161                    "curve {curve:?} printed {printed:?}"
1162                );
1163            }
1164        }
1165    }
1166
1167    /// A stock with a cyan-sensitive inhibitor layer and no dye-forming fourth
1168    /// emulsion: the arrangement ADR 0018 exists for.
1169    fn inhibitor_stock() -> &'static FilmStock {
1170        static SENSITIVITY: [f64; crate::spectral::GRID_LEN] = [1.0; crate::spectral::GRID_LEN];
1171        let mut stock = *crate::emulsion::film_stock("vision3_500t").expect("built-in stock");
1172        stock.id = "test_inhibitor_layer";
1173        stock.cl_layer = Some(crate::dye::InhibitorLayer {
1174            sensitivity: &SENSITIVITY,
1175        });
1176        Box::leak(Box::new(stock))
1177    }
1178
1179    /// ADR 0018: the layer shows where the frame has structure, and only in the
1180    /// cyan channel. A stock with such a layer renders identically until the
1181    /// stage is asked for, which is what keeps PRO 400H a three-layer stock on
1182    /// the GPU by default.
1183    #[test]
1184    fn the_inhibitor_layer_shows_only_where_the_frame_has_structure() {
1185        let off = RenderParams {
1186            film: inhibitor_stock(),
1187            ..RenderParams::default()
1188        }
1189        .prepare();
1190        let on = RenderParams {
1191            film: inhibitor_stock(),
1192            interimage: true,
1193            ..RenderParams::default()
1194        }
1195        .prepare();
1196        assert!(!off.has_inhibitor_layer());
1197        assert!(on.has_inhibitor_layer());
1198        // The fourth integral is a quantity the replayable model has no lane
1199        // for, so a backend declines whenever the layer is in the render.
1200        assert!(on.spectral_model().is_none());
1201        assert!(off.scalar_model().is_some());
1202
1203        let stage = crate::interimage::InterImage::typical(6.0);
1204        let finishing = |interimage| Finishing {
1205            emulsion: None,
1206            halation: None,
1207            grain: None,
1208            couplers: None,
1209            interimage,
1210        };
1211        // Sixty-four pixels: thirty-two warm, thirty-two cool. Both renders use
1212        // the same prepared render — same exposure, same curve, same print — so
1213        // the only thing that differs is whether the inhibitor acted.
1214        let mut pixels = Vec::new();
1215        for index in 0..64 {
1216            pixels.push(if index < 32 {
1217                [0.9, 0.2, 0.1]
1218            } else {
1219                [0.1, 0.2, 0.9]
1220            });
1221        }
1222        let mut with = pixels.clone();
1223        let mut without = pixels;
1224        render_pixels_finished(&mut with, &on, 64, 1, &finishing(Some(&stage)));
1225        render_pixels_finished(&mut without, &on, 64, 1, &finishing(None));
1226
1227        // Which half the layer sees more of is the exposure's answer, not the
1228        // eye's: a flat sensitivity integrates the reconstructed spectrum, and
1229        // a warm RGB triple is not the brighter one in it. So the expectation
1230        // comes from the render's own fourth integral.
1231        let warm = on
1232            .expose([0.9, 0.2, 0.1])
1233            .extra
1234            .expect("the layer is in the render");
1235        let cool = on
1236            .expose([0.1, 0.2, 0.9])
1237            .extra
1238            .expect("the layer is in the render");
1239        // The two pixels either side of the boundary: the brighter one is the
1240        // side whose inhibitor diffuses away, the shadow is the side that
1241        // receives it.
1242        let (bright, shadow) = if warm > cool { (31, 32) } else { (32, 31) };
1243
1244        // The sign of the *print* is not the sign of the *density*: the
1245        // inhibitor takes cyan density off the negative, and a negative with
1246        // less cyan passes more red light, which the paper then develops into
1247        // more cyan. So the shadow keeps less red than it would have, and the
1248        // bright side keeps more.
1249        assert!(
1250            with[shadow][0] < without[shadow][0],
1251            "the shadow did not lose cyan: {:?} vs {:?}",
1252            with[shadow],
1253            without[shadow]
1254        );
1255        assert!(
1256            with[bright][0] > without[bright][0],
1257            "the bright side did not gain: {:?} vs {:?}",
1258            with[bright],
1259            without[bright]
1260        );
1261        // The other two dyes are not this layer's business.
1262        for (left, right) in with.iter().zip(&without) {
1263            assert!((left[1] - right[1]).abs() < 1e-12);
1264            assert!((left[2] - right[2]).abs() < 1e-12);
1265        }
1266    }
1267
1268    /// ADR 0017's compatibility promise: the eighteen stocks that were here
1269    /// before the fourth layer exist are still the three-layer model, bit for
1270    /// bit, and a backend can still replay every one of them.
1271    #[test]
1272    fn a_stock_without_a_fourth_layer_is_still_the_three_layer_model() {
1273        for stock in crate::emulsion::FILM_STOCKS {
1274            let prepared = RenderParams {
1275                film: stock,
1276                ..RenderParams::default()
1277            }
1278            .prepare();
1279            assert!(!prepared.has_extra_layer(), "{}", stock.id);
1280
1281            let pixel = [0.4, 0.3, 0.2];
1282            let exposure = prepared.expose(pixel);
1283            assert_eq!(exposure.extra, None, "{}", stock.id);
1284            let expected: [f64; 3] = std::array::from_fn(|channel| {
1285                prepared.channels()[channel].density(exposure.layers[channel])
1286            });
1287            assert_eq!(
1288                prepared.negative_density(exposure.layers),
1289                expected,
1290                "{}",
1291                stock.id
1292            );
1293            // Still exactly one of the two replayable models: nothing about a
1294            // three-layer stock newly declines the GPU.
1295            assert!(
1296                prepared.scalar_model().is_some() || prepared.spectral_model().is_some(),
1297                "{}",
1298                stock.id
1299            );
1300        }
1301    }
1302
1303    /// The fourth layer is a density on the cyan dye, not a fourth exposure.
1304    #[test]
1305    fn a_second_emulsion_adds_density_on_the_cyan_dye() {
1306        let curve = [0.05, 1.2, 0.7, -1.0];
1307        let prepared = RenderParams {
1308            film: four_layer(curve),
1309            ..RenderParams::default()
1310        }
1311        .prepare();
1312
1313        assert!(prepared.has_extra_layer());
1314        // A second emulsion is a fourth integral and a second curve: the
1315        // scalar path cannot say it, and the spectral model has no lane for
1316        // it, so a backend has to decline rather than replay three layers.
1317        assert!(prepared.is_spectral());
1318        assert!(prepared.scalar_model().is_none());
1319        assert!(prepared.spectral_model().is_none());
1320
1321        let exposure = prepared.expose([0.4, 0.3, 0.2]);
1322        let extra = exposure.extra.expect("the stock has a second emulsion");
1323        let added = crate::curve::density_from(
1324            curve[0],
1325            curve[1],
1326            curve[2],
1327            curve[3],
1328            crate::curve::TRANSITION,
1329            crate::curve::TRANSITION,
1330            extra,
1331        );
1332
1333        let without = prepared.negative_density_with(exposure.layers, None);
1334        let with = prepared.negative_density_with(exposure.layers, Some(extra));
1335        assert!(
1336            (with[0] - without[0] - added).abs() < 1e-12,
1337            "cyan: {} + {added} vs {}",
1338            without[0],
1339            with[0]
1340        );
1341        // The other two dyes are untouched: the layer shares a dye, not a
1342        // channel.
1343        assert_eq!([with[1], with[2]], [without[1], without[2]]);
1344    }
1345
1346    /// The fourth layer is normalised on the **blue** layer's grey response,
1347    /// not on its own. The data sheet plots all four emulsions on one log H
1348    /// axis, and the distance between the blue-sensitive curve and the
1349    /// cyan-sensitive one is a speed difference that self-anchoring would
1350    /// divide out.
1351    ///
1352    /// With a sensitivity that is the blue layer's own function, the two
1353    /// integrals must agree to the last digit at every colour — including the
1354    /// ones where mid grey's exposure, −0.744, is nowhere near.
1355    #[test]
1356    fn the_fourth_layer_is_anchored_on_the_blue_layer() {
1357        let prepared = RenderParams {
1358            film: four_layer([0.0, 1.0, 1.0, 0.0]),
1359            ..RenderParams::default()
1360        }
1361        .prepare();
1362        for pixel in [[0.18, 0.18, 0.18], [0.9, 0.1, 0.05], [0.05, 0.2, 0.8]] {
1363            let exposure = prepared.expose(pixel);
1364            let extra = exposure.extra.expect("the stock has a second emulsion");
1365            let blue = exposure.layers[2];
1366            assert!(
1367                (extra - blue).abs() < 1e-6,
1368                "{pixel:?}: fourth layer {extra} vs blue layer {blue}"
1369            );
1370        }
1371    }
1372
1373    fn chain(development: DevelopmentParams) -> PreparedRender {
1374        RenderParams {
1375            development,
1376            ..RenderParams::default()
1377        }
1378        .prepare()
1379    }
1380
1381    #[test]
1382    fn print_balance_lands_mid_grey_on_target() {
1383        let prepared = chain(DevelopmentParams::default());
1384        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
1385        for channel in out {
1386            assert!(
1387                (channel - 0.18).abs() < 0.005,
1388                "mid grey printed at {channel}"
1389            );
1390        }
1391    }
1392
1393    #[test]
1394    fn a_reversal_film_is_not_printed() {
1395        // The only stage that separates a reversal from a negative is the print:
1396        // the film's own density is the picture, so what leaves is its
1397        // transmittance and not a paper's response to it. The white point is the
1398        // film's clearest density — a projector's lamp, not the absence of film.
1399        let stock = crate::emulsion::film_stock("provia_100f").expect("the reversal stock");
1400        let prepared = RenderParams {
1401            film: stock,
1402            ..RenderParams::default()
1403        }
1404        .prepare();
1405        assert!(prepared.reversal);
1406
1407        let density = [1.0, 1.5, 2.0];
1408        let out = prepared.positive(density);
1409        for channel in 0..3 {
1410            let white = prepared.channels()[channel].d_max;
1411            let expected =
1412                10.0_f64.powf(-(density[channel] + prepared.base_density[channel] - white));
1413            assert!(
1414                (out[channel] - expected).abs() < 1e-12,
1415                "channel {channel}: {} against {expected}",
1416                out[channel]
1417            );
1418        }
1419
1420        // And the ends behave: unexposed film is black, clear film is white.
1421        let black = prepared.render_pixel([0.0; 3]);
1422        let clear = prepared.render_pixel([4.0; 3]);
1423        for channel in 0..3 {
1424            assert!(black[channel] < 0.01, "unexposed at {}", black[channel]);
1425            assert!(clear[channel] > 0.9, "fully exposed at {}", clear[channel]);
1426        }
1427    }
1428
1429    /// Local slope of the whole chain, in density per decade of scene exposure,
1430    /// measured one stop either side of mid grey.
1431    fn local_contrast(prepared: &PreparedRender) -> f64 {
1432        let mid = 0.18;
1433        let low = prepared.render_pixel([mid / 2.0; 3])[1].max(1e-6);
1434        let high = prepared.render_pixel([mid * 2.0; 3])[1].max(1e-6);
1435        (high / low).log10() / 4.0_f64.log10()
1436    }
1437
1438    /// Luma of a linear RGB triple, the observer every check below uses.
1439    fn luma(rgb: [f64; 3]) -> f64 {
1440        0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
1441    }
1442
1443    /// The checks `tools/eval.py` used to make by rendering a grey ramp through
1444    /// every stock and reading the PNG back. They were the only ones that
1445    /// touched all thirty stocks instead of the default one, and they lived
1446    /// outside `cargo test`, where nothing ran them but a person remembering to.
1447    /// A stock is balanced or it is not; that is a test, not a screenshot.
1448    #[test]
1449    fn every_stock_prints_mid_grey_as_mid_grey() {
1450        for film in crate::emulsion::FILM_STOCKS {
1451            let prepared = RenderParams {
1452                film,
1453                ..RenderParams::default()
1454            }
1455            .prepare();
1456            // A reversal is its own picture: there is no print to balance.
1457            if prepared.reversal {
1458                continue;
1459            }
1460            let out = prepared.render_pixel([0.18; 3]);
1461            assert!(
1462                (luma(out) - 0.18).abs() < 0.01,
1463                "{} printed mid grey at {:.4}",
1464                film.id,
1465                luma(out)
1466            );
1467            let high = out.iter().copied().fold(f64::MIN, f64::max);
1468            let low = out.iter().copied().fold(f64::MAX, f64::min);
1469            assert!(
1470                high - low < 0.01,
1471                "{} printed mid grey {:.4} off neutral",
1472                film.id,
1473                high - low
1474            );
1475        }
1476
1477        for paper in crate::emulsion::PAPER_STOCKS {
1478            let prepared = RenderParams {
1479                paper,
1480                ..RenderParams::default()
1481            }
1482            .prepare();
1483            let out = prepared.render_pixel([0.18; 3]);
1484            assert!(
1485                (luma(out) - 0.18).abs() < 0.02,
1486                "{} printed mid grey at {:.4}",
1487                paper.id,
1488                luma(out)
1489            );
1490        }
1491    }
1492
1493    /// A ramp must not invert, whatever the stock: an inversion is a sign
1494    /// error, a clamped tone or a channel swap, and none of them should need a
1495    /// photograph to notice.
1496    #[test]
1497    fn every_stock_keeps_a_ramp_monotone() {
1498        let steps = [0.0, 0.02, 0.05, 0.1, 0.18, 0.35, 0.6, 0.8, 1.0];
1499        for film in crate::emulsion::FILM_STOCKS {
1500            let prepared = RenderParams {
1501                film,
1502                ..RenderParams::default()
1503            }
1504            .prepare();
1505            let mut previous = f64::MIN;
1506            for step in steps {
1507                let value = luma(prepared.render_pixel([step; 3]));
1508                assert!(
1509                    value >= previous - 1e-9,
1510                    "{} inverts the ramp at {step}: {value:.4} under {previous:.4}",
1511                    film.id
1512                );
1513                previous = value;
1514            }
1515        }
1516    }
1517
1518    /// The spread of a nine-step ramp, which is how a printer judges contrast:
1519    /// the slope of one stop either side of mid grey inverts its sign on a
1520    /// reversal, whose output is a transmittance rather than a reflectance.
1521    fn spread(prepared: &PreparedRender) -> f64 {
1522        let steps = [0.0, 0.02, 0.05, 0.1, 0.18, 0.35, 0.6, 0.8, 1.0];
1523        let values: Vec<f64> = steps
1524            .iter()
1525            .map(|step| luma(prepared.render_pixel([*step; 3])))
1526            .collect();
1527        let mean = values.iter().sum::<f64>() / values.len() as f64;
1528        (values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64).sqrt()
1529    }
1530
1531    /// Development reaches the render for every stock, not only the default.
1532    #[test]
1533    fn every_stock_gains_contrast_with_development() {
1534        for film in crate::emulsion::FILM_STOCKS {
1535            let at = |time_min: f64| {
1536                spread(
1537                    &RenderParams {
1538                        film,
1539                        development: DevelopmentParams {
1540                            time_min,
1541                            ..DevelopmentParams::default()
1542                        },
1543                        ..RenderParams::default()
1544                    }
1545                    .prepare(),
1546                )
1547            };
1548            let pulled = at(4.0);
1549            let normal = at(8.0);
1550            let pushed = at(16.0);
1551            assert!(
1552                pulled < normal && normal < pushed,
1553                "{}: spread {pulled:.3} / {normal:.3} / {pushed:.3} at 4 / 8 / 16 min",
1554                film.id
1555            );
1556        }
1557    }
1558
1559    #[test]
1560    fn over_development_raises_contrast() {
1561        let normal = local_contrast(&chain(DevelopmentParams::default()));
1562        let pushed = local_contrast(&chain(DevelopmentParams {
1563            time_min: 12.0,
1564            ..DevelopmentParams::default()
1565        }));
1566        assert!(pushed > normal, "normal {normal}, pushed {pushed}");
1567    }
1568
1569    #[test]
1570    fn under_development_lowers_contrast() {
1571        let normal = local_contrast(&chain(DevelopmentParams::default()));
1572        let pulled = local_contrast(&chain(DevelopmentParams {
1573            time_min: 3.0,
1574            ..DevelopmentParams::default()
1575        }));
1576        assert!(pulled < normal, "normal {normal}, pulled {pulled}");
1577    }
1578
1579    /// A silver image has no dyes. Asking for the spectral print on a
1580    /// monochrome film would integrate nothing and print a flat grey, so the
1581    /// scalar print is what the stock gets — and `is_spectral_print` agrees,
1582    /// because the CLI's summary reads it.
1583    #[test]
1584    fn a_silver_film_does_not_print_spectrally() {
1585        let prepared = RenderParams {
1586            film: crate::emulsion::film_stock("kodak_trix400").expect("the silver stock"),
1587            spectral: true,
1588            spectral_print: true,
1589            ..RenderParams::default()
1590        }
1591        .prepare();
1592        assert!(!prepared.is_spectral_print());
1593        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
1594        assert!(out.iter().all(|channel| channel.is_finite()));
1595        assert!(out[1] > 0.02 && out[1] < 0.6, "mid grey at {}", out[1]);
1596    }
1597
1598    #[test]
1599    fn spectral_path_keeps_mid_grey_on_target() {
1600        let prepared = RenderParams {
1601            spectral: true,
1602            ..RenderParams::default()
1603        }
1604        .prepare();
1605        assert!(prepared.is_spectral());
1606        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
1607        for channel in out {
1608            assert!(
1609                (channel - 0.18).abs() < 0.01,
1610                "mid grey printed at {channel}"
1611            );
1612        }
1613    }
1614
1615    #[test]
1616    fn spectral_scan_produces_neutral_grey() {
1617        let prepared = RenderParams {
1618            spectral_print: true,
1619            spectral_scan: true,
1620            ..RenderParams::default()
1621        }
1622        .prepare();
1623        assert!(prepared.is_spectral_scan());
1624
1625        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
1626        let spread = out.iter().copied().fold(f64::NEG_INFINITY, f64::max)
1627            - out.iter().copied().fold(f64::INFINITY, f64::min);
1628        assert!(spread < 0.02, "grey drifts by {spread}: {out:?}");
1629        assert!(out[1] > 0.02 && out[1] < 0.6, "mid grey at {}", out[1]);
1630    }
1631
1632    #[test]
1633    fn spectral_scan_is_monotonic_and_bounded() {
1634        let prepared = RenderParams {
1635            spectral_print: true,
1636            spectral_scan: true,
1637            ..RenderParams::default()
1638        }
1639        .prepare();
1640        let mut previous = -1.0;
1641        for i in -80..80 {
1642            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
1643            let y = prepared.render_pixel([x; 3])[1];
1644            assert!((0.0..=1.0).contains(&y));
1645            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
1646            previous = y;
1647        }
1648    }
1649
1650    #[test]
1651    fn spectral_print_keeps_mid_grey_on_target() {
1652        let prepared = RenderParams {
1653            spectral_print: true,
1654            ..RenderParams::default()
1655        }
1656        .prepare();
1657        assert!(prepared.is_spectral_print());
1658        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
1659        for channel in out {
1660            assert!(
1661                (channel - 0.18).abs() < 0.01,
1662                "mid grey printed at {channel}"
1663            );
1664        }
1665    }
1666
1667    #[test]
1668    fn spectral_print_couples_the_layers() {
1669        let scalar = RenderParams::default().prepare();
1670        let spectral = RenderParams {
1671            spectral_print: true,
1672            ..RenderParams::default()
1673        }
1674        .prepare();
1675
1676        // A cyan-dominant patch: its density sits mostly in one channel, but the
1677        // dyes overlap, so the paper's other layers must move too.
1678        let sample = [0.08, 0.42, 0.45];
1679        let a = scalar.render_pixel(sample);
1680        let b = spectral.render_pixel(sample);
1681        let difference: f64 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).sum();
1682        assert!(difference > 1e-4, "no coupling visible: {difference}");
1683    }
1684
1685    #[test]
1686    fn spectral_print_is_monotonic_and_bounded() {
1687        let prepared = RenderParams {
1688            spectral_print: true,
1689            ..RenderParams::default()
1690        }
1691        .prepare();
1692        let mut previous = -1.0;
1693        for i in -80..80 {
1694            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
1695            let y = prepared.render_pixel([x; 3])[1];
1696            assert!((0.0..=1.0).contains(&y));
1697            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
1698            previous = y;
1699        }
1700    }
1701
1702    #[test]
1703    fn the_baked_table_matches_the_live_path() {
1704        let live = RenderParams {
1705            spectral: true,
1706            ..RenderParams::default()
1707        }
1708        .prepare();
1709        let baked = RenderParams {
1710            spectral: true,
1711            lut_size: 33,
1712            ..RenderParams::default()
1713        }
1714        .prepare();
1715        assert!(baked.lut().is_some());
1716        assert!(live.lut().is_none());
1717
1718        let mut worst = 0.0_f64;
1719        for r in 0..6 {
1720            for g in 0..6 {
1721                for b in 0..6 {
1722                    let rgb = [
1723                        0.02 + 0.16 * f64::from(r),
1724                        0.02 + 0.16 * f64::from(g),
1725                        0.02 + 0.16 * f64::from(b),
1726                    ];
1727                    let a = live.render_pixel(rgb);
1728                    let c = baked.render_pixel(rgb);
1729                    for channel in 0..3 {
1730                        worst = worst.max((a[channel] - c[channel]).abs());
1731                    }
1732                }
1733            }
1734        }
1735        // 0.05 reflectance is about the corner error of a 33^3 table; the
1736        // mean difference is two orders of magnitude smaller.
1737        assert!(worst < 0.05, "baked path differs by {worst}");
1738    }
1739
1740    #[test]
1741    fn spectral_path_changes_colour_separation() {
1742        let scalar = RenderParams::default().prepare();
1743        let spectral = RenderParams {
1744            spectral: true,
1745            ..RenderParams::default()
1746        }
1747        .prepare();
1748
1749        let sample = [0.75, 0.12, 0.08];
1750        let a = scalar.render_pixel(sample);
1751        let b = spectral.render_pixel(sample);
1752        let difference: f64 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).sum();
1753        assert!(
1754            difference > 1e-4,
1755            "spectral path changed nothing: {difference}"
1756        );
1757    }
1758
1759    #[test]
1760    fn spectral_output_is_monotonic_and_bounded() {
1761        let prepared = RenderParams {
1762            spectral: true,
1763            ..RenderParams::default()
1764        }
1765        .prepare();
1766        let mut previous = -1.0;
1767        for i in -80..80 {
1768            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
1769            let y = prepared.render_pixel([x; 3])[1];
1770            assert!((0.0..=1.0).contains(&y));
1771            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
1772            previous = y;
1773        }
1774    }
1775
1776    #[test]
1777    fn output_is_monotonic_and_bounded() {
1778        let prepared = chain(DevelopmentParams::default());
1779        let mut previous = -1.0;
1780        for i in -80..80 {
1781            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
1782            let y = prepared.render_pixel([x; 3])[1];
1783            assert!((0.0..=1.0).contains(&y));
1784            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
1785            previous = y;
1786        }
1787    }
1788
1789    /// Grain has to be visible where the eye expects it: not in a flat black, not
1790    /// in a flat white, and unmistakably in between. Both ends are flat for a
1791    /// reason that is not written down anywhere — one characteristic curve is in
1792    /// its toe, the other in its shoulder.
1793    ///
1794    /// The peak is not at mid grey, and it should not be. Visible grain is the
1795    /// counting noise multiplied by the curve's local slope, and on a negative the
1796    /// straight line extends a couple of stops *above* mid grey, so the product
1797    /// peaks there. Measured with the measured stock, the spread runs 0.0003 at
1798    /// −8 EV, 0.0123 at 0, a peak of 0.0174 at +2, and 0.0004 by +8.
1799    #[test]
1800    fn grain_peaks_inside_the_straight_line() {
1801        const SIDE: usize = 64;
1802        let mut grain = crate::grain::GrainField::new(SIDE, SIDE, 36.0, 11);
1803        // A 6 µm pixel: a 6000-pixel scan of a 35 mm frame, where grain is real.
1804        grain.pixel_area_um2 = 36.0;
1805
1806        let spread = |ev: f64| {
1807            let prepared = RenderParams {
1808                exposure_ev: ev,
1809                ..RenderParams::default()
1810            }
1811            .prepare();
1812            let mut pixels = vec![[0.18; 3]; SIDE * SIDE];
1813            render_pixels_with_grain(&mut pixels, &prepared, &grain);
1814            let mean = pixels.iter().map(|p| p[0]).sum::<f64>() / pixels.len() as f64;
1815            (pixels.iter().map(|p| (p[0] - mean).powi(2)).sum::<f64>() / pixels.len() as f64).sqrt()
1816        };
1817
1818        let dark = spread(-8.0);
1819        let mid = spread(0.0);
1820        let peak = spread(2.0);
1821        let bright = spread(8.0);
1822        assert!(
1823            peak > 5.0 * dark && peak > 5.0 * bright,
1824            "peak {peak}  dark {dark}  bright {bright}"
1825        );
1826        assert!(
1827            peak > spread(-2.0) && peak > spread(6.0),
1828            "the peak is not in the middle: -2 {}, +2 {peak}, +6 {}",
1829            spread(-2.0),
1830            spread(6.0)
1831        );
1832        assert!(mid > 0.5 * peak, "mid {mid} against peak {peak}");
1833    }
1834
1835    #[test]
1836    fn probe() {
1837        for (name, params) in [
1838            (
1839                "spectral",
1840                RenderParams {
1841                    spectral: true,
1842                    ..RenderParams::default()
1843                },
1844            ),
1845            (
1846                "print",
1847                RenderParams {
1848                    spectral_print: true,
1849                    ..RenderParams::default()
1850                },
1851            ),
1852            (
1853                "scan",
1854                RenderParams {
1855                    spectral_print: true,
1856                    spectral_scan: true,
1857                    ..RenderParams::default()
1858                },
1859            ),
1860        ] {
1861            let prepared = params.prepare();
1862            let model = prepared.spectral_model().expect(name);
1863            println!("== {name}");
1864            if let Some(e) = &model.exposure {
1865                println!("  reconstruct = {:?}", e.reconstruct);
1866                println!("  reference   = {:?}", e.reference);
1867                println!(
1868                    "  basis max   = {:?}",
1869                    [
1870                        e.basis[0].iter().fold(f64::MIN, |a, &b| a.max(b)),
1871                        e.basis[1].iter().fold(f64::MIN, |a, &b| a.max(b)),
1872                        e.basis[2].iter().fold(f64::MIN, |a, &b| a.max(b)),
1873                    ]
1874                );
1875                println!(
1876                    "  film max    = {:?}",
1877                    [
1878                        e.film[0].iter().fold(f64::MIN, |a, &b| a.max(b)),
1879                        e.film[1].iter().fold(f64::MIN, |a, &b| a.max(b)),
1880                        e.film[2].iter().fold(f64::MIN, |a, &b| a.max(b)),
1881                    ]
1882                );
1883            }
1884            if let Some(p) = &model.enlarger {
1885                println!("  analytical  = {:?}", p.analytical);
1886                println!(
1887                    "  clamped={} reference={:?} masking={:?} ref={}",
1888                    p.clamped, p.reference, p.masking, p.masking_reference
1889                );
1890                println!(
1891                    "  paper max   = {:?}",
1892                    [0, 1, 2].map(|c| p.paper[c].iter().fold(f64::MIN, |a, &b| a.max(b)))
1893                );
1894            }
1895            if let Some(s) = &model.scan {
1896                println!(
1897                    "  scan clamped={} white_xyz={:?} white_rgb={:?}",
1898                    s.clamped, s.white_xyz, s.white_rgb
1899                );
1900                println!(
1901                    "  neutral[0]={:?} neutral[32]={:?}",
1902                    s.neutral[0], s.neutral[32]
1903                );
1904            }
1905        }
1906    }
1907}
1908
1909#[cfg(test)]
1910mod enlarger_tests {
1911    use super::*;
1912    use crate::filters::{FilterPack, HeatGlass};
1913
1914    fn print_with(pack: FilterPack, glass: Option<HeatGlass>) -> [f64; 3] {
1915        RenderParams {
1916            spectral_print: true,
1917            filters: pack,
1918            heat_glass: glass,
1919            ..RenderParams::default()
1920        }
1921        .prepare()
1922        .render_pixel([0.45, 0.28, 0.14])
1923    }
1924
1925    /// A pack has to change the print at all before any dial can be said to
1926    /// move it — the first thing the two failed attempts got wrong.
1927    ///
1928    /// Note what is *not* asserted here. The gap between two printed channels
1929    /// is not monotone in the dial: it widens to about 20 CC and then closes,
1930    /// because the print's response to a cast is not linear once the paper's
1931    /// layers start clipping. The ADR's "a measurable, monotone shift" is
1932    /// therefore a statement about the *enlarger* — `print_shift` — and that is
1933    /// the quantity the next test has to be written against, not a pixel.
1934    #[test]
1935    fn a_pack_changes_the_print() {
1936        let clear = print_with(FilterPack::none(), None);
1937        let heavy = print_with(FilterPack::new(0.0, 200.0, 0.0), None);
1938        let moved = (0..3)
1939            .map(|i| (clear[i] - heavy[i]).abs())
1940            .fold(0.0, f64::max);
1941        assert!(moved > 0.01, "200 CC of magenta moved the print by {moved}");
1942    }
1943
1944    /// One layer, one density, one dial: the statement the ADR now makes.
1945    ///
1946    /// A colour head is three exposure factors. Dialling magenta takes green out
1947    /// of the light, so the green layer needs *more* exposure to reach the same
1948    /// density — monotonic, because it is one integral against one spectrum and
1949    /// not a ratio of two that both contain the filter. The gap between two
1950    /// printed channels is not monotone and this test deliberately does not ask
1951    /// it to be; see the roadmap's amendment.
1952    #[test]
1953    fn magenta_moves_the_green_exposure_one_way() {
1954        let green_exposure = |cc: f64| {
1955            let prepared = RenderParams {
1956                spectral_print: true,
1957                filters: FilterPack::new(0.0, cc, 0.0),
1958                ..RenderParams::default()
1959            }
1960            .prepare();
1961            // The light the green layer needs, in log units: the print's shift
1962            // is `target - exposure`, so more shift is less light.
1963            prepared.print_shift()[1]
1964        };
1965        // From 5 CC, not 0: an empty pack returns the context untouched — equal
1966        // energy, no lamp — so the first step would measure the lamp arriving
1967        // rather than the filter closing.
1968        let mut previous: Option<f64> = None;
1969        for step in 1..=12 {
1970            let cc = 5.0 * f64::from(step);
1971            let shift = green_exposure(cc);
1972            if let Some(before) = previous {
1973                assert!(
1974                    shift > before + 1e-9,
1975                    "at {cc} CC the green layer's exposure went {before} -> {shift}"
1976                );
1977            }
1978            previous = Some(shift);
1979        }
1980        // And a step is a step: 5 CC is about 0.05 of density of green, which in
1981        // the head's log units is a small but real move.
1982        let step = green_exposure(10.0) - green_exposure(5.0);
1983        assert!(
1984            (0.005..0.08).contains(&step),
1985            "5 CC moved the green exposure by {step}"
1986        );
1987    }
1988}