euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use super::*;

/// Default energy-conserving bloom settings.
impl Default for BloomConfig3D {
    /// Creates default dual-filter bloom settings (`threshold = 1.0`, `soft_knee = 0.5`, `intensity = 0.25`, `4` mips).
    ///
    /// # Returns
    ///
    /// - `Self` - Default bloom configuration.
    fn default() -> Self {
        Self {
            enabled: true,
            threshold: 1.0,
            soft_knee: 0.5,
            intensity: 0.25,
            mip_count: 4,
        }
    }
}

/// Default photographic histogram auto-exposure settings.
impl Default for AutoExposureConfig3D {
    /// Creates default eye-adaptation auto-exposure settings centered around middle-gray `0.18`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default auto-exposure configuration.
    fn default() -> Self {
        Self {
            enabled: true,
            min_log_lum: -8.0,
            max_log_lum: 6.0,
            target_key_value: 0.18,
            adapt_speed_up: 3.0,
            adapt_speed_down: 1.5,
            min_exposure: 0.05,
            max_exposure: 16.0,
        }
    }
}

/// Default neutral linear color grading settings.
impl Default for ColorGradingConfig3D {
    /// Creates neutral identity color grading settings (`exposure_ev = 0.0`, `contrast = 1.0`, `saturation = 1.0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Default neutral color grading configuration.
    fn default() -> Self {
        Self {
            exposure_ev: 0.0,
            contrast: 1.0,
            saturation: 1.0,
            lift: Vec3::zero(),
            gamma: Vec3::splat(1.0),
            gain: Vec3::splat(1.0),
            temperature: 0.0,
            tint: 0.0,
        }
    }
}

/// Default balanced cinematic `PostFxConfig3D`.
impl Default for PostFxConfig3D {
    /// Creates a default `PostFxConfig3D` using `AgX` tone mapping, dual-filter bloom, auto-exposure, subtle vignette, and FXAA.
    ///
    /// # Returns
    ///
    /// - `Self` - Default post-FX configuration.
    fn default() -> Self {
        Self {
            bloom: BloomConfig3D::default(),
            auto_exposure: AutoExposureConfig3D::default(),
            color_grading: ColorGradingConfig3D::default(),
            vignette_intensity: 0.18,
            vignette_smoothness: 0.55,
            chromatic_aberration: 0.002,
            tone_mapper: ToneMapOperator3D::AgX,
            fxaa_enabled: true,
        }
    }
}

/// Pre-allocated zero-allocation HDR post-processing pipeline execution for `PostFxPipeline3D`.
impl PostFxPipeline3D {
    /// Creates a pre-allocated `PostFxPipeline3D` sized for `width x height` frames.
    ///
    /// # Arguments
    ///
    /// - `usize` - Framebuffer width in pixels (`>= 1`).
    /// - `usize` - Framebuffer height in pixels (`>= 1`).
    /// - `PostFxConfig3D` - Initial post-FX settings.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated HDR post-FX pipeline.
    #[must_use]
    pub fn new(width: usize, height: usize, config: PostFxConfig3D) -> Self {
        let w: usize = width.max(1);
        let h: usize = height.max(1);
        let bloom_mips: Vec<BloomMipBuffer3D> = Self::allocate_bloom_pyramid(w, h);
        Self {
            width: w,
            height: h,
            config,
            adapted_exposure: 1.0,
            adapted_avg_luminance: 0.18,
            last_bloom_input_energy: 0.0,
            last_bloom_output_energy: 0.0,
            histogram_bins: [0_u32; POSTFX_HISTOGRAM_BINS],
            bloom_mips,
            graded_srgb: vec![[0.0; 3]; w * h],
            luma_buffer: vec![0.0_f32; w * h],
            output_rgba8: vec![0_u8; w * h * 4],
        }
    }

    /// Allocates the full `POSTFX_MAX_BLOOM_MIPS` downsample/upsample pyramid for a `width x height` frame.
    ///
    /// # Arguments
    ///
    /// - `usize` - Frame width in pixels.
    /// - `usize` - Frame height in pixels.
    ///
    /// # Returns
    ///
    /// - `Vec<BloomMipBuffer3D>` - Pre-allocated bloom mip buffers.
    #[must_use]
    fn allocate_bloom_pyramid(width: usize, height: usize) -> Vec<BloomMipBuffer3D> {
        let mut mips: Vec<BloomMipBuffer3D> = Vec::with_capacity(POSTFX_MAX_BLOOM_MIPS);
        let mut mw: usize = (width / 2).max(1);
        let mut mh: usize = (height / 2).max(1);
        for _ in 0..POSTFX_MAX_BLOOM_MIPS {
            mips.push(BloomMipBuffer3D {
                width: mw,
                height: mh,
                pixels: vec![[0.0; 3]; mw * mh],
            });
            mw = (mw / 2).max(1);
            mh = (mh / 2).max(1);
        }
        mips
    }

    /// Resizes internal scratch buffers only when `(width, height)` changes; no-op with zero allocations when dimensions match.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target framebuffer width in pixels.
    /// - `usize` - Target framebuffer height in pixels.
    pub fn resize(&mut self, width: usize, height: usize) {
        let w: usize = width.max(1);
        let h: usize = height.max(1);
        if w == self.get_width() && h == self.get_height() {
            return;
        }
        let mips: Vec<BloomMipBuffer3D> = Self::allocate_bloom_pyramid(w, h);
        self.set_width(w);
        self.set_height(h);
        self.set_bloom_mips(mips);
        self.set_graded_srgb(vec![[0.0; 3]; w * h]);
        self.set_luma_buffer(vec![0.0_f32; w * h]);
        self.set_output_rgba8(vec![0_u8; w * h * 4]);
    }

    /// Executes the full HDR post-processing pipeline with zero steady-state heap allocations and returns the sRGB RGBA8 framebuffer slice.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Input linear HDR RGB framebuffer (`len >= width * height`).
    /// - `f32` - Frame delta time in seconds driving smooth auto-exposure eye adaptation.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Final sRGB RGBA8 pixel slice (`len == width * height * 4`).
    pub fn process(&mut self, hdr_input: &[[f32; 3]], dt_seconds: f32) -> &[u8] {
        let w: usize = self.get_width();
        let h: usize = self.get_height();
        let pixel_count: usize = w * h;
        if hdr_input.len() < pixel_count {
            self.get_mut_output_rgba8().fill(0);
            return self.get_output_rgba8().as_slice();
        }
        let cfg: PostFxConfig3D = self.get_config();
        let safe_dt: f32 = if dt_seconds.is_finite() {
            dt_seconds.max(0.0)
        } else {
            0.0
        };
        let (avg_lum, exposure): (f32, f32) =
            self.update_auto_exposure(hdr_input, pixel_count, cfg.get_auto_exposure(), safe_dt);
        self.set_adapted_avg_luminance(avg_lum);
        self.set_adapted_exposure(exposure);
        let bloom_cfg: BloomConfig3D = cfg.get_bloom();
        let active_mips: usize = bloom_cfg.get_mip_count().clamp(1, POSTFX_MAX_BLOOM_MIPS);
        let (bloom_in_e, bloom_out_e): (f32, f32) = if bloom_cfg.get_enabled() {
            self.run_bloom_pyramid(hdr_input, w, h, bloom_cfg, active_mips)
        } else {
            (0.0, 0.0)
        };
        self.set_last_bloom_input_energy(bloom_in_e);
        self.set_last_bloom_output_energy(bloom_out_e);
        let total_exposure: f32 =
            exposure * 2.0_f32.powf(cfg.get_color_grading().get_exposure_ev().clamp(-12.0, 12.0));
        let bloom_mix: f32 = if bloom_cfg.get_enabled() {
            bloom_cfg.get_intensity().clamp(0.0, 0.5)
        } else {
            0.0
        };
        let ca_strength: f32 = cfg.get_chromatic_aberration().clamp(0.0, 0.05);
        let vig_intensity: f32 = cfg.get_vignette_intensity().clamp(0.0, 1.0);
        let vig_smooth: f32 = cfg.get_vignette_smoothness().clamp(0.1, 1.0);
        let grading: ColorGradingConfig3D = cfg.get_color_grading();
        let tone_op: ToneMapOperator3D = cfg.get_tone_mapper();
        let fxaa_on: bool = cfg.get_fxaa_enabled();
        {
            let Self {
                bloom_mips,
                graded_srgb,
                luma_buffer,
                output_rgba8,
                ..
            } = self;
            let bw: usize = bloom_mips[0].get_width();
            let bh: usize = bloom_mips[0].get_height();
            let bloom_top: &[[f32; 3]] = bloom_mips[0].get_pixels().as_slice();
            let inv_w: f32 = 1.0 / (w as f32);
            let inv_h: f32 = 1.0 / (h as f32);
            for y in 0..h {
                let v: f32 = ((y as f32) + 0.5) * inv_h;
                let dy: f32 = v - 0.5;
                for x in 0..w {
                    let u: f32 = ((x as f32) + 0.5) * inv_w;
                    let dx: f32 = u - 0.5;
                    let r_sq: f32 = dx * dx + dy * dy;
                    let base_rgb: [f32; 3] = if ca_strength > 1.0e-5 && w > 2 && h > 2 {
                        let shift: f32 = ca_strength * r_sq;
                        let r_sample: [f32; 3] = Self::sample_hdr_bilinear(
                            hdr_input,
                            w,
                            h,
                            u + dx * shift,
                            v + dy * shift,
                        );
                        let g_sample: [f32; 3] = sanitize_hdr_rgb(hdr_input[y * w + x]);
                        let b_sample: [f32; 3] = Self::sample_hdr_bilinear(
                            hdr_input,
                            w,
                            h,
                            u - dx * shift,
                            v - dy * shift,
                        );
                        [r_sample[0], g_sample[1], b_sample[2]]
                    } else {
                        sanitize_hdr_rgb(hdr_input[y * w + x])
                    };
                    let composited: [f32; 3] = if bloom_mix > 0.0 {
                        let b_rgb: [f32; 3] = Self::sample_mip_bilinear(bloom_top, bw, bh, u, v);
                        let inv_mix: f32 = 1.0 - bloom_mix;
                        [
                            base_rgb[0] * inv_mix + b_rgb[0] * bloom_mix,
                            base_rgb[1] * inv_mix + b_rgb[1] * bloom_mix,
                            base_rgb[2] * inv_mix + b_rgb[2] * bloom_mix,
                        ]
                    } else {
                        base_rgb
                    };
                    let exposed: Vec3 = Vec3::from_array(composited).scale(total_exposure);
                    let mut graded: Vec3 = apply_color_grading(exposed, &grading);
                    if vig_intensity > 1.0e-5 {
                        let dist: f32 = (r_sq * 4.0).sqrt();
                        let t: f32 =
                            ((dist - (1.0 - vig_smooth)) / vig_smooth.max(0.05)).clamp(0.0, 1.0);
                        let smooth_v: f32 = t * t * (3.0 - 2.0 * t);
                        let vig_factor: f32 = (1.0 - vig_intensity * smooth_v).clamp(0.0, 1.0);
                        graded = graded.scale(vig_factor);
                    }
                    let mapped: Vec3 = apply_tone_map(graded, tone_op);
                    let sr: f32 = linear_to_srgb_f32(mapped.get_x());
                    let sg: f32 = linear_to_srgb_f32(mapped.get_y());
                    let sb: f32 = linear_to_srgb_f32(mapped.get_z());
                    let idx: usize = y * w + x;
                    graded_srgb[idx] = [sr, sg, sb];
                    luma_buffer[idx] = 0.299 * sr + 0.587 * sg + 0.114 * sb;
                }
            }
            if fxaa_on && w >= 3 && h >= 3 {
                Self::apply_fxaa_pass(w, h, graded_srgb, luma_buffer, output_rgba8);
            } else {
                for (idx, rgb) in graded_srgb.iter().enumerate() {
                    let base: usize = idx * 4;
                    output_rgba8[base] = srgb_f32_to_u8(rgb[0]);
                    output_rgba8[base + 1] = srgb_f32_to_u8(rgb[1]);
                    output_rgba8[base + 2] = srgb_f32_to_u8(rgb[2]);
                    output_rgba8[base + 3] = 255;
                }
            }
        }
        self.get_output_rgba8().as_slice()
    }

    /// Computes histogram log-average luminance and updates temporally smoothed auto-exposure.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Input HDR linear RGB buffer.
    /// - `usize` - Active pixel count.
    /// - `AutoExposureConfig3D` - Auto-exposure configuration.
    /// - `f32` - Frame delta time in seconds.
    ///
    /// # Returns
    ///
    /// - `(f32, f32)` - Updated `(adapted_avg_luminance, adapted_exposure)`.
    #[must_use]
    fn update_auto_exposure(
        &mut self,
        hdr_input: &[[f32; 3]],
        pixel_count: usize,
        cfg: AutoExposureConfig3D,
        dt: f32,
    ) -> (f32, f32) {
        if !cfg.get_enabled() || pixel_count == 0 {
            return (self.get_adapted_avg_luminance(), 1.0);
        }
        let min_log: f32 = cfg.get_min_log_lum();
        let max_log: f32 = cfg.get_max_log_lum().max(min_log + 0.5);
        let span: f32 = max_log - min_log;
        let inv_span: f32 = 1.0 / span;
        let bins: &mut [u32; POSTFX_HISTOGRAM_BINS] = self.get_mut_histogram_bins();
        bins.fill(0);
        let mut non_black_count: u32 = 0;
        for pixel in hdr_input.iter().take(pixel_count) {
            let safe: [f32; 3] = sanitize_hdr_rgb(*pixel);
            let lum: f32 = postfx_rgb_luminance(safe);
            if lum <= 1.0e-5 {
                bins[0] = bins[0].saturating_add(1);
            } else {
                let norm: f32 = ((lum.log2() - min_log) * inv_span).clamp(0.0, 1.0);
                let bin_idx: usize = ((norm * ((POSTFX_HISTOGRAM_BINS - 1) as f32)).round()
                    as usize)
                    .min(POSTFX_HISTOGRAM_BINS - 1);
                bins[bin_idx] = bins[bin_idx].saturating_add(1);
                non_black_count = non_black_count.saturating_add(1);
            }
        }
        let mut weighted_log_sum: f32 = 0.0;
        let mut weight_total: f32 = 0.0;
        let start_bin: usize = if non_black_count > 0 { 1 } else { 0 };
        for (bin_idx, count) in bins.iter().enumerate().skip(start_bin) {
            if *count == 0 {
                continue;
            }
            let frac: f32 = (bin_idx as f32) / ((POSTFX_HISTOGRAM_BINS - 1) as f32);
            let bin_log: f32 = min_log + frac * span;
            let w: f32 = *count as f32;
            weighted_log_sum += bin_log * w;
            weight_total += w;
        }
        let avg_log: f32 = if weight_total > 0.0 {
            weighted_log_sum / weight_total
        } else {
            min_log
        };
        let target_lum: f32 = 2.0_f32.powf(avg_log).max(1.0e-4);
        let key: f32 = cfg.get_target_key_value().max(0.01);
        let min_exp: f32 = cfg.get_min_exposure().max(0.001);
        let max_exp: f32 = cfg.get_max_exposure().max(min_exp);
        let target_exposure: f32 = (key / target_lum).clamp(min_exp, max_exp);
        let prev_exposure: f32 = self.get_adapted_exposure().clamp(min_exp, max_exp);
        let speed: f32 = if target_exposure < prev_exposure {
            cfg.get_adapt_speed_up().max(0.05)
        } else {
            cfg.get_adapt_speed_down().max(0.05)
        };
        let adapt_t: f32 = if dt > 0.0 {
            (1.0 - (-dt * speed).exp()).clamp(0.0, 1.0)
        } else {
            0.0
        };
        let next_exposure: f32 =
            (prev_exposure + (target_exposure - prev_exposure) * adapt_t).clamp(min_exp, max_exp);
        let prev_lum: f32 = self.get_adapted_avg_luminance().max(1.0e-4);
        let next_lum: f32 = (prev_lum + (target_lum - prev_lum) * adapt_t).max(1.0e-4);
        (next_lum, next_exposure)
    }

    /// Executes the dual-filter Karis-suppressed bloom downsample and normalized 3x3 tent upsample pyramid in-place.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Input linear HDR framebuffer.
    /// - `usize` - Input width.
    /// - `usize` - Input height.
    /// - `BloomConfig3D` - Bloom threshold and soft-knee configuration.
    /// - `usize` - Active mip level count (`1..=POSTFX_MAX_BLOOM_MIPS`).
    ///
    /// # Returns
    ///
    /// - `(f32, f32)` - `(prefilter_input_energy, upsampled_output_energy)` mean luminance per pixel.
    #[must_use]
    fn run_bloom_pyramid(
        &mut self,
        hdr_input: &[[f32; 3]],
        width: usize,
        height: usize,
        bloom_cfg: BloomConfig3D,
        active_mips: usize,
    ) -> (f32, f32) {
        let thresh: f32 = bloom_cfg.get_threshold();
        let knee: f32 = bloom_cfg.get_soft_knee();
        let bloom_mips: &mut Vec<BloomMipBuffer3D> = self.get_mut_bloom_mips();
        let w0: usize = bloom_mips[0].get_width();
        let h0: usize = bloom_mips[0].get_height();
        let mut input_energy_sum: f32 = 0.0;
        {
            let mip0: &mut [[f32; 3]] = bloom_mips[0].get_mut_pixels().as_mut_slice();
            for y in 0..h0 {
                let sy0: usize = (y * 2).min(height - 1);
                let sy1: usize = (sy0 + 1).min(height - 1);
                for x in 0..w0 {
                    let sx0: usize = (x * 2).min(width - 1);
                    let sx1: usize = (sx0 + 1).min(width - 1);
                    let s00: [f32; 3] = soft_knee_bloom_prefilter(
                        sanitize_hdr_rgb(hdr_input[sy0 * width + sx0]),
                        thresh,
                        knee,
                    );
                    let s10: [f32; 3] = soft_knee_bloom_prefilter(
                        sanitize_hdr_rgb(hdr_input[sy0 * width + sx1]),
                        thresh,
                        knee,
                    );
                    let s01: [f32; 3] = soft_knee_bloom_prefilter(
                        sanitize_hdr_rgb(hdr_input[sy1 * width + sx0]),
                        thresh,
                        knee,
                    );
                    let s11: [f32; 3] = soft_knee_bloom_prefilter(
                        sanitize_hdr_rgb(hdr_input[sy1 * width + sx1]),
                        thresh,
                        knee,
                    );
                    let w00: f32 = 1.0 / (1.0 + postfx_rgb_luminance(s00));
                    let w10: f32 = 1.0 / (1.0 + postfx_rgb_luminance(s10));
                    let w01: f32 = 1.0 / (1.0 + postfx_rgb_luminance(s01));
                    let w11: f32 = 1.0 / (1.0 + postfx_rgb_luminance(s11));
                    let inv_w: f32 = 1.0 / (w00 + w10 + w01 + w11).max(1.0e-5);
                    let avg: [f32; 3] = [
                        (s00[0] * w00 + s10[0] * w10 + s01[0] * w01 + s11[0] * w11) * inv_w,
                        (s00[1] * w00 + s10[1] * w10 + s01[1] * w01 + s11[1] * w11) * inv_w,
                        (s00[2] * w00 + s10[2] * w10 + s01[2] * w01 + s11[2] * w11) * inv_w,
                    ];
                    mip0[y * w0 + x] = avg;
                    input_energy_sum += postfx_rgb_luminance(avg);
                }
            }
        }
        for level in 1..active_mips {
            let (left, right): (&mut [BloomMipBuffer3D], &mut [BloomMipBuffer3D]) =
                bloom_mips.split_at_mut(level);
            let src_w: usize = left[level - 1].get_width();
            let src_h: usize = left[level - 1].get_height();
            let dst_w: usize = right[0].get_width();
            let dst_h: usize = right[0].get_height();
            let src: &[[f32; 3]] = left[level - 1].get_pixels().as_slice();
            let dst: &mut [[f32; 3]] = right[0].get_mut_pixels().as_mut_slice();
            for y in 0..dst_h {
                let sy0: usize = (y * 2).min(src_h - 1);
                let sy1: usize = (sy0 + 1).min(src_h - 1);
                for x in 0..dst_w {
                    let sx0: usize = (x * 2).min(src_w - 1);
                    let sx1: usize = (sx0 + 1).min(src_w - 1);
                    let c00: [f32; 3] = src[sy0 * src_w + sx0];
                    let c10: [f32; 3] = src[sy0 * src_w + sx1];
                    let c01: [f32; 3] = src[sy1 * src_w + sx0];
                    let c11: [f32; 3] = src[sy1 * src_w + sx1];
                    dst[y * dst_w + x] = [
                        0.25 * (c00[0] + c10[0] + c01[0] + c11[0]),
                        0.25 * (c00[1] + c10[1] + c01[1] + c11[1]),
                        0.25 * (c00[2] + c10[2] + c01[2] + c11[2]),
                    ];
                }
            }
        }
        for level in (1..active_mips).rev() {
            let (left, right): (&mut [BloomMipBuffer3D], &mut [BloomMipBuffer3D]) =
                bloom_mips.split_at_mut(level);
            let src_w: usize = right[0].get_width();
            let src_h: usize = right[0].get_height();
            let dst_w: usize = left[level - 1].get_width();
            let dst_h: usize = left[level - 1].get_height();
            let dst: &mut [[f32; 3]] = left[level - 1].get_mut_pixels().as_mut_slice();
            let src: &[[f32; 3]] = right[0].get_pixels().as_slice();
            let inv_dw: f32 = 1.0 / (dst_w as f32);
            let inv_dh: f32 = 1.0 / (dst_h as f32);
            let step_u: f32 = 1.0 / (src_w as f32);
            let step_v: f32 = 1.0 / (src_h as f32);
            for y in 0..dst_h {
                let v: f32 = ((y as f32) + 0.5) * inv_dh;
                for x in 0..dst_w {
                    let u: f32 = ((x as f32) + 0.5) * inv_dw;
                    let tent: [f32; 3] =
                        Self::sample_tent_3x3(src, src_w, src_h, u, v, step_u, step_v);
                    let cur: [f32; 3] = dst[y * dst_w + x];
                    dst[y * dst_w + x] = [
                        0.5 * (cur[0] + tent[0]),
                        0.5 * (cur[1] + tent[1]),
                        0.5 * (cur[2] + tent[2]),
                    ];
                }
            }
        }
        let mut output_energy_sum: f32 = 0.0;
        for rgb in bloom_mips[0].get_pixels().iter() {
            output_energy_sum += postfx_rgb_luminance(*rgb);
        }
        let inv_n: f32 = 1.0 / ((w0 * h0).max(1) as f32);
        (input_energy_sum * inv_n, output_energy_sum * inv_n)
    }

    /// Evaluates a normalized 3x3 tent filter (`[1,2,1; 2,4,2; 1,2,1] / 16`) for bloom upsampling.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Source bloom mip buffer.
    /// - `usize` - Source mip width.
    /// - `usize` - Source mip height.
    /// - `f32` - Normalized horizontal coordinate `u`.
    /// - `f32` - Normalized vertical coordinate `v`.
    /// - `f32` - Horizontal texel step `du`.
    /// - `f32` - Vertical texel step `dv`.
    ///
    /// # Returns
    ///
    /// - `[f32; 3]` - Energy-preserving tent-filtered RGB value.
    #[must_use]
    fn sample_tent_3x3(
        src: &[[f32; 3]],
        w: usize,
        h: usize,
        u: f32,
        v: f32,
        du: f32,
        dv: f32,
    ) -> [f32; 3] {
        let offsets: [(f32, f32, f32); 9] = [
            (-du, -dv, 1.0 / 16.0),
            (0.0, -dv, 2.0 / 16.0),
            (du, -dv, 1.0 / 16.0),
            (-du, 0.0, 2.0 / 16.0),
            (0.0, 0.0, 4.0 / 16.0),
            (du, 0.0, 2.0 / 16.0),
            (-du, dv, 1.0 / 16.0),
            (0.0, dv, 2.0 / 16.0),
            (du, dv, 1.0 / 16.0),
        ];
        let mut out: [f32; 3] = [0.0; 3];
        for (ox, oy, weight) in offsets.iter() {
            let s: [f32; 3] = Self::sample_mip_bilinear(src, w, h, u + *ox, v + *oy);
            out[0] += s[0] * *weight;
            out[1] += s[1] * *weight;
            out[2] += s[2] * *weight;
        }
        out
    }

    /// Bilinearly samples a sanitized HDR RGB image at normalized `(u, v)`.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Source HDR image slice.
    /// - `usize` - Image width.
    /// - `usize` - Image height.
    /// - `f32` - Normalized U coordinate.
    /// - `f32` - Normalized V coordinate.
    ///
    /// # Returns
    ///
    /// - `[f32; 3]` - Bilinearly filtered sanitized HDR RGB sample.
    #[must_use]
    fn sample_hdr_bilinear(src: &[[f32; 3]], w: usize, h: usize, u: f32, v: f32) -> [f32; 3] {
        let fx: f32 = (u.clamp(0.0, 1.0) * (w as f32) - 0.5).clamp(0.0, (w - 1) as f32);
        let fy: f32 = (v.clamp(0.0, 1.0) * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(w - 1);
        let y1: usize = (y0 + 1).min(h - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let c00: [f32; 3] = sanitize_hdr_rgb(src[y0 * w + x0]);
        let c10: [f32; 3] = sanitize_hdr_rgb(src[y0 * w + x1]);
        let c01: [f32; 3] = sanitize_hdr_rgb(src[y1 * w + x0]);
        let c11: [f32; 3] = sanitize_hdr_rgb(src[y1 * w + x1]);
        let mut out: [f32; 3] = [0.0; 3];
        for ch in 0..3usize {
            let top: f32 = c00[ch] + (c10[ch] - c00[ch]) * tx;
            let bot: f32 = c01[ch] + (c11[ch] - c01[ch]) * tx;
            out[ch] = top + (bot - top) * ty;
        }
        out
    }

    /// Bilinearly samples a pre-sanitized bloom mip slice at normalized `(u, v)`.
    ///
    /// # Arguments
    ///
    /// - `&[[f32; 3]]` - Source bloom mip slice.
    /// - `usize` - Mip width.
    /// - `usize` - Mip height.
    /// - `f32` - Normalized U coordinate.
    /// - `f32` - Normalized V coordinate.
    ///
    /// # Returns
    ///
    /// - `[f32; 3]` - Bilinearly filtered RGB value.
    #[must_use]
    fn sample_mip_bilinear(src: &[[f32; 3]], w: usize, h: usize, u: f32, v: f32) -> [f32; 3] {
        let fx: f32 = (u.clamp(0.0, 1.0) * (w as f32) - 0.5).clamp(0.0, (w - 1) as f32);
        let fy: f32 = (v.clamp(0.0, 1.0) * (h as f32) - 0.5).clamp(0.0, (h - 1) as f32);
        let x0: usize = fx.floor() as usize;
        let y0: usize = fy.floor() as usize;
        let x1: usize = (x0 + 1).min(w - 1);
        let y1: usize = (y0 + 1).min(h - 1);
        let tx: f32 = fx - (x0 as f32);
        let ty: f32 = fy - (y0 as f32);
        let c00: [f32; 3] = src[y0 * w + x0];
        let c10: [f32; 3] = src[y0 * w + x1];
        let c01: [f32; 3] = src[y1 * w + x0];
        let c11: [f32; 3] = src[y1 * w + x1];
        let mut out: [f32; 3] = [0.0; 3];
        for ch in 0..3usize {
            let top: f32 = c00[ch] + (c10[ch] - c00[ch]) * tx;
            let bot: f32 = c01[ch] + (c11[ch] - c01[ch]) * tx;
            out[ch] = top + (bot - top) * ty;
        }
        out
    }

    /// Runs luma-guided FXAA edge smoothing from `graded_srgb` into `output_rgba8` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `usize` - Framebuffer width.
    /// - `usize` - Framebuffer height.
    /// - `&[[f32; 3]]` - Tone-mapped sRGB `[0.0, 1.0]` pixels.
    /// - `&[f32]` - Perceptual sRGB luma buffer.
    /// - `&mut [u8]` - Destination RGBA8 buffer (`len == width * height * 4`).
    fn apply_fxaa_pass(
        w: usize,
        h: usize,
        graded_srgb: &[[f32; 3]],
        luma: &[f32],
        output_rgba8: &mut [u8],
    ) {
        for y in 0..h {
            let ym: usize = y.saturating_sub(1);
            let yp: usize = (y + 1).min(h - 1);
            for x in 0..w {
                let xm: usize = x.saturating_sub(1);
                let xp: usize = (x + 1).min(w - 1);
                let idx: usize = y * w + x;
                let lm: f32 = luma[idx];
                let ln: f32 = luma[ym * w + x];
                let ls: f32 = luma[yp * w + x];
                let lw: f32 = luma[y * w + xm];
                let le: f32 = luma[y * w + xp];
                let l_min: f32 = lm.min(ln).min(ls).min(lw).min(le);
                let l_max: f32 = lm.max(ln).max(ls).max(lw).max(le);
                let range: f32 = l_max - l_min;
                let base_out: usize = idx * 4;
                if range < FXAA_EDGE_THRESHOLD_MIN.max(l_max * FXAA_EDGE_THRESHOLD) {
                    let c: [f32; 3] = graded_srgb[idx];
                    output_rgba8[base_out] = srgb_f32_to_u8(c[0]);
                    output_rgba8[base_out + 1] = srgb_f32_to_u8(c[1]);
                    output_rgba8[base_out + 2] = srgb_f32_to_u8(c[2]);
                    output_rgba8[base_out + 3] = 255;
                    continue;
                }
                let lnw: f32 = luma[ym * w + xm];
                let lne: f32 = luma[ym * w + xp];
                let lsw: f32 = luma[yp * w + xm];
                let lse: f32 = luma[yp * w + xp];
                let avg_luma: f32 =
                    (2.0 * (ln + ls + lw + le) + (lnw + lne + lsw + lse)) * (1.0 / 12.0);
                let subpix_raw: f32 = ((avg_luma - lm).abs() / range.max(1.0e-5)).clamp(0.0, 1.0);
                let subpix_smooth: f32 = subpix_raw * subpix_raw * (3.0 - 2.0 * subpix_raw);
                let subpix_blend: f32 = subpix_smooth * subpix_smooth * FXAA_SUBPIX_QUALITY;
                let edge_h: f32 = (lnw - 2.0 * lw + lsw).abs()
                    + 2.0 * (ln - 2.0 * lm + ls).abs()
                    + (lne - 2.0 * le + lse).abs();
                let edge_v: f32 = (lnw - 2.0 * ln + lne).abs()
                    + 2.0 * (lw - 2.0 * lm + le).abs()
                    + (lsw - 2.0 * ls + lse).abs();
                let is_horizontal: bool = edge_h >= edge_v;
                let neighbor_idx: usize = if is_horizontal {
                    if (ln - lm).abs() >= (ls - lm).abs() {
                        ym * w + x
                    } else {
                        yp * w + x
                    }
                } else if (lw - lm).abs() >= (le - lm).abs() {
                    y * w + xm
                } else {
                    y * w + xp
                };
                let c_center: [f32; 3] = graded_srgb[idx];
                let c_step: [f32; 3] = graded_srgb[neighbor_idx];
                let blend: f32 = subpix_blend.clamp(0.0, 0.5);
                let r: f32 = c_center[0] + (c_step[0] - c_center[0]) * blend;
                let g: f32 = c_center[1] + (c_step[1] - c_center[1]) * blend;
                let b: f32 = c_center[2] + (c_step[2] - c_center[2]) * blend;
                output_rgba8[base_out] = srgb_f32_to_u8(r);
                output_rgba8[base_out + 1] = srgb_f32_to_u8(g);
                output_rgba8[base_out + 2] = srgb_f32_to_u8(b);
                output_rgba8[base_out + 3] = 255;
            }
        }
    }

    /// Returns the latest sRGB RGBA8 output slice (`len == width * height * 4`).
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Final post-processed RGBA8 bytes.
    #[must_use]
    pub fn output_rgba8(&self) -> &[u8] {
        self.get_output_rgba8().as_slice()
    }

    /// Returns backing scratch capacities `(bloom_total_cap, graded_cap, luma_cap, rgba_cap)` to audit zero steady-state allocations.
    ///
    /// # Returns
    ///
    /// - `(usize, usize, usize, usize)` - Internal buffer capacities.
    #[must_use]
    pub fn scratch_capacities(&self) -> (usize, usize, usize, usize) {
        let mut bloom_cap: usize = 0;
        for mip in self.get_bloom_mips().iter() {
            bloom_cap += mip.get_pixels().capacity();
        }
        (
            bloom_cap,
            self.get_graded_srgb().capacity(),
            self.get_luma_buffer().capacity(),
            self.get_output_rgba8().capacity(),
        )
    }

    /// Returns backing buffer addresses `(bloom_mip0_ptr, graded_ptr, output_rgba8_ptr)` verifying in-place reuse.
    ///
    /// # Returns
    ///
    /// - `(usize, usize, usize)` - Backing allocation pointer addresses.
    #[must_use]
    pub fn buffer_addresses(&self) -> (usize, usize, usize) {
        let bloom_ptr: usize = self
            .get_bloom_mips()
            .first()
            .map_or(0, |mip: &BloomMipBuffer3D| {
                mip.get_pixels().as_ptr() as usize
            });
        (
            bloom_ptr,
            self.get_graded_srgb().as_ptr() as usize,
            self.get_output_rgba8().as_ptr() as usize,
        )
    }
}