Skip to main content

re_render/
pt.rs

1//! M7 Box 1 — progressiver Path-Tracer (CPU-Referenzkern).
2//!
3//! Der Kern folgt der Paritäts-Doktrin: er ist die Referenz, der
4//! WGSL-Spiegel `pt.wgsl` (`re_wgpu::PtGpu`) marschiert Zug für Zug
5//! nach. Damit das herstellerneutral gelingt (die Lehre aus BUG-002),
6//! gilt auch hier:
7//!
8//! * **Keine Transzendenten im Zufallspfad.** Der Zufall ist eine
9//!   `u32`-Kette (lowbias32-Hash, nur `xor/shr/mul` — auf jeder
10//!   Plattform bitgenau) und die Gleichverteilung skaliert mit dem
11//!   Zweierpotenz-Faktor 2⁻²⁴ (exakt). Die Cosinus-Richtung kommt aus
12//!   Malley-Projektion mit Verwerfungs-Scheibe: nur `+ - * / sqrt`,
13//!   kein `sin`/`cos` — `sqrt` ist in WGSL korrekt gerundet.
14//!   Anmerkung: der Spiegel kappt die Verwerfungsschleife wie dieser
15//!   Kern auf 64 Versuche — eine ungebundene `loop` brach auf
16//!   Mesa/Naga als Funktionskörper fehlerhaft zusammen (BUG-007).
17//! * **Kamera als Datum.** Die Basisvektoren und der Pixelmaßstab
18//!   werden hier ausgerechnet und dem Spiegel vorgesetzt; der Shader
19//!   normalisiert nur noch.
20//! * **Derselbe Rechenpfad.** Die Suchschleife ist Schritt für Schritt
21//!   [`crate::sdf::trace`] nachgebaut, die running mean teilt durch
22//!   `f32(pass)` — beidseitig als Division, nicht als Reziprok-Mult.
23//!
24//! Szenenmodell: ein [`crate::sdf::SdfScene`]-Feld plus Albedo je
25//! Primitiv (Parallel-Tabelle — der SDF-Kern bleibt unverändert).
26//! Getestet wird gegen den Spiegel in `re-wgpu/tests/pt.rs`; dieser
27//! Kern trägt die Unit-Tore für Determinismus, Hemisphäre und
28//! Konvergenz.
29
30use crate::sdf::{SdfRay, SdfScene, TraceCfg, V3};
31
32/// Oberflächenabstand nach einem Streuschritt — größer als `eps_hit`
33/// der Suche, kleiner als jede Szenenkrümmung. Kernvertrag mit
34/// `pt.wgsl`.
35pub const PT_OFF: f32 = 2.0e-3;
36
37/// lowbias32 (Chris Wellon): bijektiver `u32`-Hash aus `xor/shr/mul`
38/// — ganzzahlig, also auf CPU und GPU bitidentisch. Kernvertrag.
39pub fn hash32(mut x: u32) -> u32 {
40    x ^= x >> 16;
41    x = x.wrapping_mul(0x7feb_352d);
42    x ^= x >> 15;
43    x = x.wrapping_mul(0x846c_a68b);
44    x ^= x >> 16;
45    x
46}
47
48/// Gleichverteilung auf [0,1): die oberen 24 Bit als Vielfaches von
49/// 2⁻²⁴ — `u32`→`f32`-Wandlung und Zweierpotenz-Mult sind exakt.
50pub fn unif(x: u32) -> f32 {
51    (x >> 8) as f32 * (1.0 / 16777216.0)
52}
53
54/// Ein Zug aus dem Strom: Hash vorziehen, dann abschöpfen.
55fn next(s: &mut u32) -> f32 {
56    *s = hash32(*s);
57    unif(*s)
58}
59
60/// Startwert des Pixelstroms — jede (Pass, Pixel)-Kombination startet
61/// eine eigene, wiederholbare Folge. Kernvertrag mit `pt.wgsl`.
62pub fn seed_pass(seed: u32, pass: u32, pix: u32) -> u32 {
63    hash32(seed ^ pass.wrapping_mul(0x9E37_79B9) ^ pix.wrapping_mul(0x85EB_CA77))
64}
65
66fn add(a: V3, b: V3) -> V3 {
67    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
68}
69fn sub(a: V3, b: V3) -> V3 {
70    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
71}
72fn scale(a: V3, s: f32) -> V3 {
73    [a[0] * s, a[1] * s, a[2] * s]
74}
75fn mul3(a: V3, b: V3) -> V3 {
76    [a[0] * b[0], a[1] * b[1], a[2] * b[2]]
77}
78fn dot(a: V3, b: V3) -> f32 {
79    (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2]
80}
81fn cross(a: V3, b: V3) -> V3 {
82    [
83        a[1] * b[2] - a[2] * b[1],
84        a[2] * b[0] - a[0] * b[2],
85        a[0] * b[1] - a[1] * b[0],
86    ]
87}
88/// Normalisierung als Division — dieselbe Formel wie `norm3` im
89/// Spiegel (und wie `sdf::norm`).
90fn norm(v: V3) -> V3 {
91    let l = dot(v, v).sqrt();
92    if l == 0.0 {
93        [0.0; 3]
94    } else {
95        [v[0] / l, v[1] / l, v[2] / l]
96    }
97}
98
99/// Tangentialvektor zu `n`: die Achse mit der kleinsten
100/// `n`-Betrag-Komponente wird crossed; Gleichstand schlägt in
101/// Achsenreihenfolge x, y, z durch — exakte Vergleiche, auf beiden
102/// Seiten dieselbe Entscheidung. Kernvertrag mit `pt.wgsl`.
103fn basis_t(n: V3) -> V3 {
104    let (ax, ay, az) = (n[0].abs(), n[1].abs(), n[2].abs());
105    let e = if ax <= ay && ax <= az {
106        [1.0, 0.0, 0.0]
107    } else if ay <= az {
108        [0.0, 1.0, 0.0]
109    } else {
110        [0.0, 0.0, 1.0]
111    };
112    norm(cross(e, n))
113}
114
115/// Cosinus-gewichtete Richtung um `n` (Malley): zwei Stromzüge geben
116/// per Verwerfung einen Scheibenpunkt, die Höhe holt `sqrt(1 − r²)` —
117/// die Dichte trägt den Cosinus-Faktor, das Lambda-Kürzelt den
118/// Lambert-Wegweiser (π fällt ohnehin aus dem Durchgriff). Die
119/// Verwerfung ist hart auf 64 Versuche gekappt (die Kette bricht
120/// statistisch nie aus, aber die Kappe hält den Pfad deterministisch
121/// — Kernvertrag mit `pt.wgsl`, siehe BUG-007).
122pub fn cos_dir(n: V3, s: &mut u32) -> V3 {
123    let (x, y) = {
124        let mut x = 0.0f32;
125        let mut y = 0.0f32;
126        for _ in 0..64 {
127            x = 2.0 * next(s) - 1.0;
128            y = 2.0 * next(s) - 1.0;
129            if x * x + y * y <= 1.0 {
130                break;
131            }
132        }
133        (x, y)
134    };
135    let z = (1.0 - x * x - y * y).max(0.0).sqrt();
136    let t = basis_t(n);
137    let b = cross(n, t);
138    add(add(scale(t, x), scale(b, y)), scale(n, z))
139}
140
141/// Kamera als Datum: Ursprung, orientierte Basis und Pixelmaßstab
142/// (`pxscale` = Tangens der halben Blendöffnung je Pixelhöhe). Der
143/// Spiegel rechnet nie eigenes — nur die Primärstrahl-Norm.
144#[derive(Clone, Copy, Debug, PartialEq)]
145pub struct PtCam {
146    pub pos: V3,
147    pub fwd: V3,
148    pub right: V3,
149    pub up: V3,
150    pub pxscale: f32,
151}
152
153impl PtCam {
154    /// Blick von `pos` nach `ziel`; `hint` grob oben, `hoehe` =
155    /// Bildhöhe in Einheiten, `vfov` = Vertikalfeld in Radiant.
156    pub fn look_at(pos: V3, ziel: V3, hint: V3, hoehe: f32, vfov: f32) -> Self {
157        let fwd = norm(sub(ziel, pos));
158        let mut right = norm(cross(fwd, hint));
159        if right == [0.0; 3] {
160            right = [1.0, 0.0, 0.0];
161        }
162        let up = cross(right, fwd);
163        Self {
164            pos,
165            fwd,
166            right,
167            up,
168            pxscale: (vfov * 0.5).tan() * 2.0 / hoehe,
169        }
170    }
171}
172
173/// Such- und Streuparameter — identisch auf beiden Seiten.
174#[derive(Clone, Copy, Debug, PartialEq)]
175pub struct PtCfg {
176    /// maximale Streutiefe (Anzahl diffuser Strecken)
177    pub max_depth: u32,
178    pub eps_hit: f32,
179    pub eps_step: f32,
180    pub tmax: f32,
181    pub max_steps: u32,
182    /// Himmelsstrahlung beim Ausstieg
183    pub sky: V3,
184    /// Stromwurzel über alle Pixel und Pässe
185    pub seed: u32,
186}
187
188impl Default for PtCfg {
189    fn default() -> Self {
190        Self {
191            max_depth: 4,
192            eps_hit: 2.0e-4,
193            eps_step: 1.0e-4,
194            tmax: 60.0,
195            max_steps: 128,
196            sky: [0.2, 0.35, 0.6],
197            seed: 7,
198        }
199    }
200}
201
202/// Tracer-Szene: SDF-Feld plus Albedo je Primitiv (Parallel-Tabelle,
203/// Index wie `Hit::prim`).
204pub struct PtScene<'a> {
205    pub sdf: &'a SdfScene,
206    pub albedo: &'a [V3],
207    pub cfg: PtCfg,
208}
209
210impl<'a> PtScene<'a> {
211    /// Strahl von `ro` in Richtung `rd`: ein Streupfad, summierte
212    /// Strahlung. Scheinwerfer-Logik: Emission endet den Pfad,
213    /// Diffusfläche multipliziert den Durchgriff und streut cosine-
214    /// gewichtet, Ausstieg liefert Himmel. Nach `max_depth` diffusen
215    /// Strecken endet der Pfad schweigend (kein Russian-Roulette —
216    /// Determinismus vor Varianz).
217    pub fn radiance(&self, ro: V3, rd: V3, s: &mut u32) -> V3 {
218        let tcfg = TraceCfg {
219            eps_hit: self.cfg.eps_hit,
220            eps_step: self.cfg.eps_step,
221            tmax: self.cfg.tmax,
222            max_steps: self.cfg.max_steps,
223        };
224        let mut acc = [0.0; 3];
225        let mut thr = [1.0; 3];
226        let (mut o, mut d) = (ro, rd);
227        for _ in 0..self.cfg.max_depth {
228            match crate::sdf::trace(
229                self.sdf,
230                &SdfRay {
231                    ro: o,
232                    rd: d,
233                    tmin: 0.0,
234                },
235                &tcfg,
236            ) {
237                Some(h) => {
238                    if h.emis[0] > 0.0 || h.emis[1] > 0.0 || h.emis[2] > 0.0 {
239                        acc = add(acc, mul3(thr, h.emis));
240                        return acc;
241                    }
242                    thr = mul3(thr, self.albedo[h.prim as usize]);
243                    o = add(h.pos, scale(h.n, PT_OFF));
244                    d = cos_dir(h.n, s);
245                }
246                None => {
247                    acc = add(acc, mul3(thr, self.cfg.sky));
248                    return acc;
249                }
250            }
251        }
252        acc
253    }
254
255    /// Primärstrahl durch Pixel `(x, y)` mit Jitter aus dem Strom.
256    pub fn primary(&self, cam: &PtCam, w: u32, h: u32, x: u32, y: u32, s: &mut u32) -> (V3, V3) {
257        let fx = (x as f32 + next(s)) - (w as f32) * 0.5;
258        let fy = (y as f32 + next(s)) - (h as f32) * 0.5;
259        let rd = norm(add(add(cam.fwd, scale(cam.right, fx * cam.pxscale)), {
260            scale(cam.up, fy * cam.pxscale)
261        }));
262        (cam.pos, rd)
263    }
264}
265
266/// Progressiver Accumulator: laufendes Mittel je Kanal, Passnummer in
267/// `n`. Die Mittelung teilt durch `f32(n)` (Division, kein Reziprok)
268/// — Zug um Zug dieselbe Folge wie der Spiegel.
269#[derive(Clone, Debug)]
270pub struct PtAccum {
271    pub w: u32,
272    pub h: u32,
273    pub n: u32,
274    pub rgb: Vec<f32>,
275}
276
277impl PtAccum {
278    pub fn new(w: u32, h: u32) -> Self {
279        Self {
280            w,
281            h,
282            n: 0,
283            rgb: vec![0.0; (w * h) as usize * 3],
284        }
285    }
286
287    /// Ein progressiver Durchgang: je Pixel ein frischer Strom, ein
288    /// Pfad, ein Mittel-Schritt.
289    pub fn pass(&mut self, sc: &PtScene, cam: &PtCam) {
290        self.n += 1;
291        let nf = self.n as f32;
292        for i in 0..(self.w * self.h) as usize {
293            let (x, y) = ((i as u32) % self.w, (i as u32) / self.w);
294            let mut s = seed_pass(sc.cfg.seed, self.n, i as u32);
295            let (ro, rd) = sc.primary(cam, self.w, self.h, x, y, &mut s);
296            let rad = sc.radiance(ro, rd, &mut s);
297            let b = i * 3;
298            for (slot, r) in self.rgb[b..b + 3].iter_mut().zip(rad) {
299                *slot += (r - *slot) / nf;
300            }
301        }
302    }
303
304    /// Mittlerer quadratischer Abstand gegen ein Referenzbild.
305    pub fn rmse_vs(&self, other: &[f32]) -> f32 {
306        let mut sum = 0.0;
307        for (a, b) in self.rgb.iter().zip(other.iter()) {
308            let d = a - b;
309            sum += d * d;
310        }
311        (sum / self.rgb.len() as f32).sqrt()
312    }
313}
314
315// ── Unit-Tore ──────────────────────────────────────────────────────
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use crate::sdf::SdfPrim;
321
322    fn halle() -> (SdfScene, Vec<V3>) {
323        // Bodenhalle mit Leuchtkuppel und zwei Diffus-Kugeln.
324        let black = [0.0; 3];
325        let sdf = SdfScene::from_prims(vec![
326            SdfPrim::plane([0.0; 3], [0.0, 1.0, 0.0], black),
327            SdfPrim::sphere([0.0, 6.0, 0.0], 2.0, [6.0, 4.5, 3.0]),
328            SdfPrim::sphere([1.4, 0.8, 0.0], 0.8, black),
329            SdfPrim::sphere([-1.6, 0.6, -0.8], 0.6, black),
330        ]);
331        let albedo = vec![[0.6, 0.6, 0.62], black, [0.8, 0.25, 0.15], [0.2, 0.4, 0.8]];
332        (sdf, albedo)
333    }
334
335    #[test]
336    fn strom_ist_deterministisch_und_normiert() {
337        let mut s = seed_pass(42, 1, 0);
338        let mut sum = 0.0f32;
339        let mut min = 1.0f32;
340        let mut max = 0.0f32;
341        for _ in 0..4096 {
342            let u = next(&mut s);
343            assert!((0.0..1.0).contains(&u), "Wert {u} außerhalb [0,1)");
344            sum += u;
345            min = min.min(u);
346            max = max.max(u);
347        }
348        // feste Saat → feste Folge; die Toleranzen prüft der Same selbst
349        let mean = sum / 4096.0;
350        assert!((mean - 0.5).abs() < 0.02, "Mittel {mean}");
351        assert!(min < 0.02 && max > 0.98, "Spanne [{min},{max}]");
352        // zweiter Anlauf mit derselben Wurzel: bitgleich
353        let mut s2 = seed_pass(42, 1, 0);
354        assert_eq!(next(&mut s2).to_bits(), {
355            let mut s = seed_pass(42, 1, 0);
356            next(&mut s).to_bits()
357        });
358    }
359
360    #[test]
361    fn cos_dir_trefft_hemisphaere_und_mittelt_zweidrittel_hoehe() {
362        let n = [0.0, 1.0, 0.0];
363        let mut s = seed_pass(9, 3, 11);
364        let mut zy = 0.0;
365        for _ in 0..4096 {
366            let d = cos_dir(n, &mut s);
367            assert!(dot(d, n) >= 0.0, "unter der Fläche");
368            let l = dot(d, d).sqrt();
369            assert!((l - 1.0).abs() < 1e-5, "nicht normiert: {l}");
370            zy += d[1];
371        }
372        // Malley: über der Cosinus-Dichte ist die mittlere Höhe 2/3
373        assert!((zy / 4096.0 - 2.0 / 3.0).abs() < 0.03, "Höhenmittel {zy}");
374    }
375
376    #[test]
377    fn progressiv_konvergiert_gegen_den_langlauf() {
378        let (sdf, albedo) = halle();
379        let sc = PtScene {
380            sdf: &sdf,
381            albedo: &albedo,
382            cfg: PtCfg {
383                max_depth: 3,
384                tmax: 40.0,
385                max_steps: 64,
386                ..Default::default()
387            },
388        };
389        let cam = PtCam::look_at([0.0, 1.6, 4.0], [0.0, 1.2, 0.0], [0.0, 1.0, 0.0], 24.0, 1.4);
390        let (w, h) = (12, 12);
391        let mut ref_acc = PtAccum::new(w, h);
392        for _ in 0..512 {
393            ref_acc.pass(&sc, &cam);
394        }
395        let mut fast = PtAccum::new(w, h);
396        let mut err_prev = f32::INFINITY;
397        for probe in [8, 32, 128] {
398            while fast.n < probe {
399                fast.pass(&sc, &cam);
400            }
401            let err = fast.rmse_vs(&ref_acc.rgb);
402            assert!(err < err_prev, "Konvergenz gestört: {err} nach {probe}");
403            err_prev = err;
404        }
405        // kein schwarzes Bild: die Halle muss Licht einsammeln
406        assert!(
407            ref_acc
408                .rgb
409                .iter()
410                .max_by(|a, b| a.total_cmp(b))
411                .copied()
412                .unwrap()
413                > 0.5,
414            "Bild ohne Licht"
415        );
416    }
417}