Skip to main content

re_render/
temporal.rs

1//! Temporal-Filter-Referenz (M5, Box 3): TAA und Upscaler-Grundlage.
2//!
3//! Zeitliche Filter (TAA, TAA-getriebene Upscaler wie FSR 2/3, DLSS)
4//! brauchen drei Schritte, die hier als CPU-Referenz leben —
5//! backend-neutral, deterministisch, headless testbar:
6//!
7//! 1. **Reprojektion**: Das History-Pixel liegt bei `pixel − velocity`
8//!    (Motion-Vektoren aus dem G-Buffer, [`Surface::velocity`]).
9//! 2. **Box-Clamp**: Die reprojizierte History-Farbe wird in die
10//!    Farb-Box der aktuellen 3×3-Nachbarschaft geklemmt — das ist der
11//!    Ghosting-Schutz an verdeckten Kanten.
12//! 3. **Akkumulation**: exponentielle Mischung aus (geclimpter) History
13//!    und aktuellem Farbwert.
14//!
15//! Der GPU-Pass spiegelt später exakt diese Schritte; der Jitter kommt
16//! aus [`jitter`](crate::jitter), die Velocity aus dem G-Buffer.
17//!
18//! [`Surface::velocity`]: crate::gbuffer::Surface
19
20/// Achsenparallele Box im RGB-Raum (Nachbarschafts-Grenzen eines Pixels).
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct RgbBox {
23    pub min: [f32; 3],
24    pub max: [f32; 3],
25}
26
27impl RgbBox {
28    /// Engste Box um die gegebenen Samples (Min/Max je Kanal).
29    /// Leere Sample-Liste ergibt die Null-Box.
30    pub fn from_samples(samples: &[[f32; 3]]) -> Self {
31        let mut b = Self {
32            min: [0.0; 3],
33            max: [0.0; 3],
34        };
35        if samples.is_empty() {
36            return b;
37        }
38        b.min = [f32::MAX; 3];
39        b.max = [f32::MIN; 3];
40        for s in samples {
41            for (k, &sv) in s.iter().enumerate() {
42                b.min[k] = b.min[k].min(sv);
43                b.max[k] = b.max[k].max(sv);
44            }
45        }
46        b
47    }
48
49    /// Mittelwert ± k·Standardabweichung je Kanal (variance box) —
50    /// robuster gegen einzelne Ausreißer als die reine Min/Max-Box.
51    pub fn from_variance(samples: &[[f32; 3]], k: f32) -> Self {
52        if samples.is_empty() {
53            return Self::default_box();
54        }
55        let n = samples.len() as f32;
56        let mut mean = [0.0f32; 3];
57        for s in samples {
58            for i in 0..3 {
59                mean[i] += s[i] / n;
60            }
61        }
62        let mut var = [0.0f32; 3];
63        for s in samples {
64            for i in 0..3 {
65                let d = s[i] - mean[i];
66                var[i] += d * d / n;
67            }
68        }
69        let std = var.map(|v| v.sqrt());
70        Self {
71            min: [
72                mean[0] - k * std[0],
73                mean[1] - k * std[1],
74                mean[2] - k * std[2],
75            ],
76            max: [
77                mean[0] + k * std[0],
78                mean[1] + k * std[1],
79                mean[2] + k * std[2],
80            ],
81        }
82    }
83
84    fn default_box() -> Self {
85        Self {
86            min: [0.0; 3],
87            max: [0.0; 3],
88        }
89    }
90
91    /// Klemmt eine Farbe in die Box.
92    pub fn clamp(&self, c: [f32; 3]) -> [f32; 3] {
93        [
94            c[0].clamp(self.min[0], self.max[0]),
95            c[1].clamp(self.min[1], self.max[1]),
96            c[2].clamp(self.min[2], self.max[2]),
97        ]
98    }
99
100    /// Box-Diagonale zur History-Farbe hin ausdehnen (Jimenez-2014-Trick),
101    /// bevor geklemmt wird: sonst schneidet der Clamp legitime
102    /// Kontrastkanten ab und das Bild shimmert. `amount` = 0 deaktiviert.
103    pub fn extended_toward(&self, c: [f32; 3], amount: f32) -> Self {
104        if amount <= 0.0 {
105            return *self;
106        }
107        let mut out = *self;
108        for (k, &cv) in c.iter().enumerate() {
109            let center = (self.min[k] + self.max[k]) * 0.5;
110            let p = center + (cv - center) * amount;
111            out.min[k] = out.min[k].min(p);
112            out.max[k] = out.max[k].max(p);
113        }
114        out
115    }
116}
117
118/// History-Puffer: RGB (linear) + Akkumulations-Gewicht pro Pixel.
119///
120/// Gewicht 0 = „kein gültiger Vorgänger“ (Frame 1, nach Object ID changes
121/// oder Resizes). Koordinaten werden auf den Rand geklemmt — Auslesen
122/// außerhalb ist sicher.
123#[derive(Clone, Debug, PartialEq)]
124pub struct History {
125    pub width: u32,
126    pub height: u32,
127    pub pixels: Vec<[f32; 4]>,
128}
129
130impl History {
131    pub fn new(width: u32, height: u32) -> Self {
132        let (w, h) = (width.max(1), height.max(1));
133        Self {
134            width: w,
135            height: h,
136            pixels: vec![[0.0; 4]; (w * h) as usize],
137        }
138    }
139
140    pub fn get(&self, x: u32, y: u32) -> [f32; 4] {
141        let x = x.min(self.width - 1) as usize;
142        let y = y.min(self.height - 1) as usize;
143        self.pixels[y * self.width as usize + x]
144    }
145
146    pub fn set(&mut self, x: u32, y: u32, v: [f32; 4]) {
147        let x = x.min(self.width - 1) as usize;
148        let y = y.min(self.height - 1) as usize;
149        self.pixels[y * self.width as usize + x] = v;
150    }
151
152    /// Bilineares RGB-Sample in Float-Pixelkoordinaten (Rand wird
153    /// geklemmt — kein Kraterrand bei Reprojektion über die Grenze).
154    pub fn sample_bilinear(&self, fx: f32, fy: f32) -> [f32; 3] {
155        let (w, h) = (self.width as f32 - 1.0, self.height as f32 - 1.0);
156        let fx = fx.clamp(0.0, w);
157        let fy = fy.clamp(0.0, h);
158        let x0 = fx.floor() as u32;
159        let y0 = fy.floor() as u32;
160        let (x1, y1) = (x0 + 1 < self.width, y0 + 1 < self.height);
161        let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
162        let a = self.get(x0, y0);
163        let b = self.get(if x1 { x0 + 1 } else { x0 }, y0);
164        let c = self.get(x0, if y1 { y0 + 1 } else { y0 });
165        let d = self.get(if x1 { x0 + 1 } else { x0 }, if y1 { y0 + 1 } else { y0 });
166        let mix = |i: usize| {
167            let ab = a[i] + (b[i] - a[i]) * tx;
168            let cd = c[i] + (d[i] - c[i]) * tx;
169            ab + (cd - ab) * ty
170        };
171        [mix(0), mix(1), mix(2)]
172    }
173
174    /// Bilinear interpoliertes Gewicht (Gültigkeit) an Float-Koordinaten.
175    pub fn weight_bilinear(&self, fx: f32, fy: f32) -> f32 {
176        let (w, h) = (self.width as f32 - 1.0, self.height as f32 - 1.0);
177        let fx = fx.clamp(0.0, w);
178        let fy = fy.clamp(0.0, h);
179        let x0 = fx.floor() as u32;
180        let y0 = fy.floor() as u32;
181        let x1 = (x0 + 1).min(self.width - 1);
182        let y1 = (y0 + 1).min(self.height - 1);
183        let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
184        let a = self.get(x0, y0)[3];
185        let b = self.get(x1, y0)[3];
186        let c = self.get(x0, y1)[3];
187        let d = self.get(x1, y1)[3];
188        let ab = a + (b - a) * tx;
189        let cd = c + (d - c) * tx;
190        ab + (cd - ab) * ty
191    }
192}
193
194/// TAA-Zustand: double-buffered History + ein Filterschritt pro Pixel.
195#[derive(Clone, Debug)]
196pub struct Taa {
197    history: History,
198    next: History,
199    /// Dehnung der Clamp-Box zur History hin (0 = hart geklemmt).
200    pub box_extend: f32,
201}
202
203impl Taa {
204    pub fn new(width: u32, height: u32) -> Self {
205        Self {
206            history: History::new(width, height),
207            next: History::new(width, height),
208            box_extend: 0.5,
209        }
210    }
211
212    /// Ein Frame-Schritt für Pixel `(x, y)`.
213    ///
214    /// * `current` — aktueller linearer RGB-Wert (nach Jitter-Rekonstruktion)
215    /// * `neighborhood` — die 3×3-Nachbarschaft von `current` (Box-Quelle)
216    /// * `velocity` — Bewegung in Bildschirm-Pixeln seit letztem Frame
217    /// * `blend` — Anteil der aktuellen Farbe (0..=1, typ. 0.1 bei 16 Samples)
218    ///
219    /// Schreibt in den Next-Buffer; erst [`Self::commit`] macht ihn zur
220    /// History. Gibt das gemischte Pixel zurück.
221    pub fn step(
222        &mut self,
223        x: u32,
224        y: u32,
225        current: [f32; 3],
226        neighborhood: &[[f32; 3]],
227        velocity: [f32; 2],
228        blend: f32,
229    ) -> [f32; 3] {
230        let hx = x as f32 - velocity[0];
231        let hy = y as f32 - velocity[1];
232        let h_rgb = self.history.sample_bilinear(hx, hy);
233        let valid = self.history.weight_bilinear(hx, hy) > 1e-3;
234        let clipped = RgbBox::from_samples(neighborhood)
235            .extended_toward(h_rgb, self.box_extend)
236            .clamp(h_rgb);
237        let t = if valid { blend.clamp(0.0, 1.0) } else { 1.0 };
238        let out = [
239            clipped[0] + (current[0] - clipped[0]) * t,
240            clipped[1] + (current[1] - clipped[1]) * t,
241            clipped[2] + (current[2] - clipped[2]) * t,
242        ];
243        self.next.set(x, y, [out[0], out[1], out[2], 1.0]);
244        out
245    }
246
247    /// Frame beenden: Next wird History, der alte Puffer wird geleert.
248    pub fn commit(&mut self) {
249        std::mem::swap(&mut self.history, &mut self.next);
250        for p in self.next.pixels.iter_mut() {
251            *p = [0.0; 4];
252        }
253    }
254
255    pub fn history(&self) -> &History {
256        &self.history
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    fn gray(v: f32) -> [f32; 3] {
265        [v, v, v]
266    }
267
268    #[test]
269    fn erster_frame_ist_durchgereicht() {
270        let mut t = Taa::new(2, 2);
271        let out = t.step(0, 0, gray(0.7), &[gray(0.7)], [0.0, 0.0], 0.1);
272        assert_eq!(out, gray(0.7), "ohne History muss current 1:1 durchgehen");
273    }
274
275    #[test]
276    fn akkumulation_konvergiert_exponentiell() {
277        let mut t = Taa::new(1, 1);
278        let wide = [gray(0.0), gray(1.0)]; // Box deckt alles ab
279        t.step(0, 0, gray(0.0), &wide, [0.0, 0.0], 0.5);
280        t.commit();
281        // Ziel wechselt auf 1.0 — Mischung bei blend 0.5 halbiert pro Frame.
282        let mut last = 0.0;
283        for expected in [0.5, 0.75, 0.875] {
284            let out = t.step(0, 0, gray(1.0), &wide, [0.0, 0.0], 0.5);
285            assert!((out[0] - expected).abs() < 1e-5, "Frame-Konvergenz {out:?}");
286            assert!(out[0] > last, "monoton steigend");
287            last = out[0];
288            t.commit();
289        }
290        let mut out = gray(0.875);
291        for _ in 0..8 {
292            out = t.step(0, 0, gray(1.0), &wide, [0.0, 0.0], 0.5);
293            t.commit();
294        }
295        assert!((out[0] - 1.0).abs() < 0.01, "Zielwert erreicht: {out:?}");
296    }
297
298    #[test]
299    fn ghosting_wird_in_die_nachbarschaft_geclippt() {
300        let mut t = Taa::new(1, 1);
301        t.box_extend = 0.0; // harte Klemme für den Test
302        let red = [1.0, 0.0, 0.0];
303        let green = [0.0, 1.0, 0.0];
304        t.step(0, 0, red, &[red], [0.0, 0.0], 0.5);
305        t.commit();
306        // Szene wechselt zu Grün, Geometrie bewegt sich nicht: die alte
307        // rote History liegt außerhalb der grünen Box und muss weg.
308        let out = t.step(0, 0, green, &[green], [0.0, 0.0], 0.5);
309        assert_eq!(out, green, "kein Rot-Anteil erlaubt: {out:?}");
310    }
311
312    #[test]
313    fn reprojektion_folgt_der_velocity() {
314        let mut t = Taa::new(4, 1);
315        let wide = [gray(0.0), gray(1.0)];
316        for x in 0..4 {
317            let c = if x == 2 { gray(1.0) } else { gray(0.2) };
318            t.step(x, 0, c, &wide, [0.0, 0.0], 0.5);
319        }
320        t.commit();
321        // Frame 2: alles dunkel, aber die Szene hat sich um 1 px nach
322        // rechts bewegt (velocity +1) -> der helle Streif liegt in der
323        // History bei x-1. Bei x=3 muss er auftauchen, bei x=0 nicht.
324        let out3 = t.step(3, 0, gray(0.2), &wide, [1.0, 0.0], 0.5);
325        let out0 = t.step(0, 0, gray(0.2), &wide, [1.0, 0.0], 0.5);
326        assert!(
327            out3[0] > out0[0] + 0.2,
328            "History folgte nicht: {out3:?} vs {out0:?}"
329        );
330    }
331
332    #[test]
333    fn box_dehnung_verhindert_ueberklemmen() {
334        let b = RgbBox {
335            min: [0.4; 3],
336            max: [0.6; 3],
337        };
338        let c = [0.8; 3];
339        assert_eq!(b.clamp(c), [0.6; 3], "ohne Dehnung: hart an der Kante");
340        let e = b.extended_toward(c, 0.5);
341        let v = e.clamp(c);
342        assert!(v[0] > 0.6 && v[0] <= 0.8, "Dehnung lässt Luft: {v:?}");
343        // amount 0 ist die Identität.
344        assert_eq!(b.extended_toward(c, 0.0), b);
345    }
346
347    #[test]
348    fn variance_box_und_leere_faelle() {
349        let b = RgbBox::from_variance(&[gray(0.0), gray(2.0)], 1.0);
350        assert!((b.min[0] - 0.0).abs() < 1e-5 && (b.max[0] - 2.0).abs() < 1e-5);
351        let p = RgbBox::from_variance(&[gray(1.0), gray(1.0)], 3.0);
352        assert_eq!(
353            (p.min, p.max),
354            ([1.0; 3], [1.0; 3]),
355            "k*0-Streuung -> Punkt"
356        );
357        assert_eq!(RgbBox::from_samples(&[]), RgbBox::default_box());
358    }
359
360    #[test]
361    fn rand_und_entartete_velocity_nan_frei() {
362        let mut t = Taa::new(2, 2);
363        t.step(0, 0, gray(0.5), &[gray(0.5)], [0.0, 0.0], 0.5);
364        t.commit();
365        // Velocity weit über den Rand hinaus: geklemmt, nicht NaN.
366        for v in [[100.0, -100.0], [-100.0, 0.0], [0.5, 0.5]] {
367            let out = t.step(0, 0, gray(0.5), &[gray(0.5)], v, 0.5);
368            assert!(out.iter().all(|c| c.is_finite()), "{v:?} -> {out:?}");
369        }
370    }
371}