Skip to main content

kallo_core/
emulsion.rs

1//! Built-in film and paper stocks.
2//!
3//! Every film in `data/films/` and every paper in `data/papers/` is here, one
4//! entry each, generated at build time from the `.kalofilm` and `.kalopaper`
5//! files the renderer can also read one at a time. A stock is not a summary of
6//! its sheet: it carries what the fields below say it carries, and it carries
7//! what the sheet admitted to in [`FilmStock::measured`] — one line per field,
8//! saying whether that field was measured, borrowed from another stock, or left
9//! as a compiled placeholder. A product whose whole claim is that the numbers
10//! mean something has to be able to say where each one came from.
11//!
12//! ## A stock carries its own spectra
13//!
14//! A film stock is not only a curve. It is also which wavelengths each layer
15//! records ([`FilmStock::layers`]), what the negative absorbs at print time
16//! ([`FilmStock::dyes`]) and the mask between the two ([`FilmStock::mask`]).
17//! Those three are what make two films with the same contrast look like
18//! different products, and they ride on the stock so that choosing a film
19//! changes the colour and not only the density.
20//!
21//! Not every sheet prints three dyes, so some stocks borrow the measured VISION3
22//! spectra — and [`FilmStock::measured`] says so, which is the honest version of
23//! a borrow: the number is real, it is simply not this film's.
24//!
25//! The ids name the real product. A stock called `portra400` that is not Portra
26//! 400 would be a lie, and the whole point of this project is that the numbers
27//! mean something.
28//!
29//! ## What `d_min` means, and why it is zero for film
30//!
31//! A colour negative's minimum density is **not part of its characteristic
32//! curve**. It is base, fog and — the part that matters — the orange mask: a
33//! coloured coupler that absorbs blue and is consumed where cyan dye forms. It
34//! is spectrally structured, so the model carries it as a spectrum
35//! ([`FilmStock::mask`]), not as a scalar under the curve.
36//!
37//! The curve therefore describes how much *dye* has formed, which is zero where
38//! nothing was exposed. [`FilmStock::base_density`] is the same minimum density
39//! expressed the way the non-spectral print needs it: one status density per
40//! layer. The two are not independent numbers — the mask's density at the status
41//! filter peaks is this base, and a test checks it.
42//!
43//! Paper is the exception and keeps its `d_min`: unexposed paper has a density
44//! of its own, it has no mask, and there is no second place to put it.
45
46use crate::curve::CharacteristicCurve;
47use crate::spectral::GRID_LEN;
48
49/// Which chemistry the stock is, and therefore which stages the render runs.
50///
51/// A negative is developed, printed onto paper and scanned; a reversal is
52/// developed to a positive and scanned directly, with no print between; a silver
53/// image has one curve and one sensitivity, no dye and no mask. The stock
54/// declares which one it is, and the pipeline follows.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum FilmProcess {
57    /// Colour negative: developed, printed onto paper, scanned.
58    Negative,
59    /// Colour reversal: the film is the picture, and there is no print stage.
60    Reversal,
61    /// Silver image: one curve, one sensitivity, no dye, no mask.
62    Monochrome,
63}
64/// Where a stock's numbers came from.
65///
66/// A data sheet, a printed page, a date, and the digest of the document itself.
67/// It is not decoration: a curve that cannot name its sheet is a curve someone
68/// drew, and the difference is the whole product.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct Provenance {
71    /// The publication, as the manufacturer numbers it: `E-4050`, `AF3-865E`.
72    pub publication: &'static str,
73    /// The printed page the numbers were read on, as the sheet numbers it.
74    pub page: &'static str,
75    /// The date the sheet was read, ISO 8601.
76    pub retrieved: &'static str,
77    /// The digest of the document, `sha256:...`.
78    pub checksum: &'static str,
79}
80
81impl Provenance {
82    /// A stock with no sheet behind it: a test, or a file that did not say.
83    pub const UNKNOWN: Self = Self {
84        publication: "",
85        page: "",
86        retrieved: "",
87        checksum: "",
88    };
89}
90
91/// A film stock: one characteristic curve per colour layer.
92#[derive(Debug, Clone, Copy)]
93
94pub struct FilmStock {
95    /// Stable identifier used on the command line.
96    pub id: &'static str,
97    /// The name a box or a wall label would use, without the catalogue numbers:
98    /// `PORTRA 400`, not `KODAK PROFESSIONAL PORTRA 400, C-41`.
99    pub short: &'static str,
100    /// The chemistry, and therefore which stages the render runs.
101    pub process: FilmProcess,
102    /// A second emulsion feeding the cyan dye, if the film has one.
103    ///
104    /// ADR 0017: a dye may be formed by more than one emulsion, and the
105    /// four-layer negatives are the reason. `None` — every stock before those —
106    /// is exactly the three-layer model.
107    ///
108    /// `Some` is not a scalar rendering: it forces the spectral path, because a
109    /// fourth layer is a fourth integral, and it makes the GPU decline rather
110    /// than replay three layers of a four-layer film.
111    pub extra_cyan: Option<crate::dye::Emulsion>,
112    /// A cyan-sensitive layer that releases inhibitor instead of dye, if the
113    /// film has one — ADR 0018.
114    ///
115    /// It is not a dye: it forms no density, and its effect on the measured
116    /// curve is folded into that curve. Only a frame with structure in it can
117    /// show the layer at all, which is why nothing happens unless a render asks
118    /// for [`crate::interimage::InterImage`].
119    pub cl_layer: Option<crate::dye::InhibitorLayer>,
120    /// Human-readable name.
121    pub label: &'static str,
122    /// What this stock is, and what it is not.
123    pub note: &'static str,
124    /// Red, green and blue layer curves, in dye formed: `d_min` is the fog above
125    /// the base, and zero at a normal development.
126    pub channels: [CharacteristicCurve; 3],
127    /// Status densities of the unexposed, processed film: base, fog and mask.
128    ///
129    /// Used by the non-spectral print, which has no spectrum to put there. The
130    /// spectral print uses the measured mask instead, and the two agree.
131    pub base_density: [f64; 3],
132    /// Effective developed grains per square micrometre, per layer.
133    ///
134    /// "Effective" is doing work in that sentence: a developed image's noise is
135    /// dominated by clumping, so the number is far below a count of silver
136    /// halide grains. It is whatever reproduces the manufacturer's granularity
137    /// curve, and [`crate::GrainField::for_stock`] is where it goes.
138    pub grains_per_um2: [f64; 3],
139    /// The layer sensitivities on one relative scale, 380–730 nm at 5 nm.
140    ///
141    /// Which wavelengths reach each layer, and how fast each layer is. This is
142    /// the film's *record* of colour: two stocks with the same curves but
143    /// different layers separate a scene differently.
144    pub layers: &'static [[f64; GRID_LEN]; 3],
145    /// The cyan, magenta and yellow dyes, peak-normalised absorption.
146    ///
147    /// The film's *return* of colour: what the negative passes at print time.
148    /// The published curves have D-min subtracted, so the mask is separate.
149    pub dyes: &'static [[f64; GRID_LEN]; 3],
150    /// Spectral density of base, fog and the orange mask, 380–730 nm at 5 nm.
151    pub mask: &'static [f64; GRID_LEN],
152    /// The emulsion's blur, measured from the stock's own MTF, per layer.
153    ///
154    /// `None` means the sheet did not publish a modulation-transfer curve and
155    /// the render falls back to the compiled VISION3 fit — a borrow, and the
156    /// stock's `note` says so.
157    pub sigma_um: Option<[f64; 3]>,
158    /// The development the characteristic curve was measured at, in minutes.
159    ///
160    /// Every sheet draws its curves at a stated development, and the model's
161    /// default is not it: DELTA 400's curve is 8 minutes at 24 °C, most C-41
162    /// sheets are 3¼ at 38 °C, and the model's own default is 6.5 at 20 °C.
163    /// Rendering a stock at a development it was not measured at is a contrast
164    /// factor the user did not ask for, so the reference rides on the stock and
165    /// `--dev` is what moves away from it.
166    pub reference_time_min: f64,
167    /// The temperature the curve was measured at, in °C.
168    pub reference_temp_c: f64,
169    /// The sheet this film was read from.
170    pub provenance: Provenance,
171    /// One line per field: what was measured, what was borrowed, what is a
172    /// placeholder, and what is absent.
173    ///
174    /// The order is the model's — the curve first, the grain last — rather than
175    /// the file's, because a person reading a film's record wants the film's
176    /// shape before its texture. Every sentence begins with its own verdict:
177    /// `measured: ...`, `borrowed: ...`, `placeholder: ...`, `none`.
178    pub measured: &'static [(&'static str, &'static str)],
179}
180
181/// What a paper carries.
182///
183/// A colour paper has three dye-forming layers and records colour; a silver
184/// paper has one silver image, no dyes, and records luminance. It is the
185/// paper's own fact, not a rendering preference: a colour film printed on a
186/// silver paper is a black-and-white print, and a paper that cannot say which
187/// it is cannot be printed honestly.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum PaperEmulsion {
190    /// Three dye-forming layers, RA-4: the print carries colour.
191    Colour,
192    /// One silver image, no dyes: the print carries luminance.
193    Silver,
194}
195
196/// A paper stock: one curve, because paper only has to record what is on the
197/// negative, not sample a scene.
198#[derive(Debug, Clone, Copy)]
199pub struct PaperStock {
200    /// Stable identifier used on the command line.
201    pub id: &'static str,
202    /// The name a box or a wall label would use, without the catalogue numbers.
203    pub short: &'static str,
204    /// What the paper carries: three dye-forming layers, or one silver image.
205    pub emulsion: PaperEmulsion,
206    /// Human-readable name.
207    pub label: &'static str,
208    /// What this paper is, and what it is not.
209    pub note: &'static str,
210    /// The paper's characteristic curve.
211    pub channel: CharacteristicCurve,
212    /// Linear reflectance a correctly balanced print should reach for an
213    /// 18 % grey card. This is what the print balance is solved against.
214    pub target_mid_reflectance: f64,
215    /// The paper's cyan, magenta and yellow dyes, peak-normalised absorption,
216    /// 380–730 nm at 5 nm. What the spectral scan puts between the light and
217    /// the eye.
218    pub dyes: &'static [[f64; GRID_LEN]; 3],
219    /// The paper's three layer sensitivities on one relative scale, 380–730 nm
220    /// at 5 nm. What the spectral print integrates the enlarger's light against.
221    pub layers: &'static [[f64; GRID_LEN]; 3],
222    /// The sheet this paper was read from.
223    pub provenance: Provenance,
224    /// One line per field, as a film's: measured, borrowed, placeholder or none.
225    pub measured: &'static [(&'static str, &'static str)],
226}
227
228const fn curve(d_min: f64, d_max: f64, gamma: f64, log_e0: f64) -> CharacteristicCurve {
229    CharacteristicCurve::new(d_min, d_max, gamma, log_e0)
230}
231
232// The film stocks are generated from the `.kalofilm` files at build time: the
233// data is CC BY-SA 4.0 and this program text is MIT or Apache-2.0, and `build.rs` is
234// where the two meet. Nothing in this file is a digitised number.
235include!(concat!(env!("OUT_DIR"), "/film_stocks.rs"));
236
237// The paper stocks are generated from the `.kalopaper` files the same way the
238// films are; see `build.rs`.
239
240/// Look up a film stock by id.
241#[must_use]
242pub fn film_stock(id: &str) -> Option<&'static FilmStock> {
243    FILM_STOCKS.iter().find(|stock| stock.id == id)
244}
245
246/// Look up a paper stock by id.
247#[must_use]
248pub fn paper_stock(id: &str) -> Option<&'static PaperStock> {
249    PAPER_STOCKS.iter().find(|stock| stock.id == id)
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use crate::grain::GrainField;
256
257    /// The second film is not the first one with another curve.
258    ///
259    /// Its layer sensitivities were digitised from its own data sheet, and its
260    /// curves turn their corners at rates of their own. A stock that borrowed
261    /// the first film's tables would render the same colour with a different
262    /// contrast, which is the thing this field exists to prevent.
263    #[test]
264    fn the_second_film_has_its_own_layers() {
265        let fuji = film_stock("fuji_nph400").expect("built-in stock");
266        let kodak = film_stock("vision3_500t").expect("built-in stock");
267        assert_ne!(
268            (
269                fuji.channels[0].toe_transition,
270                fuji.channels[0].shoulder_transition
271            ),
272            (
273                kodak.channels[0].toe_transition,
274                kodak.channels[0].shoulder_transition
275            ),
276            "the two films fit the same corner rates"
277        );
278        let peak = |table: &[f64; GRID_LEN]| table.iter().copied().fold(0.0_f64, f64::max);
279        let ratios: [f64; 3] =
280            std::array::from_fn(|layer| peak(&fuji.layers[layer]) / peak(&kodak.layers[layer]));
281        assert!(
282            ratios.iter().any(|ratio| (ratio - 1.0).abs() > 0.05),
283            "the two films share their layer tables: {ratios:?}"
284        );
285    }
286
287    /// What a stock says about a field matches what it carries.
288    ///
289    /// The catalogue's value is that its claims are checkable, so they are
290    /// checked. A stock that said `none` about its mask while shipping another
291    /// film's — which seven of them did until this test existed — is worse than
292    /// one that said nothing at all, because a reader believes it.
293    ///
294    /// The claims are read the way `kalo stocks --json` reads them: the word
295    /// before the first colon.
296    #[test]
297    fn the_claims_match_the_tables() {
298        fn claim<'a>(stock: &'a FilmStock, field: &str) -> &'a str {
299            stock
300                .measured
301                .iter()
302                .find(|(name, _)| *name == field)
303                .map(|(_, text)| text.split(':').next().unwrap_or("").trim())
304                .unwrap_or_else(|| panic!("{} says nothing about its {field}", stock.id))
305        }
306
307        let reference_mask: &[f64] = FILM_MASK.as_slice();
308        let reference_dyes: &[[f64; GRID_LEN]] = FILM_DYES.as_slice();
309        for stock in FILM_STOCKS {
310            for field in ["curves", "layers", "dyes", "mask", "mtf", "grain"] {
311                let verdict = claim(stock, field);
312                assert!(
313                    matches!(verdict, "measured" | "borrowed" | "placeholder" | "none"),
314                    "{}'s {field} begins with {verdict:?}",
315                    stock.id
316                );
317            }
318
319            let masks = stock.mask.as_slice();
320            let mask_empty = masks.iter().all(|value| *value == 0.0);
321            match claim(stock, "mask") {
322                "none" => assert!(
323                    mask_empty,
324                    "{} says it has no mask and carries one",
325                    stock.id
326                ),
327                "borrowed" => assert!(
328                    masks == reference_mask,
329                    "{} says its mask is borrowed and it is not the reference",
330                    stock.id
331                ),
332                _ => assert!(
333                    !mask_empty,
334                    "{} says its mask is measured and has none",
335                    stock.id
336                ),
337            }
338
339            let dyes = stock.dyes.as_slice();
340            let dyes_empty = dyes.iter().flatten().all(|value| *value == 0.0);
341            match claim(stock, "dyes") {
342                "none" => assert!(
343                    dyes_empty,
344                    "{} says it has no dyes and carries some",
345                    stock.id
346                ),
347                "borrowed" => assert!(
348                    dyes == reference_dyes,
349                    "{} says its dyes are borrowed and they are not the reference",
350                    stock.id
351                ),
352                _ => assert!(
353                    !dyes_empty,
354                    "{} says its dyes are measured and has none",
355                    stock.id
356                ),
357            }
358
359            // The render blurs every stock: a stock whose sheet published no MTF
360            // runs on the compiled VISION3 fit, so `none` is a claim the model
361            // contradicts — the honest word for a sheet without an MTF is
362            // `borrowed`, and the note has to say what is borrowed.
363            match claim(stock, "mtf") {
364                "measured" => assert!(
365                    stock.sigma_um.is_some(),
366                    "{} says its blur is measured and carries none",
367                    stock.id
368                ),
369                "borrowed" => assert!(
370                    stock.sigma_um.is_none(),
371                    "{} says its blur is borrowed and carries its own",
372                    stock.id
373                ),
374                other => panic!(
375                    "{} claims {other:?} for its blur; a stock without an MTF \
376                     borrows the measured VISION3 blur and has to say so",
377                    stock.id
378                ),
379            }
380        }
381    }
382
383    /// Every film carries three dyes, three layer sensitivities and a mask, on
384    /// the grid the model integrates over, and none of them is negative.
385    ///
386    /// This is the check that catches a table pasted in at the wrong length or
387    /// with a minus dropped: a stock with a truncated spectrum still renders,
388    /// and it renders the wrong colour in a way nothing else would notice.
389    #[test]
390    fn every_film_carries_its_own_three_spectra() {
391        for stock in FILM_STOCKS {
392            // A silver film has no dyes; its record is the grain, and a table of
393            // zeros is what "no dye absorption" looks like.
394            if stock.process == FilmProcess::Monochrome {
395                continue;
396            }
397            for (channel, table) in stock.dyes.iter().enumerate() {
398                let peak = table.iter().copied().fold(0.0_f64, f64::max);
399                assert!(
400                    (peak - 1.0).abs() < 0.02,
401                    "{} dye {channel} peaks at {peak:.3}, not at 1",
402                    stock.id
403                );
404                assert!(
405                    table.iter().all(|value| *value >= 0.0),
406                    "{} dye {channel} has a negative density",
407                    stock.id
408                );
409            }
410            assert!(
411                stock.mask.iter().all(|value| *value >= 0.0),
412                "{} has a negative mask density",
413                stock.id
414            );
415            for (channel, table) in stock.layers.iter().enumerate() {
416                let peak = table.iter().copied().fold(0.0_f64, f64::max);
417                assert!(
418                    peak > 0.0,
419                    "{} layer {channel} is dark everywhere",
420                    stock.id
421                );
422                assert!(
423                    table.iter().all(|value| *value >= 0.0),
424                    "{} layer {channel} has a negative sensitivity",
425                    stock.id
426                );
427            }
428        }
429    }
430
431    /// Each colour layer records where its own sheet says it does.
432    ///
433    /// The failure this catches is a panel read the wrong way round. The three
434    /// curves are labelled by the dye they form — Cyan-, Magenta- and
435    /// Yellow-Forming — and an extractor that assigns them by position instead
436    /// of by label can put the cyan layer's peak in the blue, produce three
437    /// smooth plausible tables, and never fail anything else. GOLD 200's sheet
438    /// draws four strokes for three layers, so the risk is not hypothetical.
439    #[test]
440    fn every_colour_layer_peaks_in_its_own_band() {
441        for stock in FILM_STOCKS {
442            if stock.process == FilmProcess::Monochrome {
443                continue;
444            }
445            for (layer, low, high) in [(0, 590.0, 700.0), (1, 490.0, 600.0), (2, 380.0, 500.0)] {
446                let (index, value) = stock.layers[layer].iter().enumerate().fold(
447                    (0, f64::NEG_INFINITY),
448                    |best, (i, &v)| {
449                        if v > best.1 { (i, v) } else { best }
450                    },
451                );
452                let wavelength = 380.0 + 5.0 * index as f64;
453                assert!(
454                    (low..=high).contains(&wavelength),
455                    "{} layer {layer} peaks at {wavelength} nm, outside {low}-{high}",
456                    stock.id
457                );
458                assert!(
459                    value > 0.0,
460                    "{} layer {layer} is dark at its peak",
461                    stock.id
462                );
463            }
464        }
465    }
466
467    /// The measured stock's status base and the mask the spectral print adds are
468    /// one measurement written two ways. If they ever drift apart, one of the two
469    /// prints is wrong and the difference is a colour cast in the shadows.
470    #[test]
471    fn the_measured_stock_carries_the_mask_as_its_base() {
472        let stock = film_stock("vision3_500t").expect("the measured stock");
473        let mask = crate::measured::spectrum(&crate::measured::FILM_MASK);
474        for (channel, wavelength) in [650.0, 550.0, 450.0].iter().enumerate() {
475            let at = mask.interpolate(*wavelength);
476            assert!(
477                (stock.base_density[channel] - at).abs() < 0.06,
478                "layer {channel}: base {:.4} against mask {at:.4}",
479                stock.base_density[channel]
480            );
481        }
482    }
483
484    /// The granularity chart gives a *density* fluctuation; the model works in
485    /// log exposure, and the curve's slope connects them. This is the round trip
486    /// through the whole derivation: at a density of 1 through a 48 µm aperture,
487    /// rms granularity has to land where the data sheet put it.
488    #[test]
489    fn the_measured_grain_reproduces_the_granularity_chart() {
490        let stock = film_stock("vision3_500t").expect("the measured stock");
491        let mut field = GrainField::for_stock(1, 1, 36.0, 0, stock);
492        field.pixel_area_um2 = 48.0 * 48.0;
493        // The chart's values at D = 1, in layer order R, G, B.
494        for (layer, published) in [0.0060, 0.0077, 0.0197].into_iter().enumerate() {
495            let sigma_d = stock.channels[layer].gamma * field.sigma(1.0, layer);
496            assert!(
497                (sigma_d - published).abs() < 0.2 * published,
498                "layer {layer}: {sigma_d:.4} against the chart's {published:.4}"
499            );
500        }
501    }
502
503    /// A film curve is dye, and dye is zero where nothing was exposed. The base
504    /// lives on the stock so that a spectral print can put the measured mask
505    /// there instead of a scalar.
506    #[test]
507    fn film_curves_start_at_zero_density() {
508        for stock in FILM_STOCKS {
509            // A reversal is the exception, and not a small one: its unexposed
510            // film is its densest state, so the curve starts at about 3.4 and
511            // falls to clear. A negative's curve is dye above base and starts at
512            // zero; a reversal's is the picture and starts at its maximum.
513            let reversal = stock.process == FilmProcess::Reversal;
514            for (layer, channel) in stock.channels.iter().enumerate() {
515                if reversal {
516                    assert!(
517                        channel.d_min > channel.d_max,
518                        "{} layer {layer}: reversal curve rises, d_min {} d_max {}",
519                        stock.id,
520                        channel.d_min,
521                        channel.d_max
522                    );
523                } else {
524                    assert!(
525                        channel.d_min.abs() < 1e-9,
526                        "{} layer {layer}: d_min {}",
527                        stock.id,
528                        channel.d_min
529                    );
530                }
531            }
532        }
533    }
534
535    /// Paper keeps its `d_min`, unlike film: unexposed paper has a density of
536    /// its own and no mask to carry it. That `d_min` is the paper's white, and
537    /// the three measured stocks have three different ones — 0.19 for the
538    /// metallic sheet, 0.10 for the two E-4021 papers. The default is one of
539    /// the latter, because a model whose prints cannot reflect more than 62 %
540    /// is modelling a specialty, not a print.
541    #[test]
542    fn the_measured_papers_carry_their_white_as_the_toe() {
543        let measured = [
544            ("portra_endura", 0.0964, 7.0),
545            ("supra_endura", 0.1010, 8.0),
546            ("endura_premier_metallic", 0.1944, 10.0),
547        ];
548        for (id, toe, transition) in measured {
549            let paper = paper_stock(id).unwrap_or_else(|| panic!("{id} is not a stock"));
550            assert!(
551                (paper.channel.d_min - toe).abs() < 1e-9,
552                "{id}: d_min {} is not the measured toe {toe}",
553                paper.channel.d_min
554            );
555            assert!(
556                (paper.channel.toe_transition - transition).abs() < 1e-9,
557                "{id}: transition {}, not the {transition} its sheet fitted",
558                paper.channel.toe_transition
559            );
560        }
561
562        // The default paper is a print: its white is around 80 % reflectance,
563        // where the metallic stock's is around 62 %.
564        let default = paper_stock("portra_endura").expect("the default paper");
565        let white = 10.0_f64.powf(-default.channel.d_min);
566        assert!(
567            (0.7..0.9).contains(&white),
568            "the default paper's white came out at {white}"
569        );
570        assert!(
571            10.0_f64.powf(
572                -paper_stock("endura_premier_metallic")
573                    .unwrap()
574                    .channel
575                    .d_min
576            ) < 0.7,
577            "the metallic paper is not greyer than a print"
578        );
579    }
580
581    /// The paper's spectra belong to the stock, not to the model: E-4021 draws
582    /// one set for PORTRA and SUPRA ENDURA, the metallic sheet another, and the
583    /// E-4021 paper is the default. If a stock were pointed at the wrong tables
584    /// nothing would fail except a spectral render's colour — which is exactly
585    /// the failure mode this project exists to make loud.
586    #[test]
587    fn the_measured_papers_carry_their_own_spectra() {
588        let peak = |table: &[f64; crate::spectral::GRID_LEN]| {
589            let (index, value) =
590                table
591                    .iter()
592                    .enumerate()
593                    .fold((0, f64::NEG_INFINITY), |best, (i, &v)| {
594                        if v > best.1 { (i, v) } else { best }
595                    });
596            (380.0 + 5.0 * index as f64, value)
597        };
598
599        let portra = paper_stock("portra_endura").expect("the default paper");
600        // The dye peaks the sheet draws: yellow 445, magenta 550, cyan 630 nm.
601        for (layer, expected) in [(2, 445.0), (1, 550.0), (0, 630.0)] {
602            let (wavelength, value) = peak(&portra.dyes[layer]);
603            assert!(
604                (wavelength - expected).abs() < 15.0,
605                "layer {layer} peaks at {wavelength} nm, not {expected}"
606            );
607            assert!((value - 1.0).abs() < 0.02, "layer {layer} peaks at {value}");
608        }
609        // The layer sensitivities: yellow-forming at 475, magenta at 550, cyan
610        // at 705, and they are on one scale, so their peaks differ by two orders.
611        let yellow = peak(&portra.layers[2]).1;
612        let cyan = peak(&portra.layers[0]).1;
613        assert!(
614            yellow > 20.0 * cyan,
615            "the layer speeds came out {yellow:.2} and {cyan:.2}"
616        );
617
618        // And the metallic stock is a different paper, with different tables.
619        let metallic = paper_stock("endura_premier_metallic").expect("the metallic paper");
620        assert!(
621            !std::ptr::eq(portra.dyes, metallic.dyes),
622            "the two papers share one dye set"
623        );
624        assert!((peak(&metallic.dyes[0]).0 - peak(&portra.dyes[0]).0).abs() > 5.0);
625    }
626
627    #[test]
628    fn ids_are_unique() {
629        let mut ids: Vec<&str> = FILM_STOCKS.iter().map(|s| s.id).collect();
630        ids.sort_unstable();
631        let count = ids.len();
632        ids.dedup();
633        assert_eq!(ids.len(), count);
634
635        let mut ids: Vec<&str> = PAPER_STOCKS.iter().map(|s| s.id).collect();
636        ids.sort_unstable();
637        let count = ids.len();
638        ids.dedup();
639        assert_eq!(ids.len(), count);
640    }
641
642    #[test]
643    fn lookups_work() {
644        assert!(film_stock("kodak_ultramax400").is_some());
645        assert!(paper_stock("fuji_crystal_archive_pearl").is_some());
646        assert!(film_stock("nope").is_none());
647    }
648
649    /// ADR 0017 is wired, and this is what keeps its blast radius visible: no
650    /// stock in the tree declares a second cyan emulsion yet, so every stock
651    /// renders through the three-layer path exactly as it did before.
652    #[test]
653    fn no_stock_has_a_second_cyan_emulsion_yet() {
654        for stock in FILM_STOCKS {
655            assert!(stock.extra_cyan.is_none(), "{} declares one", stock.id);
656        }
657    }
658}