euv-core 0.53.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
use super::*;

/// Conservative reverse-Z Hierarchical Z-Buffer construction, occluder pre-pass stamping, and O(1) occlusion queries for `HiZPyramid`.
impl HiZPyramid {
    /// Creates an empty `HiZPyramid` sized for `(viewport_width, viewport_height)` using `8x8` base cells.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target viewport width in pixels.
    /// - `usize` - Target viewport height in pixels.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated reverse-Z Hi-Z pyramid marked invalid until populated.
    #[must_use]
    pub fn new(viewport_width: usize, viewport_height: usize) -> Self {
        let mut pyramid: Self = Self {
            viewport_width: 0,
            viewport_height: 0,
            cell_size_px: HIZ_BASE_CELL_PX,
            valid: false,
            levels: Vec::new(),
            level_dims: Vec::new(),
        };
        pyramid.ensure_dimensions(viewport_width, viewport_height);
        pyramid
    }

    /// Ensures internal mip buffers match `(viewport_width, viewport_height)` without reallocating when dimensions are unchanged.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target viewport width in pixels.
    /// - `usize` - Target viewport height in pixels.
    pub fn ensure_dimensions(&mut self, viewport_width: usize, viewport_height: usize) {
        let safe_w: usize = viewport_width.max(1);
        let safe_h: usize = viewport_height.max(1);
        let cell_px: usize = self.get_cell_size_px().max(1);
        if self.get_viewport_width() == safe_w
            && self.get_viewport_height() == safe_h
            && !self.levels_slice().is_empty()
        {
            return;
        }
        self.set_viewport_width(safe_w);
        self.set_viewport_height(safe_h);
        self.set_cell_size_px(cell_px);
        self.set_valid(false);
        let Self {
            levels, level_dims, ..
        } = self;
        levels.clear();
        level_dims.clear();
        let mut cur_w: usize = safe_w.div_ceil(cell_px).max(1);
        let mut cur_h: usize = safe_h.div_ceil(cell_px).max(1);
        loop {
            level_dims.push((cur_w, cur_h));
            levels.push(vec![0.0; cur_w * cur_h]);
            if cur_w == 1 && cur_h == 1 {
                break;
            }
            cur_w = cur_w.div_ceil(2).max(1);
            cur_h = cur_h.div_ceil(2).max(1);
        }
    }

    /// Clears base level cells to reverse-Z far (`0.0`) and invalidates the pyramid prior to same-frame occluder stamping.
    pub fn clear_for_prepass(&mut self) {
        self.set_valid(false);
        let Self { levels, .. } = self;
        if let Some(base_level) = levels.first_mut() {
            base_level.fill(0.0);
        }
    }

    /// Returns the number of mip levels currently allocated in this Hi-Z pyramid.
    ///
    /// # Returns
    ///
    /// - `usize` - Mip level count (`0` when uninitialized).
    #[must_use]
    pub fn mip_count(&self) -> usize {
        self.levels_slice().len()
    }

    /// Returns an immutable slice of all mip buffers.
    ///
    /// # Returns
    ///
    /// - `&[Vec<f32>]` - Mip level depth arrays.
    #[must_use]
    fn levels_slice(&self) -> &[Vec<f32>] {
        let Self { levels, .. } = self;
        levels.as_slice()
    }

    /// Builds the full conservative reverse-Z Hi-Z mip pyramid directly from a rendered reverse-Z `depth_buffer`.
    ///
    /// # Arguments
    ///
    /// - `&[f32]` - Full-resolution reverse-Z `1/w` depth buffer (`0.0` = sky/far).
    /// - `usize` - Viewport width in pixels.
    /// - `usize` - Viewport height in pixels.
    pub fn build_from_depth_buffer(
        &mut self,
        depth_buffer: &[f32],
        viewport_width: usize,
        viewport_height: usize,
    ) {
        if viewport_width == 0
            || viewport_height == 0
            || depth_buffer.len() < viewport_width.saturating_mul(viewport_height)
        {
            self.set_valid(false);
            return;
        }
        self.ensure_dimensions(viewport_width, viewport_height);
        let cell_px: usize = self.get_cell_size_px().max(1);
        let (base_w, base_h): (usize, usize) = {
            let Self { level_dims, .. } = self;
            level_dims.first().copied().unwrap_or((1, 1))
        };
        {
            let Self { levels, .. } = self;
            if let Some(level0) = levels.first_mut() {
                for cell_y in 0..base_h {
                    let py_start: usize = cell_y * cell_px;
                    let py_end: usize = (py_start + cell_px).min(viewport_height);
                    let cell_row_off: usize = cell_y * base_w;
                    for cell_x in 0..base_w {
                        let px_start: usize = cell_x * cell_px;
                        let px_end: usize = (px_start + cell_px).min(viewport_width);
                        let mut min_inv_w: f32 = f32::INFINITY;
                        for pixel_y in py_start..py_end {
                            let row_off: usize = pixel_y * viewport_width;
                            let span: &[f32] =
                                &depth_buffer[(row_off + px_start)..(row_off + px_end)];
                            for &depth_val in span.iter() {
                                if depth_val < min_inv_w {
                                    min_inv_w = depth_val;
                                }
                            }
                            if min_inv_w <= 0.0 {
                                min_inv_w = 0.0;
                                break;
                            }
                        }
                        level0[cell_row_off + cell_x] = if min_inv_w.is_finite() {
                            min_inv_w
                        } else {
                            0.0
                        };
                    }
                }
            }
        }
        self.rebuild_mips();
    }

    /// Conservatively stamps a closed solid occluder triangle into Level 0 Hi-Z cells that lie 100% inside the triangle footprint.
    ///
    /// # Arguments
    ///
    /// - `[f32; 3]` - Triangle vertex screen X coordinates `(sx0, sx1, sx2)`.
    /// - `[f32; 3]` - Triangle vertex screen Y coordinates `(sy0, sy1, sy2)`.
    /// - `[f32; 3]` - Triangle vertex reverse-Z `1/w` values `(inv_w0, inv_w1, inv_w2)`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    pub fn stamp_occluder_triangle_conservative(
        &mut self,
        screen_x: [f32; 3],
        screen_y: [f32; 3],
        inv_w: [f32; 3],
    ) {
        let area: f32 = (screen_x[1] - screen_x[0]) * (screen_y[2] - screen_y[0])
            - (screen_y[1] - screen_y[0]) * (screen_x[2] - screen_x[0]);
        if area >= -1.0 {
            return;
        }
        let cell_px: usize = self.get_cell_size_px().max(1);
        let cell_f: f32 = cell_px as f32;
        let (base_w, base_h): (usize, usize) = {
            let Self { level_dims, .. } = self;
            match level_dims.first().copied() {
                Some(dims) => dims,
                None => return,
            }
        };
        let min_px: f32 = screen_x[0].min(screen_x[1]).min(screen_x[2]);
        let max_px: f32 = screen_x[0].max(screen_x[1]).max(screen_x[2]);
        let min_py: f32 = screen_y[0].min(screen_y[1]).min(screen_y[2]);
        let max_py: f32 = screen_y[0].max(screen_y[1]).max(screen_y[2]);
        let cell_x0: usize = ((min_px / cell_f).floor().max(0.0) as usize).min(base_w);
        let cell_x1: usize =
            ((max_px / cell_f).floor().max(0.0) as usize).min(base_w.saturating_sub(1));
        let cell_y0: usize = ((min_py / cell_f).floor().max(0.0) as usize).min(base_h);
        let cell_y1: usize =
            ((max_py / cell_f).floor().max(0.0) as usize).min(base_h.saturating_sub(1));
        let out_of_x_bounds: bool = cell_x0 > cell_x1 || cell_x0 >= base_w;
        let out_of_y_bounds: bool = cell_y0 > cell_y1 || cell_y0 >= base_h;
        if out_of_x_bounds || out_of_y_bounds {
            return;
        }
        let inv_area: f32 = 1.0 / area;
        let dw0_dx: f32 = (screen_y[1] - screen_y[2]) * inv_area;
        let dw1_dx: f32 = (screen_y[2] - screen_y[0]) * inv_area;
        let dw2_dx: f32 = -(dw0_dx + dw1_dx);
        let dw0_dy: f32 = (screen_x[2] - screen_x[1]) * inv_area;
        let dw1_dy: f32 = (screen_x[0] - screen_x[2]) * inv_area;
        let dw2_dy: f32 = -(dw0_dy + dw1_dy);
        let d_inv_w_dx: f32 = dw0_dx * inv_w[0] + dw1_dx * inv_w[1] + dw2_dx * inv_w[2];
        let d_inv_w_dy: f32 = dw0_dy * inv_w[0] + dw1_dy * inv_w[1] + dw2_dy * inv_w[2];
        let tri_min_inv_w: f32 = inv_w[0].min(inv_w[1]).min(inv_w[2]).max(0.0);
        let Self { levels, .. } = self;
        let Some(level0) = levels.first_mut() else {
            return;
        };
        let dx_step_w0: f32 = dw0_dx * cell_f;
        let dx_step_w1: f32 = dw1_dx * cell_f;
        let dx_step_w2: f32 = dw2_dx * cell_f;
        let dx_step_iw: f32 = d_inv_w_dx * cell_f;
        let bias_w0: f32 = dw0_dx.min(0.0) * cell_f + dw0_dy.min(0.0) * cell_f;
        let bias_w1: f32 = dw1_dx.min(0.0) * cell_f + dw1_dy.min(0.0) * cell_f;
        let bias_w2: f32 = dw2_dx.min(0.0) * cell_f + dw2_dy.min(0.0) * cell_f;
        let bias_iw: f32 = d_inv_w_dx.min(0.0) * cell_f + d_inv_w_dy.min(0.0) * cell_f;
        let px_start: f32 = (cell_x0 * cell_px) as f32;
        for cell_y in cell_y0..=cell_y1 {
            let py0: f32 = (cell_y * cell_px) as f32;
            let row_off: usize = cell_y * base_w;
            let mut w0_tl: f32 = ((screen_x[1] - px_start) * (screen_y[2] - py0)
                - (screen_y[1] - py0) * (screen_x[2] - px_start))
                * inv_area;
            let mut w1_tl: f32 = ((screen_x[2] - px_start) * (screen_y[0] - py0)
                - (screen_y[2] - py0) * (screen_x[0] - px_start))
                * inv_area;
            let mut w2_tl: f32 = 1.0 - w0_tl - w1_tl;
            let mut inv_w_tl: f32 = w0_tl * inv_w[0] + w1_tl * inv_w[1] + w2_tl * inv_w[2];
            for cell_x in cell_x0..=cell_x1 {
                if w0_tl + bias_w0 >= 0.0 && w1_tl + bias_w1 >= 0.0 && w2_tl + bias_w2 >= 0.0 {
                    let inv_w_cell_min: f32 = (inv_w_tl + bias_iw).max(tri_min_inv_w);
                    let cell_slot: &mut f32 = &mut level0[row_off + cell_x];
                    if inv_w_cell_min > *cell_slot {
                        *cell_slot = inv_w_cell_min;
                    }
                }
                w0_tl += dx_step_w0;
                w1_tl += dx_step_w1;
                w2_tl += dx_step_w2;
                inv_w_tl += dx_step_iw;
            }
        }
    }

    /// Rebuilds all coarser mip levels (`1..mip_count`) from Level 0 using conservative 2x2 minimum reduction and marks the pyramid valid.
    pub fn rebuild_mips(&mut self) {
        let mip_len: usize = self.mip_count();
        if mip_len == 0 {
            self.set_valid(false);
            return;
        }
        {
            let Self {
                levels, level_dims, ..
            } = self;
            for mip_idx in 1..mip_len {
                let (src_w, src_h): (usize, usize) = level_dims[mip_idx - 1];
                let (dst_w, dst_h): (usize, usize) = level_dims[mip_idx];
                let (left_slice, right_slice): (&mut [Vec<f32>], &mut [Vec<f32>]) =
                    levels.split_at_mut(mip_idx);
                let src_level: &[f32] = left_slice[mip_idx - 1].as_slice();
                let dst_level: &mut [f32] = right_slice[0].as_mut_slice();
                for dst_y in 0..dst_h {
                    let sy0: usize = (dst_y * 2).min(src_h.saturating_sub(1));
                    let sy1: usize = (sy0 + 1).min(src_h.saturating_sub(1));
                    let row0: usize = sy0 * src_w;
                    let row1: usize = sy1 * src_w;
                    let dst_row: usize = dst_y * dst_w;
                    for dst_x in 0..dst_w {
                        let sx0: usize = (dst_x * 2).min(src_w.saturating_sub(1));
                        let sx1: usize = (sx0 + 1).min(src_w.saturating_sub(1));
                        let min_top: f32 = src_level[row0 + sx0].min(src_level[row0 + sx1]);
                        let min_bot: f32 = src_level[row1 + sx0].min(src_level[row1 + sx1]);
                        dst_level[dst_row + dst_x] = min_top.min(min_bot);
                    }
                }
            }
        }
        self.set_valid(true);
    }

    /// Tests whether `world_bounds` is 100% occluded by closer geometry already recorded in this conservative reverse-Z Hi-Z pyramid.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - Candidate world-space bounding box.
    /// - `&Mat4` - Active frame view-projection matrix.
    /// - `f32` - Camera near clip distance in meters.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when guaranteed completely hidden behind closer occluders.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn is_bounds_occluded(
        &self,
        world_bounds: AxisAlignedBox3D,
        view_proj: &Mat4,
        near_plane: f32,
    ) -> bool {
        if !self.get_valid() || self.mip_count() == 0 {
            return false;
        }
        let min_pt: Vec3 = world_bounds.get_min();
        let max_pt: Vec3 = world_bounds.get_max();
        let corners: [Vec3; 8] = [
            Vec3::new(min_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
            Vec3::new(max_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
            Vec3::new(min_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
            Vec3::new(max_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
            Vec3::new(min_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
            Vec3::new(max_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
            Vec3::new(min_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
            Vec3::new(max_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
        ];
        let safe_near: f32 = near_plane.max(0.15);
        let vp_w: f32 = self.get_viewport_width() as f32;
        let vp_h: f32 = self.get_viewport_height() as f32;
        let mut min_sx: f32 = f32::INFINITY;
        let mut max_sx: f32 = f32::NEG_INFINITY;
        let mut min_sy: f32 = f32::INFINITY;
        let mut max_sy: f32 = f32::NEG_INFINITY;
        let mut nearest_inv_w: f32 = 0.0;
        for corner in corners.iter().copied() {
            let clip: [f32; 4] = view_proj.mul_point4(corner);
            if clip[3] <= safe_near {
                return false;
            }
            let inv_w: f32 = 1.0 / clip[3];
            if inv_w > nearest_inv_w {
                nearest_inv_w = inv_w;
            }
            let sx: f32 = (clip[0] * inv_w * 0.5 + 0.5) * vp_w;
            let sy: f32 = (0.5 - clip[1] * inv_w * 0.5) * vp_h;
            min_sx = min_sx.min(sx);
            max_sx = max_sx.max(sx);
            min_sy = min_sy.min(sy);
            max_sy = max_sy.max(sy);
        }
        let outside_horizontal: bool = max_sx < 0.0 || min_sx >= vp_w;
        let outside_vertical: bool = max_sy < 0.0 || min_sy >= vp_h;
        if outside_horizontal || outside_vertical {
            return false;
        }
        let clamped_x0: f32 = min_sx.clamp(0.0, (vp_w - 1.0).max(0.0));
        let clamped_x1: f32 = max_sx.clamp(0.0, (vp_w - 1.0).max(0.0));
        let clamped_y0: f32 = min_sy.clamp(0.0, (vp_h - 1.0).max(0.0));
        let clamped_y1: f32 = max_sy.clamp(0.0, (vp_h - 1.0).max(0.0));
        let cell_px: usize = self.get_cell_size_px().max(1);
        let mut cx0: usize = (clamped_x0 as usize) / cell_px;
        let mut cx1: usize = (clamped_x1 as usize) / cell_px;
        let mut cy0: usize = (clamped_y0 as usize) / cell_px;
        let mut cy1: usize = (clamped_y1 as usize) / cell_px;
        let Self {
            levels, level_dims, ..
        } = self;
        let max_mip: usize = levels.len().saturating_sub(1);
        let mut mip_idx: usize = 0;
        while mip_idx < max_mip && ((cx1 - cx0) > 1 || (cy1 - cy0) > 1) {
            cx0 >>= 1;
            cx1 >>= 1;
            cy0 >>= 1;
            cy1 >>= 1;
            mip_idx += 1;
        }
        let (mip_w, mip_h): (usize, usize) = level_dims[mip_idx];
        let level_data: &[f32] = levels[mip_idx].as_slice();
        let safe_x0: usize = cx0.min(mip_w.saturating_sub(1));
        let safe_x1: usize = cx1.min(mip_w.saturating_sub(1));
        let safe_y0: usize = cy0.min(mip_h.saturating_sub(1));
        let safe_y1: usize = cy1.min(mip_h.saturating_sub(1));
        let mut hiz_min_inv_w: f32 = f32::INFINITY;
        for cell_y in safe_y0..=safe_y1 {
            let row_off: usize = cell_y * mip_w;
            for cell_x in safe_x0..=safe_x1 {
                let sample: f32 = level_data[row_off + cell_x];
                if sample < hiz_min_inv_w {
                    hiz_min_inv_w = sample;
                }
            }
        }
        let test_inv_w: f32 =
            nearest_inv_w * HIZ_CONSERVATIVE_INV_W_SCALE + HIZ_CONSERVATIVE_INV_W_EPS;
        hiz_min_inv_w.is_finite() && test_inv_w < hiz_min_inv_w
    }

    /// Estimates the projected screen-space bounding area in square pixels of `world_bounds` for micro-cluster culling.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - Candidate world-space bounding box.
    /// - `&Mat4` - Active frame view-projection matrix.
    /// - `f32` - Viewport width in pixels.
    /// - `f32` - Viewport height in pixels.
    /// - `f32` - Camera near clip distance in meters.
    ///
    /// # Returns
    ///
    /// - `f32` - Projected screen area in square pixels (`f32::INFINITY` if intersecting near plane).
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn projected_screen_area_px(
        world_bounds: AxisAlignedBox3D,
        view_proj: &Mat4,
        viewport_w: f32,
        viewport_h: f32,
        near_plane: f32,
    ) -> f32 {
        let min_pt: Vec3 = world_bounds.get_min();
        let max_pt: Vec3 = world_bounds.get_max();
        let corners: [Vec3; 8] = [
            Vec3::new(min_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
            Vec3::new(max_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
            Vec3::new(min_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
            Vec3::new(max_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
            Vec3::new(min_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
            Vec3::new(max_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
            Vec3::new(min_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
            Vec3::new(max_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
        ];
        let safe_near: f32 = near_plane.max(0.15);
        let mut min_sx: f32 = f32::INFINITY;
        let mut max_sx: f32 = f32::NEG_INFINITY;
        let mut min_sy: f32 = f32::INFINITY;
        let mut max_sy: f32 = f32::NEG_INFINITY;
        for corner in corners.iter().copied() {
            let clip: [f32; 4] = view_proj.mul_point4(corner);
            if clip[3] <= safe_near {
                return f32::INFINITY;
            }
            let inv_w: f32 = 1.0 / clip[3];
            let sx: f32 = (clip[0] * inv_w * 0.5 + 0.5) * viewport_w;
            let sy: f32 = (0.5 - clip[1] * inv_w * 0.5) * viewport_h;
            min_sx = min_sx.min(sx);
            max_sx = max_sx.max(sx);
            min_sy = min_sy.min(sy);
            max_sy = max_sy.max(sy);
        }
        (max_sx - min_sx).max(0.0) * (max_sy - min_sy).max(0.0)
    }

    /// Samples the conservative minimum reverse-Z `1/w` stored at mip `mip_level` cell `(cell_x, cell_y)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target mip level index.
    /// - `usize` - Cell X coordinate.
    /// - `usize` - Cell Y coordinate.
    ///
    /// # Returns
    ///
    /// - `f32` - Stored reverse-Z depth (`0.0` when out of bounds or invalid).
    #[must_use]
    pub fn sample_mip_cell(&self, mip_level: usize, cell_x: usize, cell_y: usize) -> f32 {
        let Self {
            levels, level_dims, ..
        } = self;
        let Some(&(mip_w, mip_h)) = level_dims.get(mip_level) else {
            return 0.0;
        };
        if cell_x >= mip_w || cell_y >= mip_h {
            return 0.0;
        }
        levels[mip_level][cell_y * mip_w + cell_x]
    }
}

/// Hierarchical cluster DAG construction and continuous UE5 Nanite screen-error cuts for `NaniteClusterDag`.
impl NaniteClusterDag {
    /// Builds a bottom-up hierarchical `NaniteClusterDag` over the meshlets of `mesh`.
    ///
    /// # Arguments
    ///
    /// - `&Mesh3D` - Source mesh containing partitioned `Meshlet3D` clusters.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready Nanite cluster DAG for continuous LOD cuts and culling.
    #[must_use]
    pub fn from_mesh(mesh: &Mesh3D) -> Self {
        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
        if meshlets.is_empty() {
            return Self::default();
        }
        let mut nodes: Vec<NaniteClusterNode> = Vec::with_capacity(meshlets.len() * 2);
        for meshlet in meshlets.iter() {
            nodes.push(NaniteClusterNode {
                first_tri: meshlet.get_first_tri(),
                tri_count: meshlet.get_tri_count(),
                bounds: meshlet.get_bounds(),
                cone_axis: meshlet.get_cone_axis(),
                cone_cutoff: meshlet.get_cone_cutoff(),
                cluster_error: 0.0,
                parent_error: f32::INFINITY,
                lod_level: 0,
                child_start: 0,
                child_count: 0,
            });
        }
        let mut level_start: usize = 0;
        let mut level_end: usize = nodes.len();
        let mut level_count: usize = 1;
        let mut cur_lod: u8 = 0;
        while level_end - level_start > 1 {
            let next_start: usize = nodes.len();
            let next_lod: u8 = cur_lod.saturating_add(1);
            let mut cursor: usize = level_start;
            while cursor < level_end {
                let group_end: usize = (cursor + NANITE_DAG_BRANCH_FACTOR).min(level_end);
                let first_child: NaniteClusterNode = nodes[cursor];
                let mut merged_bounds: AxisAlignedBox3D = first_child.get_bounds();
                let mut axis_sum: Vec3 = Vec3::zero();
                let mut min_tri: u32 = first_child.get_first_tri();
                let mut max_tri_end: u32 = min_tri.saturating_add(first_child.get_tri_count());
                let mut max_child_err: f32 = 0.0;
                for child in nodes[cursor..group_end].iter() {
                    merged_bounds.expand_box(child.get_bounds());
                    axis_sum = axis_sum.add(child.get_cone_axis());
                    let c_start: u32 = child.get_first_tri();
                    let c_end: u32 = c_start.saturating_add(child.get_tri_count());
                    min_tri = min_tri.min(c_start);
                    max_tri_end = max_tri_end.max(c_end);
                    max_child_err = max_child_err.max(child.get_cluster_error());
                }
                let cone_axis: Vec3 = if axis_sum.length_sq() > 1.0e-6 {
                    axis_sum.normalize()
                } else {
                    Vec3::new(0.0, 1.0, 0.0)
                };
                let mut cone_cutoff: f32 = 1.0;
                for child in nodes[cursor..group_end].iter() {
                    let dot_axis: f32 = child.get_cone_axis().dot(cone_axis);
                    cone_cutoff = cone_cutoff.min(dot_axis * child.get_cone_cutoff().max(0.0));
                }
                let group_error: f32 =
                    max_child_err.max(merged_bounds.radius() * 0.04 * (next_lod as f32));
                for child in nodes[cursor..group_end].iter_mut() {
                    child.set_parent_error(group_error);
                }
                nodes.push(NaniteClusterNode {
                    first_tri: min_tri,
                    tri_count: max_tri_end.saturating_sub(min_tri),
                    bounds: merged_bounds,
                    cone_axis,
                    cone_cutoff: cone_cutoff.clamp(-1.0, 1.0),
                    cluster_error: group_error,
                    parent_error: f32::INFINITY,
                    lod_level: next_lod,
                    child_start: cursor as u32,
                    child_count: (group_end - cursor) as u16,
                });
                cursor = group_end;
            }
            level_start = next_start;
            level_end = nodes.len();
            level_count += 1;
            cur_lod = next_lod;
        }
        Self {
            nodes,
            root_start: level_start,
            level_count,
        }
    }

    /// Evaluates a continuous Nanite screen-error cut across this DAG with frustum, normal-cone, micro-area, and Hi-Z occlusion culling.
    ///
    /// # Arguments
    ///
    /// - `&NaniteCutContext<'_>` - Per-object camera, transform, frustum, Hi-Z, and screen-error parameters.
    /// - `&mut Vec<(usize, usize)>` - Reusable output triangle-range buffer cleared and populated in place.
    ///
    /// # Returns
    ///
    /// - `NaniteCutStats` - Drawn and per-stage culled cluster counts.
    pub fn select_cut(
        &self,
        context: &NaniteCutContext<'_>,
        out_ranges: &mut Vec<(usize, usize)>,
    ) -> NaniteCutStats {
        out_ranges.clear();
        let nodes: &[NaniteClusterNode] = self.get_nodes().as_slice();
        if nodes.is_empty() {
            return NaniteCutStats::default();
        }
        let mut stats: NaniteCutStats = NaniteCutStats::default();
        let mut stack: [usize; 128] = [0; 128];
        let mut sp: usize = 0;
        let root_start: usize = self.get_root_start().min(nodes.len());
        for root_idx in root_start..nodes.len() {
            if sp < stack.len() {
                stack[sp] = root_idx;
                sp += 1;
            }
        }
        let cam_pos: Vec3 = context.get_camera_position();
        let model_mat: Mat4 = context.get_model_matrix();
        let view_proj: Mat4 = context.get_view_projection();
        let normal_basis: [Vec3; 3] = context.get_normal_basis();
        let frustum: Frustum3D = context.get_frustum();
        let hiz_opt: Option<&HiZPyramid> = context.hiz_pyramid_ref();
        let cull_backface: bool = context.get_cull_backface();
        let focal_px: f32 = context.get_focal_px().max(1.0);
        let err_thresh: f32 = context.get_error_threshold_px().max(0.25);
        let near_plane: f32 = context.get_near_plane();
        let vp_w: f32 = context.get_viewport_width();
        let vp_h: f32 = context.get_viewport_height();
        let max_tris: usize = context.get_total_triangles();
        while sp > 0 {
            sp -= 1;
            let node_idx: usize = stack[sp];
            let node: NaniteClusterNode = nodes[node_idx];
            let world_bounds: AxisAlignedBox3D = model_mat.transform_bounds(node.get_bounds());
            if !frustum.intersects_bounds(&world_bounds) {
                stats.set_clusters_frustum_culled(stats.get_clusters_frustum_culled() + 1);
                continue;
            }
            let cutoff: f32 = node.get_cone_cutoff();
            if cull_backface && cutoff > 0.05 {
                let world_axis: Vec3 =
                    Mat4::transform_normal_with_basis(node.get_cone_axis(), normal_basis);
                let to_cluster: Vec3 = world_bounds.center().sub(cam_pos);
                let dist_len: f32 = to_cluster.length();
                let sin_alpha: f32 = (1.0 - cutoff * cutoff).max(0.0).sqrt();
                if to_cluster.dot(world_axis) > dist_len * sin_alpha + world_bounds.radius() {
                    stats.set_clusters_cone_culled(stats.get_clusters_cone_culled() + 1);
                    continue;
                }
            }
            let screen_area: f32 = HiZPyramid::projected_screen_area_px(
                world_bounds,
                &view_proj,
                vp_w,
                vp_h,
                near_plane,
            );
            if screen_area < NANITE_MIN_SCREEN_AREA_PX {
                stats.set_clusters_micro_culled(stats.get_clusters_micro_culled() + 1);
                continue;
            }
            if let Some(hiz) = hiz_opt
                && hiz.is_bounds_occluded(world_bounds, &view_proj, near_plane)
            {
                stats.set_clusters_hiz_culled(stats.get_clusters_hiz_culled() + 1);
                continue;
            }
            let dist: f32 = world_bounds.center().sub(cam_pos).length().max(0.5);
            let proj_error: f32 = (node.get_cluster_error() * focal_px) / dist;
            let child_count: usize = node.get_child_count() as usize;
            if child_count > 0 && proj_error > err_thresh {
                let child_start: usize = node.get_child_start() as usize;
                let child_end: usize = child_start.saturating_add(child_count).min(nodes.len());
                for child_idx in child_start..child_end {
                    if sp < stack.len() {
                        stack[sp] = child_idx;
                        sp += 1;
                    }
                }
            } else {
                let start_tri: usize = node.get_first_tri() as usize;
                let end_tri: usize = start_tri
                    .saturating_add(node.get_tri_count() as usize)
                    .min(max_tris);
                if start_tri < end_tri {
                    out_ranges.push((start_tri, end_tri));
                    stats.set_clusters_drawn(stats.get_clusters_drawn() + 1);
                }
            }
        }
        stats
    }
}

/// Accessors and builder helpers for `NaniteCutContext`.
impl<'a> NaniteCutContext<'a> {
    /// Returns the optional borrowed `HiZPyramid` reference attached to this cut context.
    ///
    /// # Returns
    ///
    /// - `Option<&'a HiZPyramid>` - Optional active Hi-Z pyramid.
    #[must_use]
    pub fn hiz_pyramid_ref(&self) -> Option<&'a HiZPyramid> {
        let Self { hiz_pyramid, .. } = self;
        *hiz_pyramid
    }

    /// Attaches an optional conservative reverse-Z `HiZPyramid` to this cut context.
    ///
    /// # Arguments
    ///
    /// - `Option<&'a HiZPyramid>` - Optional Hi-Z pyramid for cluster occlusion culling.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated cut context.
    #[must_use]
    pub fn with_hiz(mut self, pyramid: Option<&'a HiZPyramid>) -> Self {
        let Self { hiz_pyramid, .. } = &mut self;
        *hiz_pyramid = pyramid;
        self
    }

    /// Creates a `NaniteCutContext` configured for an object transform, camera frustum, and viewport projection.
    ///
    /// # Arguments
    ///
    /// - `(Vec3, Frustum3D)` - `(camera_position, frustum)` active view camera state.
    /// - `(Mat4, Mat4, [Vec3; 3])` - `(model_matrix, view_projection, normal_basis)` transform matrices.
    /// - `bool` - Whether closed-mesh normal-cone backface culling is enabled.
    /// - `(f32, f32, f32, f32)` - `(focal_px, near_plane, viewport_width, viewport_height)`.
    /// - `usize` - Total triangles in the mesh.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready Nanite cut context with default error threshold.
    #[must_use]
    pub fn for_object(
        camera_state: (Vec3, Frustum3D),
        transforms: (Mat4, Mat4, [Vec3; 3]),
        cull_backface: bool,
        projection: (f32, f32, f32, f32),
        total_triangles: usize,
    ) -> Self {
        let (camera_position, frustum): (Vec3, Frustum3D) = camera_state;
        let (model_matrix, view_projection, normal_basis): (Mat4, Mat4, [Vec3; 3]) = transforms;
        let (focal_px, near_plane, viewport_width, viewport_height): (f32, f32, f32, f32) =
            projection;
        Self {
            camera_position,
            model_matrix,
            view_projection,
            normal_basis,
            frustum,
            hiz_pyramid: None,
            cull_backface,
            focal_px,
            error_threshold_px: NANITE_DEFAULT_ERROR_THRESHOLD_PX,
            near_plane,
            viewport_width,
            viewport_height,
            total_triangles,
        }
    }
}