Skip to main content

re_render/
hdr.rs

1//! HDR-Farb-Pipeline (M5a).
2//!
3//! Der Kern einer „HDR-Pipeline“ ist die Farbverarbeitung: Die Szene
4//! rendert linear mit Werten über 1,0 (High Dynamic Range), und am Ende
5//! muss daraus ein Display-Bild in 0..1 werden. Diese Umrechnung ist
6//! reine Mathematik — backend-neutral, deterministisch und headless
7//! testbar. Sowohl der wgpu-Post-Pass (WGSL) als auch jedes andere
8//! Backend nutzen exakt dieselben Kurven, damit das Bild über Backends
9//! hinweg identisch aussieht.
10//!
11//! Pipeline-Reihenfolge pro Pixel:
12//! 1. **Belichtung** — Szenen-Luminanz (EV100) auf Display-Weiß normieren.
13//! 2. **Tone-Mapping** — HDR-linear (0..∞) auf Display-linear (0..1) stauchen.
14//! 3. **sRGB-Encoding** — Display-linear → nichtlineare Display-Werte.
15//!
16//! Alle Funktionen arbeiten auf einzelnen Kanälen (`f32`) oder
17//! RGB-Tripeln `[f32; 3]`; die WGSL-Seite spiegelt sie Kanal-für-Kanal.
18
19/// `1 / 2.4` — der sRGB-Exponent für die Rückrichtung.
20const INV_GAMMA: f32 = 1.0 / 2.4;
21
22// ── sRGB-Transfer ─────────────────────────────────────────────────────
23
24/// sRGB (0..1, nichtlinear) → linear (0..1).
25pub 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
33/// linear (0..1) → sRGB (0..1, nichtlinear).
34pub 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
42// ── Belichtung ────────────────────────────────────────────────────────
43
44/// Belichtungs-Multiplikator aus EV100. Höheres EV100 = hellere Szene =
45/// kleinerer Multiplikator. `ev100 = 0` liefert 1,0 (unverändert).
46pub fn exposure_from_ev100(ev100: f32) -> f32 {
47    (-ev100).exp2()
48}
49
50// ── Tone-Mapping-Kurven ───────────────────────────────────────────────
51
52/// Staucht HDR-lineare Werte (0..∞) auf Display-linear (0..1).
53///
54/// Alle Kurven sind monoton steigend, fixieren `0 → 0` und bleiben für
55/// positiven Input in `0..=1`.
56#[derive(Clone, Copy, Debug, PartialEq, Default)]
57pub enum ToneCurve {
58    /// Reinhard: `x / (1 + x)`. Einfach, weiche Sättigung.
59    Reinhard,
60    /// Extended Reinhard mit Weißpunkt: `x·(1 + x/white²) / (1 + x)`.
61    /// Werte ab `white` und darüber werden auf 1,0 gekämmt.
62    ReinhardExtended { white: f32 },
63    /// ACES-Filmic (Narkowicz-Approximation). Der Default moderner
64    /// Engines — kräftige, filmische Sättigung.
65    #[default]
66    Aces,
67    /// AgX (Blender/Filament-Port). Neutraler, mit sanfterem Highlight-
68    /// Roll-off und besserer Farb-Erhaltung in hellen Bereichen.
69    /// Arbeitet auf ganzen RGB-Tripeln — via [`ToneCurve::map_rgb`].
70    Agx,
71}
72
73impl ToneCurve {
74    /// Ein Kanal: HDR-linear → Display-linear (0..=1). Für Kurven, die
75    /// kanalunabhängig sind, ist das exakt `map_rgb` auf der Grauachse.
76    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                // (x·(2.51x + 0.03)) / (x·(2.43x + 0.59) + 0.14)
88                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            // AgX ist nicht kanalunabhängig — auf der Grauachse ausgewertet.
96            ToneCurve::Agx => agx([x, x, x])[0],
97        };
98        y.clamp(0.0, 1.0)
99    }
100
101    /// Ein RGB-Tripel: HDR-linear → Display-linear (0..=1). Kanalu-\
102    /// unabhängige Kurven wenden [`Self::map`] pro Kanal an; AgX läuft
103    /// durch seine volle Matrix-Kette.
104    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
112// ── AgX ────────────────────────────────────────────────────────────────
113//
114// Port der Referenz-Implementierung aus three.js/Filament (ihrerseits
115// Blender-Port mit Rec.2020-Primaries); Konstanten von
116// https://iolite-engine.com/blog_posts/minimal_agx_implementation .
117// Die Matrizen sind als Spalten notiert (GLSL-Konvention), angewandt als
118// M·v = c0·x + c1·y + c2·z.
119
120/// 3×3-Matrix aus drei Spalten-Vektoren auf einen Vektor.
121fn 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
129/// Die AgX-Sigmoid-Kontrastkurve als Polynom-Fit (Mittelfehler² ≈ 3.7e-6).
130fn 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
137/// AgX-Tonemapping: HDR-linear (sRGB-Primaries) → Display-linear.
138///
139/// Kette: sRGB→Rec.2020 → AgX-Inbettung → log2-Zustand (Normalisierung
140/// auf den Belichtungsbereich der Kurve) → Sigmoid-Kontrast →
141/// AgX-Ausbettung → Linearisierung → Rec.2020→sRGB → Klemmung.
142fn agx(color: [f32; 3]) -> [f32; 3] {
143    // sRGB <-> Rec.2020 (ITU-R BT.2407), Spalten wie im Referenz-Shader.
144    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    // log2(Pow(2, ±)) · MIDDLE_GRAY — der Belichtungsbereich der Kurve.
165    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    // Log2-Encoding des Zustands, normalisiert auf 0..=1.
171    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    // Linearisierung (Sigmoid-Raum → linear), dann Primaries zurück.
176    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// ── Die Pipeline ──────────────────────────────────────────────────────
182
183/// Konfiguration der Farb-Pipeline: Belichtung + Tone-Kurve.
184#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct HdrPipeline {
186    /// Belichtungs-Multiplikator (aus [`exposure_from_ev100`] oder frei).
187    pub exposure: f32,
188    /// Tone-Mapping-Kurve.
189    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    /// Pipeline mit Belichtung aus EV100 aufsetzen.
203    pub fn with_ev100(ev100: f32) -> Self {
204        Self {
205            exposure: exposure_from_ev100(ev100),
206            curve: ToneCurve::default(),
207        }
208    }
209
210    /// Belichten + tonemappen, Ergebnis in Display-linear (0..=1).
211    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    /// Belichten + tonemappen + sRGB-Encoding. Ergebnis in Display-sRGB
217    /// (0..=1) — das, was ins Framebuffer/Swapchain gehört.
218    pub fn process(&self, linear: [f32; 3]) -> [f32; 3] {
219        self.tonemap(linear).map(linear_to_srgb)
220    }
221
222    /// Wie [`Self::process`], aber als 8-Bit-RGB für PNG/Readback.
223    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
229// ── Luminanz und Messung ──────────────────────────────────────────────
230
231/// Rec.709-Leuchtdichte eines linearen RGB-Werts (Gewichtssumme = 1).
232pub fn luminance(rgb: [f32; 3]) -> f32 {
233    0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
234}
235
236/// Mittlere Leuchtdichte einer Menge linearer Pixel (arithmetisch).
237/// Leere Eingabe liefert 0.
238pub 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
245/// Standard-Key der Belichtungsmessung: mittleres Grau.
246pub const MIDDLE_GRAY: f32 = 0.18;
247
248/// EV100 aus gemittelter Szenen-Leuchtdichte (linear) — Formel der
249/// einfallenden Messung: `ev100 = log2(L · 100 / 12.19)`.
250/// Eine Verdopplung von L erhöht EV100 um genau 1 Blende.
251pub fn ev100_from_luminance(l: f32) -> f32 {
252    (l * 100.0 / 12.19).log2()
253}
254
255// ── Zeitliche Belichtungs-Anpassung ───────────────────────────────────
256
257/// Augen-Adaption: die Belichtung wandert mit begrenzter Geschwindigkeit
258/// (in Blenden/Sekunde) zum Zielwert, im log2-Raum — wie die Pupille.
259///
260/// Richtungsgesondert: steigt die Belichtung (Szene wird dunkler),
261/// adaptiert das Auge schnell; sinkt sie (Szene wird heller, Blendung),
262/// langsam. Beide Tempi sind konfigurierbar.
263#[derive(Clone, Copy, Debug, PartialEq)]
264pub struct AdaptiveExposure {
265    /// Aktueller Belichtungs-Multiplikator.
266    pub exposure: f32,
267    /// Erlaubter Bereich des Multiplikators.
268    pub min: f32,
269    pub max: f32,
270    /// Blenden/Sekunde, wenn die Belichtung steigt (dunkle Szene).
271    pub speed_up: f32,
272    /// Blenden/Sekunde, wenn die Belichtung sinkt (helle Szene).
273    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    /// Ziel-Belichtung für eine gemessene Szenen-Leuchtdichte:
290    /// `key / L`, in `[min, max]` geklemmt. Schwarze Szenen (L ≤ 0)
291    /// ziehen auf `max` (stärkstes Aufhellen).
292    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    /// Ein Zeitschritt: bewegt `exposure` um höchstens `speed·dt` Blenden
300    /// Richtung Ziel (überschießt nie) und gibt den neuen Wert zurück.
301    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    /// Tempo je Richtung: steigen ist schnell, sinken ist langsam.
316    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        // Bekannte Werte des sRGB-Standards.
350        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            // Sehr hell -> nahe Weiß.
389            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        // Narkowicz-ACES bei x=1: (2.51+0.03)/(2.43+0.59+0.14) = 2.54/3.16.
399        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        // Extended kämmt den Weißpunkt auf genau 1,0.
406        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        // Neutralgrau bleibt neutral (R=G=B).
418        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        // Sehr heller Input -> alle Kanäle nahe 1.
421        let hot = p.process([50.0, 50.0, 50.0]);
422        assert!(hot.iter().all(|&c| c > 0.95));
423        // Schwarz bleibt Schwarz.
424        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        // Gewichtssumme = 1 (Reziprok-Test über Primärvalenzen).
460        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        // Grün dominiert die Luminanz.
464        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        // L = 0.1219 ist per Definition EV100 = 0.
477        assert!(approx(ev100_from_luminance(0.1219), 0.0, 1e-4));
478        // Verdopplung der Leuchtdichte = +1 Blende.
479        assert!(approx(
480            ev100_from_luminance(0.2438) - ev100_from_luminance(0.1219),
481            1.0,
482            1e-4
483        ));
484        // Konsistenz mit der Belichtung: 2^-ev100 == 0.1219 / L.
485        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        // Szene ist genau mittleres Grau -> Belichtung 1,0.
497        assert!(approx(a.target_for(MIDDLE_GRAY, MIDDLE_GRAY), 1.0, 1e-6));
498        // Halb so hell -> doppelte Belichtung.
499        assert!(approx(
500            a.target_for(MIDDLE_GRAY * 0.5, MIDDLE_GRAY),
501            2.0,
502            1e-5
503        ));
504        // Schwarz zieht aufs Maximum, extrem hell unters Minimum.
505        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        // Dunkle Szene: Ziel ist 32 ( = +5 Blenden), speed_up 3 Blenden/s.
517        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        // dt = 0 ändert nichts.
521        assert!(approx(a.tick(dunkel, MIDDLE_GRAY, 0.0), 1.0, 1e-6));
522        // Nach 1 s: 3 Blenden hoch -> 8.
523        assert!(approx(a.tick(dunkel, MIDDLE_GRAY, 1.0), 8.0, 1e-4));
524        // Nach 2 s: Ziel erreicht (nur noch 2 Blenden) -> 32, und es bleibt dort.
525        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        // Heller Szenenwechsel (Belichtung muss sinken) ist langsam
535        // (speed_down = 1), der dunkle Wechsel schnell (speed_up = 3).
536        let mut langsam = AdaptiveExposure {
537            exposure: 32.0,
538            ..Default::default()
539        };
540        let hellig = langsam.tick(MIDDLE_GRAY, MIDDLE_GRAY, 1.0); // Ziel 1
541        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); // Ziel 1
548        assert!(
549            approx(dunkel, 8.0 / 32.0, 1e-3),
550            "steigt 3 Blenden/s: {dunkel}"
551        );
552        // In Blenden gemessen: steigen bewegt 3x mehr als sinken.
553        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        // AgX-Matrizen haben Zeilensumme ~1: Neutralgrau bleibt neutral.
603        // Toleranz 5e-3, weil die Referenz-Matrizen (BT.2407) nur auf
604        // 4 Nachkommastellen gerundet sind.
605        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        // Warme HDR-Lichter bleiben warm (R > G > B) — AgX desättiert
635        // sanft in Highlights, kippt aber die Farbordnung nicht.
636        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        // Und AgX verhält sich anders als ACES (eigene Kurve, kein Alias).
639        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        // Dunkleres Bild bei höherem EV100 gilt für AgX ebenso.
653        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}