Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-develop

Source of release 0.1.0

0.1.0 / src / film.lucb

## Film: a color negative stock exposed to the scene, developed, and scanned back
## to scene light, the way a 1990s show went from camera negative to tape. It
## works on the negative, at the scene's own size, before the develop: the
## develop then grades the filmed scene as a colorist graded the transfer, and
## the view stays the only tone scale. Physically based, from each stock's
## published curves (film_stocks.lucb, modelled by film_model.lucb):
##
## 1. Exposure (`expose`, film_exposure.lucb). The light, back in the camera's
##    own values (a raw's channels, or XYZ for other pictures), becomes each
##    layer's exposure through a conversion fitted on real surfaces under the
##    light on set, from the camera's spectral sensitivities to the layers'
##    (luce_color's camera module: measured, or estimated from the raw's color
##    matrices). Each layer's exposure is relative to its exposure to the light
##    the stock is balanced for (3200 K for tungsten stocks), so with the
##    filter Matched a neutral exposes all three alike. Middle grey (0.18) lands
##    on the stock's normal exposure (the 18% grey card Kodak marks on the
##    curves), moved by Film Exposure.
## 2. Light in the emulsion (film_passes.lucb). Each layer's exposure scatters
##    (an exponential fitted to the stock's MTF); halation adds light that
##    passed through and came back off the base (film_halation.lucb: a ring
##    from total internal reflection, its strength the backing's), mostly to
##    the red layer.
## 3. Development (`neutral`, `scan`). Each layer's characteristic curve (Status
##    M density over log exposure) is unmixed into the amount of its dye.
##    Development releases inhibitor (DIR couplers) that diffuses and holds back
##    development nearby: in the layer itself, which develops edges harder
##    (the MTF's rise above 100%), and in its neighbours, which saturates colors
##    and shifts hues the way the stock does (interimage, an estimate: Kodak
##    publishes none). The curves are corrected so a neutral still develops to
##    the datasheet's densities. Beyond what Kodak plots, a toe settles 0.015
##    under the first reading and a shoulder rolls off from 8 stops over grey:
##    estimates.
## 4. Grain. In dye amount, per layer, at the stock's rms granularity for that
##    exposure (48 µm aperture), scaled to the area a pixel covers on the
##    negative (Format's frame width over the scene's width).
## 5. Scan. The developed dyes' spectral density over D-min, read by a
##    densitometer with Status M's band centres (Gaussian bands: the standard's
##    tables are not public; unmixing and scanning use the same bands, so
##    neutrals round-trip), the orange mask subtracted. Each channel's density
##    is inverted through its gamma at grey back to linear light, the floor of
##    the clear negative taken out by Black, then a 3×3 matrix, fitted per
##    on a reference negative (Vision3 250D) to colors of moderate saturation,
##    turns the scan's primaries back toward AP1 (or one fitted to the stock
##    itself, with Calibration Matched), and the telecine timing (Warmth, Tint,
##    Contrast) applies.
##    With the bleach bypassed, the silver left beside the dye adds a neutral
##    density in proportion to the image (`silver`), which the scan, set for a
##    bleached negative, reads as more exposure and less color.
##
## The GPU and the CPU read the same tables: one atlas texture (`Film.texels`,
## half floats), sampled the same way by shaders/film_stages.glsl and the functions
## here. Rows:
##
##   0–32   scan: 33³ densities over dye amounts 0..top, slice b (yellow) at
##          columns b·33.., red (cyan) along a slice, green (magenta) by row
##   33     neutral development: dye amounts over log H (−4.5..2.5), 1024 samples
##   34     development under inhibition: amounts over the effective log H
##   35     the grain populations' correction to the rms granularity (48 µm)
##          over log H
##   36–38  the stochastic render's grains (film_grains.lucb), a row per layer
##          over the effective log H: each population's share developed and the
##          clouds' strength (`fit_grains`)
##   39     the fitted grains' own granularity there (rms through 48 µm) in
##          each layer's dye, for pixels the stochastic render takes from
##          their distribution
##   40     values: 0–2 the matrix from AP1 back to the camera's values, by
##          rows; 3–5 the inhibition matrix; 6 grey's log H, top, the frame
##          width in 2 µm units, grain amount; 7 grey's scanned densities, on; 8 the
##          inverse gammas times contrast, Black; 9 the floors; 10 the timing
##          gains; 11–13 the scan's matrix to AP1; 14 each layer's scatter
##          (exponential length, µm); 15 halation's strength per layer, its
##          ring's radius (µm);
##          16 each layer's inhibitor spread (µm); 17 each layer's most dye,
##          the stock's kind; 18 grain clouds' spacing (µm), 1/(2σ²), and their
##          calibration's a and b; 19 the grain's spread per unit of strength;
##          20 the retained silver's density per unit of dye density, the
##          scan's mean density at the fog, the edge effects' strength (log H
##          per unit of exhaustion) and width (µm); 21 flashing, a share of
##          grey's exposure added evenly, and the duplicates' blur (σ, µm);
##          22–34 the exposure's weights, a term per texel, its layers' weights
##          in r, g, b (film_exposure.lucb), as half floats; 35–47 what each
##          misses, so the two together hold it to about 22 bits (the weights
##          partly cancel, and grey must land exactly); 48–50 reciprocity
##          failure's q, p, t0 for the red, green and blue layers; 51 the
##          exposure time (s); 52–54 the development's kinetics; 55 its steps
##          and the share of a step's used developer left a step later; 64–319 the
##          halation's samples, offsets in µm; 320–328 the grain populations,
##          per layer three: where half develop (log H), how gradually, and
##          their strength; 329–337 the stochastic render's grains, per layer
##          three populations: grains per µm², their clouds' peak density and
##          radius (µm); 338 each layer's dye under its clouds (the floor), and
##          how many layers have grains (1 for black and white); 340–387 a
##          cloud's light taken over its peak density (film_grains.lucb's
##          `light_taken`, on its log grid); 390–421 how a pixel averages the
##          clouds (`pixel_covariance`: variance, side, diagonal), on its grid
import interop
import densitometry
import memory
from luce_std.collections import Buffer
import time
from luce_std import math
from luce_color import spectral
from luce_color import camera
from luce_color import temperature
from luce_color import xyz
import film_stocks
import film_develop
import film_paper
from film_develop import Development
import film_model
from film_model import Model, build_model, invert3, log_h_at, lut_size, curve_samples, log_low, log_high
import film_exposure
import film_halation
import film_grains
from film_exposure import Input
from settings import Settings, View, defaults
from parameters import Parameter
import recipe

# mark: Layout ================================================================

pub let atlas_width: usize = 1089
pub let atlas_rows: usize = 41
pub let neutral_row: usize = 33
pub let developed_row: usize = 34
pub let grain_row: usize = 35
pub let grains_row: usize = 36
pub let granularity_row: usize = 39
pub let values_row: usize = 40

## The negative's frame width in µm by the Format setting: 35 mm Academy (the
## 4:3 television frame), Super 35, 16 mm, 65 mm (5-perf, Super Panavision 70),
## Super 16 and IMAX's 15-perf 65 mm (camera aperture 70.41 × 51.61 mm, SMPTE 2005).
pub let frame_widths: f64[6] = [21950.0, 24890.0, 10260.0, 52480.0, 12520.0, 70410.0]

## The scanner's samples across the frame by Scan's Resolution: an HD telecine
## (a Spirit DataCine's 1920), a standard-definition one (720 across the 4:3
## picture), and film scanners at 2K, 4K and 6K. A scan reads the film through
## its own sampling aperture, one pitch wide: the film is filmed at that many
## samples, never finer, so grain and detail are what the scan resolves however
## far the viewer zooms (a camera file is often far finer: a 60 MP frame
## samples Academy's 21.95 mm every 3 µm, where single dye clouds would show).
pub let scan_widths: usize[5] = [1920, 720, 2048, 4096, 6144]

## How many samples across the frame the film is read at for `settings` (the
## compiled ones): its scan's, or 0 where nothing scans it (printed straight from
## the negative, or a slide on a lightbox), so the film is sampled at the photo's
## pixels.
pub func scan_samples(settings: const Settings*) -> usize:
    if not settings.recipe.has((i64)recipe.Stage.scan):
        return 0
    return scan_widths[(usize)math.clamp(settings.get(.scan_resolution), 0.0, 4.0)]

## Interimage at 100%: how much each layer's development is held back, in log
## exposure, per unit of dye its neighbours form (rows red, green, blue
## receiving; columns cyan, magenta, yellow formed). Kodak publishes none; an
## estimate of the strength ECN-2 stocks show. The diagonal, a layer holding
## itself back, comes from the stock's MTF (film_model.lucb).
let interimage: f64[9] = [0.0, 0.18, 0.08, 0.15, 0.0, 0.15, 0.06, 0.18, 0.0]


## Filters on the camera, by the Filter stage's Balance: Matched (the light
## balanced to the stock, as a white balance does), None, a Wratten 85, which
## warms daylight (5500 K) to about tungsten's 3200 K and takes 2/3 of a stop,
## the lighter warming 81A and 81EF (Kodak's mired shifts, +18 and +52, 1/3 and
## 2/3 of a stop), and a Tiffen ½ Coral, which Saving Private Ryan used in place
## of the 85 (Tiffen publishes no figure: an estimate, about an 81C). Their shift
## in mireds and the stops they take.
let filter_mireds: f64[6] = [0.0, 0.0, 112.0, 18.0, 52.0, 35.0]
let filter_stops: f64[6] = [0.0, 0.0, 0.667, 0.333, 0.667, 0.333]

## Color filters on the lens, by the Color Filter setting, the black-and-white
## photographer's: none, Yellow (Wratten 8), Orange (21), Red (25), Green (11)
## and Blue (47); and the cinematographer's brown Chocolate 1, 2 and 3 (The
## Godfather's Sicily). Their transmission at `nm`, modelled on Kodak's published
## Wratten curves (smooth edges at their cut-on wavelengths; estimates): yellow
## darkens a blue sky a little, orange more, red to near black and lightens skin;
## green darkens skin and reds; blue the opposite of yellow. Exposure is opened up
## by each filter's factor, so a grey stays where it was.
func transmission(filter: usize, nm: f64) -> f64:
    if filter >= 6:
        # Chocolate 1, 2, 3: Lee 156's density, a fifth, a third and a half of it.
        let share: f64[3] = [0.2, 0.35, 0.5]
        return math.pow(chocolate(nm), share[filter - 6])
    return match filter:
        1 => pass_above(nm, 480.0, 9.0)
        2 => pass_above(nm, 548.0, 9.0)
        3 => pass_above(nm, 596.0, 8.0)
        4 => 0.04 + 0.75 * math.exp(-0.5 * ((nm - 530.0) / 45.0) * ((nm - 530.0) / 45.0)) + 0.25 * pass_above(nm, 660.0, 12.0)
        5 => 0.02 + 0.6 * math.exp(-0.5 * ((nm - 445.0) / 32.0) * ((nm - 445.0) / 32.0))
        _ => 1.0

## Chocolate: no camera filter maker publishes its curve, so the brown is Lee
## Filters' 156 Chocolate lighting gel's (published every 5 nm, 405–700 nm),
## held at its ends; a camera's grades are a share of its density (estimates).
let chocolate_gel: f64[60] = [0.3029, 0.2924, 0.2696, 0.2389, 0.2144, 0.1925, 0.1680, 0.1443, 0.1265, 0.1132, 0.1003, 0.0891, 0.0809, 0.0776, 0.0785, 0.0826, 0.0876, 0.0921, 0.0970, 0.1049, 0.1197, 0.1429, 0.1716, 0.2015, 0.2317, 0.2602, 0.2772, 0.2768, 0.2558, 0.2226, 0.1889, 0.1642, 0.1563, 0.1674, 0.1964, 0.2385, 0.2809, 0.3165, 0.3383, 0.3442, 0.3394, 0.3281, 0.3136, 0.2997, 0.2924, 0.2974, 0.3159, 0.3448, 0.3755, 0.3978, 0.3964, 0.3645, 0.3216, 0.2991, 0.2968, 0.3217, 0.3823, 0.4677, 0.5580, 0.6367]

func chocolate(nm: f64) -> f64:
    let place = math.clamp((nm - 405.0) / 5.0, 0.0, 59.0)
    let below = (usize)math.min(math.floor(place), 58.0)
    let t = place - (f64)below
    return chocolate_gel[below] * (1.0 - t) + chocolate_gel[below + 1] * t

## A long-pass edge: 2% below `edge`, 92% above, over about `width` nm.
func pass_above(nm: f64, edge: f64, width: f64) -> f64:
    return 0.02 + 0.9 / (1.0 + math.exp(-(nm - edge) / width))

## Whether the film sees the light on set: film on, with a Filter (not Matched).
## the White Balance's Temperature and Tint are then that light, not a correction,
## and the scene comes to the film as the camera saw it (`camera_settings`).
pub func sees_the_light(settings: const Settings*) -> bool:
    return settings.get(.film_stock) > 0.0 and settings.get(.film_filter) >= 1.0

## The settings the scene's matrix takes: as shot when the film sees the light
## on set (it, not the white balance, then decides the color), else `settings`.
pub func camera_settings(settings: const Settings*) -> Settings:
    var out = *settings
    if sees_the_light(settings):
        out.set(.temperature, 0.0)
        out.set(.tint, 0.0)
    return out

## What a color negative is printed straight onto, with no scanner and no film
## recorder on the way (a lab's or a darkroom's photochemical chain): 2383 in
## the print view, a color paper in the paper view; so the print material sees
## the negative's dyes themselves.
pub let no_printing: i64 = 0
pub let onto_print: i64 = 1
pub let onto_paper: i64 = 2
pub func printing_onto(settings: const Settings*) -> i64:
    if settings.recipe.has((i64)recipe.Stage.scan):
        return no_printing
    if settings.get(.view) == (f64)(i64)View.print:
        return onto_print
    let paper = (usize)math.clamp(settings.get(.paper_stock), 0.0, (f64)(film_stocks.paper_count - 1))
    if settings.get(.view) == (f64)(i64)View.paper and film_stocks.paper_at(paper).kind == 1:
        return onto_paper
    return no_printing

## How many stocks there are, and stock `at`'s name (0-based; the Film Stock
## setting is one more), for building a menu.
pub func stock_count() -> i64:
    return (i64)film_stocks.stock_count

pub func stock_name(at: i64) -> str:
    return film_stocks.stock_at((usize)at).name

## How `settings` print on paper (film_paper.lucb): the Paper stage's choices,
## and whether the negative is silver (a black-and-white stock).
pub func paper_settings(settings: const Settings*) -> film_paper.PaperSettings:
    let stock = (i64)settings.get(.film_stock)
    let silvered = stock < 1 or film_stocks.stock_at((usize)(stock - 1)).kind == 2
    return film_paper.chosen_by(settings.get(.paper_stock), settings.get(.paper_grade), settings.get(.paper_enlarger),
                                settings.get(.paper_exposure), settings.get(.paper_yellow), settings.get(.paper_magenta),
                                settings.get(.paper_cyan), silvered, settings.get(.paper_surface))

## The papers (film_stocks.paper_at): how many, paper `at`'s name, and whether
## it is a color paper.
pub func paper_total() -> i64:
    return (i64)film_stocks.paper_count
pub func paper_name(at: i64) -> str:
    return film_stocks.paper_at((usize)at).name
pub func paper_is_color(at: i64) -> bool:
    return film_stocks.paper_at((usize)at).kind == 1

## Stock `at`'s kind: 0 color negative, 1 slide, 2 black and white.
pub func stock_kind(at: i64) -> i64:
    return film_stocks.stock_at((usize)at).kind

## The processes (film_develop.lucb): how many, and process `at`'s name and
## normal time (minutes) and temperature (°C), which develop_time and
## develop_temperature of 0 mean.
pub func process_total() -> i64:
    return (i64)film_develop.process_count
pub func process_name(at: i64) -> str:
    return film_develop.processes[(usize)at].name
pub func process_temperature(at: i64) -> f64:
    return film_develop.processes[(usize)at].celsius

## The process stock `at` develops in for develop_process `value`, and the
## stock's normal time in process `process` (minutes).
pub func stock_process(at: i64, value: f64) -> i64:
    let stock = film_stocks.stock_at((usize)at)
    return film_develop.chosen_for(&stock, value)
pub func stock_process_time(at: i64, process: i64) -> f64:
    let stock = film_stocks.stock_at((usize)at)
    return film_develop.normal_minutes(&stock, process)

## The Process menu's items for stock `at`, "name=value|…": its standard
## process first (value 0), then the others of its family and its
## cross-process.
pub func stock_processes(at: i64) -> interop.Owned[str]!:
    let stock = film_stocks.stock_at((usize)at)
    let kind = stock.kind
    let standard = film_develop.standard_of(&stock)
    var out: Buffer
    defer out.destroy()
    try out.put_text(film_develop.processes[(usize)standard].name)
    try out.put_text(" (standard)=0")
    for index in 0..<film_develop.process_count:
        let process = film_develop.processes[index]
        let cross = film_develop.crossed(kind, (i64)index)
        if (i64)index == standard or not (process.family == kind or cross):
            continue
        try out.put_byte('|')
        try out.put_text(process.name)
        if cross:
            try out.put_text(" (cross-processed)")
        try out.put_byte('=')
        try out.put_number((i64)index + 1)
    return try interop.copy_text(out.text())

# mark: Film ==================================================================

## A stock's model and the atlas for some settings: what a renderer or an export
## holds while film is on. `prepare` keeps it up to date.
pub struct Film:
    ## The atlas, RGBA, `atlas_width` × `atlas_rows`, as the GPU gets it (half
    ## floats) and the CPU reads it (rounded to half floats).
    pub var texels: f32[]
    var model: Model
    var stock: i64
    ## Whether the model is the stock cross-processed (film_develop.lucb).
    var cross: bool
    var on: bool
    ## What the negative goes straight onto (`printing_onto`): nothing (a
    ## scanner reads it), 2383, or a color paper (`paper`, whose table is
    ## `paper_table`); the table then holds what that material sees.
    var printing: i64
    var paper: i64
    var paper_table: f64[]
    ## The granularity wanted (rms through 48 µm, over the effective log H, per
    ## layer) as the development leaves it; what the grains depend on in the
    ## settings last prepared (`grain_key`), and what `fit_grains` last made
    ## the stochastic render's grains for (0: none). Exposure, the light and
    ## the scan's timing leave them alone, so a slider there keeps them.
    var granularity: f64[]
    var grains_wanted: i64
    var grains_fitted: i64
    ## What the developed row was last solved for (`development_key`).
    var developed_key: i64

    func release_paper_table():
        if self.paper_table.length > 0:
            free(self.paper_table) in memory.heap
        var empty: f64[]
        self.paper_table = empty

    pub func release():
        self.release_paper_table()
        if self.granularity.length > 0:
            free(self.granularity) in memory.heap
        var no_granularity: f64[]
        self.granularity = no_granularity
        self.model.release()
        if self.texels.length > 0:
            free(self.texels) in memory.heap
        var empty: f32[]
        self.texels = empty
        self.stock = 0

    ## Whether film is on for the settings last prepared.
    pub func active() -> bool:
        return self.on

    ## Make the atlas match `settings`: the stock's model when the stock changed,
    ## the development, the grey, the timing and the exposure every time, for
    ## the photo `input` describes (its camera, and the light it was taken under
    ## as the camera's white balance read it, the light on set unless the White
    ## Balance says otherwise).
    pub func prepare(settings: const Settings*, input: Input = Input()) -> !:
        let choice = (i64)settings.get(.film_stock)
        if self.texels.length == 0:
            self.texels = try new f32[atlas_width * atlas_rows * 4] --- in memory.heap
            for at in 0..<self.texels.length:
                self.texels[at] = 0.0f32
            self.granularity = try new f64[curve_samples * 3] --- in memory.heap
        self.grains_wanted = 0
        if choice == 0:
            self.on = false
            self.put(values_row, 7, 0.0, 0.0, 0.0, 0.0)
            return
        let chosen = film_stocks.stock_at((usize)(choice - 1))
        let cross = film_develop.crossed(chosen.kind, film_develop.chosen_for(&chosen, settings.get(.develop_process)))
        let printing = printing_onto(settings) if chosen.kind == 0 or cross else no_printing
        let paper = (i64)settings.get(.paper_stock)
        let reprint = printing != self.printing or (printing == onto_paper and paper != self.paper)
        if paper != self.paper:
            self.release_paper_table()
        self.printing = printing
        self.paper = paper
        if choice != self.stock or cross != self.cross:
            self.release_paper_table()
            self.model.release()
            self.model = try build_model(film_develop.cross_processed(chosen) if cross else chosen)
            self.stock = choice
            self.cross = cross
            try self.fill_model()
        elif reprint:
            try self.fill_table()
        self.on = true
        self.fill_settings(settings)
        self.fill_exposure(settings, &input)
        self.grains_wanted = grain_key(choice, cross, printing, settings)

    ## The exposure (film_exposure.lucb). The light on set is the White
    ## Balance's Temperature and Tint, or the photo's as shot. What reaches the
    ## film: with the Filter Matched, the light the stock is balanced for (a
    ## conversion filter that matches any light exactly); with a Filter chosen
    ## (None, an 85, ...), the light on set through it, so a daylight scene on
    ## tungsten film goes blue unless an 85 warms it, and the filter takes the
    ## light it absorbs. A color filter on the lens passes what its curve says,
    ## and the exposure opens up by its factor, as a photographer's does.
    func fill_exposure(settings: const Settings*, input: const Input*):
        let model = &self.model
        let chosen_kelvin = settings.get(.temperature)
        let kelvin = chosen_kelvin if chosen_kelvin > 0.0 else input.shot_kelvin
        let tint = settings.get(.tint) if chosen_kelvin > 0.0 else input.shot_tint
        let scene = spectral.illuminant(math.clamp(kelvin, 1667.0, 25000.0), tint)
        var film = model.light
        if sees_the_light(settings):
            let filter = (usize)math.clamp(settings.get(.film_filter), 0.0, 5.0)
            let through = 1.0e6 / (1.0e6 / math.max(kelvin, 1000.0) + filter_mireds[filter])
            film = spectral.illuminant(math.clamp(through, 1667.0, 25000.0), tint)
            let passed = math.exp2(-filter_stops[filter])
            for at in 0..<spectral.samples:
                film.values[at] *= passed
        var lens: f64[81]
        let color_filter = (usize)math.clamp(settings.get(.film_color_filter), 0.0, 8.0)
        var unfiltered = 0.0
        var filtered = 0.0
        for at in 0..<spectral.samples:
            lens[at] = transmission(color_filter, spectral.wavelength(at))
            for layer in 0..<(usize)3:
                let through = model.light.values[at] * model.sensitivity[layer * 81 + at]
                unfiltered += through
                filtered += through * lens[at]
        let factor = unfiltered / math.max(filtered, 1.0e-12)
        # Back into the camera's values: for a raw the inverse of the scene's
        # matrix; otherwise XYZ, its white the light on set's.
        var to_camera = input.to_camera
        var response = input.response
        if not input.raw:
            response = camera.observer()
            let white = scene.xyz()
            let point = xyz.Chromaticity(white.x / (white.x + white.y + white.z), white.y / (white.x + white.y + white.z))
            to_camera = xyz.multiply(xyz.adapt(xyz.aces_white, point), xyz.rgb_to_xyz(xyz.aces_ap1)).m
        # The camera's values scaled so white under the light on set comes to
        # Y = 1 in AP1, as the scene's matrix brings it.
        let to_ap1 = xyz.invert(xyz.Matrix3(to_camera)).m
        let ap1_y = xyz.rgb_to_xyz(xyz.aces_ap1).m
        let seen = response.of(&scene)
        var y = 0.0
        for k in 0..<(usize)3:
            let ap1 = to_ap1[k * 3] * seen[0] + to_ap1[k * 3 + 1] * seen[1] + to_ap1[k * 3 + 2] * seen[2]
            y += ap1_y[3 + k] * ap1
        let fitted = film_exposure.fit(&response, 1.0 / math.max(y, 1.0e-12), &scene, &film, lens, model.sensitivity, &model.light, factor)
        for row in 0..<(usize)3:
            self.put(values_row, row, to_camera[row * 3], to_camera[row * 3 + 1], to_camera[row * 3 + 2], 0.0)
        let law = model.stock.reciprocity
        for layer in 0..<(usize)3:
            self.put(values_row, 48 + layer, law[layer * 3], law[layer * 3 + 1], law[layer * 3 + 2], 0.0)
        let chosen_seconds = settings.get(.exposure_time)
        self.put(values_row, 51, chosen_seconds if chosen_seconds > 0.0 else input.shot_seconds, 0.0, 0.0, 0.0)
        for k in 0..<film_exposure.term_count:
            var high: f64[3]
            for layer in 0..<(usize)3:
                high[layer] = (f64)(f16)fitted.weights[k * 3 + layer]
            self.put(values_row, 22 + k, high[0], high[1], high[2], 0.0)
            self.put(values_row, 35 + k, fitted.weights[k * 3] - high[0], fitted.weights[k * 3 + 1] - high[1], fitted.weights[k * 3 + 2] - high[2], 0.0)

    func put(row: usize, column: usize, r: f64, g: f64, b: f64, a: f64):
        let at = (row * atlas_width + column) * 4
        self.texels[at] = (f32)r
        self.texels[at + 1] = (f32)g
        self.texels[at + 2] = (f32)b
        self.texels[at + 3] = (f32)a

    func fill_model() -> !:
        let model = &self.model
        try self.fill_table()
        for at in 0..<curve_samples:
            self.put(neutral_row, at, model.neutral[at * 3], model.neutral[at * 3 + 1], model.neutral[at * 3 + 2], 1.0)

    ## The table over dye amounts: the scanner's densities, or what the print
    ## stock or the paper sees when the negative prints directly.
    func fill_table() -> !:
        let model = &self.model
        if self.printing == onto_paper and self.paper_table.length == 0:
            let chosen = film_stocks.paper_at((usize)math.clamp((f64)self.paper, 0.0, (f64)(film_stocks.paper_count - 1)))
            let meter = densitometry.paper_printing(chosen.sensitivity)
            self.paper_table = try film_model.printed_by(model, &meter)
        let table = model.printed if self.printing == onto_print else (self.paper_table if self.printing == onto_paper else model.scan)
        let n = lut_size
        for b in 0..<n:
            for g in 0..<n:
                for r in 0..<n:
                    let at = ((b * n + g) * n + r) * 3
                    self.put(g, b * n + r, table[at], table[at + 1], table[at + 2], 1.0)

    func fill_settings(settings: const Settings*):
        let model = &self.model
        # The development (film_develop.lucb): the curve as this time and
        # temperature leave it. The scan keeps reading the normal curve, as a lab's
        # transfer for normal negatives does, so a push shows: more density,
        # more contrast, more grain.
        let kind = model.stock.kind
        # The stock as published (a cross-processed slide's model is a negative).
        let published = film_stocks.stock_at((usize)(self.stock - 1))
        let process = film_develop.chosen_for(&published, settings.get(.develop_process))
        let grown = film_develop.developing(&published, process, settings.get(.develop_time), settings.get(.develop_temperature),
                                            (i64)settings.get(.develop_agitation))
        # The development's kinetics, for its steps on the GPU (film_stages.glsl's
        # `progress`): saturation and induction, rate slope and grey, the
        # time against normal, the minutes and the bath's renewal.
        self.put(values_row, 52, grown.saturation[0], grown.saturation[1], grown.saturation[2], grown.induction)
        self.put(values_row, 53, grown.rate_slope[0], grown.rate_slope[1], grown.rate_slope[2], grown.grey_log_h)
        self.put(values_row, 54, grown.time, grown.minutes, grown.renewal, kept_share(&grown, grown.renewal))
        # The steps, and the share of a step's used developer still missing
        # one step later (the bath's renewal), for the even field's exhaustion.
        let step_keep = math.exp(-grown.minutes / (f64)chemistry_steps / math.max(grown.renewal, 1.0e-6))
        self.put(values_row, 55, (f64)chemistry_steps, step_keep, 0.0, 0.0)
        # The bleach bypassed (develop_silver): silver stays where the dye
        # formed, adding its own grain. Only a color negative's silver is extra.
        let retained = settings.get(.develop_silver) / 100.0 if kind == 0 else 0.0
        # Duplication between the negative and the print (the Print stage):
        # each generation's own grain adds in quadrature, an optical step's
        # specular light shows it harder (the Callier effect).
        let generations = settings.get(.print_generations)
        let optical = settings.get(.print_optical) > 0.5
        let duplicated = math.sqrt(1.0 + generation_grain * (generations + (1.0 if optical else 0.0))) * (optical_callier if optical else 1.0)
        # Grain grows with the silver developed: each developable grain develops
        # further, so σ follows the density's own factor (Kodak's pushes: about
        # 10–15 % more granularity per stop, as contrast rises).
        let coarse = grown.gain * grown.grain * (1.0 + silver_grain * retained) * duplicated
        for at in 0..<curve_samples:
            let x = log_h_at(at) + grown.shift
            let grain = along_model(model.grain, x)
            var grows: f64[3] = [1.0, 1.0, 1.0]
            if not grown.reversal:
                for layer in 0..<(usize)3:
                    grows[layer] = grown.factor(layer, x)
            for layer in 0..<(usize)3:
                self.granularity[at * 3 + layer] = grain[layer] * coarse * grows[layer]
            self.put(grain_row, at, grain[0] * coarse * grows[0], grain[1] * coarse * grows[1], grain[2] * coarse * grows[2], 1.0)
        # The grain populations' strengths, fitted to that granularity; then
        # the grain row becomes what still corrects them to it exactly at each
        # log H (three populations of fixed shape come within a few percent).
        let strengths = population_amplitudes(model, self.texels)
        for layer in 0..<(usize)3:
            for p in 0..<(usize)3:
                let at = layer * 3 + p
                self.put(values_row, 320 + at, model.populations[layer * 6 + p * 2], model.populations[layer * 6 + p * 2 + 1], strengths[at], 0.0)
        for at in 0..<curve_samples:
            var correction: f64[3]
            for layer in 0..<(usize)3:
                let amplitude = (f64)self.texels[(grain_row * atlas_width + at) * 4 + layer]
                var variance = 0.0
                for p in 0..<(usize)3:
                    let share = film_model.developed_share(model.populations, layer, p, log_h_at(at))
                    variance += strengths[layer * 3 + p] * strengths[layer * 3 + p] * share * (1.0 - share)
                correction[layer] = math.clamp(math.sqrt(amplitude * amplitude / 3.0 / math.max(variance, 1.0e-12)), 0.0, 8.0) if amplitude > 0.0 else 0.0
            self.put(grain_row, at, correction[0], correction[1], correction[2], 1.0)
        # Inhibition, and the development corrected for it: a neutral at log H x
        # develops at x − D·a(x); tabulate the inverse so it still reaches a(x).
        let strength = settings.get(.film_interimage) / 100.0
        var dir: f64[9]
        for at in 0..<(usize)9:
            dir[at] = interimage[at] * strength
        for layer in 0..<(usize)3:
            dir[layer * 4] = model.self_inhibition[layer]
        # A layer's development, held back by D·dye, stays monotonic only while
        # the hold grows slower than the exposure: Σ D·|dye per log H| under 1
        # wherever the curves are steepest. The interimage matrix is ECN-2's; on a
        # steep stock (a slide's dyes change three times as fast) it is scaled
        # until that sum is 0.7 at most.
        var steepest: f64[3] = [0.0, 0.0, 0.0]
        for at in 1..<curve_samples:
            for layer in 0..<(usize)3:
                let slope = math.abs(developed_amount(model, grown, layer, at) - developed_amount(model, grown, layer, at - 1)) / (log_h_at(at) - log_h_at(at - 1))
                steepest[layer] = math.max(steepest[layer], slope)
        for row in 0..<(usize)3:
            let own = dir[row * 4] * steepest[row]
            let others = dir[row * 3] * steepest[0] + dir[row * 3 + 1] * steepest[1] + dir[row * 3 + 2] * steepest[2] - own
            if own + others > 0.7 and others > 0.0:
                let keep = math.max(0.0, 0.7 - own) / others
                for column in 0..<(usize)3:
                    if column != row:
                        dir[row * 3 + column] *= keep
        for row in 0..<(usize)3:
            self.put(values_row, 3 + row, dir[row * 3], dir[row * 3 + 1], dir[row * 3 + 2], 0.0)
        # The developer's edge effects (film_develop.lucb): development held back
        # by how much developed nearby, all layers alike, over the developer's
        # own spread. In log H per unit of exhaustion (the mean share of each
        # layer's most), within the same monotonic bound.
        # Edge effects per unit of developer the bath has not yet renewed: a
        # property of the developer (its strength at its own agitation, over
        # what an even patch keeps unrenewed then). The stock's published MTF
        # already holds its standard process's at that process's agitation;
        # the film adds the difference.
        let kept = kept_share(&grown, grown.renewal)
        let used_per_unit = grown.used_edge / kept_share(&grown, grown.own_renewal)
        # The standard process's, kept unrenewed as this agitation keeps it.
        let standard_per_unit = grown.standard_edge / kept
        # Per unit of developer missing beyond what an even field of the same
        # exposure misses (film_stages.glsl's `developed`): nothing in an even area.
        let edge = edge_gain * (used_per_unit - standard_per_unit)
        # A large even patch is held back by the inhibitor its own development
        # releases (`even_field`: with the dye each step forms), which depends
        # on this table: built for the dye's own inhibitor, the even field's
        # found through it, built again, until it settles. So a large even patch
        # still reaches the published curve.
        # Each layer's most dye and the stock's kind, which the inhibitor reads.
        self.put(values_row, 17, model.most[0], model.most[1], model.most[2], (f64)kind)
        let key = development_key(self.stock, self.cross, settings)
        if key != self.developed_key:
            self.solve_developed(model, &grown, dir)
            self.developed_key = key
        # Grey's log H, and each channel's gamma there.
        let grey = model.grey_log_h
        let contrast = 1.0 + settings.get(.film_contrast) / 200.0
        let black = settings.get(.film_black) / 100.0
        let frame = frame_widths[(usize)math.clamp(settings.get(.film_format), 0.0, 5.0)]
        # The frame in 2 µm units: IMAX's 70 410 µm is past what a half float
        # holds (65 504), and halving rounds every other format as before.
        self.put(values_row, 6, grey, model.top, frame / 2.0, settings.get(.film_grain) / 100.0)
        self.put(values_row, 17, model.most[0], model.most[1], model.most[2], (f64)kind)
        # The grain's clouds: their spacing, the Gaussian's 1/(2σ²) in cells, and
        # its calibration (grain_shape).
        let shape = grain_shape(model.stock.grain_width)
        let width = model.stock.grain_width
        self.put(values_row, 18, model.stock.grain_cell, 1.0 / (2.0 * width * width), shape[0], shape[1])
        self.put(values_row, 19, shape[2], 0.0, 0.0, 0.0)
        let fog_scan = self.scanned_lut([model.neutral[0], model.neutral[1], model.neutral[2]], model.top)
        # No silver while the scan is set up and its matrix fitted: the lab's scan
        # is set for a bleached negative.
        let fog_density = (fog_scan[0] + fog_scan[1] + fog_scan[2]) / 3.0
        let steps = settings.get(.print_generations) + (1.0 if settings.get(.print_optical) > 0.5 else 0.0)
        # A dye-transfer print's dye spreads from matrix to blank (15–25 µm wide,
        # an estimate).
        let spread = dye_spread if settings.get(.print_material) > 0.5 else 0.0
        self.put(values_row, 21, settings.get(.film_flash) / 100.0, math.sqrt(generation_blur * generation_blur * steps + spread * spread), 0.0, 0.0)
        self.put(values_row, 20, 0.0, fog_density, edge, grown.edge_width)
        let warmth = settings.get(.film_warmth) / 100.0
        let tint = settings.get(.film_tint) / 100.0
        # Printer lights (the Print stage), in points of 0.025 log exposure on the
        # print: a gain on the scene light before printing density's 0.6 per
        # decade (film_print.lucb); more red light prints more cyan.
        let point = -0.025 / 0.6
        let lights = [math.pow(10.0, point * settings.get(.print_red)), math.pow(10.0, point * settings.get(.print_green)),
                      math.pow(10.0, point * settings.get(.print_blue))]
        self.put(values_row, 10, math.exp2(0.5 * warmth) * lights[0], math.exp2(-0.5 * tint) * lights[1], math.exp2(-0.5 * warmth) * lights[2], 0.0)
        self.put(values_row, 14, model.scatter[0], model.scatter[1], model.scatter[2], 0.0)
        self.put(values_row, 16, model.spread[0], model.spread[1], model.spread[2], 0.0)
        # Halation from the stock's base and backing, or with its backing
        # removed (as CineStill takes Vision3's rem-jet off).
        let halo = settings.get(.film_halation) / 100.0
        let backing = film_halation.no_backing if settings.get(.film_backing) > 0.5 else model.stock.backing
        let returned = film_halation.kernel(model.stock.base_thickness, model.stock.base_index, backing)
        let ring = 2.0 * model.stock.base_thickness * math.tan(math.asin(1.0 / model.stock.base_index))
        self.put(values_row, 15, returned.strength[0] * halo, returned.strength[1] * halo, returned.strength[2] * halo, ring)
        for k in 0..<film_halation.sample_count:
            self.put(values_row, 64 + k, returned.offsets[k * 2], returned.offsets[k * 2 + 1], 0.0, 0.0)
        for row in 0..<(usize)3:
            self.put(values_row, 11 + row, 1.0 if row == 0 else 0.0, 1.0 if row == 1 else 0.0, 1.0 if row == 2 else 0.0, 0.0)
        if self.printing != no_printing:
            # Printing density goes to the print as it is, at the print view's
            # 0.6 per decade about the normal negative's grey (film_print.lucb,
            # film_paper.lucb), where the printer lights or the enlarger's
            # exposure put the print's mid-grey: no scanner's gamma, matrix or
            # timing, only the printer lights (values 10). 2383 takes its
            # layers' balance (`print_balance`); a paper's curves are its own.
            let at_grey = self.scan_of(self.balanced_grey(grey))
            let balance: f64[3] = print_balance if self.printing == onto_print else [1.0, 1.0, 1.0]
            self.put(values_row, 7, at_grey[0], at_grey[1], at_grey[2], 1.0)
            self.put(values_row, 8, balance[0] / 0.6, balance[1] / 0.6, balance[2] / 0.6, 0.0)
            self.put(values_row, 9, 0.0, 0.0, 0.0, 0.0)
            self.put(values_row, 10, lights[0], lights[1], lights[2], 0.0)
            self.put(values_row, 20, retained * silver_density, fog_density, edge, grown.edge_width)
            return
        if kind == 1:
            # A slide is seen, not scanned: its table holds scene light already.
            # Contrast is a power about grey; Black has nothing to take out.
            self.put(values_row, 7, 0.0, 0.0, 0.0, 1.0)
            self.put(values_row, 8, contrast, contrast, contrast, 0.0)
            self.put(values_row, 9, 0.0, 0.0, 0.0, 0.0)
            return
        let at_grey = self.scan_of(self.balanced_grey(grey))
        let below = self.scan_of(self.neutral_at(grey - 0.3))
        let above = self.scan_of(self.neutral_at(grey + 0.3))
        self.put(values_row, 7, at_grey[0], at_grey[1], at_grey[2], 1.0)
        var inverse: f64[3]
        var floors: f64[3]
        for channel in 0..<(usize)3:
            inverse[channel] = contrast * 0.6 / math.max(above[channel] - below[channel], 1.0e-6)
            floors[channel] = 0.18 * math.pow(10.0, -at_grey[channel] * inverse[channel])
        self.put(values_row, 8, inverse[0], inverse[1], inverse[2], black)
        self.put(values_row, 9, floors[0], floors[1], floors[2], 0.0)
        # The scan's matrix, fitted (the identity while fitting). Black and white
        # comes out neutral by itself; a cross-processed slide is scanned as any
        # negative, its crossovers and loud color left as they are.
        if kind == 2 or self.cross:
            self.put(values_row, 20, retained * silver_density, fog_density, edge, grown.edge_width)
            return
        # Calibrated to the reference negative (a scanner set up once, every
        # stock's own color showing), or matched to this stock.
        let fitted = self.fit_matrix() if settings.get(.scan_calibration) > 0.5 else reference_scan
        for row in 0..<(usize)3:
            self.put(values_row, 11 + row, fitted[row * 3], fitted[row * 3 + 1], fitted[row * 3 + 2], 0.0)
        self.put(values_row, 20, retained * silver_density, fog_density, edge, grown.edge_width)

    ## The print layers' contrast that prints this negative's grey scale
    ## neutral (each layer's printing-density gamma about grey over their mean).
    func print_balance_of() -> f64[3]:
        let grey = self.model.grey_log_h
        let high = self.scan_of(self.neutral_at(grey + 0.3))
        let low = self.scan_of(self.neutral_at(grey - 0.3))
        let gammas: f64[3] = [high[0] - low[0], high[1] - low[1], high[2] - low[2]]
        let mean = (gammas[0] + gammas[1] + gammas[2]) / 3.0
        return [mean / gammas[0], mean / gammas[1], mean / gammas[2]]

    ## The matrix from the scan's channels to AP1 that best returns colors of
    ## moderate saturation to themselves (least squares), its rows scaled so
    ## neutrals stay neutral.
    func fit_matrix() -> f64[9]:
        var ata: f64[9]
        var atb: f64[9]
        for at in 0..<(usize)9:
            ata[at] = 0.0
            atb[at] = 0.0
        let levels: f64[4] = [0.05, 0.12, 0.25, 0.4]
        for r in levels:
            for g in levels:
                for b in levels:
                    let lum = 0.272228717 * r + 0.674081766 * g + 0.053689517 * b
                    for brightness in [0.5, 1.0, 2.0]:
                        let scale = 0.18 * brightness / lum
                        let scene: f64[3] = [r * scale, g * scale, b * scale]
                        let shot = develop(&self, scene, 0.5, 0.5, 1.0, false)
                        # Normal equations: Σ shot·shotᵀ and Σ shot·sceneᵀ.
                        for i in 0..<(usize)3:
                            for j in 0..<(usize)3:
                                ata[i * 3 + j] += shot[i] * shot[j]
                                atb[i * 3 + j] += shot[i] * scene[j]
        let inverse = invert3(ata) else return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
        # X = (AᵀA)⁻¹AᵀB maps a shot (row) to a scene (row); the matrix applied to
        # a column vector is its transpose.
        var solved: f64[9]
        for i in 0..<(usize)3:
            for j in 0..<(usize)3:
                solved[i * 3 + j] = inverse[i * 3] * atb[j] + inverse[i * 3 + 1] * atb[3 + j] + inverse[i * 3 + 2] * atb[6 + j]
        var out: f64[9]
        for row in 0..<(usize)3:
            let sum = solved[row] + solved[3 + row] + solved[6 + row]
            for column in 0..<(usize)3:
                out[row * 3 + column] = solved[column * 3 + row] / sum
        return out

    ## The neutral dye amounts at `log_h`, read from the atlas.
    func neutral_at(log_h: f64) -> f64[3]:
        return self.along(neutral_row, log_h)

    ## A large grey patch's dye: each layer exposed at grey plus the halo an even
    ## field gives it (values 15), which a lab balances out as it times or
    ## scans; halos stay where light is uneven.
    func balanced_grey(log_h: f64) -> f64[3]:
        let halo = self.value(15)
        var out: f64[3]
        for layer in 0..<(usize)3:
            out[layer] = self.neutral_at(log_h + math.log10(1.0 + halo[layer]))[layer]
        return out

    ## The scan of `amounts`, read from the atlas.
    func scan_of(amounts: f64[3]) -> f64[3]:
        return self.scanned_lut(amounts, self.value(6)[1])

    ## Atlas texel (`column`, `row`) as the GPU holds it.
    func texel(row: usize, column: usize) -> f64[3]:
        let at = (row * atlas_width + column) * 4
        return [(f64)(f16)self.texels[at], (f64)(f16)self.texels[at + 1], (f64)(f16)self.texels[at + 2]]

    ## Values texel `column`, as the GPU holds it.
    pub func value(column: usize) -> f64[4]:
        let at = (values_row * atlas_width + column) * 4
        return [(f64)(f16)self.texels[at], (f64)(f16)self.texels[at + 1], (f64)(f16)self.texels[at + 2], (f64)(f16)self.texels[at + 3]]

    ## The developed row for even fields that develop with their own inhibitor
    ## (`even_field`), which depends on this table: built for the dye's own
    ## inhibitor, the even field's found through it (every eighth sample, the
    ## rest between them), built again until it settles (damped half way each
    ## round: strong interimage would swing). So a large even patch still
    ## reaches the published curve.
    func solve_developed(model: const Model*, grown: const Development*, dir: f64[9]):
        var hold: f64[3072]
        for at in 0..<curve_samples:
            let neutral_hold = inhibitor(model.stock.kind, model.most, [model.neutral[at * 3], model.neutral[at * 3 + 1], model.neutral[at * 3 + 2]])
            for k in 0..<(usize)3:
                hold[at * 3 + k] = neutral_hold[k]
        let every: usize = 8
        for _ in 0..<60:
            self.fill_developed(model, grown, dir, hold)
            var moved = 0.0
            var ended_at: f64[3072]
            var at: usize = 0
            while at < curve_samples:
                let x = log_h_at(at)
                let (ended, _) = even_field_at(&self, [x, x, x])
                for k in 0..<(usize)3:
                    ended_at[at * 3 + k] = ended[k]
                at += every
            for sample in 0..<curve_samples:
                let below = sample - sample % every
                let above = below + every if below + every < curve_samples else below
                let t = (f64)(sample - below) / (f64)(above - below) if above > below else 0.0
                for k in 0..<(usize)3:
                    let ended = ended_at[below * 3 + k] * (1.0 - t) + ended_at[above * 3 + k] * t
                    moved = math.max(moved, math.abs(ended - hold[sample * 3 + k]))
                    hold[sample * 3 + k] = 0.5 * (hold[sample * 3 + k] + ended)
            if moved < 1.0e-4:
                break
        self.fill_developed(model, grown, dir, hold)

    ## The development under inhibition (the atlas's developed row): a neutral
    ## at log H x, held back by `hold` (its even field's inhibitor), develops
    ## at x − D·hold(x); tabulated over the effective log H so it still reaches
    ## the published dye.
    func fill_developed(model: const Model*, grown: const Development*, dir: f64[9], hold: const f64[3072]):
        for layer in 0..<(usize)3:
            var source: usize = 0
            for at in 0..<curve_samples:
                let wanted = log_h_at(at)
                # March along the neutral ramp to where its effective log H passes `wanted`.
                while source + 1 < curve_samples and held_at(dir, hold, layer, source + 1) < wanted:
                    source += 1
                let low = held_at(dir, hold, layer, source)
                let next = source + 1 if source + 1 < curve_samples else source
                let high = held_at(dir, hold, layer, next)
                let t = math.clamp((wanted - low) / math.max(high - low, 1.0e-9), 0.0, 1.0) if source + 1 < curve_samples else 1.0
                let amount = developed_amount(model, *grown, layer, source) * (1.0 - t) + developed_amount(model, *grown, layer, next) * t
                let base = (developed_row * atlas_width + at) * 4
                self.texels[base + layer] = (f32)(amount if wanted >= held_at(dir, hold, layer, 0) else developed_amount(model, *grown, layer, 0))
                self.texels[base + 3] = 1.0f32

    ## The stochastic render's grains for the settings last prepared
    ## (film_grains.lucb): fitted to the development's curve over its floor and
    ## to its granularity, at each effective log H. Slower than `prepare` (a
    ## fraction of a second), so done only when the render begins.
    pub func fit_grains() -> !:
        if self.has_grains() or not self.on:
            return
        let kind = self.model.stock.kind
        let layers: usize = 1 if kind == 2 else 3
        var floors: f64[3] = [1.0e300, 1.0e300, 1.0e300]
        for at in 0..<curve_samples:
            let amounts = self.texel(developed_row, at)
            for layer in 0..<(usize)3:
                floors[layer] = math.min(floors[layer], amounts[layer])
        var curves = try new f64[curve_samples * 3] --- in memory.heap
        defer free(curves) in memory.heap
        for at in 0..<curve_samples:
            let amounts = self.texel(developed_row, at)
            for layer in 0..<(usize)3:
                curves[at * 3 + layer] = math.max(amounts[layer] - floors[layer], 0.0)
        # The granularity is read through each channel; the grains are fitted
        # in their layer's dye, which the channel sees through the scan's slope
        # (not 1: the dyes' unwanted absorptions, the table's own shape).
        var wanted = try new f64[curve_samples * 3] --- in memory.heap
        defer free(wanted) in memory.heap
        for at in 0..<curve_samples:
            let amounts: f64[3] = [floors[0] + curves[at * 3], floors[1] + curves[at * 3 + 1], floors[2] + curves[at * 3 + 2]]
            let slopes = self.scan_slopes(amounts)
            for layer in 0..<(usize)3:
                var own = slopes[layer * 4]
                if layers == 1:
                    own = slopes[0] + slopes[3] + slopes[6]
                wanted[at * 3 + layer] = self.granularity[at * 3 + layer] / math.max(own, 0.05)
        let peak = film_grains.silver_peak if kind == 2 else film_grains.color_peak
        var fitted = try film_grains.fit(layers, curves, wanted, kind == 1, peak)
        defer fitted.release()
        for layer in 0..<(usize)3:
            for at in 0..<curve_samples:
                let base = (at * 3 + layer) * 4
                self.put(grains_row + layer, at, fitted.table[base], fitted.table[base + 1], fitted.table[base + 2], fitted.table[base + 3])
            for p in 0..<film_grains.populations:
                let g = fitted.geometry[layer * 3 + p]
                let used = layer < layers
                self.put(values_row, 329 + layer * 3 + p, g.density if used else 0.0, g.peak, g.radius, 0.0)
        for at in 0..<curve_samples:
            self.put(granularity_row, at, fitted.granularity[at * 3], fitted.granularity[at * 3 + 1], fitted.granularity[at * 3 + 2], 1.0)
        self.put(values_row, 338, floors[0], floors[1], floors[2], (f64)layers)
        for at in 0..<film_grains.peak_count:
            self.put(values_row, 340 + at, film_grains.light_taken(film_grains.peak_at(at)), 0.0, 0.0, 0.0)
        for at in 0..<film_grains.covariance_count:
            let shares = film_grains.pixel_covariance(film_grains.covariance_width(at))
            self.put(values_row, 390 + at, shares[0], shares[1], shares[2], 0.0)
        self.grains_fitted = self.grains_wanted

    ## The scan's reading of dye `amounts` (the retained silver included) as
    ## density (a slide's light too).
    pub func density_read(amounts: f64[3]) -> f64[3]:
        let read = silver(&self, self.scanned_lut(amounts, self.value(6)[1]))
        if self.model.stock.kind != 1:
            return read
        var out: f64[3]
        for c in 0..<(usize)3:
            out[c] = -math.log10(math.max(math.sinh(read[c]) / 256.0, 1.0e-30))
        return out

    ## The granularity wanted for layer `layer` at effective log H `log_h` (rms
    ## through 48 µm).
    pub func granularity_at(layer: usize, log_h: f64) -> f64:
        let x = math.clamp((log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
        let below = (usize)math.min(math.floor(x), (f64)(curve_samples - 2))
        let t = x - (f64)below
        return self.granularity[below * 3 + layer] * (1.0 - t) + self.granularity[(below + 1) * 3 + layer] * t

    ## Layer `layer`'s developed dye at effective log H `log_h`.
    pub func curve_amount(layer: usize, log_h: f64) -> f64:
        return self.curve(developed_row, layer, log_h)

    ## Layer `layer`'s granularity at effective log H `log_h` as the atlas holds it.
    pub func grain_granularity(layer: usize, log_h: f64) -> f64:
        return self.curve(granularity_row, layer, log_h)

    ## The most share of each population of layer `layer` developed anywhere
    ## from effective log H `low` to `high` (the table's nodes between them and
    ## its ends; the shares are linear between nodes).
    pub func share_bound(layer: usize, low: f64, high: f64) -> f64[3]:
        let starts = self.grain_table(layer, low)
        let ends = self.grain_table(layer, high)
        var out: f64[3]
        for p in 0..<(usize)3:
            out[p] = math.max(starts[p], ends[p])
        let first = (usize)math.ceil(math.clamp((low - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1))
        let last = (usize)math.floor(math.clamp((high - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1))
        var at = first
        while at <= last and at < curve_samples:
            let base = ((grains_row + layer) * atlas_width + at) * 4
            for p in 0..<(usize)3:
                out[p] = math.max(out[p], (f64)(f16)self.texels[base + p])
            at += 1
        return out

    ## Whether `fit_grains` has fitted the grains for the settings last prepared.
    pub func has_grains() -> bool:
        return self.on and self.grains_wanted != 0 and self.grains_fitted == self.grains_wanted

    ## The grains' populations as the atlas holds them (as the GPU reads them).
    pub func grain_geometry() -> film_grains.Geometry[9]:
        var out: film_grains.Geometry[9]
        for at in 0..<(usize)9:
            let v = self.value(329 + at)
            out[at] = film_grains.Geometry(density = v[0], peak = v[1], radius = v[2])
        return out

    ## Layer `layer`'s grain table at effective log H `log_h`: its populations'
    ## shares developed and the clouds' strength (film_stages.glsl's `grain_table`).
    pub func grain_table(layer: usize, log_h: f64) -> f64[4]:
        let x = math.clamp((log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
        let below = (usize)math.min(math.floor(x), (f64)(curve_samples - 2))
        let t = x - (f64)below
        let row = grains_row + layer
        let a = (row * atlas_width + below) * 4
        let b = a + 4
        var out: f64[4]
        for k in 0..<(usize)4:
            out[k] = (f64)(f16)self.texels[a + k] * (1.0 - t) + (f64)(f16)self.texels[b + k] * t
        return out

    ## The scan's slopes at dye `amounts`: how each channel's density (a slide's
    ## light as density too) moves with each layer's dye (layer by row). The
    ## stochastic render reads a pixel's grain through them, about the
    ## developed film's reading there.
    pub func scan_slopes(amounts: f64[3]) -> f64[9]:
        let top = self.value(6)[1]
        var slopes: f64[9]
        for layer in 0..<(usize)3:
            # Either side of it, inside the table (at its ends it holds still).
            var up = amounts
            var down = amounts
            up[layer] = math.min(amounts[layer] + 0.02, top)
            down[layer] = math.max(amounts[layer] - 0.02, 0.0)
            let span = math.max(up[layer] - down[layer], 1.0e-6)
            let above = self.density_read(up)
            let below = self.density_read(down)
            # A dye never makes a channel lighter (the table's steps near its
            # ends can say otherwise).
            for channel in 0..<(usize)3:
                slopes[layer * 3 + channel] = math.max((above[channel] - below[channel]) / span, 0.0)
        return slopes

    ## What the grains add on average to each channel's density over the
    ## developed film's where each layer developed at `log_h`, read through the
    ## scan's `slopes` there (Campbell, exact for them): each layer's clouds
    ## are fitted to read its curve through its own channel, but another
    ## channel sees them fainter, and faint clouds lose less to the averaging
    ## of light, so they read denser there than their share of the mean. The
    ## published curves are read through every channel at once, so the
    ## stochastic render takes this off (film_stages.glsl's `grain_bias`).
    pub func grain_bias(log_h: f64[3], slopes: f64[9], traced: bool[3]) -> f64[3]:
        let base = self.value(338)
        let layers = (usize)base[3]
        var out: f64[3] = [0.0, 0.0, 0.0]
        for channel in 0..<(usize)3:
            for layer in 0..<layers:
                if not traced[layer]:
                    continue
                # Black and white: one silver for the three amounts the table reads.
                var factor = slopes[layer * 3 + channel]
                if layers == 1:
                    factor = slopes[channel] + slopes[3 + channel] + slopes[6 + channel]
                let table = self.grain_table(layer, log_h[layer])
                for p in 0..<film_grains.populations:
                    let v = self.value(329 + layer * 3 + p)
                    let area = v[0] * table[p] * v[2] * v[2] * film_grains.size_square_mean
                    let peak = v[1] * table[3]
                    out[channel] += area * (self.taken(factor * peak) - factor * self.taken(peak))
        return out

    ## film_grains.lucb's `light_taken`, from the atlas as the GPU reads it.
    func taken(q: f64) -> f64:
        let place = math.clamp(math.log(math.max(q, film_grains.peak_low) / film_grains.peak_low) / math.log(film_grains.peak_high / film_grains.peak_low), 0.0, 1.0) * (f64)(film_grains.peak_count - 1)
        let below = (usize)math.min(math.floor(place), (f64)(film_grains.peak_count - 2))
        let t = place - (f64)below
        return self.value(340 + below)[0] * (1.0 - t) + self.value(341 + below)[0] * t

    ## Bilinear between texel centres at (`x`, `y`) in texels, as the GPU filters.
    func bilinear(x: f64, y: f64) -> f64[3]:
        let x0 = (usize)math.floor(x)
        let y0 = (usize)math.floor(y)
        let x1 = x0 + 1 if x0 + 1 < atlas_width else x0
        let y1 = y0 + 1 if y0 + 1 < atlas_rows else y0
        let tx = x - (f64)x0
        let ty = y - (f64)y0
        let a = self.texel(y0, x0)
        let b = self.texel(y0, x1)
        let c = self.texel(y1, x0)
        let d = self.texel(y1, x1)
        var out: f64[3]
        for k in 0..<(usize)3:
            out[k] = (a[k] * (1.0 - tx) + b[k] * tx) * (1.0 - ty) + (c[k] * (1.0 - tx) + d[k] * tx) * ty
        return out

    ## Row `row`'s curves at `log_h`, all three channels at the same place.
    func along(row: usize, log_h: f64) -> f64[3]:
        let x = math.clamp((log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
        return self.bilinear(x, (f64)row)

    ## Row `row`'s curve `channel` at `log_h`.
    func curve(row: usize, channel: usize, log_h: f64) -> f64:
        return self.along(row, log_h)[channel]

    ## The scan's densities at `amounts` (0..`top`), trilinear: two bilinear
    ## reads in neighbouring slices.
    func scanned_lut(amounts: f64[3], top: f64) -> f64[3]:
        let last = (f64)(lut_size - 1)
        let r = math.clamp(amounts[0] / top, 0.0, 1.0) * last
        let g = math.clamp(amounts[1] / top, 0.0, 1.0) * last
        let b = math.clamp(amounts[2] / top, 0.0, 1.0) * last
        let slice = math.min(math.floor(b), last - 1.0)
        let t = b - slice
        let near_slice = self.bilinear(slice * (f64)lut_size + r, g)
        let far_slice = self.bilinear((slice + 1.0) * (f64)lut_size + r, g)
        return [near_slice[0] + (far_slice[0] - near_slice[0]) * t, near_slice[1] + (far_slice[1] - near_slice[1]) * t, near_slice[2] + (far_slice[2] - near_slice[2]) * t]

## Layer `layer`'s effective log H for neutral sample `at` under interimage `dir`.
## The strength of each layer's three grain populations (film_model.lucb's
## `fit_populations`): fitted (least squares, none negative) so the spread of
## their grains developing, A²·P·(1 − P) summed, has the variance the
## granularity table (`texels`' grain row: the published rms granularity, as
## development and the process change it) gives a cloud of uniform random
## strength, amplitude²/3, at every log H of the layer's curve.
func population_amplitudes(model: const Model*, texels: const f32[]) -> f64[9]:
    var out: f64[9]
    for layer in 0..<(usize)3:
        var normal: f64[9]
        var right: f64[3]
        for k in 0..<(usize)9:
            normal[k] = 0.0
        for k in 0..<(usize)3:
            right[k] = 0.0
        var at: usize = 0
        while at < curve_samples:
            let log_h = log_h_at(at)
            let amplitude = (f64)texels[(grain_row * atlas_width + at) * 4 + layer]
            let target = amplitude * amplitude / 3.0
            var basis: f64[3]
            for p in 0..<(usize)3:
                let share = film_model.developed_share(model.populations, layer, p, log_h)
                basis[p] = share * (1.0 - share)
            for a in 0..<(usize)3:
                for b in 0..<(usize)3:
                    normal[a * 3 + b] += basis[a] * basis[b]
                right[a] += basis[a] * target
            at += 8
        let squares = film_grains.nonnegative3(normal, right)
        for p in 0..<(usize)3:
            out[layer * 3 + p] = math.sqrt(squares[p])
    return out

## How many steps development runs in (film_passes.lucb, film_stages.glsl):
## enough for the release's course over time (the fields are single floats).
pub let chemistry_steps: usize = 16

## The share of the developer a large even grey patch used that is still
## missing at the end, with the bath renewing it with time constant `renewal`
## (minutes): each step's use, as grey develops, decays until the end.
func kept_share(grown: const Development*, renewal: f64) -> f64:
    let n = chemistry_steps
    let decay = math.exp(-grown.minutes / (f64)n / math.max(renewal, 1.0e-6))
    var sum = 0.0
    var before = 0.0
    for step in 1..=n:
        var now = 0.0
        for layer in 0..<(usize)3:
            now += grown.progress(layer, grown.grey_log_h, (f64)step / (f64)n) / 3.0
        sum += (now - before) * math.pow(decay, (f64)(n - step))
        before = now
    return math.max(sum, 1.0e-6)

## Layer `layer`'s dye at curve sample `at` once developed as `grown`
## (film_develop.lucb): on a negative, its normal amount over fog times the
## kinetics' factor, the fog grown, flattened above grey by the compensation; on
## a slide, the first developer's negative silver (the halide its dye did not
## get) grown by the factor, its fog taking from what is left.
func developed_amount(model: const Model*, grown: Development, layer: usize, at: usize) -> f64:
    let x = log_h_at(at) + grown.shift
    let normal = along_model(model.neutral, x)[layer]
    if grown.reversal:
        let top = model.neutral[layer]
        let bottom = model.neutral[(curve_samples - 1) * 3 + layer]
        let span = math.max(top - bottom, 1.0e-9)
        var taken = math.min(1.0, (top - normal) / span * grown.factor(layer, x))
        taken += grown.fog(layer) * (1.0 - taken)
        return bottom + span * (1.0 - math.clamp(taken, 0.0, 1.0)) * grown.gain
    let fog = model.neutral[layer]
    var rise = grown.gain * (normal - fog) * grown.factor(layer, x)
    # Compensation: above grey the developer runs out, and the slope flattens.
    if grown.compensation > 0.0 and model.stock.kind != 1:
        let at_grey = model.grey_log_h + grown.shift
        let grey = grown.gain * (along_model(model.neutral, at_grey)[layer] - fog) * grown.factor(layer, at_grey)
        if rise > grey:
            rise = grey + (rise - grey) * (1.0 - grown.compensation)
    return fog + grown.fog(layer) + rise

## A curve of `curve_samples` × 3 values (a model's neutral or grain) at
## `log_h`, linearly, held at its ends.
func along_model(c: f64[], log_h: f64) -> f64[3]:
    let place = math.clamp((log_h - log_low) / (log_high - log_low), 0.0, 1.0) * (f64)(curve_samples - 1)
    let low = (usize)math.floor(place)
    let high = low + 1 if low + 1 < curve_samples else low
    let t = place - (f64)low
    return [c[low * 3] * (1.0 - t) + c[high * 3] * t, c[low * 3 + 1] * (1.0 - t) + c[high * 3 + 1] * t,
            c[low * 3 + 2] * (1.0 - t) + c[high * 3 + 2] * t]

## Neutral sample `at`'s effective log H for layer `layer`, held back by
## inhibitor `hold` through `dir`.
func held_at(dir: const f64[9], hold: const f64[3072], layer: usize, at: usize) -> f64:
    return log_h_at(at) - (dir[layer * 3] * hold[at * 3] + dir[layer * 3 + 1] * hold[at * 3 + 1] + dir[layer * 3 + 2] * hold[at * 3 + 2])

func effective(model: const Model*, dir: const f64[9], layer: usize, at: usize) -> f64:
    let held = inhibitor(model.stock.kind, model.most, [model.neutral[at * 3], model.neutral[at * 3 + 1], model.neutral[at * 3 + 2]])
    return log_h_at(at) - (dir[layer * 3] * held[0] + dir[layer * 3 + 1] * held[1] + dir[layer * 3 + 2] * held[2])

## What holds development back, for dye `amounts`: the dye itself on a negative;
## on a slide the first developer's negative image, which is what the dye is not
## (each layer's `most` less it).
func inhibitor(kind: i64, most: f64[3], amounts: f64[3]) -> f64[3]:
    if kind != 1:
        return amounts
    return [most[0] - amounts[0], most[1] - amounts[1], most[2] - amounts[2]]

# mark: Per pixel =============================================================

## A hash of a cell to 0..1, the same as the shader's.
func hashed(px: u32, py: u32) -> f64:
    var x = px *% 1664525 +% py *% 1013904223
    x = x ^ (x >> 16)
    x = x *% 0x7feb352d
    x = x ^ (x >> 15)
    x = x *% 0x846ca68b
    x = x ^ (x >> 16)
    return (f64)(x >> 8) / 16777216.0

## How strong grain must be, for clouds `cell` µm apart, for a 48 µm aperture (a
## 42.5 µm square of the same area) over a patch of them to read a granularity
## of 1: measured on `clouded`'s blend as a·(1 − e^(−s/b))/s for an aperture s
## clouds wide, within 6% (`grain_shape` gives a and b).
func grain_gain(cell: f64, a: f64, b: f64) -> f64:
    let side = 42.5 / cell
    return side / (a * (1.0 - math.exp(-side / b)))

## For clouds `width` cells wide (a Gaussian's σ): `grain_gain`'s a and b, and the
## blend's spread at a point per unit of strength. Measured for widths 0.35 and
## 0.5 (the stocks' two), and between them interpolated.
func grain_shape(width: f64) -> f64[3]:
    let t = math.clamp((width - 0.35) / 0.15, 0.0, 1.0)
    return [0.5534 + (0.5435 - 0.5534) * t, 1.0817 + (1.3708 - 1.0817) * t, 0.4216 + (0.3257 - 0.4216) * t]

## The three layers' exposure to scene light `c` (AP1): relative, 0.18 for a
## grey card at normal exposure (film_stages.glsl's `expose`).
pub func expose(film: const Film*, c: f64[3]) -> f64[3]:
    var fitted = film_exposure.Fit()
    var values: f64[3]
    for row in 0..<(usize)3:
        let m = film.value(row)
        values[row] = m[0] * c[0] + m[1] * c[1] + m[2] * c[2]
    for k in 0..<film_exposure.term_count:
        let high = film.value(22 + k)
        let low = film.value(35 + k)
        for layer in 0..<(usize)3:
            fitted.weights[k * 3 + layer] = high[layer] + low[layer]
    var e = film_exposure.apply(&fitted, values)
    # Reciprocity failure, each layer at its own exposure.
    var law: f64[9]
    for layer in 0..<(usize)3:
        let v = film.value(48 + layer)
        law[layer * 3] = v[0]
        law[layer * 3 + 1] = v[1]
        law[layer * 3 + 2] = v[2]
    let seconds = film.value(51)[0]
    for layer in 0..<(usize)3:
        e[layer] *= math.exp2(-film_exposure.failure(law, layer, seconds, e[layer]))
    # Flashing: an even exposure over the whole negative, a share of grey's
    # (grey exposes each layer 0.18).
    let flash = film.value(21)[0] * 0.18
    return [math.max(e[0], 1.0e-8) + flash, math.max(e[1], 1.0e-8) + flash, math.max(e[2], 1.0e-8) + flash]

func log_exposure(film: const Film*, e: f64[3]) -> f64[3]:
    let grey = film.value(6)[0]
    return [math.log10(math.max(e[0] / 0.18, 1.0e-8)) + grey, math.log10(math.max(e[1] / 0.18, 1.0e-8)) + grey,
            math.log10(math.max(e[2] / 0.18, 1.0e-8)) + grey]

## What holds development back where exposure `e` falls, if nothing held it
## back there: each layer's dye on a negative, its negative image on a slide.
pub func neutral(film: const Film*, e: f64[3]) -> f64[3]:
    let log_h = log_exposure(film, e)
    let v17 = film.value(17)
    return inhibitor((i64)v17[3], [v17[0], v17[1], v17[2]],
                     [film.curve(neutral_row, 0, log_h[0]), film.curve(neutral_row, 1, log_h[1]), film.curve(neutral_row, 2, log_h[2])])

## A large even field of exposure `e` developed step by step (the steps'
## fields make the same sums: film_passes.lucb's `develop_steps`): each step
## each layer forms dye as far as the kinetics take it then, under the
## inhibitor the steps before released, and releases inhibitor with that dye
## (DIR couplers react as the dye forms) and uses developer with it, of which
## the bath renews some by the end. The inhibitor it ends with, and the
## developer it still misses (so an even field has no edge effect).
pub func even_field(film: const Film*, e: f64[3]) -> (f64[3], f64):
    return even_field_at(film, log_exposure(film, e))

func even_field_at(film: const Film*, log_h: f64[3]) -> (f64[3], f64):
    let most = film.value(17)
    let v55 = film.value(55)
    let n = (usize)v55[0]
    var held: f64[3] = [0.0, 0.0, 0.0]
    var used = 0.0
    var before: f64[3] = [0.0, 0.0, 0.0]
    for step in 1..=n:
        let now = progress(film, log_h, (f64)step / (f64)n)
        let kept = math.pow(v55[1], (f64)(n - step))
        let forms = inhibiting(film, log_h, held)
        for k in 0..<(usize)3:
            let grown = now[k] - before[k]
            held[k] += forms[k] * grown
            used += kept * forms[k] / math.max(most[k], 1.0e-9) * grown / 3.0
        before = now
    return (held, used)

## The inhibitor each layer releases with its dye where it develops at log H
## `log_h` held back by inhibitor `held`: its dye there once developed (on a
## slide, its first developer's negative image: what the dye is not).
func inhibiting(film: const Film*, log_h: f64[3], held: f64[3]) -> f64[3]:
    let v17 = film.value(17)
    var held_back: f64[3]
    for k in 0..<(usize)3:
        let d = film.value(3 + k)
        held_back[k] = log_h[k] - (d[0] * held[0] + d[1] * held[1] + d[2] * held[2])
    return inhibitor((i64)v17[3], [v17[0], v17[1], v17[2]], [film.curve(developed_row, 0, held_back[0]), film.curve(developed_row, 1, held_back[1]),
                                                           film.curve(developed_row, 2, held_back[2])])

## How much developer a large even field of exposure `e` still misses at the
## end (`even_field`).
pub func even_exhaustion(film: const Film*, e: f64[3]) -> f64:
    return even_field(film, e).1

## What the developed row depends on, as one number: the stock, cross
## processing, the development and the interimage.
func development_key(stock: i64, cross: bool, settings: const Settings*) -> i64:
    var key = stock *% 31 +% (1 if cross else 0)
    for parameter in [Parameter.develop_process, Parameter.develop_time, Parameter.develop_temperature, Parameter.develop_agitation,
                      Parameter.film_interimage, Parameter.develop_silver]:
        key = key *% 1000003 +% (i64)math.round(settings.get(parameter) * 1000.0)
    return key + 1

## What the stochastic render's grains depend on (`Film.fit_grains`), as one
## number: the development (its curve and granularity), the duplicates' grain,
## and what reads the negative (the scan's or the print material's table, the
## silver it sees).
func grain_key(stock: i64, cross: bool, printing: i64, settings: const Settings*) -> i64:
    var key = development_key(stock, cross, settings) *% 1000003 +% printing
    for parameter in [Parameter.print_generations, Parameter.print_optical, Parameter.print_silver, Parameter.print_material,
                      Parameter.scan_calibration, Parameter.paper_stock, Parameter.paper_grade, Parameter.paper_enlarger,
                      Parameter.paper_exposure, Parameter.paper_surface, Parameter.paper_yellow, Parameter.paper_magenta, Parameter.paper_cyan]:
        key = key *% 1000003 +% (i64)math.round(settings.get(parameter) * 1000.0)
    return key if key != 0 else 1

## A place on the developed negative: each layer's dye, and the effective log
## H it developed at (which sets its granularity).
pub struct Developed:
    pub var amounts: f64[3]
    pub var effective: f64[3]

## How much developer the inhibitor `held` used up there: each layer's share of
## its most, averaged (0..1), which the edge effects spread.
pub func exhaustion(film: const Film*, held: f64[3]) -> f64:
    let most = film.value(17)
    return (held[0] / math.max(most[0], 1.0e-9) + held[1] / math.max(most[1], 1.0e-9) + held[2] / math.max(most[2], 1.0e-9)) / 3.0

## Exposure `e` developed, held back by the inhibitor around it (`held`, as the
## development's steps released and spread it) and by the developer used up
## around it (`exhausted`); `share` of the way through the development
## (film_stages.glsl's `developed`).
pub func developed(film: const Film*, e: f64[3], held: f64[3], exhausted: f64, share: f64 = 1.0) -> Developed:
    let log_h = log_exposure(film, e)
    let edge = film.value(20)[2]
    # The edge effects: developer missing beyond what an even field of this
    # exposure would miss (Eberhard: a dense border beside a thin one gets the
    # thin one's to spare).
    let even = even_exhaustion(film, e)
    var out: Developed
    for k in 0..<(usize)3:
        let d = film.value(3 + k)
        out.effective[k] = log_h[k] - (d[0] * held[0] + d[1] * held[1] + d[2] * held[2]) - edge * (exhausted - even)
    out.amounts = developed_amounts(film, out.effective, share)
    return out

## Each layer's dye where it developed at effective log H `log_h`, `share` of the way
## through the development.
pub func developed_amounts(film: const Film*, log_h: f64[3], share: f64 = 1.0) -> f64[3]:
    var out: f64[3]
    for k in 0..<(usize)3:
        out[k] = film.curve(developed_row, k, log_h[k])
    if share < 1.0:
        # Part of the way: from the unexposed film's (a negative's fog, a
        # slide's most dye), grown as far as the kinetics say.
        let grown = progress(film, log_h, share)
        for k in 0..<(usize)3:
            let base = film.curve(developed_row, k, log_low)
            out[k] = base + (out[k] - base) * grown[k]
    return out

## How far each layer at log H `log_h` has developed `share` of the way through
## the development (film_develop.lucb's `progress`, from the atlas's values as
## the GPU reads them).
pub func progress(film: const Film*, log_h: f64[3], share: f64) -> f64[3]:
    let v52 = film.value(52)
    let v53 = film.value(53)
    let length = film.value(54)[0]
    var out: f64[3]
    for k in 0..<(usize)3:
        let whole = factor_at(v52[k], v53[k], log_h[k], v53[3], v52[3], length)
        out[k] = factor_at(v52[k], v53[k], log_h[k], v53[3], v52[3], length * math.clamp(share, 0.0, 1.0)) / math.max(whole, 1.0e-12)
    return out

func factor_at(saturation: f64, slope: f64, log_h: f64, grey: f64, start: f64, length: f64) -> f64:
    let u = saturation * math.pow(10.0, slope * (log_h - grey))
    let running = math.max(length - start, 0.0) / math.max(1.0 - start, 1.0e-9)
    return (1.0 - math.exp(-u * running)) / math.max(1.0 - math.exp(-u), 1.0e-12)

## A step of development at exposure `e` (film_stages.glsl's stage 8): from share
## `begun` to `reached` of the way through, the inhibitor each layer releases
## with the dye it forms in the step, held back by the inhibitor `held` the
## steps before released around it (on a slide the first developer's image),
## and fourth the developer it uses, `keep` of it still missing at the end
## (the bath renews the rest).
pub func release(film: const Film*, e: f64[3], held: f64[3], begun: f64, reached: f64, keep: f64) -> f64[4]:
    let log_h = log_exposure(film, e)
    let v17 = film.value(17)
    let forms = inhibiting(film, log_h, held)
    let after = progress(film, log_h, reached)
    let before = progress(film, log_h, begun)
    var out: f64[4]
    var used = 0.0
    for k in 0..<(usize)3:
        let grown = after[k] - before[k]
        out[k] = forms[k] * grown
        used += forms[k] / math.max(v17[k], 1.0e-9) * grown / 3.0
    out[3] = keep * used
    return out

## The negative as dye clouds, at (`x`, `y`) µm on it: one cloud per cell (the
## stock's spacing, or a pixel of `pitch` µm when that is wider) at a random place in it, each
## taking the developed film at its own centre (`field`, from `context`) plus
## its grain, the spread in how many of its grains developed (per population,
## `population_amplitudes`); the point is the clouds around it blended by Gaussians half a cell
## wide (the stock's width: Acros's are narrow, crisp). So the image is made of the clouds: nothing finer than them survives,
## and the grain follows what is on the negative. The second result is what
## inverting the grain would add on average, which the scan takes back off (the
## scan inverts density exponentially, so even grain would brighten each channel
## by exp((ln 10·γ⁻¹·σ)² / 2); a scanner averaging light over the grain does
## not; σ is the blend's spread at a point, 0.326 of the strength).
pub func clouded(film: const Film*, x: f64, y: f64, pitch: f64, field: func(void*, f64, f64) -> Developed, context: void*) -> (f64[3], f64[3]):
    let v6 = film.value(6)
    let v8 = film.value(8)
    let v18 = film.value(18)
    let cell = math.max(v18[0], pitch)
    let scale = v6[3] * grain_gain(cell, v18[2], v18[3])
    let kind = (i64)film.value(17)[3]
    let monochrome = kind == 2
    # One cell in, so the first cells' neighbours are not negative.
    let u = x / cell + 1.0
    let v = y / cell + 1.0
    let cx = (i64)math.floor(u)
    let cy = (i64)math.floor(v)
    var sum: f64[3] = [0.0, 0.0, 0.0]
    var spread: f64[3] = [0.0, 0.0, 0.0]
    var total = 0.0
    for dy in -1..=1:
        for dx in -1..=1:
            let kx = (u32)(cx + dx)
            let ky = (u32)(cy + dy)
            # Places in 1/256 of a cell, exact in single floats too.
            let px = (f64)(cx + dx) + math.floor(hashed(kx, ky) * 256.0) / 256.0
            let py = (f64)(cy + dy) + math.floor(hashed(kx +% 0x9e3779b9, ky) * 256.0) / 256.0
            let w = math.exp(-v18[1] * ((u - px) * (u - px) + (v - py) * (v - py)))
            let place = field(context, (px - 1.0) * cell, (py - 1.0) * cell)
            for k in 0..<(usize)3:
                # Black and white has one layer of silver: one grain for all three.
                let layer = (u32)k if not monochrome else 0
                # The cloud's grains, many per population: the share of them
                # developed at this exposure, P, is P plus the binomial spread
                # √(P(1 − P)) times a deviate fixed for the site and population
                # (the emulsion is one realization: more exposure or development
                # develops more of the same grains).
                var noise = 0.0
                var variance = 0.0
                for p in 0..<(usize)3:
                    let population = film.value(320 + k * 3 + p)
                    let share = 1.0 / (1.0 + math.exp(-(place.effective[k] - population[0]) / population[1]))
                    let index = layer *% 3 +% (u32)p
                    let first = hashed(kx +% index *% 7919, ky +% 0x85ebca6b +% index *% 104729)
                    let second = hashed(kx +% index *% 7919 +% 0x632be5ab, ky +% 0x85ebca6b +% index *% 104729)
                    let deviate = math.sqrt(-2.0 * math.log(math.max(first, 1.0e-7))) * math.cos(2.0 * math.pi * second)
                    let binomial = share * (1.0 - share)
                    noise += population[2] * math.sqrt(binomial) * deviate
                    variance += population[2] * population[2] * binomial
                # A slide's developed grains take dye away (the first developer's).
                let sign = -1.0 if kind == 1 else 1.0
                let corrected = film.curve(grain_row, k, place.effective[k]) * scale
                sum[k] += w * (place.amounts[k] + sign * noise * corrected)
                spread[k] += w * math.sqrt(3.0 * variance) * corrected
            total += w
    var amounts: f64[3]
    var unbias: f64[3]
    for k in 0..<(usize)3:
        amounts[k] = sum[k] / total
        let sigma = film.value(19)[0] * spread[k] / total
        # A slide's table is not inverted exponentially: nothing to take off.
        unbias[k] = 0.5 * 2.302585092994046 * v8[k] * sigma * sigma if kind != 1 else 0.0
    return (amounts, unbias)

## The silver a bypassed bleach leaves on a negative, as neutral density per unit
## of the dye's density over its fog. Labs' infrared readings put a fully
## unbleached print 1.8 over normal at a D-max near 4 (about 0.45); a negative
## forms about as much silver as dye (0.6–1.0): an estimate between them.
let silver_density: f64 = 0.8
## How much coarser the grain is with all the silver kept: the silver image's
## grain over the dye clouds' (an estimate, +30–60 % on print film).
let silver_grain: f64 = 0.4

## What each duplication between negative and print does (an interpositive, an
## internegative): blur, σ in µm on the negative, from the 2004 SMPTE study
## (camera negative 2100 lines per picture height, answer print 1400, release
## print through IP and IN 1000: two steps take 0.71 of the answer print's
## resolution, about 4.4 µm each on a 35 mm frame); grain, the intermediate's
## σD (0.004) against a negative's (0.008), squared; an optical step's
## grain, 1.3 times harder (an estimate from the Callier effect).
let generation_blur: f64 = 4.4
let generation_grain: f64 = 0.25
let optical_callier: f64 = 1.3
## A dye-transfer print's dye spread, σ in µm (about 20 µm wide at half height).
let dye_spread: f64 = 8.5

## The scanner's matrix from its channels to AP1, calibrated on a reference
## negative, Kodak Vision3 250D 5207 (today's ECN-2 dye set): `fit_matrix` for it
## at the default settings (the test below holds the two together). Through it,
## each stock shows the color its dyes, mask and interimage give it, as a
## telecine set up once shows each stock it runs.
let reference_scan: f64[9] = [0.5844744297270579, 0.3910015515880218, 0.024524018684920285,
                              0.0064365562204247275, 1.026855233362786, -0.033291789583210864,
                              -0.0016053762051531303, 0.2199420447155561, 0.7816633314895971]

## 2383's layers' contrast against the shape its curves share here (Kodak's
## graph runs them together where they could be read apart): Kodak matches
## them to its camera negatives so a normal grey scale prints neutral. Fitted
## so the reference negative, Vision3 250D 5207, does (`print_balance_of`; the
## test below holds them together); each stock then prints its own balance.
let print_balance: f64[3] = [1.0410326816317843, 0.9123142358797784, 1.0601060980601724]

## Edge effects in log H per unit of their strength (film_develop.lucb's share of
## a step added as overshoot). For a negative of gamma 0.6 whose dye is about 2
## at most, a step's border gains about 0.15 of the hold's difference: 1 / 0.15.
## An estimate, as the strengths are.
let edge_gain: f64 = 6.7

## Scanned densities `d` with the retained silver added (values row 20).
func silver(film: const Film*, d: f64[3]) -> f64[3]:
    let v20 = film.value(20)
    if v20[0] <= 0.0:
        return d
    let added = v20[0] * math.max((d[0] + d[1] + d[2]) / 3.0 - v20[1], 0.0)
    return [d[0] + added, d[1] + added, d[2] + added]

## Dye `amounts` scanned back to AP1, less `unbias` in density. `matrix` false
## skips the scan's matrix and the timing (for fitting the matrix).
pub func finish(film: const Film*, amounts: f64[3], unbias: f64[3], matrix: bool = true) -> f64[3]:
    return finish_density(film, scanned(film, amounts), unbias, matrix)

## What the scanner reads of dye `amounts` (the retained silver included): a
## negative's densities, a slide's asinh-encoded light.
pub func scanned(film: const Film*, amounts: f64[3]) -> f64[3]:
    return silver(film, film.scanned_lut(amounts, film.value(6)[1]))

## What a scanner reads from `light` (a negative's transmittance, a slide's
## light averaged over a pixel's area): density, or a slide's asinh encoding.
pub func reading_of(film: const Film*, light: f64[3]) -> f64[3]:
    if film.value(17)[3] == 1.0:
        return [asinh(256.0 * light[0]), asinh(256.0 * light[1]), asinh(256.0 * light[2])]
    return [-math.log10(math.max(light[0], 1.0e-30)), -math.log10(math.max(light[1], 1.0e-30)), -math.log10(math.max(light[2], 1.0e-30))]

func asinh(x: f64) -> f64:
    let magnitude = math.abs(x)
    return math.copysign(math.log(magnitude + math.sqrt(magnitude * magnitude + 1.0)), x)

## What the scanner read, `d` (`scanned`), back to AP1, less `unbias` in density.
pub func finish_density(film: const Film*, d: f64[3], unbias: f64[3], matrix: bool = true) -> f64[3]:
    let v8 = film.value(8)
    if film.value(17)[3] == 1.0:
        # A slide: scene light (asinh-encoded), Contrast a power about grey; the timing.
        let gains = film.value(10)
        var out: f64[3]
        for k in 0..<(usize)3:
            let grown = math.exp(d[k])
            let light = 0.5 * (grown - 1.0 / grown) / 256.0
            out[k] = 0.18 * math.pow(math.max(light, 0.0) / 0.18, v8[k]) * gains[k]
        return out
    let v7 = film.value(7)
    let v9 = film.value(9)
    var linear: f64[3]
    for k in 0..<(usize)3:
        let shown = 0.18 * math.pow(10.0, (d[k] - unbias[k] - v7[k]) * v8[k])
        linear[k] = (shown - v8[3] * v9[k]) / (1.0 - v8[3] * v9[k] / 0.18)
    if not matrix:
        return linear
    let m0 = film.value(11)
    let m1 = film.value(12)
    let m2 = film.value(13)
    let gains = film.value(10)
    return [math.max((m0[0] * linear[0] + m0[1] * linear[1] + m0[2] * linear[2]) * gains[0], 0.0),
            math.max((m1[0] * linear[0] + m1[1] * linear[1] + m1[2] * linear[2]) * gains[1], 0.0),
            math.max((m2[0] * linear[0] + m2[1] * linear[1] + m2[2] * linear[2]) * gains[2], 0.0)]

func same_everywhere(context: void*, x: f64, y: f64) -> Developed:
    _ = x
    _ = y
    return *(Developed*)context

## Exposure `e`, held back by `held`, where the negative is the same all around
## (a large even patch), grained at pixel (`x`, `y`) (centres, in pixels of
## `pitch` µm) and scanned back to AP1. `matrix` false skips the grain, the
## scan's matrix and the timing.
pub func scan(film: const Film*, e: f64[3], held: f64[3], exhausted: f64, x: f64, y: f64, pitch: f64, matrix: bool = true,
              share: f64 = 1.0) -> f64[3]:
    var here = developed(film, e, held, exhausted, share)
    if film.value(6)[3] > 0.0 and matrix:
        let (amounts, unbias) = clouded(film, x * pitch, y * pitch, pitch, same_everywhere, (void*)&here)
        return finish(film, amounts, unbias)
    return finish(film, here.amounts, [0.0, 0.0, 0.0], matrix)

## Scene light `c` through the film where nothing around it differs: what a
## large even patch gives (scatter and edges change nothing there; halation
## adds its even share), grained at pixel (`x`, `y`) of `pitch` µm.
pub func develop(film: const Film*, c: f64[3], x: f64, y: f64, pitch: f64, matrix: bool = true) -> f64[3]:
    let exposed = expose(film, c)
    let halo = film.value(15)
    let e = [exposed[0] * (1.0 + halo[0]), exposed[1] * (1.0 + halo[1]), exposed[2] * (1.0 + halo[2])]
    let (held, missing) = even_field(film, e)
    return scan(film, e, held, missing, x, y, pitch, matrix)

# mark: Tests =================================================================

test "a stock's model builds quickly":
    var settings = defaults_with_film()
    let started = time.now()
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    let built = time.now()
    settings.set(.film_interimage, 150.0)
    film.prepare(&settings) catch failure:
        assert(false)
        return
    print(f"film model: {(built - started) // 1000000} ms, settings: {(time.now() - built) // 1000000} ms")

test "grey comes back in place, and the ramp around it neutral with the film's toe and shoulder":
    var settings = defaults_with_film()
    settings.set(.film_grain, 0.0)
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    let grey = develop(&film, [0.18, 0.18, 0.18], 0.5, 0.5, 20.0)
    for k in 0..<(usize)3:
        assert(math.abs(grey[k] / 0.18 - 1.0) < 0.01)
    # Two stops either side stay within a quarter stop of themselves and of
    # neutral; four stops over, the shoulder holds them back.
    for value in [0.045, 0.72]:
        let shot = develop(&film, [value, value, value], 0.5, 0.5, 20.0)
        for k in 0..<(usize)3:
            assert(math.abs(math.log2(shot[k] / value)) < 0.35)
        assert(math.abs(math.log2(shot[0] / shot[1])) < 0.1 and math.abs(math.log2(shot[2] / shot[1])) < 0.1)
    let bright = develop(&film, [2.88, 2.88, 2.88], 0.5, 0.5, 20.0)
    assert(bright[1] < 2.88 and bright[1] > 1.8)

test "every stock builds, returns grey in place and keeps neutrals neutral":
    for choice in 1..=(i64)film_stocks.stock_count:
        var settings = defaults_with_film()
        settings.set(.film_stock, (f64)choice)
        settings.set(.film_grain, 0.0)
        # The curves and the scan's timing, without halation: on a stock with
        # no backing (CineStill) even an even field halates, a little red.
        settings.set(.film_halation, 0.0)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        defer film.release()
        let grey = develop(&film, [0.18, 0.18, 0.18], 0.5, 0.5, 20.0)
        let bright = develop(&film, [0.72, 0.72, 0.72], 0.5, 0.5, 20.0)
        print(f"{film_stocks.stock_at((usize)(choice - 1)).name}: grey {grey[0]} {grey[1]} {grey[2]}, +2 stops {bright[0]} {bright[1]} {bright[2]}")
        let stock = film_stocks.stock_at((usize)(choice - 1))
        for k in 0..<(usize)3:
            if stock.kind == 1:
                # A slide shows grey as the slide does, darker than a scan of a
                # negative brings it back, and steeper.
                assert(grey[k] < 0.18 and grey[k] > 0.08 and bright[k] / grey[k] > 4.0)
            else:
                assert(math.abs(grey[k] / 0.18 - 1.0) < 0.01)
        assert(math.abs(math.log2(grey[0] / grey[1])) < 0.1 and math.abs(math.log2(grey[2] / grey[1])) < 0.1)
        # Above grey a slide's layers part as its sheet's curves do (Velvia 100's
        # green falls faster: the magenta lean its highlights are known for;
        # E100's Status A curves, seen by the eye through its dyes, leave its
        # blue 0.19 stop behind two stops over).
        let apart = 0.2 if stock.kind == 1 else 0.1
        assert(math.abs(math.log2(bright[0] / bright[1])) < apart and math.abs(math.log2(bright[2] / bright[1])) < apart)

test "CineStill has no backing: its halation is red and far stronger than Vision3's":
    let still = film_stocks.stock_at(23)
    let vision = film_stocks.stock_at(6)
    assert(still.name == "CineStill 800T" and vision.name == "Kodak Vision3 500T 5219")
    let bare = film_halation.kernel(still.base_thickness, still.base_index, still.backing)
    let backed = film_halation.kernel(vision.base_thickness, vision.base_index, vision.backing)
    assert(still.backing == film_halation.no_backing)
    assert(bare.strength[0] > 10.0 * backed.strength[0])
    assert(bare.strength[0] > bare.strength[1] and bare.strength[1] > bare.strength[2])

test "film saturates warm colors and keeps their hue near":
    # A scan matched to its stock, so colors of moderate saturation come back.
    var settings = defaults_with_film()
    settings.set(.film_grain, 0.0)
    settings.set(.scan_calibration, 1.0)
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    # A skin-like AP1 color at middle grey's luminance.
    let skin: f64[3] = [0.26, 0.16, 0.11]
    let shot = develop(&film, skin, 0.5, 0.5, 20.0)
    let spread_in = skin[0] - skin[2]
    let spread_out = shot[0] - shot[2]
    assert(spread_out > spread_in * 0.95)
    assert(shot[0] > shot[1] and shot[1] > shot[2])

test "through the reference scanner each stock keeps its own color":
    # Skin's red-blue spread against the scene's: Vision3 50D's saturated dyes
    # against EXR 200T's, as one telecine set up on Vision3 250D shows them.
    let skin: f64[3] = [0.26, 0.16, 0.11]
    var spreads: f64[2]
    for (at, choice) in [((usize)0, 10.0), ((usize)1, 2.0)]:
        var settings = defaults_with_film()
        settings.set(.film_stock, choice)
        settings.set(.film_grain, 0.0)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        let shot = develop(&film, skin, 0.5, 0.5, 20.0)
        film.release()
        spreads[at] = (shot[0] - shot[2]) / (skin[0] - skin[2])
    # (0.95 against 0.73: interimage releases inhibitor with the dye actually
    # formed, a little gentler than with the dye unheld.)
    assert(spreads[0] > spreads[1] + 0.2)

test "grain averages out and follows the stock's granularity":
    var settings = defaults_with_film()
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    var sum = 0.0
    var squares = 0.0
    let count = 4000
    for at in 0..<count:
        let shot = develop(&film, [0.18, 0.18, 0.18], (f64)(at % 200) + 0.5, (f64)(at // 200) + 0.5, 3.7)
        sum += shot[1]
        squares += shot[1] * shot[1]
    let mean = sum / (f64)count
    let deviation = math.sqrt(squares / (f64)count - mean * mean)
    assert(math.abs(mean / 0.18 - 1.0) < 0.05)
    assert(deviation > 0.002 and deviation < 0.05)

test "grain leaves a patch's average color where it was":
    var means: f64[6]
    for (index, grain) in [0.0, 150.0].indexed():
        var settings = defaults_with_film()
        settings.set(.film_grain, grain)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        defer film.release()
        var sum: f64[3] = [0.0, 0.0, 0.0]
        for at in 0..<(usize)4000:
            let shot = develop(&film, [0.18, 0.144, 0.108], (f64)(at % 200) + 0.5, (f64)(at // 200) + 0.5, 31.0)
            for k in 0..<(usize)3:
                sum[k] += shot[k] / 4000.0
        for k in 0..<(usize)3:
            means[index * 3 + k] = sum[k]
    for k in 0..<(usize)3:
        assert(math.abs(means[3 + k] / means[k] - 1.0) < 0.04)

test "grain through a 48 µm aperture reads its granularity, soft clouds or crisp":
    for choice in [1.0, 6.0]:
        var settings = defaults_with_film()
        settings.set(.film_stock, choice)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        defer film.release()
        # An even patch at grey, sampled every 2 µm, through 21 × 21 samples (42 µm):
        # the green layer's density spread against its granularity there.
        let e = expose(&film, [0.18, 0.18, 0.18])
        let held = neutral(&film, e)
        var here = developed(&film, e, held, exhaustion(&film, held))
        # The published rms granularity there (normal development, as here).
        let wanted = along_model(film.model.grain, here.effective[1])[1]
        var sum = 0.0
        var squares = 0.0
        let blocks = 30
        for by in 0..<blocks:
            for bx in 0..<blocks:
                var mean = 0.0
                for y in 0..<21:
                    for x in 0..<21:
                        let (amounts, _) = clouded(&film, (f64)(bx * 21 + x) * 2.0, (f64)(by * 21 + y) * 2.0, 2.0, same_everywhere, (void*)&here)
                        mean += (amounts[1] - here.amounts[1]) / 441.0
                sum += mean
                squares += mean * mean
        let count = (f64)(blocks * blocks)
        let deviation = math.sqrt(squares / count - (sum / count) * (sum / count))
        print(f"grain through 42 µm: {deviation / wanted} of the granularity")
        assert(math.abs(deviation / wanted - 1.0) < 0.12)

test "tungsten film in daylight goes blue, an 85 brings it back":
    var settings = defaults_with_film()
    settings.set(.film_grain, 0.0)
    var shown: f64[9]
    for (index, filter) in [0.0, 1.0, 2.0].indexed():
        settings.set(.film_filter, filter)
        var film = Film()
        film.prepare(&settings, Input(shot_kelvin = 5500.0)) catch failure:
            assert(false)
            return
        defer film.release()
        let grey = develop(&film, [0.18, 0.18, 0.18], 0.5, 0.5, 20.0)
        for k in 0..<(usize)3:
            shown[index * 3 + k] = grey[k]
    # Matched: neutral. None: blue. 85: near neutral again, two thirds of a stop darker.
    assert(math.abs(math.log2(shown[2] / shown[0])) < 0.05)
    assert(shown[5] / shown[3] > 1.4)
    assert(math.abs(math.log2(shown[8] / shown[6])) < 0.25)
    let darker = math.log2(shown[7] / shown[1])
    assert(darker < -0.4 and darker > -1.0)

test "a red filter on black and white darkens blue sky and lightens red, grey staying put":
    var shots: f64[9]
    for (index, filter) in [0.0, 3.0].indexed():
        var settings = defaults_with_film()
        settings.set(.film_stock, 6.0)
        settings.set(.film_grain, 0.0)
        settings.set(.film_color_filter, filter)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        defer film.release()
        shots[index * 4] = develop(&film, [0.05, 0.12, 0.30], 0.5, 0.5, 20.0)[1]
        shots[index * 4 + 1] = develop(&film, [0.35, 0.06, 0.05], 0.5, 0.5, 20.0)[1]
        shots[index * 4 + 2] = develop(&film, [0.18, 0.18, 0.18], 0.5, 0.5, 20.0)[1]
    assert(shots[4] < shots[0] * 0.6)
    assert(shots[5] > shots[1] * 1.5)
    assert(math.abs(math.log2(shots[6] / shots[2])) < 0.2)

test "every format films a grey card (IMAX's frame fits the atlas)":
    for format in 0..<(usize)6:
        var settings = defaults()
        settings.set(.film_stock, 9.0)
        settings.set(.film_format, (f64)format)
        var made = Film()
        made.prepare(&settings) catch failure:
            assert(false)
            return
        defer made.release()
        let out = develop(&made, [0.18, 0.18, 0.18], 10.0, 10.0, 20.0)
        for k in 0..<(usize)3:
            assert(out[k] > 0.05 and out[k] < 1.0)

## The scanned red density of a large even field where the layers'
## exposures are `e` (relative, 0.18 grey), developed with each other's
## inhibitor (interimage).
func red_density(film: const Film*, e: f64[3]) -> f64:
    let (held, missing) = even_field(film, e)
    let here = developed(film, e, held, missing)
    return film.density_read(here.amounts)[0]

test "interimage makes a single colour steeper than a neutral, as colour negatives are":
    # Vision3 250D: the red record's gamma (scanned density per log H, ±0.3
    # about grey) exposed with the others (a grey scale) and alone (the others
    # held at grey). With the others developing too, their inhibitor holds the
    # red back; alone it develops freely: the "gamma ratio" of colour
    # negatives, 1.0–1.3 (research: docs/PHYSICAL-FILM.md, part 4).
    var settings = defaults()
    settings.set(.film_stock, 9.0)
    var made = Film()
    made.prepare(&settings) catch failure:
        assert(false)
        return
    defer made.release()
    let low = 0.18 * math.pow(10.0, -0.3)
    let high = 0.18 * math.pow(10.0, 0.3)
    let neutral_gamma = (red_density(&made, [high, high, high]) - red_density(&made, [low, low, low])) / 0.6
    let alone_gamma = (red_density(&made, [high, 0.18, 0.18]) - red_density(&made, [low, 0.18, 0.18])) / 0.6
    print(f"Vision3 250D red gamma: neutral {neutral_gamma}, alone {alone_gamma}, ratio {alone_gamma / neutral_gamma}")
    assert(alone_gamma / neutral_gamma > 1.0 and alone_gamma / neutral_gamma < 1.3)

test "every stock's grains make its published granularity":
    # The stochastic render's fitted grains (Campbell's variance of the field)
    # against each stock's granularity, in its layers' dye, across its curve
    # (toe to shoulder, where the dye is a tenth to nine tenths of its range).
    var worst = 0.0
    for stock in 1..=film_stocks.stock_count:
        var settings = defaults()
        settings.set(.film_stock, (f64)stock)
        var made = Film()
        made.prepare(&settings) catch failure:
            assert(false)
            return
        defer made.release()
        made.fit_grains() catch failure:
            assert(false)
            return
        let layers: usize = 1 if made.value(17)[3] == 2.0 else 3
        for layer in 0..<layers:
            var low = 1.0e9
            var high = -1.0e9
            for at in 0..<curve_samples:
                let v = made.curve(developed_row, layer, log_h_at(at))
                low = math.min(low, v)
                high = math.max(high, v)
            for at in 0..<curve_samples:
                if at % 16 != 0:
                    continue
                let h = log_h_at(at)
                let v = made.curve(developed_row, layer, h)
                if v < low + 0.1 * (high - low) or v > low + 0.9 * (high - low):
                    continue
                let amounts = [made.curve(developed_row, 0, h), made.curve(developed_row, 1, h), made.curve(developed_row, 2, h)]
                let slopes = made.scan_slopes(amounts)
                let own = slopes[0] + slopes[3] + slopes[6] if layers == 1 else slopes[layer * 4]
                let wanted = made.granularity_at(layer, h) / math.max(own, 0.05)
                let fitted = made.grain_granularity(layer, h)
                if wanted > 1.0e-4:
                    worst = math.max(worst, math.abs(fitted / wanted - 1.0))
    # All within a few percent but one: Vision 500T 5279's green toe, where the
    # fit's populations develop out of order and the fast clouds are not large
    # enough at their densest (18 %: docs/PHYSICAL-FILM.md, part 5).
    print(f"grain fit: worst {worst * 100.0} % from the published granularity")
    assert(worst < 0.2)

func defaults_with_film() -> Settings:
    var out = defaults()
    out.set(.film_stock, 1.0)
    return out

test "the reference scanner is Vision3 250D's fit":
    var settings = defaults_with_film()
    settings.set(.film_stock, 9.0)
    settings.set(.film_grain, 0.0)
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    assert(film_stocks.stock_at(8).name == "Kodak Vision3 250D 5207")
    let fitted = film.fit_matrix()
    var close = true
    for at in 0..<(usize)9:
        close = close and math.abs(fitted[at] - reference_scan[at]) < 0.002
    if not close:
        # What to put in reference_scan when the exposure or the scan changed.
        print(f"reference_scan: {fitted[0]}, {fitted[1]}, {fitted[2]}, {fitted[3]}, {fitted[4]}, {fitted[5]}, {fitted[6]}, {fitted[7]}, {fitted[8]}")
    assert(close)

test "2383's layers are balanced to print Vision3 250D's grey scale neutral":
    var settings = defaults_with_film()
    settings.set(.film_stock, 9.0)
    settings.set(.film_grain, 0.0)
    settings.recipe = recipe.mode(1)
    settings.set(.view, (f64)(i64)View.print)
    var film = Film()
    film.prepare(&settings) catch failure:
        assert(false)
        return
    defer film.release()
    assert(film.printing == onto_print)
    let fitted = film.print_balance_of()
    var close = true
    for at in 0..<(usize)3:
        close = close and math.abs(fitted[at] - print_balance[at]) < 0.002
    if not close:
        # What to put in print_balance when the negative's model changed.
        print(f"print_balance: {fitted[0]}, {fitted[1]}, {fitted[2]}")
    assert(close)
    # A grey scale on it prints neutral (printing density over grey, per stop).
    for k in [-3.0, -1.0, 1.0, 3.0]:
        let v = 0.18 * math.exp2(k)
        let out = develop(&film, [v, v, v], 0.5, 0.5, 20.0)
        assert(math.abs(math.log2(out[0] / out[1])) < 0.08 and math.abs(math.log2(out[2] / out[1])) < 0.08)

test "a push develops more of the same grains: its grain follows the normal one's":
    var noises: f64[800]
    for (index, minutes) in [0.0, 5.0].indexed():
        var settings = defaults_with_film()
        settings.set(.film_stock, 3.0)
        settings.set(.develop_time, minutes)
        var film = Film()
        film.prepare(&settings) catch failure:
            assert(false)
            return
        defer film.release()
        let e = expose(&film, [0.09, 0.09, 0.09])
        let held = neutral(&film, e)
        var here = developed(&film, e, held, even_exhaustion(&film, e))
        for at in 0..<400:
            let (amounts, _) = clouded(&film, (f64)(at % 20) * 3.0, (f64)(at // 20) * 3.0, 3.0, same_everywhere, (void*)&here)
            noises[(usize)index * 400 + (usize)at] = amounts[1] - here.amounts[1]
    var ab = 0.0
    var aa = 0.0
    var bb = 0.0
    for at in 0..<400:
        ab += noises[at] * noises[400 + at]
        aa += noises[at] * noises[at]
        bb += noises[400 + at] * noises[400 + at]
    let correlation = ab / math.sqrt(aa * bb)
    print(f"grain normal against pushed: correlation {correlation}")
    assert(correlation > 0.7)