1use kallo_spectral::Spectrum;
16use kallo_spectral::sensor::cie1931_xyz;
17
18use crate::model::{ScanModel, inverse3, table, tables};
19use crate::spectral::{GRID_LEN, GRID_START_NM, GRID_STEP_NM};
20
21#[derive(Debug, Clone, Copy)]
23struct Band {
24 peak_nm: f64,
25 width_nm: f64,
26}
27
28const PAPER_DYES: [Band; 3] = [
30 Band {
31 peak_nm: 650.0,
32 width_nm: 55.0,
33 },
34 Band {
35 peak_nm: 550.0,
36 width_nm: 50.0,
37 },
38 Band {
39 peak_nm: 450.0,
40 width_nm: 55.0,
41 },
42];
43
44const PAPER_BASE_DENSITY: f64 = 0.06;
46
47const NEUTRAL_MAX_DENSITY: f64 = 3.0;
49const NEUTRAL_STEPS: usize = 32;
51pub(crate) const NEUTRAL_ENTRIES: usize = NEUTRAL_STEPS + 1;
54
55const D50_SPD: [f64; 71] = [
61 24.49, 27.18, 29.87, 39.59, 49.31, 52.91, 56.51, 58.27, 60.03, 58.93, 57.82, 66.32, 74.83,
62 81.04, 87.25, 88.93, 90.61, 90.99, 91.37, 93.24, 95.11, 93.54, 91.96, 93.84, 95.72, 96.17,
63 96.61, 96.87, 97.13, 99.61, 102.10, 101.43, 100.75, 101.54, 102.32, 101.16, 100.00, 98.87,
64 97.73, 98.33, 98.92, 96.21, 93.50, 95.59, 97.69, 98.48, 99.27, 99.16, 99.04, 97.38, 95.72,
65 97.29, 98.86, 97.26, 95.67, 96.93, 98.19, 100.60, 103.00, 101.07, 99.13, 93.26, 87.38, 89.49,
66 91.60, 92.25, 92.89, 84.87, 76.85, 81.68, 86.51,
67];
68
69const XYZ_TO_SRGB: [[f64; 3]; 3] = [
71 [3.240_454_2, -1.537_138_5, -0.498_531_4],
72 [-0.969_266_0, 1.876_010_8, 0.041_556_0],
73 [0.055_643_4, -0.204_025_9, 1.057_225_2],
74];
75
76#[derive(Debug, Clone)]
78pub struct ScanContext {
79 grid: Spectrum,
80 dye: [Spectrum; 3],
81 illuminant: Spectrum,
82 cmf: [Spectrum; 3],
83 white_xyz: [f64; 3],
85 white_rgb: [f64; 3],
87 neutral_rgb: Vec<[f64; 3]>,
90}
91
92impl ScanContext {
93 #[must_use]
99 pub fn new() -> Self {
100 let grid = Spectrum::uniform(GRID_START_NM, GRID_STEP_NM, GRID_LEN)
101 .expect("the internal grid is a valid constant");
102
103 let dye: [Spectrum; 3] = PAPER_DYES.map(|band| gaussian(&grid, band));
104 let illuminant = Spectrum::new(
106 crate::spectral::GRID_START_NM,
107 crate::spectral::GRID_STEP_NM,
108 D50_SPD.to_vec(),
109 )
110 .expect("the D50 table matches the internal grid");
111
112 let cmf: [Spectrum; 3] = std::array::from_fn(|axis| {
113 let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
114 for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
115 let wavelength = GRID_START_NM + GRID_STEP_NM * index as f64;
116 *value = cie1931_xyz(wavelength)[axis].max(0.0);
117 }
118 spectrum
119 });
120
121 let mut context = Self {
122 grid,
123 dye,
124 illuminant,
125 cmf,
126 white_xyz: [1.0; 3],
127 white_rgb: [1.0; 3],
128 neutral_rgb: Vec::new(),
129 };
130
131 context.recompute();
132 context
133 }
134
135 fn matrix(&self, xyz: [f64; 3]) -> [f64; 3] {
137 let mut rgb = [0.0_f64; 3];
138 for (row, value) in XYZ_TO_SRGB.iter().zip(rgb.iter_mut()) {
139 *value = row[0] * xyz[0] + row[1] * xyz[1] + row[2] * xyz[2];
140 }
141 rgb
142 }
143
144 fn normalised_xyz(&self, density_cmy: [f64; 3]) -> [f64; 3] {
145 let xyz = self.xyz(density_cmy);
146 std::array::from_fn(|axis| xyz[axis] / self.white_xyz[axis].max(1e-12))
147 }
148
149 fn balance(&self, rgb: [f64; 3], mean_density: f64) -> [f64; 3] {
151 if self.neutral_rgb.is_empty() {
152 return rgb;
153 }
154 let position = (mean_density / NEUTRAL_MAX_DENSITY * NEUTRAL_STEPS as f64)
155 .clamp(0.0, NEUTRAL_STEPS as f64);
156 let low = position.floor() as usize;
157 let high = (low + 1).min(NEUTRAL_STEPS);
158 let fraction = position - low as f64;
159
160 let neutral: [f64; 3] = std::array::from_fn(|axis| {
161 self.neutral_rgb[low][axis] * (1.0 - fraction) + self.neutral_rgb[high][axis] * fraction
162 });
163 let target = (neutral[0].max(1e-12) * neutral[1].max(1e-12) * neutral[2].max(1e-12)).cbrt();
164 std::array::from_fn(|axis| rgb[axis] * target / neutral[axis].max(1e-12))
165 }
166
167 #[must_use]
175 pub fn measured() -> Self {
176 Self::measured_with(&crate::measured::PAPER_DYES)
177 }
178
179 #[must_use]
181 pub fn measured_with(dyes: &[[f64; GRID_LEN]; 3]) -> Self {
182 Self::new().with_dyes(dyes.map(|table| crate::measured::spectrum(&table)))
183 }
184
185 #[must_use]
188 pub fn with_dyes(mut self, dye: [Spectrum; 3]) -> Self {
189 self.dye = dye.map(|spectrum| spectrum.resampled(&self.grid));
190 self.recompute();
191 self
192 }
193
194 fn recompute(&mut self) {
196 self.white_xyz = self.xyz([0.0; 3]);
197 self.white_rgb = self.matrix([1.0; 3]);
198 self.neutral_rgb = (0..=NEUTRAL_STEPS)
199 .map(|index| {
200 let density = NEUTRAL_MAX_DENSITY * index as f64 / NEUTRAL_STEPS as f64;
201 let rgb = self.matrix(self.normalised_xyz([density; 3]));
202 std::array::from_fn(|axis| rgb[axis] / self.white_rgb[axis].max(1e-12))
203 })
204 .collect();
205 }
206
207 #[must_use]
209 pub fn grid(&self) -> &Spectrum {
210 &self.grid
211 }
212
213 #[must_use]
215 pub fn dye(&self) -> &[Spectrum; 3] {
216 &self.dye
217 }
218
219 #[must_use]
221 pub fn illuminant(&self) -> &Spectrum {
222 &self.illuminant
223 }
224
225 #[must_use]
227 pub fn cmf(&self) -> &[Spectrum; 3] {
228 &self.cmf
229 }
230
231 #[must_use]
233 pub fn white_xyz(&self) -> [f64; 3] {
234 self.white_xyz
235 }
236
237 #[must_use]
239 pub fn white_rgb(&self) -> [f64; 3] {
240 self.white_rgb
241 }
242
243 #[must_use]
246 pub fn neutral_rgb(&self) -> &[[f64; 3]] {
247 &self.neutral_rgb
248 }
249
250 #[must_use]
255 pub fn model(&self) -> Option<ScanModel> {
256 let inverse = inverse3(self.analytical_matrix());
257 Some(ScanModel {
258 analytical: inverse.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
259 clamped: inverse.is_some(),
260 dye: tables(&self.dye)?,
261 illuminant: table(&self.illuminant)?,
262 cmf: tables(&self.cmf)?,
263 matrix: XYZ_TO_SRGB,
264 white_xyz: self.white_xyz,
265 white_rgb: self.white_rgb,
266 neutral: self.neutral_rgb.as_slice().try_into().ok()?,
267 neutral_max_density: NEUTRAL_MAX_DENSITY,
268 base_density: PAPER_BASE_DENSITY,
269 })
270 }
271
272 fn analytical_matrix(&self) -> [[f64; 3]; 3] {
284 let probes = [650.0, 550.0, 450.0];
285 let mut matrix = [[0.0_f64; 3]; 3];
286 for (row, wavelength) in probes.iter().enumerate() {
287 for (column, dye) in self.dye.iter().enumerate() {
288 matrix[row][column] = dye.interpolate(*wavelength);
289 }
290 }
291 matrix
292 }
293
294 fn analytical(&self, status: [f64; 3]) -> [f64; 3] {
295 solve3(self.analytical_matrix(), status)
296 .map(|values| values.map(|value| value.max(0.0)))
297 .unwrap_or(status)
298 }
299
300 fn reflectance(&self, status_density: [f64; 3]) -> Spectrum {
301 let density_cmy = self.analytical(status_density);
302 let step = self.grid.step_nm();
303 let mut reflectance = self.grid.clone();
304 for (index, value) in reflectance.values_mut().iter_mut().enumerate() {
305 let mut density = PAPER_BASE_DENSITY;
306 for (value, dye) in density_cmy.iter().zip(&self.dye) {
307 density += value * dye.values()[index];
308 }
309 *value = (-density * std::f64::consts::LOG2_10).exp2();
310 }
311 let _ = step;
312 reflectance
313 }
314
315 fn xyz(&self, density_cmy: [f64; 3]) -> [f64; 3] {
316 let reflectance = self.reflectance(density_cmy);
317 let step = self.grid.step_nm();
318 let mut xyz = [0.0_f64; 3];
319 for (index, reflectance_value) in reflectance.values().iter().enumerate() {
320 let light = reflectance_value * self.illuminant.values()[index];
321 for (value, cmf) in xyz.iter_mut().zip(&self.cmf) {
322 *value += light * cmf.values()[index];
323 }
324 }
325 for value in &mut xyz {
326 *value *= step;
327 }
328 xyz
329 }
330
331 #[must_use]
336 pub fn scan(&self, density_cmy: [f64; 3]) -> [f64; 3] {
337 let rgb = self.matrix(self.normalised_xyz(density_cmy));
338 let white_relative: [f64; 3] =
339 std::array::from_fn(|axis| rgb[axis] / self.white_rgb[axis].max(1e-12));
340 let mean = (density_cmy[0] + density_cmy[1] + density_cmy[2]) / 3.0;
341 let balanced = self.balance(white_relative, mean);
342 balanced.map(|value| value.clamp(0.0, 1.0))
343 }
344}
345
346impl Default for ScanContext {
347 fn default() -> Self {
348 Self::new()
349 }
350}
351
352pub(crate) fn solve3(mut matrix: [[f64; 3]; 3], mut rhs: [f64; 3]) -> Option<[f64; 3]> {
354 for column in 0..3 {
355 let pivot = (column..3)
356 .max_by(|&a, &b| matrix[a][column].abs().total_cmp(&matrix[b][column].abs()))?;
357 if matrix[pivot][column].abs() < 1e-9 {
358 return None;
359 }
360 matrix.swap(column, pivot);
361 rhs.swap(column, pivot);
362 let pivot_row = matrix[column];
363 let pivot_value = pivot_row[column];
364 for row in (column + 1)..3 {
365 let factor = matrix[row][column] / pivot_value;
366 for (cell, value) in pivot_row.iter().enumerate().skip(column) {
367 matrix[row][cell] -= factor * value;
368 }
369 rhs[row] -= factor * rhs[column];
370 }
371 }
372 let mut solution = [0.0; 3];
373 for row in (0..3).rev() {
374 let mut sum = rhs[row];
375 for (column, value) in solution.iter().enumerate().skip(row + 1) {
376 sum -= matrix[row][column] * value;
377 }
378 solution[row] = sum / matrix[row][row];
379 }
380 Some(solution)
381}
382
383fn gaussian(grid: &Spectrum, band: Band) -> Spectrum {
384 let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
385 for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
386 let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
387 let z = (wavelength - band.peak_nm) / band.width_nm;
388 *value = (-0.5 * z * z).exp();
389 }
390 spectrum
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn paper_white_maps_to_one() {
399 let context = ScanContext::new();
400 let rgb = context.scan([0.0; 3]);
401 for channel in rgb {
402 assert!((channel - 1.0).abs() < 0.01, "white scans at {channel}");
403 }
404 }
405
406 #[test]
407 fn measured_dyes_replace_the_placeholders() {
408 let baseline = ScanContext::new().scan([1.0, 0.6, 0.3]);
409 let grid = ScanContext::new().grid().clone();
410 let narrow: [Spectrum; 3] = [450.0, 550.0, 650.0].map(|peak| {
411 let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
412 for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
413 let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
414 *value = (-0.5 * ((wavelength - peak) / 12.0).powi(2)).exp();
415 }
416 spectrum
417 });
418 let replaced = ScanContext::new().with_dyes(narrow).scan([1.0, 0.6, 0.3]);
419 let difference: f64 = baseline
420 .iter()
421 .zip(&replaced)
422 .map(|(a, b)| (a - b).abs())
423 .sum();
424 assert!(difference > 1e-3, "replacing the dyes changed nothing");
425 }
426
427 #[test]
428 fn neutral_densities_scan_neutral() {
429 let context = ScanContext::new();
430 for step in 1..=10 {
431 let density = 0.15 * f64::from(step);
432 let rgb = context.scan([density; 3]);
433 let spread = rgb.iter().copied().fold(f64::NEG_INFINITY, f64::max)
434 - rgb.iter().copied().fold(f64::INFINITY, f64::min);
435 assert!(spread < 0.02, "grey {density} drifts by {spread}: {rgb:?}");
436 }
437 }
438
439 #[test]
440 fn more_density_means_darker() {
441 let context = ScanContext::new();
442 let light = context.scan([0.2; 3]);
443 let dark = context.scan([1.5; 3]);
444 for channel in 0..3 {
445 assert!(dark[channel] < light[channel]);
446 }
447 }
448}