use kallo_spectral::{DictionaryUpsampler, PolynomialUpsampler, Sensor, Spectrum, Upsampler};
use crate::model::{ExposureModel, inverse3, tables};
pub const GRID_START_NM: f64 = 380.0;
pub const GRID_STEP_NM: f64 = 5.0;
pub const GRID_LEN: usize = 71;
#[derive(Debug, Clone, Default)]
pub enum CameraProfile {
#[default]
Srgb,
Generic,
Observer,
Measured(Sensor),
}
impl CameraProfile {
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::Srgb => "srgb-primaries",
Self::Generic => "generic-camera",
Self::Observer => "cie1931-approx",
Self::Measured(sensor) => sensor.name(),
}
}
#[must_use]
pub fn sensor(&self, grid: &kallo_spectral::Spectrum) -> Sensor {
match self {
Self::Srgb => Sensor::srgb(grid),
Self::Generic => Sensor::generic_camera(grid),
Self::Observer => Sensor::cie1931(grid),
Self::Measured(sensor) => sensor.resampled(grid),
}
}
}
#[derive(Debug, Clone)]
pub struct SpectralContext {
grid: Spectrum,
camera: Sensor,
film: Sensor,
upsampler: PolynomialUpsampler,
dictionary: Option<DictionaryUpsampler>,
threshold: f64,
reference: [f64; 3],
extra: Option<[f64; GRID_LEN]>,
}
impl Default for SpectralContext {
fn default() -> Self {
Self::new()
}
}
impl SpectralContext {
#[must_use]
pub fn new() -> Self {
Self::for_layers("vision3_500t", &kallo_spectral::layers::CHANNELS)
}
#[must_use]
pub fn for_stock(stock: &crate::emulsion::FilmStock) -> Self {
let mut context = Self::for_layers(stock.id, stock.layers);
let peak = stock
.layers
.iter()
.flat_map(|table| table.iter())
.fold(0.0_f64, |a, &b| a.max(b));
context.extra = stock
.extra_cyan
.and_then(|emulsion| sensitivity_table(&context.grid, emulsion.sensitivity, peak))
.or_else(|| stock.cl_layer.map(|layer| *layer.sensitivity));
context
}
#[must_use]
fn for_layers(name: &str, layers: &[[f64; GRID_LEN]; 3]) -> Self {
let grid = Spectrum::uniform(GRID_START_NM, GRID_STEP_NM, GRID_LEN)
.expect("the internal grid is a valid constant");
let camera = CameraProfile::default().sensor(&grid);
let film = Sensor::film_layers_from(&grid, name, layers);
let upsampler = PolynomialUpsampler;
let mut context = Self {
grid,
camera,
film,
upsampler,
dictionary: None,
threshold: 0.02,
reference: [1.0; 3],
extra: None,
};
context.refresh_reference();
context
}
fn refresh_reference(&mut self) {
let grey = self
.reconstruct([0.18; 3])
.unwrap_or_else(|| Spectrum::filled(self.grid.clone(), 0.0));
self.reference = self.film.respond(&grey);
}
#[must_use]
pub fn with_atoms(mut self, atoms: &[Spectrum]) -> Self {
let resampled: Vec<Spectrum> = atoms
.iter()
.map(|atom| atom.resampled(&self.grid))
.collect();
if !resampled.is_empty() {
self.dictionary = Some(DictionaryUpsampler::new(resampled));
self.refresh_reference();
}
self
}
#[must_use]
pub fn with_camera(mut self, camera: CameraProfile) -> Self {
self.camera = camera.sensor(&self.grid);
self.refresh_reference();
self
}
#[must_use]
pub fn with_threshold(mut self, threshold: f64) -> Self {
self.threshold = threshold.max(0.0);
self
}
#[must_use]
pub fn has_dictionary(&self) -> bool {
self.dictionary.is_some()
}
#[must_use]
pub fn identity(&self) -> String {
format!(
"camera={};film={};grid={}:{}:{}",
self.camera.name(),
self.film.name(),
self.grid.start_nm(),
self.grid.step_nm(),
self.grid.len()
)
}
#[must_use]
pub fn grid(&self) -> &Spectrum {
&self.grid
}
#[must_use]
pub fn camera(&self) -> &Sensor {
&self.camera
}
#[must_use]
pub fn film(&self) -> &Sensor {
&self.film
}
#[must_use]
pub fn reference(&self) -> [f64; 3] {
self.reference
}
#[must_use]
pub fn model(&self) -> Option<ExposureModel> {
if self.has_dictionary() {
return None;
}
let basis = PolynomialUpsampler::basis(&self.grid);
let system = self.upsampler.system(&self.camera, &self.grid).ok()?;
Some(ExposureModel {
reconstruct: inverse3(system).unwrap_or([[0.0; 3]; 3]),
basis: tables(&basis)?,
film: tables(self.film.channels())?,
reference: self.reference,
})
}
#[must_use]
pub fn expose(&self, linear: [f64; 3]) -> Option<[f64; 3]> {
self.expose_with_extra(linear).map(|(layers, _)| layers)
}
#[must_use]
pub fn expose_with_extra(&self, linear: [f64; 3]) -> Option<([f64; 3], Option<f64>)> {
let spectrum = self.reconstruct(linear)?;
let radiance = spectrum.values();
let response = self.film.respond(&spectrum);
let layers = std::array::from_fn(|channel| {
let normalised = response[channel] * 0.18 / self.reference[channel].max(1e-12);
normalised.max(1e-10).log10()
});
let extra = self.extra.map(|sensitivity| {
let total = sensitivity
.iter()
.zip(radiance)
.map(|(sensitivity, radiance)| sensitivity * radiance)
.sum::<f64>()
* self.grid.step_nm();
let normalised = total * 0.18 / self.reference[2].max(1e-12);
normalised.max(1e-10).log10()
});
Some((layers, extra))
}
}
fn sensitivity_table(grid: &Spectrum, sensitivity: &[f32], peak: f64) -> Option<[f64; GRID_LEN]> {
if sensitivity.is_empty() || peak <= 0.0 {
return None;
}
let mut table = Spectrum::uniform(
crate::dye::SENSITIVITY_START_NM,
crate::dye::SENSITIVITY_STEP_NM,
sensitivity.len(),
)
.ok()?;
for (slot, value) in table.values_mut().iter_mut().zip(sensitivity) {
*slot = f64::from(*value) / peak;
}
crate::model::table(&table.resampled(grid))
}
impl SpectralContext {
fn reconstruct(&self, linear: [f64; 3]) -> Option<Spectrum> {
if let Some(dictionary) = &self.dictionary {
let candidate = dictionary
.reconstruct(&linear, &self.camera, &self.grid)
.ok()?;
let measured = self.camera.respond(&candidate);
let residual: f64 = (0..3)
.map(|index| (measured[index] - linear[index]).powi(2))
.sum::<f64>()
.sqrt();
let scale: f64 = (0..3)
.map(|index| linear[index].powi(2))
.sum::<f64>()
.sqrt()
.max(1e-9);
if residual / scale <= self.threshold {
return Some(candidate);
}
}
self.upsampler
.reconstruct(&linear, &self.camera, &self.grid)
.ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mid_grey_stays_at_mid_grey() {
let context = SpectralContext::new();
let log_e = context.expose([0.18, 0.18, 0.18]).unwrap();
let expected = 0.18_f64.log10();
for channel in log_e {
assert!((channel - expected).abs() < 1e-6, "{channel} vs {expected}");
}
}
#[test]
fn the_default_camera_gives_back_the_colour_it_was_handed() {
let context = SpectralContext::new();
for linear in [
[0.18, 0.18, 0.18],
[0.9, 0.1, 0.1],
[0.1, 0.1, 0.9],
[0.4, 0.3, 0.2],
] {
let spectrum = context.reconstruct(linear).expect("polynomial solves");
let back = context.camera().respond(&spectrum);
for channel in 0..3 {
assert!(
(back[channel] - linear[channel]).abs() < 1e-6,
"{linear:?} came back as {back:?}"
);
}
}
}
#[test]
fn a_saturated_green_exceeds_what_the_smooth_prior_can_hold() {
let context = SpectralContext::new();
let linear = [0.1, 0.9, 0.1];
let spectrum = context.reconstruct(linear).expect("polynomial solves");
let back = context.camera().respond(&spectrum);
assert!(spectrum.min() >= 0.0, "reflectance went negative");
assert!(
back[0] > 0.2,
"expected the clamp to lift red above 0.2, got {back:?}"
);
}
#[test]
fn a_saturated_colour_separates_the_layers() {
let context = SpectralContext::new();
let log_e = context.expose([0.9, 0.1, 0.1]).unwrap();
assert!(log_e[0] > log_e[2], "{log_e:?}");
assert!((log_e[0] - log_e[2]) > 0.05, "no separation: {log_e:?}");
}
#[test]
fn a_dictionary_is_used_when_it_covers_the_colour() {
let context = SpectralContext::new();
let atoms: Vec<Spectrum> = [0.18_f64, 0.4, 0.05]
.iter()
.map(|level| {
context
.upsampler
.reconstruct(&[*level; 3], context.camera(), context.grid())
.unwrap()
})
.collect();
let with_dictionary = context.with_atoms(&atoms);
assert!(with_dictionary.has_dictionary());
let neutral = with_dictionary.expose([0.18; 3]).unwrap();
assert!((neutral[0] - 0.18_f64.log10()).abs() < 1e-6);
}
#[test]
fn exposure_is_monotonic() {
let context = SpectralContext::new();
let mut previous = f64::NEG_INFINITY;
for step in 0..40 {
let value = 0.001 * 1.2_f64.powi(step);
let log_e = context.expose([value; 3]).unwrap()[1];
assert!(log_e > previous, "not monotonic at {value}");
previous = log_e;
}
}
}