use crate::emulsion::FilmStock;
#[derive(Debug, Clone)]
pub struct GrainField {
pub width: usize,
pub height: usize,
pub pixel_area_um2: f64,
pub grains_per_um2: [f64; 3],
pub seed: u64,
pub monochrome: bool,
pub grain_um: [f64; 3],
pub radius: [usize; 3],
pub weights: [[f64; Self::STENCIL]; 3],
}
impl GrainField {
const STENCIL: usize = 5;
const STENCIL_NARROWING: f64 = 0.74;
pub const CENTRE: usize = 2;
pub const DEFAULT_GRAINS_PER_UM2: f64 = 3.6;
#[must_use]
pub fn new(width: usize, height: usize, frame_mm: f64, seed: u64) -> Self {
let pixel_mm = frame_mm.max(1e-9) / width.max(1) as f64;
let pixel_um = pixel_mm * 1000.0;
Self {
width,
height,
pixel_area_um2: pixel_um * pixel_um,
grains_per_um2: [Self::DEFAULT_GRAINS_PER_UM2; 3],
seed,
monochrome: false,
grain_um: [0.0; 3],
radius: [0; 3],
weights: [[0.0; Self::STENCIL]; 3],
}
.with_grain_sizes(Self::spacing_of(&[Self::DEFAULT_GRAINS_PER_UM2; 3]))
}
#[must_use]
pub fn for_stock(
width: usize,
height: usize,
frame_mm: f64,
seed: u64,
stock: &FilmStock,
) -> Self {
Self {
grains_per_um2: stock.grains_per_um2,
monochrome: stock.process == crate::emulsion::FilmProcess::Monochrome,
..Self::new(width, height, frame_mm, seed)
}
.with_grain_sizes(Self::spacing_of(&stock.grains_per_um2))
}
#[must_use]
pub fn spacing_of(grains_per_um2: &[f64; 3]) -> [f64; 3] {
std::array::from_fn(|layer| {
let n = grains_per_um2[layer];
if n > 0.0 { 1.0 / n.sqrt() } else { 0.0 }
})
}
#[must_use]
pub fn with_grain_sizes(mut self, grain_um: [f64; 3]) -> Self {
self.grain_um = grain_um;
let pixel_um = self.pixel_area_um2.sqrt().max(1e-9);
for (layer, &diameter) in grain_um.iter().enumerate() {
let sigma_px =
diameter.max(0.0) / (std::f64::consts::SQRT_2 * Self::STENCIL_NARROWING) / pixel_um;
let radius = if sigma_px < 0.1 {
0
} else {
(3.0 * sigma_px).ceil().min((Self::STENCIL / 2) as f64) as usize
};
self.radius[layer] = radius;
let mut weights = [0.0; Self::STENCIL];
if radius == 0 {
weights[Self::CENTRE] = 1.0;
} else {
for (tap, weight) in weights.iter_mut().enumerate() {
let offset = tap as f64 - Self::CENTRE as f64;
if offset.abs() <= radius as f64 {
*weight = (-0.5 * (offset / sigma_px).powi(2)).exp();
}
}
let norm: f64 = weights.iter().map(|weight| weight * weight).sum::<f64>();
let norm = norm.sqrt();
for weight in &mut weights {
*weight /= norm;
}
let mut per_axis = 0.0;
for lag in 0..=radius {
let mut pair = 0.0;
for tap in 0..(Self::STENCIL - lag) {
pair += weights[tap] * weights[tap + lag];
}
per_axis += if lag == 0 { pair } else { 2.0 * pair };
}
let amplitude = 1.0 / per_axis.sqrt();
for weight in &mut weights {
*weight *= amplitude;
}
}
self.weights[layer] = weights;
}
self
}
#[must_use]
pub fn has_kernel(&self) -> bool {
self.radius.iter().any(|&radius| radius > 0)
}
#[must_use]
pub fn sigma(&self, density: f64, channel: usize) -> f64 {
let covered = 1.0 - 10.0_f64.powf(-density.max(0.0));
let grains = self.grains_per_um2[channel].max(0.0) * self.pixel_area_um2 * covered;
1.0 / (std::f64::consts::LN_10 * (grains + 1.0).sqrt())
}
#[must_use]
pub fn jitter(&self, x: usize, y: usize, mean_density: f64, channel: usize) -> f64 {
let record = if self.monochrome { 0 } else { channel };
self.sigma(mean_density, record) * self.correlated(x, y, record)
}
fn correlated(&self, x: usize, y: usize, channel: usize) -> f64 {
let radius = self.radius[channel];
if radius == 0 {
return self.normal(x, y, channel);
}
let weights = &self.weights[channel];
let reach = radius as isize;
let mut sum = 0.0;
for dy in -reach..=reach {
let row = clamp(y, dy, self.height);
let wy = weights[(dy + Self::CENTRE as isize) as usize];
for dx in -reach..=reach {
let column = clamp(x, dx, self.width);
sum += wy
* weights[(dx + Self::CENTRE as isize) as usize]
* self.normal(column, row, channel);
}
}
sum
}
fn normal(&self, x: usize, y: usize, channel: usize) -> f64 {
let channel = if self.monochrome { 0 } else { channel };
let u1 = self.uniform(x, y, channel, 0);
let u2 = self.uniform(x, y, channel, 1);
(-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}
const UNIFORM_BITS: u64 = 23;
fn uniform(&self, x: usize, y: usize, channel: usize, lane: u64) -> f64 {
let mut state = self.seed.wrapping_mul(0xD6E8_FEB8_6659_FD93)
^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F)
^ (channel as u64).wrapping_mul(0x1656_67B1_9E37_79F9)
^ lane.wrapping_mul(0x2545_F491_4F6C_DD1D);
let bits = splitmix64(&mut state) >> (64 - Self::UNIFORM_BITS);
(bits as f64 + 0.5) * (1.0 / (1u64 << Self::UNIFORM_BITS) as f64)
}
}
fn clamp(value: usize, offset: isize, limit: usize) -> usize {
let shifted = value as isize + offset;
shifted.clamp(0, limit.saturating_sub(1) as isize) as usize
}
fn splitmix64(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wide_grain_correlates_its_neighbours() {
let field = GrainField::new(7040, 100, 36.0, 3).with_grain_sizes([10.0; 3]);
assert!(
field.has_kernel(),
"a 10 µm grain must be wider than a pixel"
);
let (mut sum_lag, mut sum_sq, mut count) = (0.0, 0.0, 0.0);
for y in 10..90 {
for x in 10..4000 {
let here = field.jitter(x, y, 1.0, 0);
let right = field.jitter(x + 1, y, 1.0, 0);
sum_lag += here * right;
sum_sq += here * here;
count += 1.0;
}
}
let lag_one = (sum_lag / count) / (sum_sq / count);
assert!(
lag_one > 0.2,
"neighbouring pixels should agree, lag-1 correlation {lag_one}"
);
let narrow = GrainField::new(7040, 100, 36.0, 3).with_grain_sizes([0.3; 3]);
assert!(
!narrow.has_kernel(),
"a third of a micrometre is a delta here"
);
}
#[test]
fn a_wide_aperture_sees_the_counting_statistics_with_or_without_a_stencil() {
let frame_mm = 400.0 * 4.8 / 1000.0;
let flat = GrainField::new(400, 400, frame_mm, 11).with_grain_sizes([0.02; 3]);
let clumped = GrainField::new(400, 400, frame_mm, 11).with_grain_sizes([3.5; 3]);
assert!(clumped.has_kernel(), "3.5 µm is wider than a pixel here");
let expected = clumped.sigma(1.0, 0) * 4.8 / 48.0;
for field in [&flat, &clumped] {
let measured = aperture_rms(field, 10);
assert!(
(measured / expected - 1.0).abs() < 0.1,
"48 µm granularity {measured:.4e}, expected {expected:.4e}"
);
}
let share: f64 = clumped.weights[0].iter().map(|w| w * w).sum();
let per_pixel = aperture_rms(&clumped, 1) / clumped.sigma(1.0, 0);
assert!(
(share - per_pixel).abs() < 0.01,
"the taps say {share:.3} per pixel, the field draws {per_pixel:.3}"
);
}
#[test]
fn the_stencil_says_how_much_of_the_counting_statistics_one_pixel_keeps() {
let field = GrainField::new(7040, 8, 36.0, 3).with_grain_sizes([3.5; 3]);
let share: f64 = field.weights[0].iter().map(|w| w * w).sum();
assert!(
(share - 0.445).abs() < 0.01,
"a 3.5 µm clump at 5.11 µm per pixel keeps {share:.3}, not 0.445"
);
let finer = GrainField::new(7040, 8, 12.0, 3).with_grain_sizes([3.5; 3]);
let finer_share: f64 = finer.weights[0].iter().map(|w| w * w).sum();
assert!(
finer_share < share,
"finer pixels keep less: {finer_share:.3} vs {share:.3}"
);
}
fn aperture_rms(field: &GrainField, block: usize) -> f64 {
let mut sums = Vec::new();
let mut y = block;
while y + block < field.height {
let mut x = block;
while x + block < field.width {
let mut sum = 0.0;
for dy in 0..block {
for dx in 0..block {
sum += field.jitter(x + dx, y + dy, 1.0, 0);
}
}
sums.push(sum / (block * block) as f64);
x += block;
}
y += block;
}
let mean = sums.iter().sum::<f64>() / sums.len() as f64;
let variance = sums.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / sums.len() as f64;
variance.sqrt()
}
#[test]
fn a_silver_film_draws_one_grain_field() {
let mut field = GrainField::new(8, 8, 36.0, 7);
field.monochrome = true;
for y in 0..8 {
for x in 0..8 {
let red = field.jitter(x, y, 1.0, 0);
assert_eq!(
red,
field.jitter(x, y, 1.0, 1),
"layer 1 differs at {x},{y}"
);
assert_eq!(
red,
field.jitter(x, y, 1.0, 2),
"layer 2 differs at {x},{y}"
);
}
}
field.monochrome = false;
assert_ne!(
field.jitter(3, 4, 1.0, 0),
field.jitter(3, 4, 1.0, 1),
"a colour film's layers are separate emulsions"
);
}
fn field(pixel_area: f64) -> GrainField {
GrainField {
monochrome: false,
width: 4,
height: 4,
pixel_area_um2: pixel_area,
grains_per_um2: [GrainField::DEFAULT_GRAINS_PER_UM2; 3],
seed: 7,
grain_um: [0.0; 3],
radius: [0; 3],
weights: [[0.0; GrainField::STENCIL]; 3],
}
}
#[test]
fn sigma_follows_the_aperture_area() {
let big = field(2300.0); let half = field(1150.0);
let ratio = half.sigma(1.0, 0) / big.sigma(1.0, 0);
assert!((ratio - 2.0_f64.sqrt()).abs() < 0.02, "ratio {ratio}");
}
#[test]
fn sigma_is_largest_where_fewest_grains_have_developed() {
let field = field(36.0);
assert!(field.sigma(0.0, 0) > field.sigma(1.0, 0));
assert!(field.sigma(1.0, 0) > field.sigma(3.0, 0));
}
#[test]
fn the_fallback_density_is_the_order_of_a_real_grain_count() {
let field = field(2300.0);
let sigma = field.sigma(1.0, 0);
assert!(
(0.002..0.008).contains(&sigma),
"sigma {sigma} at a 48 µm aperture"
);
}
#[test]
fn the_same_seed_draws_the_same_grain() {
let a = field(36.0);
let b = field(36.0);
assert_eq!(a.jitter(2, 3, 1.0, 0), b.jitter(2, 3, 1.0, 0));
assert_ne!(a.jitter(2, 3, 1.0, 0), a.jitter(2, 3, 1.0, 1));
assert_ne!(a.jitter(2, 3, 1.0, 0), a.jitter(3, 3, 1.0, 0));
}
#[test]
fn the_fluctuation_has_no_bias() {
let field = field(36.0);
let n = 20_000;
let mut sum = 0.0;
for index in 0..n {
sum += field.normal(index % 500, index / 500, 0);
}
let mean = sum / n as f64;
assert!(mean.abs() < 0.03, "mean {mean}");
}
}