1const INV_GAMMA: f32 = 1.0 / 2.4;
21
22pub fn srgb_to_linear(c: f32) -> f32 {
26 if c <= 0.04045 {
27 c / 12.92
28 } else {
29 ((c + 0.055) / 1.055).powf(2.4)
30 }
31}
32
33pub fn linear_to_srgb(c: f32) -> f32 {
35 if c <= 0.0031308 {
36 c * 12.92
37 } else {
38 1.055 * c.powf(INV_GAMMA) - 0.055
39 }
40}
41
42pub fn exposure_from_ev100(ev100: f32) -> f32 {
47 (-ev100).exp2()
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Default)]
57pub enum ToneCurve {
58 Reinhard,
60 ReinhardExtended { white: f32 },
63 #[default]
66 Aces,
67 Agx,
71}
72
73impl ToneCurve {
74 pub fn map(&self, x: f32) -> f32 {
77 if x <= 0.0 {
78 return 0.0;
79 }
80 let y = match self {
81 ToneCurve::Reinhard => x / (1.0 + x),
82 ToneCurve::ReinhardExtended { white } => {
83 let w = white.max(1e-3);
84 (x * (1.0 + x / (w * w))) / (1.0 + x)
85 }
86 ToneCurve::Aces => {
87 const A: f32 = 2.51;
89 const B: f32 = 0.03;
90 const C: f32 = 2.43;
91 const D: f32 = 0.59;
92 const E: f32 = 0.14;
93 (x * (A * x + B)) / (x * (C * x + D) + E)
94 }
95 ToneCurve::Agx => agx([x, x, x])[0],
97 };
98 y.clamp(0.0, 1.0)
99 }
100
101 pub fn map_rgb(&self, x: [f32; 3]) -> [f32; 3] {
105 match self {
106 ToneCurve::Agx => agx(x),
107 _ => x.map(|c| self.map(c)),
108 }
109 }
110}
111
112fn m3(c0: [f32; 3], c1: [f32; 3], c2: [f32; 3], v: [f32; 3]) -> [f32; 3] {
122 [
123 c0[0] * v[0] + c1[0] * v[1] + c2[0] * v[2],
124 c0[1] * v[0] + c1[1] * v[1] + c2[1] * v[2],
125 c0[2] * v[0] + c1[2] * v[1] + c2[2] * v[2],
126 ]
127}
128
129fn agx_sigmoid(x: f32) -> f32 {
131 let x2 = x * x;
132 let x4 = x2 * x2;
133 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x
134 - 0.00232
135}
136
137fn agx(color: [f32; 3]) -> [f32; 3] {
143 const SRGB_TO_2020: [[f32; 3]; 3] = [
145 [0.6274, 0.0691, 0.0164],
146 [0.3293, 0.9195, 0.0880],
147 [0.0433, 0.0113, 0.8956],
148 ];
149 const SRGB_FROM_2020: [[f32; 3]; 3] = [
150 [1.6605, -0.1246, -0.0182],
151 [-0.5876, 1.1329, -0.1006],
152 [-0.0728, -0.0083, 1.1187],
153 ];
154 const INSET: [[f32; 3]; 3] = [
155 [0.856_627_17, 0.137_318_97, 0.111_898_21],
156 [0.095_121_24, 0.761_242, 0.076_799_415],
157 [0.048_251_607, 0.101_439_04, 0.811_302_36],
158 ];
159 const OUTSET: [[f32; 3]; 3] = [
160 [1.127_100_6, -0.141_329_77, -0.141_329_77],
161 [-0.110_606_64, 1.157_823_7, -0.110_606_64],
162 [-0.016_493_939, -0.016_493_939, 1.251_936_4],
163 ];
164 const MIN_EV: f32 = -12.47393;
166 const MAX_EV: f32 = 4.026069;
167
168 let mut c = m3(SRGB_TO_2020[0], SRGB_TO_2020[1], SRGB_TO_2020[2], color);
169 c = m3(INSET[0], INSET[1], INSET[2], c);
170 c = c.map(|v| v.max(1e-10).log2());
172 c = c.map(|v| ((v - MIN_EV) / (MAX_EV - MIN_EV)).clamp(0.0, 1.0));
173 c = c.map(agx_sigmoid);
174 c = m3(OUTSET[0], OUTSET[1], OUTSET[2], c);
175 c = c.map(|v| v.max(0.0).powf(2.2));
177 c = m3(SRGB_FROM_2020[0], SRGB_FROM_2020[1], SRGB_FROM_2020[2], c);
178 c.map(|v| v.clamp(0.0, 1.0))
179}
180
181#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct HdrPipeline {
186 pub exposure: f32,
188 pub curve: ToneCurve,
190}
191
192impl Default for HdrPipeline {
193 fn default() -> Self {
194 Self {
195 exposure: 1.0,
196 curve: ToneCurve::default(),
197 }
198 }
199}
200
201impl HdrPipeline {
202 pub fn with_ev100(ev100: f32) -> Self {
204 Self {
205 exposure: exposure_from_ev100(ev100),
206 curve: ToneCurve::default(),
207 }
208 }
209
210 pub fn tonemap(&self, linear: [f32; 3]) -> [f32; 3] {
212 let exposed = linear.map(|c| c * self.exposure);
213 self.curve.map_rgb(exposed)
214 }
215
216 pub fn process(&self, linear: [f32; 3]) -> [f32; 3] {
219 self.tonemap(linear).map(linear_to_srgb)
220 }
221
222 pub fn process_u8(&self, linear: [f32; 3]) -> [u8; 3] {
224 self.process(linear)
225 .map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8)
226 }
227}
228
229pub fn luminance(rgb: [f32; 3]) -> f32 {
233 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
234}
235
236pub fn mean_luminance(pixels: &[[f32; 3]]) -> f32 {
239 if pixels.is_empty() {
240 return 0.0;
241 }
242 pixels.iter().map(|p| luminance(*p)).sum::<f32>() / pixels.len() as f32
243}
244
245pub const MIDDLE_GRAY: f32 = 0.18;
247
248pub fn ev100_from_luminance(l: f32) -> f32 {
252 (l * 100.0 / 12.19).log2()
253}
254
255#[derive(Clone, Copy, Debug, PartialEq)]
264pub struct AdaptiveExposure {
265 pub exposure: f32,
267 pub min: f32,
269 pub max: f32,
270 pub speed_up: f32,
272 pub speed_down: f32,
274}
275
276impl Default for AdaptiveExposure {
277 fn default() -> Self {
278 Self {
279 exposure: 1.0,
280 min: 1e-4,
281 max: 1e4,
282 speed_up: 3.0,
283 speed_down: 1.0,
284 }
285 }
286}
287
288impl AdaptiveExposure {
289 pub fn target_for(&self, mean_lum: f32, key: f32) -> f32 {
293 if mean_lum <= 0.0 {
294 return self.max;
295 }
296 (key / mean_lum).clamp(self.min, self.max)
297 }
298
299 pub fn tick(&mut self, mean_lum: f32, key: f32, dt: f32) -> f32 {
302 let target = self.target_for(mean_lum, key);
303 let cur = self.exposure.max(1e-9).log2();
304 let tgt = target.max(1e-9).log2();
305 let delta = self.speed_for(tgt > cur).max(0.0) * dt.max(0.0);
306 let new_log = if tgt > cur {
307 (cur + delta).min(tgt)
308 } else {
309 (cur - delta).max(tgt)
310 };
311 self.exposure = new_log.exp2();
312 self.exposure
313 }
314
315 fn speed_for(&self, rising: bool) -> f32 {
317 if rising {
318 self.speed_up
319 } else {
320 self.speed_down
321 }
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 fn approx(a: f32, b: f32, eps: f32) -> bool {
330 (a - b).abs() < eps
331 }
332
333 #[test]
334 fn srgb_und_linear_sind_invers() {
335 for &c in &[0.0, 0.01, 0.18, 0.5, 0.75, 1.0] {
336 assert!(
337 approx(srgb_to_linear(linear_to_srgb(c)), c, 1e-4),
338 "linear→srgb→linear {c}"
339 );
340 assert!(
341 approx(linear_to_srgb(srgb_to_linear(c)), c, 1e-4),
342 "srgb→linear→srgb {c}"
343 );
344 }
345 }
346
347 #[test]
348 fn srgb_ankerpunkte() {
349 assert!(approx(srgb_to_linear(0.5), 0.21404, 1e-4));
351 assert!(approx(linear_to_srgb(0.21404), 0.5, 1e-3));
352 assert_eq!(srgb_to_linear(0.0), 0.0);
353 assert!(approx(srgb_to_linear(1.0), 1.0, 1e-6));
354 assert_eq!(linear_to_srgb(0.0), 0.0);
355 assert!(approx(linear_to_srgb(1.0), 1.0, 1e-6));
356 }
357
358 #[test]
359 fn belichtung_exponentiell() {
360 assert!(approx(exposure_from_ev100(0.0), 1.0, 1e-6));
361 assert!(approx(exposure_from_ev100(1.0), 0.5, 1e-6));
362 assert!(approx(exposure_from_ev100(-1.0), 2.0, 1e-6));
363 assert!(approx(exposure_from_ev100(2.0), 0.25, 1e-6));
364 }
365
366 #[test]
367 fn kurven_monoton_und_begrenzt() {
368 let kurven = [
369 ToneCurve::Reinhard,
370 ToneCurve::ReinhardExtended { white: 4.0 },
371 ToneCurve::Aces,
372 ToneCurve::Agx,
373 ];
374 for curve in kurven {
375 assert_eq!(curve.map(0.0), 0.0, "{curve:?}: Schwarz bleibt Schwarz");
376 let mut last = -1.0;
377 let mut x = 0.0;
378 while x <= 1000.0 {
379 let y = curve.map(x);
380 assert!(
381 (0.0..=1.0).contains(&y),
382 "{curve:?}: {x} -> {y} außerhalb 0..1"
383 );
384 assert!(y >= last, "{curve:?}: nicht monoton bei {x}");
385 last = y;
386 x += 0.25;
387 }
388 assert!(
390 curve.map(1000.0) > 0.99,
391 "{curve:?}: sättigt nicht auf Weiß"
392 );
393 }
394 }
395
396 #[test]
397 fn aces_bekannte_referenz() {
398 assert!(approx(ToneCurve::Aces.map(1.0), 2.54 / 3.16, 1e-5));
400 }
401
402 #[test]
403 fn reinhard_und_extended_anker() {
404 assert!(approx(ToneCurve::Reinhard.map(1.0), 0.5, 1e-6));
405 assert!(approx(
407 ToneCurve::ReinhardExtended { white: 4.0 }.map(4.0),
408 1.0,
409 1e-5
410 ));
411 assert!(ToneCurve::ReinhardExtended { white: 4.0 }.map(8.0) <= 1.0);
412 }
413
414 #[test]
415 fn pipeline_erhaelt_grauachse_und_klemmt() {
416 let p = HdrPipeline::default();
417 let out = p.process([0.18, 0.18, 0.18]);
419 assert!(approx(out[0], out[1], 1e-6) && approx(out[1], out[2], 1e-6));
420 let hot = p.process([50.0, 50.0, 50.0]);
422 assert!(hot.iter().all(|&c| c > 0.95));
423 assert_eq!(p.process([0.0, 0.0, 0.0]), [0.0, 0.0, 0.0]);
425 }
426
427 #[test]
428 fn pipeline_dunkelt_hoheres_ev_ab() {
429 let linear = [0.5, 0.3, 0.2];
430 let dunkel = HdrPipeline::with_ev100(2.0).process(linear);
431 let hell = HdrPipeline::with_ev100(-1.0).process(linear);
432 assert!(
433 dunkel[0] < hell[0],
434 "höheres EV100 muss dunkler werden: {:?} vs {:?}",
435 dunkel,
436 hell
437 );
438 }
439
440 #[test]
441 fn process_u8_im_berreich() {
442 let p = HdrPipeline::default();
443 let black = p.process_u8([0.0, 0.0, 0.0]);
444 assert_eq!(black, [0, 0, 0]);
445 let white = p.process_u8([100.0, 100.0, 100.0]);
446 assert!(white.iter().all(|&v| v >= 250), "weiß -> {white:?}");
447 let mid = p.process_u8([0.18, 0.18, 0.18]);
448 assert!(
449 mid.iter().all(|&v| (1..=254).contains(&v)),
450 "grau -> {mid:?}"
451 );
452 }
453
454 #[test]
455 fn luminanz_anker_und_gewichte() {
456 assert!(approx(luminance([0.0, 0.0, 0.0]), 0.0, 1e-6));
457 assert!(approx(luminance([1.0, 1.0, 1.0]), 1.0, 1e-6));
458 assert!(approx(luminance([0.18, 0.18, 0.18]), 0.18, 1e-6));
459 let sum =
461 luminance([1.0, 0.0, 0.0]) + luminance([0.0, 1.0, 0.0]) + luminance([0.0, 0.0, 1.0]);
462 assert!(approx(sum, 1.0, 1e-6));
463 assert!(luminance([0.0, 1.0, 0.0]) > luminance([1.0, 0.0, 0.0]));
465 }
466
467 #[test]
468 fn mittlere_luminanz() {
469 assert_eq!(mean_luminance(&[]), 0.0);
470 let m = mean_luminance(&[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]);
471 assert!(approx(m, 0.5, 1e-6));
472 }
473
474 #[test]
475 fn ev100_anker_und_blendenregel() {
476 assert!(approx(ev100_from_luminance(0.1219), 0.0, 1e-4));
478 assert!(approx(
480 ev100_from_luminance(0.2438) - ev100_from_luminance(0.1219),
481 1.0,
482 1e-4
483 ));
484 let l = 0.7;
486 assert!(approx(
487 exposure_from_ev100(ev100_from_luminance(l)),
488 0.1219 / l,
489 1e-4
490 ));
491 }
492
493 #[test]
494 fn ziel_belichtung_aus_messung() {
495 let a = AdaptiveExposure::default();
496 assert!(approx(a.target_for(MIDDLE_GRAY, MIDDLE_GRAY), 1.0, 1e-6));
498 assert!(approx(
500 a.target_for(MIDDLE_GRAY * 0.5, MIDDLE_GRAY),
501 2.0,
502 1e-5
503 ));
504 assert_eq!(a.target_for(0.0, MIDDLE_GRAY), a.max);
506 let eng = AdaptiveExposure {
507 min: 0.5,
508 max: 2.0,
509 ..Default::default()
510 };
511 assert_eq!(eng.target_for(1000.0, MIDDLE_GRAY), 0.5);
512 }
513
514 #[test]
515 fn adaption_naehert_schrittweise_ohne_ueberschiessen() {
516 let mut a = AdaptiveExposure::default();
518 let dunkel = MIDDLE_GRAY / 32.0;
519 assert!(approx(a.target_for(dunkel, MIDDLE_GRAY), 32.0, 1e-4));
520 assert!(approx(a.tick(dunkel, MIDDLE_GRAY, 0.0), 1.0, 1e-6));
522 assert!(approx(a.tick(dunkel, MIDDLE_GRAY, 1.0), 8.0, 1e-4));
524 assert!(approx(a.tick(dunkel, MIDDLE_GRAY, 1.0), 32.0, 1e-3));
526 assert!(
527 approx(a.tick(dunkel, MIDDLE_GRAY, 5.0), 32.0, 1e-3),
528 "überschießt nicht"
529 );
530 }
531
532 #[test]
533 fn adaption_richungsunterschied() {
534 let mut langsam = AdaptiveExposure {
537 exposure: 32.0,
538 ..Default::default()
539 };
540 let hellig = langsam.tick(MIDDLE_GRAY, MIDDLE_GRAY, 1.0); assert!(approx(hellig, 16.0, 1e-3), "sinkt 1 Blende/s: {hellig}");
542
543 let mut schnell = AdaptiveExposure {
544 exposure: 1.0 / 32.0,
545 ..Default::default()
546 };
547 let dunkel = schnell.tick(MIDDLE_GRAY / 32.0, MIDDLE_GRAY, 1.0); assert!(
549 approx(dunkel, 8.0 / 32.0, 1e-3),
550 "steigt 3 Blenden/s: {dunkel}"
551 );
552 let steigt = (schnell.exposure * 32.0).log2();
554 let sinkt = (32.0 / hellig).log2();
555 assert!(
556 approx(sinkt, 1.0, 1e-3) && approx(steigt, 3.0, 1e-3),
557 "3 Blenden vs 1 Blende"
558 );
559 }
560
561 #[test]
562 fn adaption_deterministisch_und_begrenzt() {
563 let folge = |seed: f32| {
564 let mut a = AdaptiveExposure {
565 exposure: seed,
566 ..Default::default()
567 };
568 let mut out = Vec::new();
569 for i in 0..20 {
570 let l = MIDDLE_GRAY * (1.0 + (i as f32 * 0.7).sin());
571 out.push(a.tick(l, MIDDLE_GRAY, 1.0 / 60.0));
572 }
573 out
574 };
575 let a = folge(1.0);
576 let b = folge(1.0);
577 assert_eq!(a, b, "gleiche Eingabe -> gleiche Folge");
578 let eng = AdaptiveExposure {
579 min: 0.25,
580 max: 4.0,
581 ..Default::default()
582 };
583 let mut g = eng;
584 for _ in 0..200 {
585 g.tick(1e-6, MIDDLE_GRAY, 1.0);
586 assert!(
587 g.exposure <= 4.0 + 1e-5 && g.exposure >= 0.25 - 1e-5,
588 "Ausreißer {}",
589 g.exposure
590 );
591 g.tick(1e6, MIDDLE_GRAY, 1.0);
592 assert!(
593 g.exposure <= 4.0 + 1e-5 && g.exposure >= 0.25 - 1e-5,
594 "Ausreißer {}",
595 g.exposure
596 );
597 }
598 }
599
600 #[test]
601 fn agx_erhaelt_grauachse() {
602 for &g in &[0.01f32, 0.18, 0.5, 2.0, 40.0] {
606 let out = ToneCurve::Agx.map_rgb([g, g, g]);
607 assert!(
608 (out[0] - out[1]).abs() < 5e-3 && (out[1] - out[2]).abs() < 5e-3,
609 "grau {g} -> {out:?}"
610 );
611 }
612 }
613
614 #[test]
615 fn agx_anker_und_monotonie() {
616 assert_eq!(ToneCurve::Agx.map_rgb([0.0, 0.0, 0.0]), [0.0, 0.0, 0.0]);
617 let hot = ToneCurve::Agx.map_rgb([100.0, 100.0, 100.0]);
618 assert!(hot.iter().all(|&c| c > 0.95), "weiß -> {hot:?}");
619 let mut last = -1.0;
620 let mut x = 0.0f32;
621 while x <= 200.0 {
622 let y = ToneCurve::Agx.map(x);
623 assert!(
624 (0.0..=1.0).contains(&y) && y >= last,
625 "Agx nicht monoton bei {x}"
626 );
627 last = y;
628 x += 0.1;
629 }
630 }
631
632 #[test]
633 fn agx_erhaelt_farbreihenfolge() {
634 let out = ToneCurve::Agx.map_rgb([3.0, 1.2, 0.3]);
637 assert!(out[0] > out[1] && out[1] > out[2], "Reihenfolge {out:?}");
638 let aces = ToneCurve::Aces.map_rgb([3.0, 1.2, 0.3]);
640 let delta = (out[0] - aces[0]).abs() + (out[1] - aces[1]).abs() + (out[2] - aces[2]).abs();
641 assert!(delta > 0.01, "AgX == ACES? {out:?} vs {aces:?}");
642 }
643
644 #[test]
645 fn pipeline_mit_agx() {
646 let p = HdrPipeline {
647 exposure: 1.3,
648 curve: ToneCurve::Agx,
649 };
650 let out = p.process([0.5, 0.35, 0.2]);
651 assert!(out.iter().all(|&c| (0.0..=1.0).contains(&c)), "{out:?}");
652 let dunkel = HdrPipeline {
654 curve: ToneCurve::Agx,
655 ..HdrPipeline::with_ev100(3.0)
656 }
657 .process([0.5, 0.35, 0.2]);
658 let hell = HdrPipeline {
659 curve: ToneCurve::Agx,
660 ..HdrPipeline::with_ev100(-1.0)
661 }
662 .process([0.5, 0.35, 0.2]);
663 assert!(dunkel[0] < hell[0]);
664 }
665}