Skip to main content

kallo_core/
contact.rs

1//! The contact proof: the film laid on paper, exposed once.
2//!
3//! A print is made frame by frame, and each frame gets its own exposure — that
4//! is what the enlarger's test strip is for. A **contact proof** is the other
5//! arrangement: the negative lies flat on the paper, the whole sheet is exposed
6//! once, and no frame is corrected. What the paper then says is not what the
7//! frames could look like, but what the film actually carries, relative to the
8//! rest of the roll.
9//!
10//! That difference is the whole value of a proof, and it is also why this module
11//! cannot be built out of `render`: a render solves one exposure per picture,
12//! and a proof must not solve any.
13//!
14//! Two consequences are modelled here rather than drawn:
15//!
16//! * The **rebate** is clear film, so it prints black; the sprocket holes are
17//!   holes, so they print black as well. A negative's contact proof therefore
18//!   has a black band along each frame, and the edge markings are the light
19//!   marks on it. (The classic "black border with white sprocket holes" is a
20//!   *positive* film: on a slide the unexposed rebate becomes black dye and the
21//!   holes are the only thing light gets through.)
22//! * **One exposure.** The sheet is printed on the middle frame's balance: a
23//!   laboratory's average printer, not a per-frame correction. The frames that
24//!   were developed longer than that print denser, and the ones developed less
25//!   print thinner, which is the comparison the sheet exists for.
26//!
27//! The layout is one strip per development, not one strip carrying every
28//! development: five development times are five pieces of film, and a sheet
29//! that showed them as one continuous strip would be claiming an order the
30//! film never had.
31
32use crate::development::DevelopmentParams;
33use crate::emulsion::{FilmProcess, FilmStock, PaperStock};
34use crate::pipeline::{Finishing, RenderParams};
35
36/// The image area of one 35 mm frame, across the film.
37pub const FRAME_W_MM: f64 = 36.0;
38/// The image area of one 35 mm frame, along the film.
39pub const FRAME_H_MM: f64 = 24.0;
40/// The clear film on each side of a 35 mm frame: 35 mm of film, 24 mm of image.
41pub const REBATE_MM: f64 = 5.5;
42/// The film left beyond the frame where the strip was cut.
43pub const CUT_MM: f64 = 2.0;
44/// Paper between two strips on the sheet.
45pub const GAP_MM: f64 = 6.0;
46/// Paper around the strips.
47pub const MARGIN_MM: f64 = 12.0;
48/// How the sheet's strips are put in rows.
49pub const COLUMNS: usize = 3;
50
51/// The development ladder a proof is made for when nobody names one: the same
52/// three-to-fifteen minutes the interface's roll carries.
53pub const LADDER_MINUTES: [f64; 5] = [3.0, 6.0, 9.0, 12.0, 15.0];
54
55/// One frame on the sheet, in pixels.
56#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct FrameRect {
58    /// Which frame on the roll, counting from one.
59    pub number: usize,
60    /// How long this frame was developed, in minutes. Filled in by
61    /// [`print()`].
62    pub minutes: f64,
63    /// Left edge of the image area.
64    pub x: usize,
65    /// Top edge of the image area.
66    pub y: usize,
67    /// Width of the image area.
68    pub width: usize,
69    /// Height of the image area.
70    pub height: usize,
71}
72
73/// Which way the strips lie on the paper.
74///
75/// A 35 mm frame is 24 mm across the film and 36 mm along it, so a strip is a
76/// long rectangle with its perforations on the long edges — and a photograph
77/// made with the camera on its side lies sideways on it. The sheet is paper,
78/// and strips can be laid either way: a proof of a vertical frame lays them
79/// down so the pictures stand up, which is how a photographer lays out a proof
80/// sheet, because the point of one is to look at the pictures.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Strips {
83    /// The film's own way: the frame is 36 mm along the strip.
84    Horizontal,
85    /// The strip turned a quarter turn: the frame is 36 mm down the strip and
86    /// the edge markings run down the sheet.
87    Vertical,
88}
89
90/// The sheet's physical arrangement, resolved to pixels.
91///
92/// Kept separate from the render so that a caller can size the frame before
93/// asking for it — the photo has to be cropped and sampled at exactly this
94/// width, because a sheet scaled afterwards would be a lie about grain and
95/// about the size of the film.
96#[derive(Debug, Clone, PartialEq)]
97pub struct SheetGeometry {
98    /// Output resolution, in dots per inch.
99    pub dpi: f64,
100    /// Sheet width in pixels.
101    pub width: usize,
102    /// Sheet height in pixels.
103    pub height: usize,
104    /// Paper margin around the strips, in pixels.
105    pub margin: usize,
106    /// The frame's pixel size, which is the size a frame is developed at.
107    pub frame: (usize, usize),
108    /// Which way the strips lie.
109    pub strips: Strips,
110    /// One rect per development, in the order they were given.
111    pub frames: Vec<FrameRect>,
112}
113
114impl SheetGeometry {
115    /// Lay `count` single-frame strips on a sheet at `dpi`.
116    ///
117    /// # Panics
118    ///
119    /// Cannot panic: `count` is clamped to at least one, and the dpi is clamped
120    /// to a sane positive range.
121    #[must_use]
122    pub fn new(count: usize, dpi: f64, strips: Strips) -> Self {
123        let count = count.max(1);
124        let dpi = if dpi.is_finite() && dpi > 0.0 {
125            dpi.clamp(72.0, 2400.0)
126        } else {
127            600.0
128        };
129        let per_mm = dpi / 25.4;
130        let px = |mm: f64| (mm * per_mm).round() as usize;
131
132        // The frame as the film carries it: 36 mm along the strip and 24 mm
133        // across it, whichever way the strip is laid on the paper.
134        let (long, short) = (px(FRAME_W_MM), px(FRAME_H_MM));
135        let frame = match strips {
136            Strips::Horizontal => (long, short),
137            Strips::Vertical => (short, long),
138        };
139        let cut = px(CUT_MM);
140        let rebate = px(REBATE_MM);
141        let gap = px(GAP_MM);
142        let margin = px(MARGIN_MM);
143        // The strip: the frame, the cut ends at the ends of the strip, and the
144        // clear film along its sides.
145        let strip = match strips {
146            Strips::Horizontal => (frame.0 + cut * 2, frame.1 + rebate * 2),
147            Strips::Vertical => (frame.0 + rebate * 2, frame.1 + cut * 2),
148        };
149        let (across, along) = match strips {
150            Strips::Horizontal => (cut, rebate),
151            Strips::Vertical => (rebate, cut),
152        };
153
154        let columns = COLUMNS.min(count);
155        let rows = count.div_ceil(columns);
156        let width = margin * 2 + columns * strip.0 + gap * columns.saturating_sub(1);
157        let height = margin * 2 + rows * strip.1 + gap * rows.saturating_sub(1);
158
159        let mut frames = Vec::with_capacity(count);
160        for index in 0..count {
161            let column = index % columns;
162            let row = index / columns;
163            frames.push(FrameRect {
164                number: index + 1,
165                minutes: 0.0,
166                x: margin + column * (strip.0 + gap) + across,
167                y: margin + row * (strip.1 + gap) + along,
168                width: frame.0,
169                height: frame.1,
170            });
171        }
172
173        Self {
174            dpi,
175            width,
176            height,
177            margin,
178            frame,
179            strips,
180            frames,
181        }
182    }
183
184    /// The strip a frame sits in: the image plus its rebate and cut edges.
185    #[must_use]
186    pub fn strip_of(&self, frame: &FrameRect) -> (usize, usize, usize, usize) {
187        let per_mm = self.dpi / 25.4;
188        let cut = (CUT_MM * per_mm).round() as usize;
189        let rebate = (REBATE_MM * per_mm).round() as usize;
190        // Across the strip is the cut end when the strip lies along it, and the
191        // rebate when it does not.
192        let (across, along) = match self.strips {
193            Strips::Horizontal => (cut, rebate),
194            Strips::Vertical => (rebate, cut),
195        };
196        (
197            frame.x - across,
198            frame.y - along,
199            frame.width + across * 2,
200            frame.height + along * 2,
201        )
202    }
203}
204
205/// Everything the proof is printed with.
206pub struct ContactSpec {
207    /// The negative.
208    pub film: &'static FilmStock,
209    /// The paper it lies on.
210    pub paper: &'static PaperStock,
211    /// One development per strip, in the order the strips are laid.
212    pub developments: Vec<DevelopmentParams>,
213    /// The exposure the frame was given, in stops.
214    pub exposure_ev: f64,
215    /// Enlarger exposure on top of the solved balance, in stops.
216    pub print_ev: f64,
217    /// Expose and print through the spectral model.
218    pub spectral: bool,
219    /// The film's own blur.
220    pub emulsion: bool,
221    /// Grain.
222    pub grain: bool,
223    /// Halation.
224    pub halation: bool,
225    /// DIR couplers.
226    pub couplers: bool,
227    /// Print the edge markings: the stock, the frame number, the development.
228    pub edge_codes: bool,
229}
230
231/// A printed contact proof.
232#[derive(Debug, Clone)]
233pub struct Contact {
234    /// Where everything is.
235    pub geometry: SheetGeometry,
236    /// The print, row-major, linear light.
237    pub pixels: Vec<[f64; 3]>,
238}
239
240/// Develop one frame at every time, lay the strips on paper, and expose it once.
241///
242/// `frame` is the photograph already sampled at `geometry.frame` — the caller
243/// crops and resizes, because that is I/O and this crate has none. It is the
244/// picture the way up the photographer made it; when the strips lie vertically
245/// the picture is the same picture, and the film under it is laid down turned.
246///
247/// # Panics
248///
249/// Panics when `frame` does not hold exactly `geometry.frame.0 * geometry.frame.1`
250/// pixels, which is a caller's bug; a silent short frame would print as a hole
251/// in the sheet. It also panics if the geometry and the development list differ
252/// in length.
253#[must_use]
254pub fn print(frame: &[[f64; 3]], geometry: &SheetGeometry, spec: &ContactSpec) -> Contact {
255    let (frame_w, frame_h) = geometry.frame;
256    assert_eq!(
257        frame.len(),
258        frame_w * frame_h,
259        "the frame must be sampled at the sheet's frame size"
260    );
261    assert_eq!(
262        geometry.frames.len(),
263        spec.developments.len(),
264        "one strip per development, and one development per strip"
265    );
266    let per_mm = geometry.dpi / 25.4;
267    let px = |mm: f64| (mm * per_mm).round() as usize;
268
269    // The strip is always drawn the film's own way — 36 mm along it — and then
270    // laid on the paper. A vertical strip is that drawing turned, not a second
271    // drawing, so the picture reaches it a quarter turn the other way.
272    let (laid_w, laid_h) = (px(FRAME_W_MM), px(FRAME_H_MM));
273    let stood = (geometry.strips == Strips::Vertical)
274        .then(|| turned_pixels(frame, frame_w, frame_h, Turn::Clockwise));
275    let frame = stood.as_deref().unwrap_or(frame);
276
277    // One finishing chain, shared by every strip: the five strips are five
278    // developments of one exposure, so they carry the same grain and the same
279    // optics. A different seed per strip would say the strips were cut from
280    // different negatives, and they were not.
281    let pixel_um = FRAME_W_MM * 1000.0 / laid_w as f64;
282    let emulsion = spec
283        .emulsion
284        .then(|| crate::mtf::EmulsionBlur::for_stock(spec.film, pixel_um));
285    let halation = spec
286        .halation
287        .then(|| crate::halation::Halation::typical(pixel_um));
288    let couplers = spec
289        .couplers
290        .then(|| crate::couplers::Couplers::typical(pixel_um));
291    let grain = spec
292        .grain
293        .then(|| crate::grain::GrainField::for_stock(laid_w, laid_h, FRAME_W_MM, 0, spec.film));
294    let finishing = Finishing {
295        emulsion: emulsion.as_ref(),
296        halation: halation.as_ref(),
297        grain: grain.as_ref(),
298        couplers: couplers.as_ref(),
299        interimage: None,
300    };
301    let bare = Finishing {
302        emulsion: None,
303        halation: None,
304        grain: None,
305        couplers: None,
306        interimage: None,
307    };
308
309    // Develop every strip. `PreparedRender` freezes one development's curves,
310    // so the ladder is a vector of them rather than one reused render.
311    let mut prepared = Vec::with_capacity(spec.developments.len());
312    let mut negatives = Vec::with_capacity(spec.developments.len());
313    for development in &spec.developments {
314        let params = RenderParams {
315            film: spec.film,
316            paper: spec.paper,
317            development: *development,
318            exposure_ev: spec.exposure_ev,
319            spectral: spec.spectral,
320            camera: crate::spectral::CameraProfile::default(),
321            lut_size: 0,
322            spectral_print: spec.spectral,
323            spectral_scan: false,
324            interimage: false,
325            print_exposure_ev: spec.print_ev,
326            filters: crate::filters::FilterPack::none(),
327            heat_glass: None,
328        };
329        let render = params.prepare();
330        negatives.push(render.develop(frame, laid_w, laid_h, &finishing));
331        prepared.push(render);
332    }
333
334    // The sheet's one exposure: the middle development's balance. A roll has an
335    // average, and the average is what a laboratory printer prints it at.
336    let printer = &prepared[prepared.len() / 2];
337    let paper_white = printer.positive([12.0; 3]);
338    let mut pixels = vec![paper_white; geometry.width * geometry.height];
339
340    // One strip on its own paper, drawn the film's way: the frame is 36 mm
341    // along it and the markings sit in the clear film above and below.
342    let cut = px(CUT_MM);
343    let clear = px(REBATE_MM);
344    let strip_size = (laid_w + cut * 2, laid_h + clear * 2);
345    let mut strip_rect = FrameRect {
346        number: 0,
347        minutes: 0.0,
348        x: cut,
349        y: clear,
350        width: laid_w,
351        height: laid_h,
352    };
353    let strip_geometry = SheetGeometry {
354        dpi: geometry.dpi,
355        width: strip_size.0,
356        height: strip_size.1,
357        margin: 0,
358        frame: (laid_w, laid_h),
359        strips: Strips::Horizontal,
360        frames: vec![strip_rect],
361    };
362
363    let mut geometry = geometry.clone();
364    for index in 0..geometry.frames.len() {
365        let mut rect = geometry.frames[index];
366        rect.minutes = spec.developments[index].time_min;
367        geometry.frames[index] = rect;
368        // The strip is drawn on its own canvas, so the edge code is stamped
369        // with this canvas's rect — but the code has to name the development
370        // this strip came from, not the canvas's placeholder.
371        strip_rect.number = rect.number;
372        strip_rect.minutes = rect.minutes;
373
374        // The unexposed rebate: base, fog and mask, developed for this strip's
375        // time. Fog grows with development, so each strip has its own.
376        let rebate = prepared[index].develop(&[[0.0; 3]], 1, 1, &bare).densities[0];
377        let mut strip = vec![printer.positive(rebate); strip_size.0 * strip_size.1];
378        // Perforations are holes in the film, so they print as light: they
379        // are drawn before the markings, which sit between them and the frame.
380        punch_holes(&mut strip, &strip_geometry, &strip_rect, printer, per_mm);
381        if spec.edge_codes {
382            stamp_strip(
383                &mut strip,
384                &strip_geometry,
385                &strip_rect,
386                spec,
387                printer,
388                rebate,
389            );
390        }
391        // The frame itself: the strip's printed image, laid over its rebate.
392        blit(
393            &mut strip,
394            strip_size.0,
395            &printer.print(&negatives[index]),
396            laid_w,
397            laid_h,
398            cut,
399            clear,
400        );
401
402        let (sx, sy, _, _) = geometry.strip_of(&rect);
403        match geometry.strips {
404            Strips::Horizontal => blit(
405                &mut pixels,
406                geometry.width,
407                &strip,
408                strip_size.0,
409                strip_size.1,
410                sx,
411                sy,
412            ),
413            Strips::Vertical => {
414                // The paper's strips lie down the sheet; the strip itself is
415                // the same print, turned.
416                let stood = turned_pixels(&strip, strip_size.0, strip_size.1, Turn::Anticlockwise);
417                blit(
418                    &mut pixels,
419                    geometry.width,
420                    &stood,
421                    strip_size.1,
422                    strip_size.0,
423                    sx,
424                    sy,
425                );
426            }
427        }
428    }
429
430    Contact { geometry, pixels }
431}
432
433/// Which way a quarter turn goes.
434#[derive(Debug, Clone, Copy)]
435enum Turn {
436    /// The picture's top edge goes to its left edge.
437    Anticlockwise,
438    /// The picture's top edge goes to its right edge.
439    Clockwise,
440}
441
442/// Turn a picture a quarter turn, without resampling a pixel.
443fn turned_pixels(pixels: &[[f64; 3]], width: usize, height: usize, turn: Turn) -> Vec<[f64; 3]> {
444    let mut out = vec![[0.0; 3]; pixels.len()];
445    // The turned picture is `height` wide and `width` tall.
446    for y in 0..width {
447        for x in 0..height {
448            out[y * height + x] = match turn {
449                Turn::Anticlockwise => pixels[x * width + (width - 1 - y)],
450                Turn::Clockwise => pixels[(height - 1 - x) * width + y],
451            };
452        }
453    }
454    out
455}
456
457/// Copy a block into the canvas at `(x, y)`.
458fn blit(
459    canvas: &mut [[f64; 3]],
460    canvas_width: usize,
461    block: &[[f64; 3]],
462    block_width: usize,
463    block_height: usize,
464    x: usize,
465    y: usize,
466) {
467    for row in 0..block_height {
468        let from = row * block_width;
469        let to = (y + row) * canvas_width + x;
470        canvas[to..to + block_width].copy_from_slice(&block[from..from + block_width]);
471    }
472}
473
474/// Sprocket holes: 1.98 mm along the film, 2.79 mm across it, on a 4.75 mm pitch.
475fn punch_holes(
476    canvas: &mut [[f64; 3]],
477    geometry: &SheetGeometry,
478    rect: &FrameRect,
479    printer: &crate::pipeline::PreparedRender,
480    per_mm: f64,
481) {
482    let hole = printer.positive([0.0; 3]);
483    let (sx, sy, sw, _) = geometry.strip_of(rect);
484    let width = (1.98 * per_mm).round() as usize;
485    let height = (2.79 * per_mm).round() as usize;
486    let pitch = (4.75 * per_mm).round() as usize;
487    let rebate = (REBATE_MM * per_mm).round() as usize;
488    let cut = (CUT_MM * per_mm).round() as usize;
489    let radius = (0.4 * per_mm).round().max(1.0) as usize;
490    let top = sy + (rebate - height) / 2;
491    let bottom = rect.y + rect.height + (rebate - height) / 2;
492    let mut x = sx + cut;
493    while x + width <= sx + sw {
494        rounded(
495            canvas,
496            geometry.width,
497            (x, top, width, height),
498            radius,
499            hole,
500        );
501        rounded(
502            canvas,
503            geometry.width,
504            (x, bottom, width, height),
505            radius,
506            hole,
507        );
508        x += pitch;
509    }
510}
511
512/// A rectangle with rounded corners, filled row by row.
513fn rounded(
514    canvas: &mut [[f64; 3]],
515    width: usize,
516    rect: (usize, usize, usize, usize),
517    radius: usize,
518    colour: [f64; 3],
519) {
520    let (x, y, w, h) = rect;
521    for row in 0..h {
522        let inset = if row < radius {
523            let dy = radius - row;
524            radius - ((radius * radius - dy * dy) as f64).sqrt() as usize
525        } else if row >= h.saturating_sub(radius) {
526            let dy = radius - (h - 1 - row);
527            radius - ((radius * radius - dy * dy) as f64).sqrt() as usize
528        } else {
529            0
530        };
531        if inset * 2 >= w {
532            continue;
533        }
534        let start = (y + row) * width + x + inset;
535        canvas[start..start + w - inset * 2].fill(colour);
536    }
537}
538
539/// The edge markings of one strip: the stock on the top rebate, the frame and
540/// the development on the bottom one.
541fn stamp_strip(
542    canvas: &mut [[f64; 3]],
543    geometry: &SheetGeometry,
544    rect: &FrameRect,
545    spec: &ContactSpec,
546    printer: &crate::pipeline::PreparedRender,
547    rebate: [f64; 3],
548) {
549    let per_mm = geometry.dpi / 25.4;
550    // 1.2 mm of text, in the 1.35 mm between the perforations and the frame:
551    // that is where a real edge code sits, and for the same reason.
552    let scale = ((1.2 * per_mm) / 7.0).round().max(1.0) as usize;
553    let gap = (0.06 * per_mm).round() as usize;
554    let text = printer.positive(std::array::from_fn(|channel| rebate[channel] + 1.2));
555    let (sx, _, sw, _) = geometry.strip_of(rect);
556    let height = 7 * scale;
557    let top = rect.y - height - gap;
558    let bottom = rect.y + rect.height + gap;
559
560    let mut line = String::from("KALLO ");
561    line.push_str(spec.film.short);
562    let fitted = fit(&line, sw.saturating_sub(scale * 2), scale);
563    stamp(
564        canvas,
565        geometry.width,
566        sx + scale,
567        top,
568        scale,
569        &fitted,
570        text,
571    );
572
573    let lower = format!("{:02}  {:.1} MIN", rect.number, rect.minutes);
574    stamp(
575        canvas,
576        geometry.width,
577        sx + scale,
578        bottom,
579        scale,
580        &lower,
581        text,
582    );
583}
584
585/// Keep the start of `text` that fits in `width` pixels.
586fn fit(text: &str, width: usize, scale: usize) -> String {
587    let advance = 6 * scale;
588    let room = width / advance.max(1);
589    text.chars().take(room).collect()
590}
591
592/// Draw one line of 5×7 text, cell `scale` pixels square.
593fn stamp(
594    canvas: &mut [[f64; 3]],
595    canvas_width: usize,
596    x: usize,
597    y: usize,
598    scale: usize,
599    text: &str,
600    colour: [f64; 3],
601) {
602    let advance = 6 * scale;
603    for (index, character) in text.chars().enumerate() {
604        let Some(rows) = glyph(character) else {
605            continue;
606        };
607        let origin = x + index * advance;
608        for (row, bits) in rows.iter().enumerate() {
609            for (column, bit) in bits.chars().enumerate() {
610                if bit != '1' {
611                    continue;
612                }
613                for dy in 0..scale {
614                    let line = (y + row * scale + dy) * canvas_width + origin + column * scale;
615                    canvas[line..line + scale].fill(colour);
616                }
617            }
618        }
619    }
620}
621
622/// A 5×7 bitmap font: what a strip's edge is legible enough for.
623///
624/// It is a drawing, not a typeface: the model has no fonts and does not want
625/// one. The glyphs are the ones a frame number and a stock name need.
626fn glyph(character: char) -> Option<[&'static str; 7]> {
627    let glyphs: &[(char, [&str; 7])] = &[
628        (
629            'A',
630            [
631                "01110", "10001", "10001", "11111", "10001", "10001", "10001",
632            ],
633        ),
634        (
635            'B',
636            [
637                "11110", "10001", "10001", "11110", "10001", "10001", "11110",
638            ],
639        ),
640        (
641            'C',
642            [
643                "01110", "10001", "10000", "10000", "10000", "10001", "01110",
644            ],
645        ),
646        (
647            'D',
648            [
649                "11110", "10001", "10001", "10001", "10001", "10001", "11110",
650            ],
651        ),
652        (
653            'E',
654            [
655                "11111", "10000", "10000", "11110", "10000", "10000", "11111",
656            ],
657        ),
658        (
659            'F',
660            [
661                "11111", "10000", "10000", "11110", "10000", "10000", "10000",
662            ],
663        ),
664        (
665            'G',
666            [
667                "01110", "10001", "10000", "10111", "10001", "10001", "01110",
668            ],
669        ),
670        (
671            'H',
672            [
673                "10001", "10001", "10001", "11111", "10001", "10001", "10001",
674            ],
675        ),
676        (
677            'I',
678            [
679                "11111", "00100", "00100", "00100", "00100", "00100", "11111",
680            ],
681        ),
682        (
683            'J',
684            [
685                "00111", "00010", "00010", "00010", "00010", "10010", "01100",
686            ],
687        ),
688        (
689            'K',
690            [
691                "10001", "10010", "10100", "11000", "10100", "10010", "10001",
692            ],
693        ),
694        (
695            'L',
696            [
697                "10000", "10000", "10000", "10000", "10000", "10000", "11111",
698            ],
699        ),
700        (
701            'M',
702            [
703                "10001", "11011", "10101", "10101", "10001", "10001", "10001",
704            ],
705        ),
706        (
707            'N',
708            [
709                "10001", "11001", "10101", "10011", "10001", "10001", "10001",
710            ],
711        ),
712        (
713            'O',
714            [
715                "01110", "10001", "10001", "10001", "10001", "10001", "01110",
716            ],
717        ),
718        (
719            'P',
720            [
721                "11110", "10001", "10001", "11110", "10000", "10000", "10000",
722            ],
723        ),
724        (
725            'Q',
726            [
727                "01110", "10001", "10001", "10001", "10101", "10010", "01101",
728            ],
729        ),
730        (
731            'R',
732            [
733                "11110", "10001", "10001", "11110", "10100", "10010", "10001",
734            ],
735        ),
736        (
737            'S',
738            [
739                "01111", "10000", "10000", "01110", "00001", "00001", "11110",
740            ],
741        ),
742        (
743            'T',
744            [
745                "11111", "00100", "00100", "00100", "00100", "00100", "00100",
746            ],
747        ),
748        (
749            'U',
750            [
751                "10001", "10001", "10001", "10001", "10001", "10001", "01110",
752            ],
753        ),
754        (
755            'V',
756            [
757                "10001", "10001", "10001", "10001", "10001", "01010", "00100",
758            ],
759        ),
760        (
761            'W',
762            [
763                "10001", "10001", "10001", "10101", "10101", "10101", "01010",
764            ],
765        ),
766        (
767            'X',
768            [
769                "10001", "10001", "01010", "00100", "01010", "10001", "10001",
770            ],
771        ),
772        (
773            'Y',
774            [
775                "10001", "10001", "01010", "00100", "00100", "00100", "00100",
776            ],
777        ),
778        (
779            'Z',
780            [
781                "11111", "00001", "00010", "00100", "01000", "10000", "11111",
782            ],
783        ),
784        (
785            '0',
786            [
787                "01110", "10001", "10011", "10101", "11001", "10001", "01110",
788            ],
789        ),
790        (
791            '1',
792            [
793                "00100", "01100", "00100", "00100", "00100", "00100", "01110",
794            ],
795        ),
796        (
797            '2',
798            [
799                "01110", "10001", "00001", "00010", "00100", "01000", "11111",
800            ],
801        ),
802        (
803            '3',
804            [
805                "11111", "00010", "00100", "00010", "00001", "10001", "01110",
806            ],
807        ),
808        (
809            '4',
810            [
811                "00010", "00110", "01010", "10010", "11111", "00010", "00010",
812            ],
813        ),
814        (
815            '5',
816            [
817                "11111", "10000", "11110", "00001", "00001", "10001", "01110",
818            ],
819        ),
820        (
821            '6',
822            [
823                "00110", "01000", "10000", "11110", "10001", "10001", "01110",
824            ],
825        ),
826        (
827            '7',
828            [
829                "11111", "00001", "00010", "00100", "01000", "01000", "01000",
830            ],
831        ),
832        (
833            '8',
834            [
835                "01110", "10001", "10001", "01110", "10001", "10001", "01110",
836            ],
837        ),
838        (
839            '9',
840            [
841                "01110", "10001", "10001", "01111", "00001", "00010", "01100",
842            ],
843        ),
844        (
845            '-',
846            [
847                "00000", "00000", "00000", "11111", "00000", "00000", "00000",
848            ],
849        ),
850        (
851            '.',
852            [
853                "00000", "00000", "00000", "00000", "00000", "01100", "01100",
854            ],
855        ),
856        (
857            ' ',
858            [
859                "00000", "00000", "00000", "00000", "00000", "00000", "00000",
860            ],
861        ),
862    ];
863    glyphs
864        .iter()
865        .find(|(candidate, _)| *candidate == character)
866        .map(|(_, rows)| *rows)
867}
868
869/// Whether a stock can be contact printed at all.
870///
871/// A reversal is its own picture: there is no paper between the film and the
872/// eye, so there is nothing for a contact proof to be. The caller turns this
873/// into the error a person reads; the model just says what it knows.
874#[must_use]
875pub fn printable(film: &FilmStock) -> bool {
876    film.process != FilmProcess::Reversal
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882    use crate::emulsion::{film_stock, paper_stock};
883
884    fn frame(width: usize, height: usize) -> Vec<[f64; 3]> {
885        let mut pixels = Vec::with_capacity(width * height);
886        for row in 0..height {
887            for column in 0..width {
888                // A horizontal ramp with a bright square, so the print has
889                // something with structure in it.
890                let ramp = column as f64 / width as f64;
891                let square = (row > height / 3 && row < height / 2)
892                    && (column > width / 3 && column < width / 2);
893                let value = if square { 0.85 } else { 0.02 + 0.6 * ramp };
894                pixels.push([value, value * 0.9, value * 0.8]);
895            }
896        }
897        pixels
898    }
899
900    fn spec(times: &[f64]) -> (ContactSpec, SheetGeometry, Vec<[f64; 3]>) {
901        let film = film_stock("kodak_portra_400").expect("film");
902        let paper = paper_stock("portra_endura").expect("paper");
903        let geometry = SheetGeometry::new(times.len(), 300.0, Strips::Horizontal);
904        let pixels = frame(geometry.frame.0, geometry.frame.1);
905        let developments = times
906            .iter()
907            .map(|minutes| DevelopmentParams {
908                time_min: *minutes,
909                temp_c: 20.0,
910                reference_time_min: film.reference_time_min,
911                reference_temp_c: film.reference_temp_c,
912                ..DevelopmentParams::default()
913            })
914            .collect();
915        (
916            ContactSpec {
917                film,
918                paper,
919                developments,
920                exposure_ev: 0.0,
921                print_ev: 0.0,
922                spectral: false,
923                emulsion: true,
924                grain: false,
925                halation: false,
926                couplers: false,
927                edge_codes: true,
928            },
929            geometry,
930            pixels,
931        )
932    }
933
934    #[test]
935    fn the_sheet_is_five_strips_on_one_row_of_paper() {
936        let geometry = SheetGeometry::new(5, 300.0, Strips::Horizontal);
937        let per_mm: f64 = 300.0 / 25.4;
938        let px = |mm: f64| (mm * per_mm).round() as usize;
939        let strip_w = px(FRAME_W_MM) + px(CUT_MM) * 2;
940        let strip_h = px(FRAME_H_MM) + px(REBATE_MM) * 2;
941        let gap = px(GAP_MM);
942        let margin = px(MARGIN_MM);
943        assert_eq!(geometry.width, margin * 2 + strip_w * 3 + gap * 2);
944        assert_eq!(geometry.height, margin * 2 + strip_h * 2 + gap);
945        assert_eq!(geometry.frames.len(), 5);
946        assert_eq!(geometry.frames[0].x, margin + px(CUT_MM));
947        assert_eq!(geometry.frames[3].y, margin + strip_h + gap + px(REBATE_MM));
948    }
949
950    /// A vertical sheet turns every strip, and keeps the ladder's order.
951    ///
952    /// The strips are the film's own: 36 mm along and 24 across, so standing
953    /// them up swaps those, and the rows still read left to right and top to
954    /// bottom. A sheet that ran the ladder up a column instead would be a
955    /// picture of a proof, not a proof.
956    #[test]
957    fn a_vertical_sheet_stands_its_strips_up() {
958        let laid = SheetGeometry::new(5, 300.0, Strips::Horizontal);
959        let stood = SheetGeometry::new(5, 300.0, Strips::Vertical);
960        assert_eq!((stood.frame.0, stood.frame.1), (laid.frame.1, laid.frame.0));
961        let (_, _, strip_w, strip_h) = stood.strip_of(&stood.frames[0]);
962        assert!(
963            strip_h > strip_w,
964            "a vertical strip stands up: {strip_w} wide, {strip_h} tall"
965        );
966        for frame in &stood.frames {
967            assert!(frame.height > frame.width, "the frame stands up too");
968        }
969        // Three strips in the first row, left to right; the fourth starts the
970        // next one.
971        assert!(stood.frames[0].x < stood.frames[1].x);
972        assert_eq!(stood.frames[0].y, stood.frames[1].y);
973        assert!(stood.frames[3].y > stood.frames[0].y);
974    }
975
976    /// A picture that is bright at the top prints bright at the top of a
977    /// vertical frame.
978    ///
979    /// The frame is laid on the strip a quarter turn one way and the sheet is
980    /// turned back the other, and the test is that the two turns cancel: with
981    /// both going the same way the photograph would print upside down.
982    #[test]
983    fn a_vertical_frame_prints_the_way_up() {
984        let film = film_stock("kodak_portra_400").expect("film");
985        let paper = paper_stock("portra_endura").expect("paper");
986        let geometry = SheetGeometry::new(1, 300.0, Strips::Vertical);
987        let (width, height) = geometry.frame;
988        let mut frame_pixels = vec![[0.02; 3]; width * height];
989        for row in 0..height / 4 {
990            for x in 0..width {
991                frame_pixels[row * width + x] = [0.9; 3];
992            }
993        }
994        let spec = ContactSpec {
995            film,
996            paper,
997            developments: vec![DevelopmentParams {
998                time_min: 9.0,
999                temp_c: 20.0,
1000                reference_time_min: film.reference_time_min,
1001                reference_temp_c: film.reference_temp_c,
1002                ..DevelopmentParams::default()
1003            }],
1004            exposure_ev: 0.0,
1005            print_ev: 0.0,
1006            spectral: false,
1007            emulsion: false,
1008            grain: false,
1009            halation: false,
1010            couplers: false,
1011            edge_codes: false,
1012        };
1013        let contact = print(&frame_pixels, &geometry, &spec);
1014        let frame = contact.geometry.frames[0];
1015        let mean = |from: usize, to: usize| {
1016            let mut sum = 0.0;
1017            for row in from..to {
1018                for x in frame.x..frame.x + frame.width {
1019                    let pixel = contact.pixels[row * contact.geometry.width + x];
1020                    sum += (pixel[0] + pixel[1] + pixel[2]) / 3.0;
1021                }
1022            }
1023            sum / (frame.width * (to - from)) as f64
1024        };
1025        let top = mean(frame.y, frame.y + frame.height / 4);
1026        let bottom = mean(
1027            frame.y + frame.height - frame.height / 4,
1028            frame.y + frame.height,
1029        );
1030        assert!(
1031            top > bottom,
1032            "the bright band must print at the top of the frame: {top} against {bottom}"
1033        );
1034    }
1035
1036    #[test]
1037    fn the_margin_is_paper_and_the_rebate_is_not() {
1038        let (spec, geometry, pixels) = spec(&[3.0, 6.0, 9.0, 12.0, 15.0]);
1039        let contact = print(&pixels, &geometry, &spec);
1040        let mean = |colour: [f64; 3]| (colour[0] + colour[1] + colour[2]) / 3.0;
1041        let corner = contact.pixels[0];
1042        let (sx, sy, _, _) = contact.geometry.strip_of(&contact.geometry.frames[0]);
1043        let rebate = contact.pixels[sy * contact.geometry.width + sx];
1044        assert!(
1045            mean(corner) > 0.8,
1046            "the paper margin prints as paper, got {corner:?}"
1047        );
1048        assert!(
1049            mean(rebate) < mean(corner) * 0.6,
1050            "the clear rebate prints dark, got {rebate:?} against {corner:?}"
1051        );
1052    }
1053
1054    #[test]
1055    fn the_frames_differ_along_the_ladder() {
1056        let (spec, geometry, pixels) = spec(&[3.0, 6.0, 9.0, 12.0, 15.0]);
1057        let contact = print(&pixels, &geometry, &spec);
1058        let mean = |frame: &FrameRect| {
1059            let mut sum = 0.0;
1060            for row in frame.y..frame.y + frame.height {
1061                for x in frame.x..frame.x + frame.width {
1062                    let pixel = contact.pixels[row * contact.geometry.width + x];
1063                    sum += (pixel[0] + pixel[1] + pixel[2]) / 3.0;
1064                }
1065            }
1066            sum / (frame.width * frame.height) as f64
1067        };
1068        let first = mean(&contact.geometry.frames[0]);
1069        let last = mean(&contact.geometry.frames[4]);
1070        assert!(
1071            (first - last).abs() > 0.02,
1072            "five developments of one exposure must not print alike: {first} vs {last}"
1073        );
1074    }
1075
1076    #[test]
1077    fn a_reversal_is_not_printable() {
1078        let film = film_stock("provia_100f").expect("film");
1079        assert!(!printable(film));
1080    }
1081
1082    #[test]
1083    fn the_glyphs_cover_what_an_edge_needs() {
1084        for character in "KALLO PORTRA 400 3.0 MIN-".chars() {
1085            assert!(glyph(character).is_some(), "no glyph for {character:?}");
1086        }
1087    }
1088}