Skip to main content

euv_core/game/engine3d/renderer/
impl.rs

1use super::*;
2
3/// Persistent work-stealing multi-core thread pool for `Engine3dWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5impl Engine3dWorkerPool {
6    /// Creates a warm persistent worker pool sized to host CPU cores (`1..=24` total threads including caller) with extended lock-free spin-before-park dispatch.
7    ///
8    /// # Returns
9    ///
10    /// - `Self` - Initialized worker pool with zero per-frame thread spawn overhead.
11    #[must_use]
12    pub(crate) fn new() -> Self {
13        let total: usize = available_parallelism()
14            .map(usize::from)
15            .unwrap_or(4)
16            .clamp(1, ENGINE3D_WORKER_MAX_THREADS);
17        let requested_workers: usize = total.saturating_sub(1);
18        let mut slots: Vec<Engine3dWorkerSlot> = Vec::with_capacity(requested_workers);
19        for _ in 0..requested_workers {
20            slots.push(Engine3dWorkerSlot::default());
21        }
22        let shared: Arc<Engine3dPoolShared> = Arc::new(Engine3dPoolShared {
23            active_job: AtomicUsize::new(0),
24            active_workers: AtomicUsize::new(0),
25            caller_parked: AlignedAtomicUsize {
26                value: AtomicUsize::new(0),
27            },
28            caller_lock: Mutex::new(()),
29            wake_caller: Condvar::new(),
30            slots,
31        });
32        let mut spawned_count: usize = 0;
33        for idx in 0..requested_workers {
34            let shared_clone: Arc<Engine3dPoolShared> = Arc::clone(&shared);
35            let name: String = format!("{ENGINE3D_WORKER_PREFIX}-{idx}");
36            let spawn_res: io::Result<JoinHandle<()>> =
37                Builder::new().name(name).spawn(move || {
38                    let slot: &Engine3dWorkerSlot = &shared_clone.slots[idx];
39                    let mut seen_epoch: usize = 0;
40                    loop {
41                        let mut spins: u32 = 0;
42                        let job_ptr: usize = loop {
43                            let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
44                            if cur_epoch != seen_epoch {
45                                let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
46                                if ptr != 0 {
47                                    seen_epoch = cur_epoch;
48                                    break ptr;
49                                }
50                            }
51                            if spins < ENGINE3D_WORKER_SPIN_LIMIT {
52                                spins += 1;
53                                spin_loop();
54                                continue;
55                            }
56                            let Ok(mut guard) = slot.lock.lock() else {
57                                return;
58                            };
59                            slot.parked.store(1, Ordering::SeqCst);
60                            let parked_ptr: Option<usize> = loop {
61                                let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
62                                if locked_epoch != seen_epoch {
63                                    let ptr: usize =
64                                        shared_clone.active_job.load(Ordering::Acquire);
65                                    if ptr != 0 {
66                                        seen_epoch = locked_epoch;
67                                        break Some(ptr);
68                                    }
69                                }
70                                let Ok(next_guard) = slot.wake.wait(guard) else {
71                                    break None;
72                                };
73                                guard = next_guard;
74                            };
75                            slot.parked.store(0, Ordering::SeqCst);
76                            let Some(ptr) = parked_ptr else {
77                                return;
78                            };
79                            break ptr;
80                        };
81                        // SAFETY: Caller keeps `Engine3dJob` pinned on its stack until `workers_done >= active_workers`.
82                        let job: &Engine3dJob = unsafe { &*(job_ptr as *const Engine3dJob) };
83                        run_engine3d_job_loop(job);
84                        let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
85                        let finished: usize =
86                            job.workers_done.value.fetch_add(1, Ordering::SeqCst) + 1;
87                        if finished >= expected
88                            && shared_clone.caller_parked.value.load(Ordering::SeqCst) != 0
89                        {
90                            let _guard: Result<
91                                MutexGuard<'_, ()>,
92                                PoisonError<MutexGuard<'_, ()>>,
93                            > = shared_clone.caller_lock.lock();
94                            shared_clone.wake_caller.notify_one();
95                        }
96                    }
97                });
98            if spawn_res.is_ok() {
99                spawned_count += 1;
100            } else {
101                break;
102            }
103        }
104        Self {
105            worker_count: spawned_count,
106            dispatch_lock: Mutex::new(()),
107            shared,
108        }
109    }
110}
111
112/// Structure-of-Arrays allocation and disjoint raw pointer helpers for `RtProbeGridSoa`.
113impl RtProbeGridSoa {
114    /// Resizes all 13 SoA probe arrays to `len` elements without reallocating once capacity suffices.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Mutable SoA probe grid.
119    /// - `usize` - Total probe count `gw * gh`.
120    pub(crate) fn resize(&mut self, len: usize) {
121        let Self {
122            shadow,
123            refl_r,
124            refl_g,
125            refl_b,
126            gi_r,
127            gi_g,
128            gi_b,
129            ao,
130            depth,
131            nx,
132            ny,
133            nz,
134            world_x,
135            world_y,
136            world_z,
137            valid,
138        } = self;
139        if shadow.len() == len {
140            return;
141        }
142        shadow.resize(len, 1.0);
143        refl_r.resize(len, 0.0);
144        refl_g.resize(len, 0.0);
145        refl_b.resize(len, 0.0);
146        gi_r.resize(len, 0.0);
147        gi_g.resize(len, 0.0);
148        gi_b.resize(len, 0.0);
149        ao.resize(len, 1.0);
150        depth.resize(len, 0.0);
151        nx.resize(len, 0.0);
152        ny.resize(len, 1.0);
153        nz.resize(len, 0.0);
154        world_x.resize(len, 0.0);
155        world_y.resize(len, 0.0);
156        world_z.resize(len, 0.0);
157        valid.resize(len, 0);
158    }
159
160    /// Returns whether this SoA probe grid is empty.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - SoA probe grid reference.
165    ///
166    /// # Returns
167    ///
168    /// - `bool` - `true` when zero probes are stored.
169    #[inline(always)]
170    #[must_use]
171    pub(crate) fn is_empty(&self) -> bool {
172        let Self { valid, .. } = self;
173        valid.is_empty()
174    }
175
176    /// Captures base writable addresses for parallel disjoint-tile writes across Barrier 1 workers.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Mutable SoA probe grid.
181    ///
182    /// # Returns
183    ///
184    /// - `RtProbeGridMutPtrs` - Raw base pointer bundle for disjoint tile writes.
185    #[must_use]
186    pub(crate) fn mut_ptrs(&mut self) -> RtProbeGridMutPtrs {
187        let Self {
188            shadow,
189            refl_r,
190            refl_g,
191            refl_b,
192            gi_r,
193            gi_g,
194            gi_b,
195            ao,
196            depth,
197            nx,
198            ny,
199            nz,
200            world_x,
201            world_y,
202            world_z,
203            valid,
204        } = self;
205        RtProbeGridMutPtrs {
206            shadow: shadow.as_mut_ptr() as usize,
207            refl_r: refl_r.as_mut_ptr() as usize,
208            refl_g: refl_g.as_mut_ptr() as usize,
209            refl_b: refl_b.as_mut_ptr() as usize,
210            gi_r: gi_r.as_mut_ptr() as usize,
211            gi_g: gi_g.as_mut_ptr() as usize,
212            gi_b: gi_b.as_mut_ptr() as usize,
213            ao: ao.as_mut_ptr() as usize,
214            depth: depth.as_mut_ptr() as usize,
215            nx: nx.as_mut_ptr() as usize,
216            ny: ny.as_mut_ptr() as usize,
217            nz: nz.as_mut_ptr() as usize,
218            world_x: world_x.as_mut_ptr() as usize,
219            world_y: world_y.as_mut_ptr() as usize,
220            world_z: world_z.as_mut_ptr() as usize,
221            valid: valid.as_mut_ptr() as usize,
222        }
223    }
224}
225
226/// Disjoint probe writes into `RtProbeGridSoa` via raw base addresses.
227impl RtProbeGridMutPtrs {
228    /// Marks probe `idx` as invalid sky with zeroed radiance.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Raw pointer bundle.
233    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
234    #[inline(always)]
235    pub(crate) unsafe fn write_invalid(&self, idx: usize) {
236        let Self { valid, .. } = *self;
237        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
238        unsafe {
239            *(valid as *mut u8).add(idx) = 0;
240        }
241    }
242
243    /// Writes a probe's world-space surface position at disjoint index `idx` for next-frame temporal validation.
244    ///
245    /// # Arguments
246    ///
247    /// - `&Self` - Raw pointer bundle.
248    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
249    /// - `Vec3` - World-space surface position.
250    #[inline(always)]
251    pub(crate) unsafe fn write_world_pos(&self, idx: usize, world_p: Vec3) {
252        let Self {
253            world_x: p_wx,
254            world_y: p_wy,
255            world_z: p_wz,
256            ..
257        } = *self;
258        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
259        unsafe {
260            *(p_wx as *mut f32).add(idx) = world_p.get_x();
261            *(p_wy as *mut f32).add(idx) = world_p.get_y();
262            *(p_wz as *mut f32).add(idx) = world_p.get_z();
263        }
264    }
265
266    /// Writes a valid traced probe into all 13 SoA arrays at disjoint index `idx`.
267    ///
268    /// # Arguments
269    ///
270    /// - `&Self` - Raw pointer bundle.
271    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
272    /// - `(f32, f32, f32)` - Scalar terms `(shadow, ao, depth)`.
273    /// - `(Vec3, Vec3, Vec3)` - Vector terms `(refl, gi, normal)`.
274    #[inline(always)]
275    pub(crate) unsafe fn write_valid(
276        &self,
277        idx: usize,
278        scalars: (f32, f32, f32),
279        vectors: (Vec3, Vec3, Vec3),
280    ) {
281        let Self {
282            shadow: p_shadow,
283            refl_r: p_rr,
284            refl_g: p_rg,
285            refl_b: p_rb,
286            gi_r: p_gr,
287            gi_g: p_gg,
288            gi_b: p_gb,
289            ao: p_ao,
290            depth: p_depth,
291            nx: p_nx,
292            ny: p_ny,
293            nz: p_nz,
294            valid: p_valid,
295            ..
296        } = *self;
297        let (shadow, ao, depth): (f32, f32, f32) = scalars;
298        let (refl, gi, normal): (Vec3, Vec3, Vec3) = vectors;
299        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
300        unsafe {
301            *(p_shadow as *mut f32).add(idx) = shadow;
302            *(p_rr as *mut f32).add(idx) = refl.get_x();
303            *(p_rg as *mut f32).add(idx) = refl.get_y();
304            *(p_rb as *mut f32).add(idx) = refl.get_z();
305            *(p_gr as *mut f32).add(idx) = gi.get_x();
306            *(p_gg as *mut f32).add(idx) = gi.get_y();
307            *(p_gb as *mut f32).add(idx) = gi.get_z();
308            *(p_ao as *mut f32).add(idx) = ao;
309            *(p_depth as *mut f32).add(idx) = depth;
310            *(p_nx as *mut f32).add(idx) = normal.get_x();
311            *(p_ny as *mut f32).add(idx) = normal.get_y();
312            *(p_nz as *mut f32).add(idx) = normal.get_z();
313            *(p_valid as *mut u8).add(idx) = 1;
314        }
315    }
316}
317
318/// Zero-initialized constructor helper for fixed-capacity stack `RtProbeRowStack`.
319impl Default for RtProbeRowStack {
320    /// Returns a zeroed L1-resident single-row probe buffer with `valid = 0` across all `PROBE_ROW_STACK_CAP` lanes.
321    ///
322    /// # Returns
323    ///
324    /// - `Self` - Ready stack-allocated probe row buffer.
325    fn default() -> Self {
326        Self {
327            shadow: [1.0; PROBE_ROW_STACK_CAP],
328            refl_r: [0.0; PROBE_ROW_STACK_CAP],
329            refl_g: [0.0; PROBE_ROW_STACK_CAP],
330            refl_b: [0.0; PROBE_ROW_STACK_CAP],
331            gi_r: [0.0; PROBE_ROW_STACK_CAP],
332            gi_g: [0.0; PROBE_ROW_STACK_CAP],
333            gi_b: [0.0; PROBE_ROW_STACK_CAP],
334            ao: [1.0; PROBE_ROW_STACK_CAP],
335            depth: [0.0; PROBE_ROW_STACK_CAP],
336            nx: [0.0; PROBE_ROW_STACK_CAP],
337            ny: [1.0; PROBE_ROW_STACK_CAP],
338            nz: [0.0; PROBE_ROW_STACK_CAP],
339            valid: [0; PROBE_ROW_STACK_CAP],
340        }
341    }
342}
343
344/// Borrowed row view constructor for `RtProbeRowStack`.
345impl RtProbeRowStack {
346    /// Borrows the active `0..gw` prefix of this stack row as a zero-copy `RtProbeRowView`.
347    ///
348    /// # Arguments
349    ///
350    /// - `&Self` - Stack probe row reference.
351    /// - `usize` - Active probe grid width `gw <= 256`.
352    ///
353    /// # Returns
354    ///
355    /// - `RtProbeRowView<'_>` - Zero-copy borrowed SoA row view.
356    #[inline(always)]
357    #[must_use]
358    pub(crate) fn as_view(&self, gw: usize) -> RtProbeRowView<'_> {
359        let Self {
360            shadow,
361            refl_r,
362            refl_g,
363            refl_b,
364            gi_r,
365            gi_g,
366            gi_b,
367            ao,
368            depth,
369            nx,
370            ny,
371            nz,
372            valid,
373        } = self;
374        RtProbeRowView {
375            shadow: &shadow[..gw],
376            refl_r: &refl_r[..gw],
377            refl_g: &refl_g[..gw],
378            refl_b: &refl_b[..gw],
379            gi_r: &gi_r[..gw],
380            gi_g: &gi_g[..gw],
381            gi_b: &gi_b[..gw],
382            ao: &ao[..gw],
383            depth: &depth[..gw],
384            nx: &nx[..gw],
385            ny: &ny[..gw],
386            nz: &nz[..gw],
387            valid: &valid[..gw],
388        }
389    }
390}
391
392/// Default empty per-thread probe row denoise scratch state.
393impl Default for RtProbeRowScratch {
394    /// Creates an empty per-thread 2-row probe denoise scratch cache invalidated at generation `0`.
395    ///
396    /// # Returns
397    ///
398    /// - `Self` - Ready per-thread probe row scratch state.
399    fn default() -> Self {
400        Self {
401            frame_gen: 0,
402            cached_gy_a: usize::MAX,
403            cached_gy_b: usize::MAX,
404            buf_a: RtProbeRowStack::default(),
405            buf_b: RtProbeRowStack::default(),
406        }
407    }
408}
409
410/// 4-corner SIMD bilateral probe cell loader and vectorized 1x/4x upsampler for `CachedProbeCell`.
411impl CachedProbeCell {
412    /// Returns an empty invalid probe cell sentinel.
413    ///
414    /// # Returns
415    ///
416    /// - `Self` - Invalid cell with `vmask == 0`.
417    #[inline(always)]
418    #[must_use]
419    pub(crate) fn empty() -> Self {
420        Self {
421            depth: [0.0; 4],
422            shadow: [0.0; 4],
423            refl_r: [0.0; 4],
424            refl_g: [0.0; 4],
425            refl_b: [0.0; 4],
426            gi_r: [0.0; 4],
427            gi_g: [0.0; 4],
428            gi_b: [0.0; 4],
429            ao: [0.0; 4],
430            tol_scale: [0.0; 4],
431            tol_bias: [0.0; 4],
432            valid_u32: [0; 4],
433            vmask: 0,
434        }
435    }
436
437    /// Loads a single bilinear probe corner `i` into `cell`, returning its bitmask contribution (`1 << i` or `0`).
438    ///
439    /// # Arguments
440    ///
441    /// - `&mut Self` - Destination cell updated in-place.
442    /// - `usize` - Corner lane index `0..4`.
443    /// - `&RtProbeRowView<'_>` - Source probe row.
444    /// - `usize` - Column index `gx`.
445    /// - `(f32, f32, f32)` - Surface normal `(snx, sny, snz)`.
446    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
447    ///
448    /// # Returns
449    ///
450    /// - `u8` - `1 << i` when corner passes validity and normal agreement, else `0`.
451    #[inline(always)]
452    fn load_corner(
453        cell: &mut Self,
454        item_index: usize,
455        row: &RtProbeRowView<'_>,
456        gx: usize,
457        sn: (f32, f32, f32),
458        flags: (bool, bool),
459    ) -> u8 {
460        if row.valid[gx] != 0 {
461            let (snx, sny, snz): (f32, f32, f32) = sn;
462            let ndot: f32 = snx.mul_add(row.nx[gx], sny.mul_add(row.ny[gx], snz * row.nz[gx]));
463            if ndot >= 0.78 {
464                let (do_refl, gi_active): (bool, bool) = flags;
465                cell.valid_u32[item_index] = u32::MAX;
466                if ndot > 0.95 {
467                    cell.tol_scale[item_index] = 0.58;
468                    cell.tol_bias[item_index] = 2.4;
469                } else {
470                    cell.tol_scale[item_index] = 0.20;
471                    cell.tol_bias[item_index] = 0.75;
472                }
473                cell.depth[item_index] = row.depth[gx];
474                cell.shadow[item_index] = row.shadow[gx];
475                if do_refl {
476                    cell.refl_r[item_index] = row.refl_r[gx];
477                    cell.refl_g[item_index] = row.refl_g[gx];
478                    cell.refl_b[item_index] = row.refl_b[gx];
479                }
480                if gi_active {
481                    cell.gi_r[item_index] = row.gi_r[gx];
482                    cell.gi_g[item_index] = row.gi_g[gx];
483                    cell.gi_b[item_index] = row.gi_b[gx];
484                    cell.ao[item_index] = row.ao[gx];
485                }
486                return 1_u8 << item_index;
487            }
488        }
489        cell.valid_u32[item_index] = 0;
490        0
491    }
492
493    /// Loads and normal-filters the 4 bilinear corner probes `(r0/r1, gx0/gx1)` in-place into `cell` once per `(gx0, gx1, tid)` span without copying or closure calls.
494    ///
495    /// # Arguments
496    ///
497    /// - `&mut Self` - Destination 16-byte-aligned SIMD probe cell updated in-place.
498    /// - `&RtProbeRowView<'_>` - Top probe row `gy0`.
499    /// - `&RtProbeRowView<'_>` - Bottom probe row `gy1`.
500    /// - `(usize, usize)` - Column indices `(gx0, gx1)`.
501    /// - `Vec3` - Pixel unit shading normal.
502    /// - `(bool, bool)` - `(do_refl, gi_active)` flags to skip unneeded channels.
503    #[inline(always)]
504    pub(crate) fn load_into(
505        cell: &mut Self,
506        r0: &RtProbeRowView<'_>,
507        r1: &RtProbeRowView<'_>,
508        gx_pair: (usize, usize),
509        normal: Vec3,
510        flags: (bool, bool),
511    ) {
512        let (gx0, gx1): (usize, usize) = gx_pair;
513        let sn: (f32, f32, f32) = (normal.get_x(), normal.get_y(), normal.get_z());
514        let mut vmask: u8 = Self::load_corner(cell, 0, r0, gx0, sn, flags);
515        vmask |= Self::load_corner(cell, 1, r0, gx1, sn, flags);
516        vmask |= Self::load_corner(cell, 2, r1, gx0, sn, flags);
517        vmask |= Self::load_corner(cell, 3, r1, gx1, sn, flags);
518        cell.vmask = vmask;
519    }
520
521    /// Shifts a cached `(gx, gx+1)` cell one column right in place for `(gx+1, gx+2)`, reusing corners `1 -> 0` and `3 -> 2` and loading only the 2 new right-hand probes.
522    ///
523    /// # Arguments
524    ///
525    /// - `&mut Self` - Cached cell updated in place.
526    /// - `&RtProbeRowView<'_>` - Top probe row `gy0`.
527    /// - `&RtProbeRowView<'_>` - Bottom probe row `gy1`.
528    /// - `usize` - New right-hand column index `gx + 2`.
529    /// - `Vec3` - Pixel unit shading normal.
530    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
531    #[inline(always)]
532    pub(crate) fn shift_right_in_place(
533        cell: &mut Self,
534        r0: &RtProbeRowView<'_>,
535        r1: &RtProbeRowView<'_>,
536        gx_new: usize,
537        normal: Vec3,
538        flags: (bool, bool),
539    ) {
540        let (do_refl, gi_active): (bool, bool) = flags;
541        cell.valid_u32[0] = cell.valid_u32[1];
542        cell.valid_u32[2] = cell.valid_u32[3];
543        cell.tol_scale[0] = cell.tol_scale[1];
544        cell.tol_scale[2] = cell.tol_scale[3];
545        cell.tol_bias[0] = cell.tol_bias[1];
546        cell.tol_bias[2] = cell.tol_bias[3];
547        cell.depth[0] = cell.depth[1];
548        cell.depth[2] = cell.depth[3];
549        cell.shadow[0] = cell.shadow[1];
550        cell.shadow[2] = cell.shadow[3];
551        if do_refl {
552            cell.refl_r[0] = cell.refl_r[1];
553            cell.refl_r[2] = cell.refl_r[3];
554            cell.refl_g[0] = cell.refl_g[1];
555            cell.refl_g[2] = cell.refl_g[3];
556            cell.refl_b[0] = cell.refl_b[1];
557            cell.refl_b[2] = cell.refl_b[3];
558        }
559        if gi_active {
560            cell.gi_r[0] = cell.gi_r[1];
561            cell.gi_r[2] = cell.gi_r[3];
562            cell.gi_g[0] = cell.gi_g[1];
563            cell.gi_g[2] = cell.gi_g[3];
564            cell.gi_b[0] = cell.gi_b[1];
565            cell.gi_b[2] = cell.gi_b[3];
566            cell.ao[0] = cell.ao[1];
567            cell.ao[2] = cell.ao[3];
568        }
569        let sn: (f32, f32, f32) = (normal.get_x(), normal.get_y(), normal.get_z());
570        let mut vmask: u8 = ((cell.vmask & 2) >> 1) | ((cell.vmask & 8) >> 1);
571        vmask |= Self::load_corner(cell, 1, r0, gx_new, sn, flags);
572        vmask |= Self::load_corner(cell, 3, r1, gx_new, sn, flags);
573        cell.vmask = vmask;
574    }
575
576    /// Evaluates bilateral probe upsampling for 4 horizontal pixels lying within the same cached `(gx0, gx1)` cell, reading depths from `out.depths[off..off+4]` and writing into `out` at `off <= 28`.
577    ///
578    /// # Arguments
579    ///
580    /// - `&Self` - Pre-packed 4-corner probe cell.
581    /// - `[f32; 4]` - Horizontal fractional coordinates `fx` of the 4 pixels.
582    /// - `(f32, f32)` - Vertical bilinear weights `(wy0, wy1)`.
583    /// - `(bool, bool, bool)` - `(check_shadow_edge, do_refl, gi_active)`.
584    /// - `(&mut RunScratch32, usize)` - Destination 32-pixel L1 scratch (containing `depths`) and lane offset `off <= 28`.
585    ///
586    /// # Returns
587    ///
588    /// - `bool` - `true` when all 4 pixels succeeded without requiring edge fallback rays.
589    #[inline(always)]
590    #[must_use]
591    pub(crate) fn sample_4x_same_cell(
592        cell: &Self,
593        fx_4: [f32; 4],
594        wy: (f32, f32),
595        flags: (bool, bool, bool),
596        dst: (&mut RunScratch32, usize),
597    ) -> bool {
598        let vmask: u8 = cell.vmask;
599        if vmask == 0 {
600            return false;
601        }
602        let (out, off): (&mut RunScratch32, usize) = dst;
603        let (wy0, wy1): (f32, f32) = wy;
604        let (check_shadow_edge, do_refl, gi_active): (bool, bool, bool) = flags;
605        #[cfg(target_arch = "aarch64")]
606        {
607            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`, and NEON `vld1q_f32`/`vst1q_f32` support arbitrary 4-byte-aligned element offsets.
608            unsafe {
609                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
610                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
611                let eps: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1e-4);
612                let d_4: core::arch::aarch64::float32x4_t =
613                    core::arch::aarch64::vld1q_f32(out.depths.as_ptr().add(off));
614                let fx_v: core::arch::aarch64::float32x4_t =
615                    core::arch::aarch64::vld1q_f32(fx_4.as_ptr());
616                let wx0_v: core::arch::aarch64::float32x4_t =
617                    core::arch::aarch64::vsubq_f32(one, fx_v);
618                let wy0_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(wy0);
619                let wy1_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(wy1);
620                let bw0: core::arch::aarch64::float32x4_t =
621                    core::arch::aarch64::vmulq_f32(wx0_v, wy0_v);
622                let bw1: core::arch::aarch64::float32x4_t =
623                    core::arch::aarch64::vmulq_f32(fx_v, wy0_v);
624                let bw2: core::arch::aarch64::float32x4_t =
625                    core::arch::aarch64::vmulq_f32(wx0_v, wy1_v);
626                let bw3: core::arch::aarch64::float32x4_t =
627                    core::arch::aarch64::vmulq_f32(fx_v, wy1_v);
628                let tol_hi: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
629                    core::arch::aarch64::vdupq_n_f32(2.4),
630                    d_4,
631                    core::arch::aarch64::vdupq_n_f32(0.58),
632                );
633                let inv_tol_hi: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(tol_hi);
634                let mut tol_lo_ready: bool = false;
635                let mut tol_lo: core::arch::aarch64::float32x4_t = zero;
636                let mut inv_tol_lo: core::arch::aarch64::float32x4_t = zero;
637                let mut w_sum: core::arch::aarch64::float32x4_t = zero;
638                let mut s_sum: core::arch::aarch64::float32x4_t = zero;
639                let mut s_min: core::arch::aarch64::float32x4_t =
640                    core::arch::aarch64::vdupq_n_f32(2.0);
641                let mut s_max: core::arch::aarch64::float32x4_t =
642                    core::arch::aarch64::vdupq_n_f32(-1.0);
643                let mut rr_sum: core::arch::aarch64::float32x4_t = zero;
644                let mut rg_sum: core::arch::aarch64::float32x4_t = zero;
645                let mut rb_sum: core::arch::aarch64::float32x4_t = zero;
646                let mut gr_sum: core::arch::aarch64::float32x4_t = zero;
647                let mut gg_sum: core::arch::aarch64::float32x4_t = zero;
648                let mut gb_sum: core::arch::aarch64::float32x4_t = zero;
649                let mut ao_sum: core::arch::aarch64::float32x4_t = zero;
650                for char_item in 0..4_usize {
651                    if (vmask & (1_u8 << char_item)) == 0 {
652                        continue;
653                    }
654                    let bw_c: core::arch::aarch64::float32x4_t = match char_item {
655                        0 => bw0,
656                        1 => bw1,
657                        2 => bw2,
658                        _ => bw3,
659                    };
660                    let (tol_c, inv_tol_c): (
661                        core::arch::aarch64::float32x4_t,
662                        core::arch::aarch64::float32x4_t,
663                    ) = if cell.tol_scale[char_item] > 0.4 {
664                        (tol_hi, inv_tol_hi)
665                    } else {
666                        if !tol_lo_ready {
667                            tol_lo = core::arch::aarch64::vfmaq_f32(
668                                core::arch::aarch64::vdupq_n_f32(0.75),
669                                d_4,
670                                core::arch::aarch64::vdupq_n_f32(0.20),
671                            );
672                            inv_tol_lo = Renderer3D::neon_rcp_4x(tol_lo);
673                            tol_lo_ready = true;
674                        }
675                        (tol_lo, inv_tol_lo)
676                    };
677                    let d_diff: core::arch::aarch64::float32x4_t =
678                        core::arch::aarch64::vabsq_f32(core::arch::aarch64::vsubq_f32(
679                            d_4,
680                            core::arch::aarch64::vdupq_n_f32(cell.depth[char_item]),
681                        ));
682                    let in_tol: core::arch::aarch64::uint32x4_t =
683                        core::arch::aarch64::vcleq_f32(d_diff, tol_c);
684                    let wt_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
685                        eps,
686                        bw_c,
687                        core::arch::aarch64::vfmsq_f32(one, d_diff, inv_tol_c),
688                    );
689                    let wt: core::arch::aarch64::float32x4_t =
690                        core::arch::aarch64::vbslq_f32(in_tol, wt_raw, zero);
691                    w_sum = core::arch::aarch64::vaddq_f32(w_sum, wt);
692                    let sh_c: core::arch::aarch64::float32x4_t =
693                        core::arch::aarch64::vdupq_n_f32(cell.shadow[char_item]);
694                    s_sum = core::arch::aarch64::vfmaq_f32(s_sum, wt, sh_c);
695                    if check_shadow_edge {
696                        s_min = core::arch::aarch64::vminq_f32(
697                            s_min,
698                            core::arch::aarch64::vbslq_f32(
699                                in_tol,
700                                sh_c,
701                                core::arch::aarch64::vdupq_n_f32(2.0),
702                            ),
703                        );
704                        s_max = core::arch::aarch64::vmaxq_f32(
705                            s_max,
706                            core::arch::aarch64::vbslq_f32(
707                                in_tol,
708                                sh_c,
709                                core::arch::aarch64::vdupq_n_f32(-1.0),
710                            ),
711                        );
712                    }
713                    if do_refl {
714                        rr_sum = core::arch::aarch64::vfmaq_f32(
715                            rr_sum,
716                            wt,
717                            core::arch::aarch64::vdupq_n_f32(cell.refl_r[char_item]),
718                        );
719                        rg_sum = core::arch::aarch64::vfmaq_f32(
720                            rg_sum,
721                            wt,
722                            core::arch::aarch64::vdupq_n_f32(cell.refl_g[char_item]),
723                        );
724                        rb_sum = core::arch::aarch64::vfmaq_f32(
725                            rb_sum,
726                            wt,
727                            core::arch::aarch64::vdupq_n_f32(cell.refl_b[char_item]),
728                        );
729                    }
730                    if gi_active {
731                        gr_sum = core::arch::aarch64::vfmaq_f32(
732                            gr_sum,
733                            wt,
734                            core::arch::aarch64::vdupq_n_f32(cell.gi_r[char_item]),
735                        );
736                        gg_sum = core::arch::aarch64::vfmaq_f32(
737                            gg_sum,
738                            wt,
739                            core::arch::aarch64::vdupq_n_f32(cell.gi_g[char_item]),
740                        );
741                        gb_sum = core::arch::aarch64::vfmaq_f32(
742                            gb_sum,
743                            wt,
744                            core::arch::aarch64::vdupq_n_f32(cell.gi_b[char_item]),
745                        );
746                        ao_sum = core::arch::aarch64::vfmaq_f32(
747                            ao_sum,
748                            wt,
749                            core::arch::aarch64::vdupq_n_f32(cell.ao[char_item]),
750                        );
751                    }
752                }
753                if core::arch::aarch64::vminvq_f32(w_sum) <= 1e-5 {
754                    return false;
755                }
756                if check_shadow_edge {
757                    let near_m: core::arch::aarch64::uint32x4_t =
758                        core::arch::aarch64::vcltq_f32(d_4, core::arch::aarch64::vdupq_n_f32(42.0));
759                    let edge_m: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
760                        near_m,
761                        core::arch::aarch64::vcgtq_f32(
762                            core::arch::aarch64::vsubq_f32(s_max, s_min),
763                            core::arch::aarch64::vdupq_n_f32(0.12),
764                        ),
765                    );
766                    if core::arch::aarch64::vmaxvq_u32(edge_m) != 0 {
767                        return false;
768                    }
769                }
770                let inv_ws: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(w_sum);
771                core::arch::aarch64::vst1q_f32(
772                    out.shadow.as_mut_ptr().add(off),
773                    core::arch::aarch64::vmulq_f32(s_sum, inv_ws),
774                );
775                if do_refl {
776                    core::arch::aarch64::vst1q_f32(
777                        out.refl_r.as_mut_ptr().add(off),
778                        core::arch::aarch64::vmulq_f32(rr_sum, inv_ws),
779                    );
780                    core::arch::aarch64::vst1q_f32(
781                        out.refl_g.as_mut_ptr().add(off),
782                        core::arch::aarch64::vmulq_f32(rg_sum, inv_ws),
783                    );
784                    core::arch::aarch64::vst1q_f32(
785                        out.refl_b.as_mut_ptr().add(off),
786                        core::arch::aarch64::vmulq_f32(rb_sum, inv_ws),
787                    );
788                }
789                if gi_active {
790                    core::arch::aarch64::vst1q_f32(
791                        out.gi_r.as_mut_ptr().add(off),
792                        core::arch::aarch64::vmulq_f32(gr_sum, inv_ws),
793                    );
794                    core::arch::aarch64::vst1q_f32(
795                        out.gi_g.as_mut_ptr().add(off),
796                        core::arch::aarch64::vmulq_f32(gg_sum, inv_ws),
797                    );
798                    core::arch::aarch64::vst1q_f32(
799                        out.gi_b.as_mut_ptr().add(off),
800                        core::arch::aarch64::vmulq_f32(gb_sum, inv_ws),
801                    );
802                    core::arch::aarch64::vst1q_f32(
803                        out.ao.as_mut_ptr().add(off),
804                        core::arch::aarch64::vmulq_f32(ao_sum, inv_ws),
805                    );
806                }
807            }
808            true
809        }
810        #[cfg(target_arch = "x86_64")]
811        {
812            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`, and SSE2 is mandatory on `x86_64`.
813            unsafe {
814                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
815                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
816                let eps: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1e-4);
817                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
818                let d_4: core::arch::x86_64::__m128 =
819                    core::arch::x86_64::_mm_loadu_ps(out.depths.as_ptr().add(off));
820                let fx_v: core::arch::x86_64::__m128 =
821                    core::arch::x86_64::_mm_loadu_ps(fx_4.as_ptr());
822                let wx0_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(one, fx_v);
823                let wy0_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(wy0);
824                let wy1_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(wy1);
825                let bw0: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(wx0_v, wy0_v);
826                let bw1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(fx_v, wy0_v);
827                let bw2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(wx0_v, wy1_v);
828                let bw3: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(fx_v, wy1_v);
829                let tol_hi: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
830                    core::arch::x86_64::_mm_mul_ps(d_4, core::arch::x86_64::_mm_set1_ps(0.58)),
831                    core::arch::x86_64::_mm_set1_ps(2.4),
832                );
833                let inv_tol_hi: core::arch::x86_64::__m128 =
834                    core::arch::x86_64::_mm_div_ps(one, tol_hi);
835                let mut tol_lo_ready: bool = false;
836                let mut tol_lo: core::arch::x86_64::__m128 = zero;
837                let mut inv_tol_lo: core::arch::x86_64::__m128 = zero;
838                let mut w_sum: core::arch::x86_64::__m128 = zero;
839                let mut s_sum: core::arch::x86_64::__m128 = zero;
840                let mut s_min: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(2.0);
841                let mut s_max: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-1.0);
842                let mut rr_sum: core::arch::x86_64::__m128 = zero;
843                let mut rg_sum: core::arch::x86_64::__m128 = zero;
844                let mut rb_sum: core::arch::x86_64::__m128 = zero;
845                let mut gr_sum: core::arch::x86_64::__m128 = zero;
846                let mut gg_sum: core::arch::x86_64::__m128 = zero;
847                let mut gb_sum: core::arch::x86_64::__m128 = zero;
848                let mut ao_sum: core::arch::x86_64::__m128 = zero;
849                for color_item in 0..4_usize {
850                    if (vmask & (1_u8 << color_item)) == 0 {
851                        continue;
852                    }
853                    let bw_c: core::arch::x86_64::__m128 = match color_item {
854                        0 => bw0,
855                        1 => bw1,
856                        2 => bw2,
857                        _ => bw3,
858                    };
859                    let (tol_c, inv_tol_c): (
860                        core::arch::x86_64::__m128,
861                        core::arch::x86_64::__m128,
862                    ) = if cell.tol_scale[color_item] > 0.4 {
863                        (tol_hi, inv_tol_hi)
864                    } else {
865                        if !tol_lo_ready {
866                            tol_lo = core::arch::x86_64::_mm_add_ps(
867                                core::arch::x86_64::_mm_mul_ps(
868                                    d_4,
869                                    core::arch::x86_64::_mm_set1_ps(0.20),
870                                ),
871                                core::arch::x86_64::_mm_set1_ps(0.75),
872                            );
873                            inv_tol_lo = core::arch::x86_64::_mm_div_ps(one, tol_lo);
874                            tol_lo_ready = true;
875                        }
876                        (tol_lo, inv_tol_lo)
877                    };
878                    let d_diff: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_andnot_ps(
879                        abs_mask,
880                        core::arch::x86_64::_mm_sub_ps(
881                            d_4,
882                            core::arch::x86_64::_mm_set1_ps(cell.depth[color_item]),
883                        ),
884                    );
885                    let in_tol: core::arch::x86_64::__m128 =
886                        core::arch::x86_64::_mm_cmple_ps(d_diff, tol_c);
887                    let wt_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
888                        eps,
889                        core::arch::x86_64::_mm_mul_ps(
890                            bw_c,
891                            core::arch::x86_64::_mm_sub_ps(
892                                one,
893                                core::arch::x86_64::_mm_mul_ps(d_diff, inv_tol_c),
894                            ),
895                        ),
896                    );
897                    let wt: core::arch::x86_64::__m128 =
898                        core::arch::x86_64::_mm_and_ps(in_tol, wt_raw);
899                    w_sum = core::arch::x86_64::_mm_add_ps(w_sum, wt);
900                    let sh_c: core::arch::x86_64::__m128 =
901                        core::arch::x86_64::_mm_set1_ps(cell.shadow[color_item]);
902                    s_sum = core::arch::x86_64::_mm_add_ps(
903                        s_sum,
904                        core::arch::x86_64::_mm_mul_ps(wt, sh_c),
905                    );
906                    if check_shadow_edge {
907                        let sh_min_cand: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
908                            core::arch::x86_64::_mm_and_ps(in_tol, sh_c),
909                            core::arch::x86_64::_mm_andnot_ps(
910                                in_tol,
911                                core::arch::x86_64::_mm_set1_ps(2.0),
912                            ),
913                        );
914                        let sh_max_cand: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
915                            core::arch::x86_64::_mm_and_ps(in_tol, sh_c),
916                            core::arch::x86_64::_mm_andnot_ps(
917                                in_tol,
918                                core::arch::x86_64::_mm_set1_ps(-1.0),
919                            ),
920                        );
921                        s_min = core::arch::x86_64::_mm_min_ps(s_min, sh_min_cand);
922                        s_max = core::arch::x86_64::_mm_max_ps(s_max, sh_max_cand);
923                    }
924                    if do_refl {
925                        rr_sum = core::arch::x86_64::_mm_add_ps(
926                            rr_sum,
927                            core::arch::x86_64::_mm_mul_ps(
928                                wt,
929                                core::arch::x86_64::_mm_set1_ps(cell.refl_r[color_item]),
930                            ),
931                        );
932                        rg_sum = core::arch::x86_64::_mm_add_ps(
933                            rg_sum,
934                            core::arch::x86_64::_mm_mul_ps(
935                                wt,
936                                core::arch::x86_64::_mm_set1_ps(cell.refl_g[color_item]),
937                            ),
938                        );
939                        rb_sum = core::arch::x86_64::_mm_add_ps(
940                            rb_sum,
941                            core::arch::x86_64::_mm_mul_ps(
942                                wt,
943                                core::arch::x86_64::_mm_set1_ps(cell.refl_b[color_item]),
944                            ),
945                        );
946                    }
947                    if gi_active {
948                        gr_sum = core::arch::x86_64::_mm_add_ps(
949                            gr_sum,
950                            core::arch::x86_64::_mm_mul_ps(
951                                wt,
952                                core::arch::x86_64::_mm_set1_ps(cell.gi_r[color_item]),
953                            ),
954                        );
955                        gg_sum = core::arch::x86_64::_mm_add_ps(
956                            gg_sum,
957                            core::arch::x86_64::_mm_mul_ps(
958                                wt,
959                                core::arch::x86_64::_mm_set1_ps(cell.gi_g[color_item]),
960                            ),
961                        );
962                        gb_sum = core::arch::x86_64::_mm_add_ps(
963                            gb_sum,
964                            core::arch::x86_64::_mm_mul_ps(
965                                wt,
966                                core::arch::x86_64::_mm_set1_ps(cell.gi_b[color_item]),
967                            ),
968                        );
969                        ao_sum = core::arch::x86_64::_mm_add_ps(
970                            ao_sum,
971                            core::arch::x86_64::_mm_mul_ps(
972                                wt,
973                                core::arch::x86_64::_mm_set1_ps(cell.ao[color_item]),
974                            ),
975                        );
976                    }
977                }
978                if core::arch::x86_64::_mm_movemask_ps(core::arch::x86_64::_mm_cmple_ps(
979                    w_sum,
980                    core::arch::x86_64::_mm_set1_ps(1e-5),
981                )) != 0
982                {
983                    return false;
984                }
985                if check_shadow_edge {
986                    let near_m: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
987                        d_4,
988                        core::arch::x86_64::_mm_set1_ps(42.0),
989                    );
990                    let edge_m: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
991                        near_m,
992                        core::arch::x86_64::_mm_cmpgt_ps(
993                            core::arch::x86_64::_mm_sub_ps(s_max, s_min),
994                            core::arch::x86_64::_mm_set1_ps(0.12),
995                        ),
996                    );
997                    if core::arch::x86_64::_mm_movemask_ps(edge_m) != 0 {
998                        return false;
999                    }
1000                }
1001                let inv_ws: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_div_ps(one, w_sum);
1002                core::arch::x86_64::_mm_storeu_ps(
1003                    out.shadow.as_mut_ptr().add(off),
1004                    core::arch::x86_64::_mm_mul_ps(s_sum, inv_ws),
1005                );
1006                if do_refl {
1007                    core::arch::x86_64::_mm_storeu_ps(
1008                        out.refl_r.as_mut_ptr().add(off),
1009                        core::arch::x86_64::_mm_mul_ps(rr_sum, inv_ws),
1010                    );
1011                    core::arch::x86_64::_mm_storeu_ps(
1012                        out.refl_g.as_mut_ptr().add(off),
1013                        core::arch::x86_64::_mm_mul_ps(rg_sum, inv_ws),
1014                    );
1015                    core::arch::x86_64::_mm_storeu_ps(
1016                        out.refl_b.as_mut_ptr().add(off),
1017                        core::arch::x86_64::_mm_mul_ps(rb_sum, inv_ws),
1018                    );
1019                }
1020                if gi_active {
1021                    core::arch::x86_64::_mm_storeu_ps(
1022                        out.gi_r.as_mut_ptr().add(off),
1023                        core::arch::x86_64::_mm_mul_ps(gr_sum, inv_ws),
1024                    );
1025                    core::arch::x86_64::_mm_storeu_ps(
1026                        out.gi_g.as_mut_ptr().add(off),
1027                        core::arch::x86_64::_mm_mul_ps(gg_sum, inv_ws),
1028                    );
1029                    core::arch::x86_64::_mm_storeu_ps(
1030                        out.gi_b.as_mut_ptr().add(off),
1031                        core::arch::x86_64::_mm_mul_ps(gb_sum, inv_ws),
1032                    );
1033                    core::arch::x86_64::_mm_storeu_ps(
1034                        out.ao.as_mut_ptr().add(off),
1035                        core::arch::x86_64::_mm_mul_ps(ao_sum, inv_ws),
1036                    );
1037                }
1038            }
1039            true
1040        }
1041        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1042        {
1043            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`; `simd128` is enabled on `wasm32`.
1044            unsafe {
1045                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
1046                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
1047                let eps: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1e-4);
1048                let d_4: core::arch::wasm32::v128 =
1049                    core::arch::wasm32::v128_load(out.depths.as_ptr().add(off).cast());
1050                let fx_v: core::arch::wasm32::v128 =
1051                    core::arch::wasm32::v128_load(fx_4.as_ptr().cast());
1052                let wx0_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(one, fx_v);
1053                let wy0_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(wy0);
1054                let wy1_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(wy1);
1055                let bw0: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(wx0_v, wy0_v);
1056                let bw1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(fx_v, wy0_v);
1057                let bw2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(wx0_v, wy1_v);
1058                let bw3: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(fx_v, wy1_v);
1059                let tol_hi: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1060                    core::arch::wasm32::f32x4_mul(d_4, core::arch::wasm32::f32x4_splat(0.58)),
1061                    core::arch::wasm32::f32x4_splat(2.4),
1062                );
1063                let inv_tol_hi: core::arch::wasm32::v128 =
1064                    core::arch::wasm32::f32x4_div(one, tol_hi);
1065                let mut tol_lo_ready: bool = false;
1066                let mut tol_lo: core::arch::wasm32::v128 = zero;
1067                let mut inv_tol_lo: core::arch::wasm32::v128 = zero;
1068                let mut w_sum: core::arch::wasm32::v128 = zero;
1069                let mut s_sum: core::arch::wasm32::v128 = zero;
1070                let mut s_min: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(2.0);
1071                let mut s_max: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(-1.0);
1072                let mut rr_sum: core::arch::wasm32::v128 = zero;
1073                let mut rg_sum: core::arch::wasm32::v128 = zero;
1074                let mut rb_sum: core::arch::wasm32::v128 = zero;
1075                let mut gr_sum: core::arch::wasm32::v128 = zero;
1076                let mut gg_sum: core::arch::wasm32::v128 = zero;
1077                let mut gb_sum: core::arch::wasm32::v128 = zero;
1078                let mut ao_sum: core::arch::wasm32::v128 = zero;
1079                for cell_item in 0..4_usize {
1080                    if (vmask & (1_u8 << cell_item)) == 0 {
1081                        continue;
1082                    }
1083                    let bw_c: core::arch::wasm32::v128 = match cell_item {
1084                        0 => bw0,
1085                        1 => bw1,
1086                        2 => bw2,
1087                        _ => bw3,
1088                    };
1089                    let (tol_c, inv_tol_c): (core::arch::wasm32::v128, core::arch::wasm32::v128) =
1090                        if cell.tol_scale[cell_item] > 0.4 {
1091                            (tol_hi, inv_tol_hi)
1092                        } else {
1093                            if !tol_lo_ready {
1094                                tol_lo = core::arch::wasm32::f32x4_add(
1095                                    core::arch::wasm32::f32x4_mul(
1096                                        d_4,
1097                                        core::arch::wasm32::f32x4_splat(0.20),
1098                                    ),
1099                                    core::arch::wasm32::f32x4_splat(0.75),
1100                                );
1101                                inv_tol_lo = core::arch::wasm32::f32x4_div(one, tol_lo);
1102                                tol_lo_ready = true;
1103                            }
1104                            (tol_lo, inv_tol_lo)
1105                        };
1106                    let d_diff: core::arch::wasm32::v128 =
1107                        core::arch::wasm32::f32x4_abs(core::arch::wasm32::f32x4_sub(
1108                            d_4,
1109                            core::arch::wasm32::f32x4_splat(cell.depth[cell_item]),
1110                        ));
1111                    let in_tol: core::arch::wasm32::v128 =
1112                        core::arch::wasm32::f32x4_le(d_diff, tol_c);
1113                    let wt_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1114                        eps,
1115                        core::arch::wasm32::f32x4_mul(
1116                            bw_c,
1117                            core::arch::wasm32::f32x4_sub(
1118                                one,
1119                                core::arch::wasm32::f32x4_mul(d_diff, inv_tol_c),
1120                            ),
1121                        ),
1122                    );
1123                    let wt: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(in_tol, wt_raw);
1124                    w_sum = core::arch::wasm32::f32x4_add(w_sum, wt);
1125                    let sh_c: core::arch::wasm32::v128 =
1126                        core::arch::wasm32::f32x4_splat(cell.shadow[cell_item]);
1127                    s_sum = core::arch::wasm32::f32x4_add(
1128                        s_sum,
1129                        core::arch::wasm32::f32x4_mul(wt, sh_c),
1130                    );
1131                    if check_shadow_edge {
1132                        s_min = core::arch::wasm32::f32x4_pmin(
1133                            s_min,
1134                            core::arch::wasm32::v128_bitselect(
1135                                sh_c,
1136                                core::arch::wasm32::f32x4_splat(2.0),
1137                                in_tol,
1138                            ),
1139                        );
1140                        s_max = core::arch::wasm32::f32x4_pmax(
1141                            s_max,
1142                            core::arch::wasm32::v128_bitselect(
1143                                sh_c,
1144                                core::arch::wasm32::f32x4_splat(-1.0),
1145                                in_tol,
1146                            ),
1147                        );
1148                    }
1149                    if do_refl {
1150                        rr_sum = core::arch::wasm32::f32x4_add(
1151                            rr_sum,
1152                            core::arch::wasm32::f32x4_mul(
1153                                wt,
1154                                core::arch::wasm32::f32x4_splat(cell.refl_r[cell_item]),
1155                            ),
1156                        );
1157                        rg_sum = core::arch::wasm32::f32x4_add(
1158                            rg_sum,
1159                            core::arch::wasm32::f32x4_mul(
1160                                wt,
1161                                core::arch::wasm32::f32x4_splat(cell.refl_g[cell_item]),
1162                            ),
1163                        );
1164                        rb_sum = core::arch::wasm32::f32x4_add(
1165                            rb_sum,
1166                            core::arch::wasm32::f32x4_mul(
1167                                wt,
1168                                core::arch::wasm32::f32x4_splat(cell.refl_b[cell_item]),
1169                            ),
1170                        );
1171                    }
1172                    if gi_active {
1173                        gr_sum = core::arch::wasm32::f32x4_add(
1174                            gr_sum,
1175                            core::arch::wasm32::f32x4_mul(
1176                                wt,
1177                                core::arch::wasm32::f32x4_splat(cell.gi_r[cell_item]),
1178                            ),
1179                        );
1180                        gg_sum = core::arch::wasm32::f32x4_add(
1181                            gg_sum,
1182                            core::arch::wasm32::f32x4_mul(
1183                                wt,
1184                                core::arch::wasm32::f32x4_splat(cell.gi_g[cell_item]),
1185                            ),
1186                        );
1187                        gb_sum = core::arch::wasm32::f32x4_add(
1188                            gb_sum,
1189                            core::arch::wasm32::f32x4_mul(
1190                                wt,
1191                                core::arch::wasm32::f32x4_splat(cell.gi_b[cell_item]),
1192                            ),
1193                        );
1194                        ao_sum = core::arch::wasm32::f32x4_add(
1195                            ao_sum,
1196                            core::arch::wasm32::f32x4_mul(
1197                                wt,
1198                                core::arch::wasm32::f32x4_splat(cell.ao[cell_item]),
1199                            ),
1200                        );
1201                    }
1202                }
1203                if core::arch::wasm32::i32x4_bitmask(core::arch::wasm32::f32x4_le(
1204                    w_sum,
1205                    core::arch::wasm32::f32x4_splat(1e-5),
1206                )) != 0
1207                {
1208                    return false;
1209                }
1210                if check_shadow_edge {
1211                    let near_m: core::arch::wasm32::v128 =
1212                        core::arch::wasm32::f32x4_lt(d_4, core::arch::wasm32::f32x4_splat(18.0));
1213                    let edge_m: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1214                        near_m,
1215                        core::arch::wasm32::f32x4_gt(
1216                            core::arch::wasm32::f32x4_sub(s_max, s_min),
1217                            core::arch::wasm32::f32x4_splat(0.12),
1218                        ),
1219                    );
1220                    if core::arch::wasm32::v128_any_true(edge_m) {
1221                        return false;
1222                    }
1223                }
1224                let inv_ws: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_div(one, w_sum);
1225                core::arch::wasm32::v128_store(
1226                    out.shadow.as_mut_ptr().add(off).cast(),
1227                    core::arch::wasm32::f32x4_mul(s_sum, inv_ws),
1228                );
1229                if do_refl {
1230                    core::arch::wasm32::v128_store(
1231                        out.refl_r.as_mut_ptr().add(off).cast(),
1232                        core::arch::wasm32::f32x4_mul(rr_sum, inv_ws),
1233                    );
1234                    core::arch::wasm32::v128_store(
1235                        out.refl_g.as_mut_ptr().add(off).cast(),
1236                        core::arch::wasm32::f32x4_mul(rg_sum, inv_ws),
1237                    );
1238                    core::arch::wasm32::v128_store(
1239                        out.refl_b.as_mut_ptr().add(off).cast(),
1240                        core::arch::wasm32::f32x4_mul(rb_sum, inv_ws),
1241                    );
1242                }
1243                if gi_active {
1244                    core::arch::wasm32::v128_store(
1245                        out.gi_r.as_mut_ptr().add(off).cast(),
1246                        core::arch::wasm32::f32x4_mul(gr_sum, inv_ws),
1247                    );
1248                    core::arch::wasm32::v128_store(
1249                        out.gi_g.as_mut_ptr().add(off).cast(),
1250                        core::arch::wasm32::f32x4_mul(gg_sum, inv_ws),
1251                    );
1252                    core::arch::wasm32::v128_store(
1253                        out.gi_b.as_mut_ptr().add(off).cast(),
1254                        core::arch::wasm32::f32x4_mul(gb_sum, inv_ws),
1255                    );
1256                    core::arch::wasm32::v128_store(
1257                        out.ao.as_mut_ptr().add(off).cast(),
1258                        core::arch::wasm32::f32x4_mul(ao_sum, inv_ws),
1259                    );
1260                }
1261            }
1262            true
1263        }
1264        #[cfg(not(target_arch = "aarch64"))]
1265        #[cfg(not(target_arch = "x86_64"))]
1266        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1267        {
1268            for (lane, &fx) in fx_4.iter().enumerate() {
1269                let dst_i: usize = off + lane;
1270                let depth_l: f32 = out.depths[dst_i];
1271                let wx0: f32 = 1.0 - fx;
1272                let bws: [f32; 4] = [wx0 * wy0, fx * wy0, wx0 * wy1, fx * wy1];
1273                let (vm, sh, s_min, s_max, rf, gi, ao): (u32, f32, f32, f32, Vec3, Vec3, f32) =
1274                    Self::sample_1x(cell, bws, depth_l, (do_refl, gi_active));
1275                let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
1276                    18.0
1277                } else {
1278                    42.0
1279                };
1280                if vm == 0 || (check_shadow_edge && depth_l < edge_max_d && (s_max - s_min) > 0.12)
1281                {
1282                    return false;
1283                }
1284                out.shadow[dst_i] = sh;
1285                if do_refl {
1286                    out.refl_r[dst_i] = rf.get_x();
1287                    out.refl_g[dst_i] = rf.get_y();
1288                    out.refl_b[dst_i] = rf.get_z();
1289                }
1290                if gi_active {
1291                    out.gi_r[dst_i] = gi.get_x();
1292                    out.gi_g[dst_i] = gi.get_y();
1293                    out.gi_b[dst_i] = gi.get_z();
1294                    out.ao[dst_i] = ao;
1295                }
1296            }
1297            true
1298        }
1299    }
1300
1301    /// Evaluates bilateral probe upsampling for a single pixel against a cached 4-corner SIMD cell.
1302    ///
1303    /// # Arguments
1304    ///
1305    /// - `&Self` - Pre-packed 4-corner probe cell.
1306    /// - `[f32; 4]` - Bilinear corner weights `[w00, w10, w01, w11]`.
1307    /// - `f32` - Pixel linear depth.
1308    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
1309    ///
1310    /// # Returns
1311    ///
1312    /// - `(u32, f32, f32, f32, Vec3, Vec3, f32)` - `(valid_matches, shadow, s_min, s_max, refl, gi, ao)`.
1313    #[inline(always)]
1314    #[must_use]
1315    pub(crate) fn sample_1x(
1316        cell: &Self,
1317        bws: [f32; 4],
1318        depth: f32,
1319        flags: (bool, bool),
1320    ) -> (u32, f32, f32, f32, Vec3, Vec3, f32) {
1321        if cell.vmask == 0 {
1322            return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1323        }
1324        let (do_refl, gi_active): (bool, bool) = flags;
1325        #[cfg(target_arch = "aarch64")]
1326        {
1327            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; NEON is mandatory on `aarch64`.
1328            unsafe {
1329                let d_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(depth);
1330                let c_depth: core::arch::aarch64::float32x4_t =
1331                    core::arch::aarch64::vld1q_f32(cell.depth.as_ptr());
1332                let c_tscale: core::arch::aarch64::float32x4_t =
1333                    core::arch::aarch64::vld1q_f32(cell.tol_scale.as_ptr());
1334                let c_tbias: core::arch::aarch64::float32x4_t =
1335                    core::arch::aarch64::vld1q_f32(cell.tol_bias.as_ptr());
1336                let c_vbits: core::arch::aarch64::uint32x4_t =
1337                    core::arch::aarch64::vld1q_u32(cell.valid_u32.as_ptr());
1338                let d_diff: core::arch::aarch64::float32x4_t =
1339                    core::arch::aarch64::vabsq_f32(core::arch::aarch64::vsubq_f32(d_v, c_depth));
1340                let tol: core::arch::aarch64::float32x4_t =
1341                    core::arch::aarch64::vfmaq_f32(c_tbias, d_v, c_tscale);
1342                let in_tol: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
1343                    c_vbits,
1344                    core::arch::aarch64::vcleq_f32(d_diff, tol),
1345                );
1346                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
1347                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
1348                let bws_v: core::arch::aarch64::float32x4_t =
1349                    core::arch::aarch64::vld1q_f32(bws.as_ptr());
1350                let inv_tol: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(tol);
1351                let wt_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1352                    core::arch::aarch64::vdupq_n_f32(1e-4),
1353                    bws_v,
1354                    core::arch::aarch64::vfmsq_f32(one, d_diff, inv_tol),
1355                );
1356                let wt: core::arch::aarch64::float32x4_t =
1357                    core::arch::aarch64::vbslq_f32(in_tol, wt_raw, zero);
1358                let w_sum: f32 = core::arch::aarch64::vaddvq_f32(wt);
1359                if w_sum <= 1e-5 {
1360                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1361                }
1362                let inv_ws: f32 = 1.0 / w_sum;
1363                let c_shadow: core::arch::aarch64::float32x4_t =
1364                    core::arch::aarch64::vld1q_f32(cell.shadow.as_ptr());
1365                let sh: f32 =
1366                    core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(wt, c_shadow))
1367                        * inv_ws;
1368                let (s_min, s_max): (f32, f32) = if gi_active {
1369                    (sh, sh)
1370                } else {
1371                    (
1372                        core::arch::aarch64::vminvq_f32(core::arch::aarch64::vbslq_f32(
1373                            in_tol,
1374                            c_shadow,
1375                            core::arch::aarch64::vdupq_n_f32(2.0),
1376                        )),
1377                        core::arch::aarch64::vmaxvq_f32(core::arch::aarch64::vbslq_f32(
1378                            in_tol,
1379                            c_shadow,
1380                            core::arch::aarch64::vdupq_n_f32(-1.0),
1381                        )),
1382                    )
1383                };
1384                let refl: Vec3 = if do_refl {
1385                    let rr: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1386                        wt,
1387                        core::arch::aarch64::vld1q_f32(cell.refl_r.as_ptr()),
1388                    )) * inv_ws;
1389                    let rg: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1390                        wt,
1391                        core::arch::aarch64::vld1q_f32(cell.refl_g.as_ptr()),
1392                    )) * inv_ws;
1393                    let rb: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1394                        wt,
1395                        core::arch::aarch64::vld1q_f32(cell.refl_b.as_ptr()),
1396                    )) * inv_ws;
1397                    Vec3::new(rr, rg, rb)
1398                } else {
1399                    Vec3::zero()
1400                };
1401                let (gi, ao): (Vec3, f32) = if gi_active {
1402                    let gr: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1403                        wt,
1404                        core::arch::aarch64::vld1q_f32(cell.gi_r.as_ptr()),
1405                    )) * inv_ws;
1406                    let gg: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1407                        wt,
1408                        core::arch::aarch64::vld1q_f32(cell.gi_g.as_ptr()),
1409                    )) * inv_ws;
1410                    let gb: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1411                        wt,
1412                        core::arch::aarch64::vld1q_f32(cell.gi_b.as_ptr()),
1413                    )) * inv_ws;
1414                    let ao_v: f32 =
1415                        core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1416                            wt,
1417                            core::arch::aarch64::vld1q_f32(cell.ao.as_ptr()),
1418                        )) * inv_ws;
1419                    (Vec3::new(gr, gg, gb), ao_v)
1420                } else {
1421                    (Vec3::zero(), 1.0)
1422                };
1423                (1, sh, s_min, s_max, refl, gi, ao)
1424            }
1425        }
1426        #[cfg(target_arch = "x86_64")]
1427        {
1428            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; SSE2 is mandatory on `x86_64`.
1429            unsafe {
1430                let d_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(depth);
1431                let c_depth: core::arch::x86_64::__m128 =
1432                    core::arch::x86_64::_mm_load_ps(cell.depth.as_ptr());
1433                let c_tscale: core::arch::x86_64::__m128 =
1434                    core::arch::x86_64::_mm_load_ps(cell.tol_scale.as_ptr());
1435                let c_tbias: core::arch::x86_64::__m128 =
1436                    core::arch::x86_64::_mm_load_ps(cell.tol_bias.as_ptr());
1437                let c_vbits: core::arch::x86_64::__m128 =
1438                    core::arch::x86_64::_mm_castsi128_ps(core::arch::x86_64::_mm_load_si128(
1439                        cell.valid_u32
1440                            .as_ptr()
1441                            .cast::<core::arch::x86_64::__m128i>(),
1442                    ));
1443                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
1444                let d_diff: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_andnot_ps(
1445                    abs_mask,
1446                    core::arch::x86_64::_mm_sub_ps(d_v, c_depth),
1447                );
1448                let tol: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1449                    c_tbias,
1450                    core::arch::x86_64::_mm_mul_ps(d_v, c_tscale),
1451                );
1452                let in_tol: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
1453                    c_vbits,
1454                    core::arch::x86_64::_mm_cmple_ps(d_diff, tol),
1455                );
1456                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
1457                let bws_v: core::arch::x86_64::__m128 =
1458                    core::arch::x86_64::_mm_loadu_ps(bws.as_ptr());
1459                let wt_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1460                    core::arch::x86_64::_mm_set1_ps(1e-4),
1461                    core::arch::x86_64::_mm_mul_ps(
1462                        bws_v,
1463                        core::arch::x86_64::_mm_sub_ps(
1464                            one,
1465                            core::arch::x86_64::_mm_div_ps(d_diff, tol),
1466                        ),
1467                    ),
1468                );
1469                let wt: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(in_tol, wt_raw);
1470                let w_sum: f32 = Renderer3D::sse_hsum_4x(wt);
1471                if w_sum <= 1e-5 {
1472                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1473                }
1474                let inv_ws: f32 = 1.0 / w_sum;
1475                let c_shadow: core::arch::x86_64::__m128 =
1476                    core::arch::x86_64::_mm_load_ps(cell.shadow.as_ptr());
1477                let sh: f32 =
1478                    Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(wt, c_shadow)) * inv_ws;
1479                let (s_min, s_max): (f32, f32) = if gi_active {
1480                    (sh, sh)
1481                } else {
1482                    let s_min_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
1483                        core::arch::x86_64::_mm_and_ps(in_tol, c_shadow),
1484                        core::arch::x86_64::_mm_andnot_ps(
1485                            in_tol,
1486                            core::arch::x86_64::_mm_set1_ps(2.0),
1487                        ),
1488                    );
1489                    let s_max_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
1490                        core::arch::x86_64::_mm_and_ps(in_tol, c_shadow),
1491                        core::arch::x86_64::_mm_andnot_ps(
1492                            in_tol,
1493                            core::arch::x86_64::_mm_set1_ps(-1.0),
1494                        ),
1495                    );
1496                    (
1497                        Renderer3D::sse_hmin_4x(s_min_v),
1498                        Renderer3D::sse_hmax_4x(s_max_v),
1499                    )
1500                };
1501                let refl: Vec3 = if do_refl {
1502                    let rr: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1503                        wt,
1504                        core::arch::x86_64::_mm_load_ps(cell.refl_r.as_ptr()),
1505                    )) * inv_ws;
1506                    let rg: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1507                        wt,
1508                        core::arch::x86_64::_mm_load_ps(cell.refl_g.as_ptr()),
1509                    )) * inv_ws;
1510                    let rb: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1511                        wt,
1512                        core::arch::x86_64::_mm_load_ps(cell.refl_b.as_ptr()),
1513                    )) * inv_ws;
1514                    Vec3::new(rr, rg, rb)
1515                } else {
1516                    Vec3::zero()
1517                };
1518                let (gi, ao): (Vec3, f32) = if gi_active {
1519                    let gr: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1520                        wt,
1521                        core::arch::x86_64::_mm_load_ps(cell.gi_r.as_ptr()),
1522                    )) * inv_ws;
1523                    let gg: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1524                        wt,
1525                        core::arch::x86_64::_mm_load_ps(cell.gi_g.as_ptr()),
1526                    )) * inv_ws;
1527                    let gb: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1528                        wt,
1529                        core::arch::x86_64::_mm_load_ps(cell.gi_b.as_ptr()),
1530                    )) * inv_ws;
1531                    let ao_v: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1532                        wt,
1533                        core::arch::x86_64::_mm_load_ps(cell.ao.as_ptr()),
1534                    )) * inv_ws;
1535                    (Vec3::new(gr, gg, gb), ao_v)
1536                } else {
1537                    (Vec3::zero(), 1.0)
1538                };
1539                (1, sh, s_min, s_max, refl, gi, ao)
1540            }
1541        }
1542        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1543        {
1544            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; `simd128` is enabled on `wasm32`.
1545            unsafe {
1546                let d_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(depth);
1547                let c_depth: core::arch::wasm32::v128 =
1548                    core::arch::wasm32::v128_load(cell.depth.as_ptr().cast());
1549                let c_tscale: core::arch::wasm32::v128 =
1550                    core::arch::wasm32::v128_load(cell.tol_scale.as_ptr().cast());
1551                let c_tbias: core::arch::wasm32::v128 =
1552                    core::arch::wasm32::v128_load(cell.tol_bias.as_ptr().cast());
1553                let c_vbits: core::arch::wasm32::v128 =
1554                    core::arch::wasm32::v128_load(cell.valid_u32.as_ptr().cast());
1555                let d_diff: core::arch::wasm32::v128 =
1556                    core::arch::wasm32::f32x4_abs(core::arch::wasm32::f32x4_sub(d_v, c_depth));
1557                let tol: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1558                    c_tbias,
1559                    core::arch::wasm32::f32x4_mul(d_v, c_tscale),
1560                );
1561                let in_tol: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1562                    c_vbits,
1563                    core::arch::wasm32::f32x4_le(d_diff, tol),
1564                );
1565                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
1566                let bws_v: core::arch::wasm32::v128 =
1567                    core::arch::wasm32::v128_load(bws.as_ptr().cast());
1568                let wt_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1569                    core::arch::wasm32::f32x4_splat(1e-4),
1570                    core::arch::wasm32::f32x4_mul(
1571                        bws_v,
1572                        core::arch::wasm32::f32x4_sub(
1573                            one,
1574                            core::arch::wasm32::f32x4_div(d_diff, tol),
1575                        ),
1576                    ),
1577                );
1578                let wt: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(in_tol, wt_raw);
1579                let w_sum: f32 = Renderer3D::wasm_hsum_4x(wt);
1580                if w_sum <= 1e-5 {
1581                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1582                }
1583                let inv_ws: f32 = 1.0 / w_sum;
1584                let c_shadow: core::arch::wasm32::v128 =
1585                    core::arch::wasm32::v128_load(cell.shadow.as_ptr().cast());
1586                let sh: f32 =
1587                    Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(wt, c_shadow)) * inv_ws;
1588                let (s_min, s_max): (f32, f32) = if gi_active {
1589                    (sh, sh)
1590                } else {
1591                    let s_min_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_bitselect(
1592                        c_shadow,
1593                        core::arch::wasm32::f32x4_splat(2.0),
1594                        in_tol,
1595                    );
1596                    let s_max_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_bitselect(
1597                        c_shadow,
1598                        core::arch::wasm32::f32x4_splat(-1.0),
1599                        in_tol,
1600                    );
1601                    (
1602                        Renderer3D::wasm_hmin_4x(s_min_v),
1603                        Renderer3D::wasm_hmax_4x(s_max_v),
1604                    )
1605                };
1606                let refl: Vec3 = if do_refl {
1607                    let rr: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1608                        wt,
1609                        core::arch::wasm32::v128_load(cell.refl_r.as_ptr().cast()),
1610                    )) * inv_ws;
1611                    let rg: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1612                        wt,
1613                        core::arch::wasm32::v128_load(cell.refl_g.as_ptr().cast()),
1614                    )) * inv_ws;
1615                    let rb: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1616                        wt,
1617                        core::arch::wasm32::v128_load(cell.refl_b.as_ptr().cast()),
1618                    )) * inv_ws;
1619                    Vec3::new(rr, rg, rb)
1620                } else {
1621                    Vec3::zero()
1622                };
1623                let (gi, ao): (Vec3, f32) = if gi_active {
1624                    let gr: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1625                        wt,
1626                        core::arch::wasm32::v128_load(cell.gi_r.as_ptr().cast()),
1627                    )) * inv_ws;
1628                    let gg: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1629                        wt,
1630                        core::arch::wasm32::v128_load(cell.gi_g.as_ptr().cast()),
1631                    )) * inv_ws;
1632                    let gb: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1633                        wt,
1634                        core::arch::wasm32::v128_load(cell.gi_b.as_ptr().cast()),
1635                    )) * inv_ws;
1636                    let ao_v: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1637                        wt,
1638                        core::arch::wasm32::v128_load(cell.ao.as_ptr().cast()),
1639                    )) * inv_ws;
1640                    (Vec3::new(gr, gg, gb), ao_v)
1641                } else {
1642                    (Vec3::zero(), 1.0)
1643                };
1644                (1, sh, s_min, s_max, refl, gi, ao)
1645            }
1646        }
1647        #[cfg(not(target_arch = "aarch64"))]
1648        #[cfg(not(target_arch = "x86_64"))]
1649        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1650        {
1651            let mut w_sum: f32 = 0.0;
1652            let mut s_sum: f32 = 0.0;
1653            let mut s_min: f32 = 2.0;
1654            let mut s_max: f32 = -1.0;
1655            let mut rr_sum: f32 = 0.0;
1656            let mut rg_sum: f32 = 0.0;
1657            let mut rb_sum: f32 = 0.0;
1658            let mut gr_sum: f32 = 0.0;
1659            let mut gg_sum: f32 = 0.0;
1660            let mut gb_sum: f32 = 0.0;
1661            let mut ao_sum: f32 = 0.0;
1662            let mut valid_matches: u32 = 0;
1663            let mut rem: u8 = cell.vmask;
1664            while rem != 0 {
1665                let item_index: usize = rem.trailing_zeros() as usize;
1666                rem &= rem - 1;
1667                let tol: f32 = depth.mul_add(cell.tol_scale[item_index], cell.tol_bias[item_index]);
1668                let d_diff: f32 = (depth - cell.depth[item_index]).abs();
1669                if d_diff > tol {
1670                    continue;
1671                }
1672                let wt: f32 = bws[item_index].mul_add(1.0 - d_diff / tol, 1e-4);
1673                w_sum += wt;
1674                let sh: f32 = cell.shadow[item_index];
1675                s_sum = sh.mul_add(wt, s_sum);
1676                s_min = s_min.min(sh);
1677                s_max = s_max.max(sh);
1678                if do_refl {
1679                    rr_sum = cell.refl_r[item_index].mul_add(wt, rr_sum);
1680                    rg_sum = cell.refl_g[item_index].mul_add(wt, rg_sum);
1681                    rb_sum = cell.refl_b[item_index].mul_add(wt, rb_sum);
1682                }
1683                if gi_active {
1684                    gr_sum = cell.gi_r[item_index].mul_add(wt, gr_sum);
1685                    gg_sum = cell.gi_g[item_index].mul_add(wt, gg_sum);
1686                    gb_sum = cell.gi_b[item_index].mul_add(wt, gb_sum);
1687                    ao_sum = cell.ao[item_index].mul_add(wt, ao_sum);
1688                }
1689                valid_matches += 1;
1690            }
1691            if valid_matches > 0 && w_sum > 1e-5 {
1692                let inv_ws: f32 = 1.0 / w_sum;
1693                (
1694                    valid_matches,
1695                    s_sum * inv_ws,
1696                    s_min,
1697                    s_max,
1698                    Vec3::new(rr_sum * inv_ws, rg_sum * inv_ws, rb_sum * inv_ws),
1699                    Vec3::new(gr_sum * inv_ws, gg_sum * inv_ws, gb_sum * inv_ws),
1700                    ao_sum * inv_ws,
1701                )
1702            } else {
1703                (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0)
1704            }
1705        }
1706    }
1707}
1708
1709/// Borrowed row view helper for `RtProbeGridSoa`.
1710impl RtProbeGridSoa {
1711    /// Borrows row `gy` of width `gw` from this full SoA grid as a zero-copy `RtProbeRowView`.
1712    ///
1713    /// # Arguments
1714    ///
1715    /// - `&Self` - Full SoA probe grid reference.
1716    /// - `usize` - Coarse probe row index `gy`.
1717    /// - `usize` - Coarse probe grid width `gw`.
1718    ///
1719    /// # Returns
1720    ///
1721    /// - `RtProbeRowView<'_>` - Zero-copy borrowed SoA row view.
1722    #[inline(always)]
1723    #[must_use]
1724    pub(crate) fn row_view(&self, gy: usize, gw: usize) -> RtProbeRowView<'_> {
1725        let Self {
1726            shadow,
1727            refl_r,
1728            refl_g,
1729            refl_b,
1730            gi_r,
1731            gi_g,
1732            gi_b,
1733            ao,
1734            depth,
1735            nx,
1736            ny,
1737            nz,
1738            valid,
1739            ..
1740        } = self;
1741        let source_val: usize = gy * gw;
1742        let event_ref: usize = source_val + gw;
1743        RtProbeRowView {
1744            shadow: &shadow[source_val..event_ref],
1745            refl_r: &refl_r[source_val..event_ref],
1746            refl_g: &refl_g[source_val..event_ref],
1747            refl_b: &refl_b[source_val..event_ref],
1748            gi_r: &gi_r[source_val..event_ref],
1749            gi_g: &gi_g[source_val..event_ref],
1750            gi_b: &gi_b[source_val..event_ref],
1751            ao: &ao[source_val..event_ref],
1752            depth: &depth[source_val..event_ref],
1753            nx: &nx[source_val..event_ref],
1754            ny: &ny[source_val..event_ref],
1755            nz: &nz[source_val..event_ref],
1756            valid: &valid[source_val..event_ref],
1757        }
1758    }
1759}
1760
1761/// Default zero-allocation UE5-class `Renderer3D` with identity motion-vector matrices and pre-allocated subsystems.
1762impl Default for Renderer3D {
1763    /// Creates an empty `Renderer3D` initialized with identity previous projection, Hi-Z pyramid, Lumen cache, VSM, Clustered Lighting, TSR, and frame governor.
1764    ///
1765    /// # Returns
1766    ///
1767    /// - `Self` - Ready UE5-class 3D renderer.
1768    fn default() -> Self {
1769        Self {
1770            color_buffer: Vec::new(),
1771            aa_buffer: Vec::new(),
1772            depth_buffer: Vec::new(),
1773            g_tri_idx: Vec::new(),
1774            luma_buffer: Vec::new(),
1775            shaded_tris: Vec::new(),
1776            smooth_tris: Vec::new(),
1777            nanite_dags_cache: Vec::new(),
1778            cached_rdg_schedule: RenderGraphSchedule3D::default(),
1779            cached_rdg_key: 0,
1780            last_executed_rdg_passes: 0,
1781            rgba_scratch: Vec::new(),
1782            rt_probes: RtProbeGridSoa::default(),
1783            prev_rt_probes: RtProbeGridSoa::default(),
1784            has_probe_history: false,
1785            prev_probe_gw: 0,
1786            prev_probe_gh: 0,
1787            prev_probe_rt_mode: RayTracingMode::default(),
1788            prev_sun_dir: Vec3::zero(),
1789            rt_probes_wide_denoised: RtProbeGridSoa::default(),
1790            bloom_a: Vec::new(),
1791            bloom_b: Vec::new(),
1792            bloom_tile_active: Vec::new(),
1793            visible_scratch: Vec::new(),
1794            cluster_ranges_scratch: Vec::new(),
1795            projected_verts_scratch: Vec::new(),
1796            unique_meshes_scratch: HashSet::new(),
1797            saved_objs_scratch: Vec::new(),
1798            raster_tris_scratch: Vec::new(),
1799            tile_counts_scratch: Vec::new(),
1800            tile_offsets_scratch: Vec::new(),
1801            tile_cursors_scratch: Vec::new(),
1802            tile_tri_indices_scratch: Vec::new(),
1803            gpu_target: GpuCompositeTarget::default(),
1804            has_taa_history: false,
1805            prev_vp_m0: 0.0,
1806            prev_view_proj: Mat4::identity(),
1807            has_prev_vp: false,
1808            prev_render_dims: (0, 0),
1809            prev_rt_step: 0,
1810            hiz_pyramid: HiZPyramid::default(),
1811            hiz_occluder_flags_scratch: Vec::new(),
1812            lumen_cache: LumenRadianceCache::default(),
1813            light_clusters: LightClusterGrid3D::default(),
1814            virtual_shadow_map: VirtualShadowMap::default(),
1815            tsr_upscaler: TsrUpscaler::default(),
1816            tsr_internal_scratch: Vec::new(),
1817            frame_governor: AdaptiveFrameGovernor::default(),
1818            render_graph: RenderGraph3D::default(),
1819            rt_stride_bias: 0,
1820            geom_chunks_scratch: Vec::new(),
1821            adapted_exposure: 1.0,
1822            frame_index: 0,
1823            last_world_revision: 0,
1824            last_quality_fingerprint: 0,
1825            taa_accumulated_frames: 0,
1826            cached_world_reuses: 0,
1827            width: 0,
1828            height: 0,
1829            last_stats: RenderStats3D::default(),
1830            sky_lut: Vec::new(),
1831            sky_lut_key: 0,
1832            aces_lut: Self::build_aces3d_lut(),
1833            reserved_object_cap: 0,
1834            reserved_mesh_cap: 0,
1835        }
1836    }
1837}
1838
1839/// High-FPS UE5-class Deferred GGX PBR + Persistent Multi-Core Tiled SIMD BVH4/BVH8 + Lumen GI + Volumetric Fog + SIMD Bloom + Morphological AA/TAA renderer.
1840impl Renderer3D {
1841    /// Builds the 1025-entry L1-resident ACES filmic + sRGB gamma LUT for zero-`powf` sky and scalar tonemapping.
1842    ///
1843    /// # Returns
1844    ///
1845    /// - `Vec<u8>` - Precomputed sRGB byte LUT of length `ACES3D_LUT_SIZE`.
1846    #[must_use]
1847    fn build_aces3d_lut() -> Vec<u8> {
1848        let mut table: Vec<u8> = Vec::with_capacity(ACES3D_LUT_SIZE);
1849        let max_idx_f: f32 = (ACES3D_LUT_SIZE - 1) as f32;
1850        for slot in 0..ACES3D_LUT_SIZE {
1851            if slot + 1 >= ACES3D_LUT_SIZE {
1852                table.push(255);
1853            } else {
1854                let norm_u: f32 = (slot as f32) / max_idx_f;
1855                let linear_val: f32 = ACES3D_LUT_KNEE * norm_u / (1.0 - norm_u);
1856                let num: f32 = linear_val * (2.51 * linear_val + 0.03);
1857                let den: f32 = linear_val * (2.43 * linear_val + 0.59) + 0.14;
1858                let mapped: f32 = (num / den).clamp(0.0, 1.0);
1859                let srgb: f32 = mapped.powf(1.0 / 2.2);
1860                table.push((srgb.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
1861            }
1862        }
1863        table
1864    }
1865
1866    /// Maps a linear HDR RGB triple to RGBA8 via `aces_lut` with zero `powf` calls.
1867    ///
1868    /// # Arguments
1869    ///
1870    /// - `&[u8]` - Precomputed ACES+sRGB LUT (`ACES3D_LUT_SIZE`).
1871    /// - `Vec3` - Exposed linear HDR radiance.
1872    ///
1873    /// # Returns
1874    ///
1875    /// - `[u8; 4]` - Tone-mapped RGBA8 pixel with opaque alpha `255`.
1876    #[inline(always)]
1877    #[must_use]
1878    fn lut_aces3d_rgba8(aces_lut: &[u8], exposed: Vec3) -> [u8; 4] {
1879        let max_idx: usize = ACES3D_LUT_SIZE - 1;
1880        let max_f: f32 = max_idx as f32;
1881        let rx: f32 = exposed.get_x().max(0.0);
1882        let gx: f32 = exposed.get_y().max(0.0);
1883        let bx: f32 = exposed.get_z().max(0.0);
1884        let ri: usize = (((rx / (rx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1885        let gi: usize = (((gx / (gx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1886        let bi: usize = (((bx / (bx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1887        [aces_lut[ri], aces_lut[gi], aces_lut[bi], 255]
1888    }
1889
1890    /// Deterministic fast 2D hash returning `[0.0, 1.0]` for procedural 3D atmospheric cloud strata and night stars.
1891    ///
1892    /// # Arguments
1893    ///
1894    /// - `i32` - Integer cell X coordinate.
1895    /// - `i32` - Integer cell Y coordinate.
1896    ///
1897    /// # Returns
1898    ///
1899    /// - `f32` - Pseudo-random scalar in `[0.0, 1.0]`.
1900    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1901    #[must_use]
1902    fn sky_hash_2d(ix: i32, iy: i32) -> f32 {
1903        let mut bits: u32 = (ix as u32)
1904            .wrapping_mul(374_761_393)
1905            .wrapping_add((iy as u32).wrapping_mul(668_265_263));
1906        bits = (bits ^ (bits >> 13)).wrapping_mul(1_274_126_177);
1907        bits ^= bits >> 16;
1908        ((bits & 0x00FF_FFFF) as f32) * (1.0 / 16_777_215.0)
1909    }
1910
1911    /// Smooth cubic Hermite value noise for layered volumetric-look sky clouds.
1912    ///
1913    /// # Arguments
1914    ///
1915    /// - `f32` - Continuous U coordinate.
1916    /// - `f32` - Continuous V coordinate.
1917    ///
1918    /// # Returns
1919    ///
1920    /// - `f32` - Interpolated noise sample in `[0.0, 1.0]`.
1921    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1922    #[must_use]
1923    fn sky_value_noise(coord_u: f32, coord_v: f32) -> f32 {
1924        let fu: f32 = coord_u.floor();
1925        let fv: f32 = coord_v.floor();
1926        let iu: i32 = fu as i32;
1927        let iv: i32 = fv as i32;
1928        let tu: f32 = coord_u - fu;
1929        let tv: f32 = coord_v - fv;
1930        let su: f32 = tu * tu * (3.0 - 2.0 * tu);
1931        let sv: f32 = tv * tv * (3.0 - 2.0 * tv);
1932        let v00: f32 = Self::sky_hash_2d(iu, iv);
1933        let v10: f32 = Self::sky_hash_2d(iu + 1, iv);
1934        let v01: f32 = Self::sky_hash_2d(iu, iv + 1);
1935        let v11: f32 = Self::sky_hash_2d(iu + 1, iv + 1);
1936        let top: f32 = v00 + (v10 - v00) * su;
1937        let bot: f32 = v01 + (v11 - v01) * su;
1938        top + (bot - top) * sv
1939    }
1940
1941    /// Multi-octave domain-rotated fractional Brownian motion for layered cirrus and backlit cumulus clouds.
1942    ///
1943    /// # Arguments
1944    ///
1945    /// - `f32` - Cloud dome X coordinate.
1946    /// - `f32` - Cloud dome Z coordinate.
1947    ///
1948    /// # Returns
1949    ///
1950    /// - `f32` - Normalized cloud density in `[0.0, 1.0]`.
1951    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1952    #[must_use]
1953    fn sky_cloud_fbm(coord_x: f32, coord_z: f32) -> f32 {
1954        let mut sum: f32 = 0.0;
1955        let mut amp: f32 = 0.54;
1956        let mut norm: f32 = 0.0;
1957        let mut px: f32 = coord_x;
1958        let mut pz: f32 = coord_z;
1959        for _ in 0..4usize {
1960            sum += Self::sky_value_noise(px, pz) * amp;
1961            norm += amp;
1962            let nx: f32 = px * 1.72 - pz * 0.58 + 11.4;
1963            let nz: f32 = px * 0.58 + pz * 1.72 + 6.7;
1964            px = nx;
1965            pz = nz;
1966            amp *= 0.50;
1967        }
1968        if norm > 0.0 { sum / norm } else { 0.0 }
1969    }
1970
1971    /// Computes a deterministic 64-bit key fingerprinting `sun` lighting and atmosphere colors.
1972    ///
1973    /// # Arguments
1974    ///
1975    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
1976    ///
1977    /// # Returns
1978    ///
1979    /// - `u64` - Non-zero fingerprint invalidating the sky LUT on atmosphere changes.
1980    #[must_use]
1981    fn sky_sun_fingerprint(sun: &DirectionalLight3D) -> u64 {
1982        let dir: Vec3 = sun.get_direction();
1983        let hor: Vec3 = sun.get_sky_horizon();
1984        let zen: Vec3 = sun.get_sky_zenith();
1985        let col: Vec3 = sun.get_color();
1986        let words: [u32; 13] = [
1987            dir.get_x().to_bits(),
1988            dir.get_y().to_bits(),
1989            dir.get_z().to_bits(),
1990            hor.get_x().to_bits(),
1991            hor.get_y().to_bits(),
1992            hor.get_z().to_bits(),
1993            zen.get_x().to_bits(),
1994            zen.get_y().to_bits(),
1995            zen.get_z().to_bits(),
1996            col.get_x().to_bits(),
1997            col.get_y().to_bits(),
1998            col.get_z().to_bits(),
1999            sun.get_time_of_day().to_bits(),
2000        ];
2001        let mut hash: u64 = 0xCBF2_9CE4_8422_2325;
2002        for word in words.into_iter() {
2003            hash ^= word as u64;
2004            hash = hash.wrapping_mul(0x0100_0000_01B3);
2005        }
2006        hash.max(1)
2007    }
2008
2009    /// Evaluates physically inspired Rayleigh + Mie sky radiance with layered backlit clouds and night starfield along `dir` (excluding the sharp solar core added at full pixel resolution).
2010    ///
2011    /// # Arguments
2012    ///
2013    /// - `Vec3` - Unit view or reflection direction.
2014    /// - `&DirectionalLight3D` - Active sky & sun lighting parameters.
2015    ///
2016    /// # Returns
2017    ///
2018    /// - `Vec3` - Linear HDR atmospheric dome radiance.
2019    #[must_use]
2020    fn eval_atmospheric_dome(dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2021        let up: f32 = dir.get_y().clamp(0.0, 1.0);
2022        let elev_mix: f32 = up.powf(0.58);
2023        let horizon_band: f32 = (1.0 - up) * (1.0 - up) * (1.0 - up);
2024        let sun_dir: Vec3 = sun.get_direction();
2025        let sun_col: Vec3 = sun.get_color();
2026        let sun_dot: f32 = dir.dot(sun_dir).max(0.0);
2027        let sd2: f32 = sun_dot * sun_dot;
2028        let sd4: f32 = sd2 * sd2;
2029        let sd8: f32 = sd4 * sd4;
2030        let hour: f32 = sun.get_time_of_day().rem_euclid(24.0);
2031        let is_night: bool = !(5.8..=19.2).contains(&hour);
2032        let is_sunset: bool = (5.5..7.5).contains(&hour) || (16.5..19.5).contains(&hour);
2033        let mut col: Vec3 = sun
2034            .get_sky_horizon()
2035            .lerp(sun.get_sky_zenith(), elev_mix)
2036            .add(sun.get_sky_horizon().scale(horizon_band * 0.22));
2037        let mie_strength: f32 = if is_sunset {
2038            0.55
2039        } else if is_night {
2040            0.18
2041        } else {
2042            0.34
2043        };
2044        col = col.add(
2045            sun_col.scale((sd4 * 0.24 + sd8 * 0.42 + horizon_band * sd2 * 0.38) * mie_strength),
2046        );
2047        if is_night && up > 0.08 {
2048            let star_u: f32 = (dir.get_x() / (up + 0.35)) * 42.0;
2049            let star_v: f32 = (dir.get_z() / (up + 0.35)) * 42.0;
2050            let star_h: f32 = Self::sky_hash_2d(star_u.floor() as i32, star_v.floor() as i32);
2051            if star_h > 0.992 {
2052                let star_bright: f32 = ((star_h - 0.992) * 125.0) * (up * 1.4).clamp(0.0, 1.0);
2053                col = col.add(Vec3::new(0.85, 0.92, 1.15).scale(star_bright * 1.45));
2054            }
2055        }
2056        if up > 0.015 {
2057            let proj_inv: f32 = 1.0 / (up + 0.14);
2058            let cloud_u: f32 = dir.get_x() * proj_inv * 0.95;
2059            let cloud_v: f32 = dir.get_z() * proj_inv * 0.95;
2060            let warp: f32 = Self::sky_value_noise(cloud_u * 0.7 + 2.3, cloud_v * 0.7 - 1.9);
2061            let raw_c: f32 =
2062                Self::sky_cloud_fbm(cloud_u + (warp - 0.5) * 0.85, cloud_v + (warp - 0.5) * 0.65);
2063            let rim_c: f32 = Self::sky_cloud_fbm(
2064                cloud_u + sun_dir.get_x() * 0.22,
2065                cloud_v + sun_dir.get_z() * 0.22,
2066            );
2067            let horizon_fade: f32 = ((up - 0.015) * 9.0).clamp(0.0, 1.0);
2068            let density_thresh: f32 = if is_night { 0.38 } else { 0.44 };
2069            let cov: f32 = ((raw_c - density_thresh) * 3.1).clamp(0.0, 1.0);
2070            let cloud_alpha: f32 = cov * cov * (3.0 - 2.0 * cov) * horizon_fade * 0.84;
2071            if cloud_alpha > 0.005 {
2072                let silver_rim: f32 =
2073                    ((raw_c - rim_c) * 3.2 + 0.25).clamp(0.0, 1.0) * (0.28 + 0.72 * sd4);
2074                let cloud_col: Vec3 = if is_sunset {
2075                    let base_shadow: Vec3 = Vec3::new(0.11, 0.07, 0.18);
2076                    let warm_belly: Vec3 = Vec3::new(1.18, 0.42, 0.34);
2077                    let gold_rim: Vec3 = Vec3::new(2.25, 1.28, 0.56);
2078                    base_shadow
2079                        .lerp(
2080                            warm_belly,
2081                            (0.25 + 0.75 * horizon_band + sd2 * 0.45).clamp(0.0, 1.0),
2082                        )
2083                        .add(gold_rim.scale(silver_rim * 0.88))
2084                } else if is_night {
2085                    let storm_core: Vec3 = Vec3::new(0.024, 0.036, 0.082);
2086                    let neon_glow: Vec3 = Vec3::new(0.24, 0.12, 0.36).lerp(
2087                        Vec3::new(0.08, 0.28, 0.42),
2088                        (dir.get_x() * 0.5 + 0.5).clamp(0.0, 1.0),
2089                    );
2090                    storm_core
2091                        .lerp(neon_glow, (horizon_band * 0.85 + 0.18).clamp(0.0, 1.0))
2092                        .add(sun_col.scale(silver_rim * 0.35))
2093                } else {
2094                    let cool_base: Vec3 = Vec3::new(0.46, 0.56, 0.72);
2095                    let bright_top: Vec3 = Vec3::new(1.38, 1.36, 1.32);
2096                    cool_base.lerp(bright_top, (0.45 + 0.55 * silver_rim).clamp(0.0, 1.0))
2097                };
2098                col = col.lerp(cloud_col, cloud_alpha);
2099            }
2100        }
2101        col
2102    }
2103
2104    /// Rebuilds the pre-baked hemi-octahedral `sky_lut` only when `sun` changes (`0.00 ms` steady state).
2105    ///
2106    /// # Arguments
2107    ///
2108    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
2109    fn ensure_sky_lut(&mut self, sun: &DirectionalLight3D) {
2110        let key: u64 = Self::sky_sun_fingerprint(sun);
2111        let needed: usize = SKY3D_LUT_W * SKY3D_LUT_H;
2112        let Self {
2113            sky_lut,
2114            sky_lut_key,
2115            ..
2116        } = self;
2117        if *sky_lut_key == key && sky_lut.len() == needed {
2118            return;
2119        }
2120        if sky_lut.len() != needed {
2121            sky_lut.resize(needed, [0.0; 3]);
2122        }
2123        let inv_w: f32 = 1.0 / ((SKY3D_LUT_W - 1) as f32);
2124        let inv_h: f32 = 1.0 / ((SKY3D_LUT_H - 1) as f32);
2125        let lut_ptr: usize = sky_lut.as_mut_ptr() as usize;
2126        let sun_copy: DirectionalLight3D = *sun;
2127        parallel_for_ranges(SKY3D_LUT_H, 16, |y0: usize, y1: usize| {
2128            let base: *mut [f32; 3] = lut_ptr as *mut [f32; 3];
2129            for row_idx in y0..y1 {
2130                let sv: f32 = (row_idx as f32) * inv_h * 2.0 - 1.0;
2131                // SAFETY: `parallel_for_ranges` partitions `[0, SKY3D_LUT_H)` into disjoint rows of `sky_lut`.
2132                let row: &mut [[f32; 3]] =
2133                    unsafe { from_raw_parts_mut(base.add(row_idx * SKY3D_LUT_W), SKY3D_LUT_W) };
2134                for (col_idx, dst) in row.iter_mut().enumerate() {
2135                    let su: f32 = (col_idx as f32) * inv_w * 2.0 - 1.0;
2136                    let oct_px: f32 = 0.5 * (su + sv);
2137                    let oct_pz: f32 = 0.5 * (su - sv);
2138                    let oct_py: f32 = (1.0 - oct_px.abs() - oct_pz.abs()).max(0.0);
2139                    let dir: Vec3 = Vec3::new(oct_px, oct_py, oct_pz).normalize();
2140                    let col: Vec3 = Self::eval_atmospheric_dome(dir, &sun_copy);
2141                    *dst = [col.get_x(), col.get_y(), col.get_z()];
2142                }
2143            }
2144        });
2145        *sky_lut_key = key;
2146    }
2147
2148    /// Bilinearly samples the pre-baked hemi-octahedral `sky_lut` along unnormalized or unit ray `dir` and adds full-resolution solar/lunar disk radiance.
2149    ///
2150    /// # Arguments
2151    ///
2152    /// - `&[[f32; 3]]` - Pre-baked hemi-octahedral sky dome LUT (`SKY3D_LUT_W * SKY3D_LUT_H`).
2153    /// - `Vec3` - View or reflection ray direction.
2154    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
2155    ///
2156    /// # Returns
2157    ///
2158    /// - `Vec3` - Linear HDR sky radiance including clouds, stars, and crisp sun/moon disk.
2159    #[inline(always)]
2160    #[must_use]
2161    fn sample_sky_lut(sky_lut: &[[f32; 3]], dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2162        if sky_lut.len() < SKY3D_LUT_W * SKY3D_LUT_H {
2163            return Self::sample_sky(dir, sun);
2164        }
2165        let rx: f32 = dir.get_x();
2166        let ry: f32 = dir.get_y().max(0.0);
2167        let rz: f32 = dir.get_z();
2168        let inv_l1: f32 = 1.0 / (rx.abs() + ry + rz.abs()).max(1.0e-5);
2169        let oct_px: f32 = rx * inv_l1;
2170        let oct_pz: f32 = rz * inv_l1;
2171        let max_x: usize = SKY3D_LUT_W - 1;
2172        let max_y: usize = SKY3D_LUT_H - 1;
2173        let lut_u: f32 =
2174            ((0.5 * (oct_px + oct_pz) + 0.5) * (max_x as f32)).clamp(0.0, max_x as f32);
2175        let lut_v: f32 =
2176            ((0.5 * (oct_px - oct_pz) + 0.5) * (max_y as f32)).clamp(0.0, max_y as f32);
2177        let x0: usize = (lut_u as usize).min(max_x);
2178        let y0: usize = (lut_v as usize).min(max_y);
2179        let x1: usize = (x0 + 1).min(max_x);
2180        let y1: usize = (y0 + 1).min(max_y);
2181        let tx: f32 = lut_u - (x0 as f32);
2182        let ty: f32 = lut_v - (y0 as f32);
2183        let om_tx: f32 = 1.0 - tx;
2184        let om_ty: f32 = 1.0 - ty;
2185        let w00: f32 = om_tx * om_ty;
2186        let w10: f32 = tx * om_ty;
2187        let w01: f32 = om_tx * ty;
2188        let w11: f32 = tx * ty;
2189        let r0: usize = y0 * SKY3D_LUT_W;
2190        let r1: usize = y1 * SKY3D_LUT_W;
2191        let c00: [f32; 3] = sky_lut[r0 + x0];
2192        let c10: [f32; 3] = sky_lut[r0 + x1];
2193        let c01: [f32; 3] = sky_lut[r1 + x0];
2194        let c11: [f32; 3] = sky_lut[r1 + x1];
2195        let mut col: Vec3 = Vec3::new(
2196            c00[0] * w00 + c10[0] * w10 + c01[0] * w01 + c11[0] * w11,
2197            c00[1] * w00 + c10[1] * w10 + c01[1] * w01 + c11[1] * w11,
2198            c00[2] * w00 + c10[2] * w10 + c01[2] * w01 + c11[2] * w11,
2199        );
2200        let sun_dir: Vec3 = sun.get_direction();
2201        let raw_dot: f32 = dir.dot(sun_dir);
2202        if raw_dot > 0.0 {
2203            let sun_dot: f32 = raw_dot / dir.length().max(1.0e-5);
2204            if sun_dot > 0.9945 {
2205                let disk: f32 = ((sun_dot - 0.9945) * (1.0 / 0.0055)).clamp(0.0, 1.0);
2206                let disk_s: f32 = disk * disk * (3.0 - 2.0 * disk);
2207                col = col.add(sun.get_color().scale(disk_s * 4.2 + 0.55));
2208            } else if sun_dot > 0.94 {
2209                let halo: f32 = ((sun_dot - 0.94) * (1.0 / 0.06)).clamp(0.0, 1.0);
2210                let h2: f32 = halo * halo;
2211                col = col.add(sun.get_color().scale(h2 * h2 * 0.65));
2212            }
2213        }
2214        col
2215    }
2216
2217    /// Evaluates physically inspired Rayleigh + Mie atmospheric sky, clouds, and HDR solar disk radiance along `dir`.
2218    ///
2219    /// # Arguments
2220    ///
2221    /// - `Vec3` - Unit view or reflection direction.
2222    /// - `&DirectionalLight3D` - Active sky & sun lighting parameters.
2223    ///
2224    /// # Returns
2225    ///
2226    /// - `Vec3` - Linear HDR sky radiance.
2227    #[must_use]
2228    pub fn sample_sky(dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2229        let mut col: Vec3 = Self::eval_atmospheric_dome(dir, sun);
2230        let sun_dot: f32 = dir.dot(sun.get_direction()).max(0.0);
2231        if sun_dot > 0.9945 {
2232            let disk: f32 = ((sun_dot - 0.9945) * (1.0 / 0.0055)).clamp(0.0, 1.0);
2233            let disk_s: f32 = disk * disk * (3.0 - 2.0 * disk);
2234            col = col.add(sun.get_color().scale(disk_s * 4.2 + 0.55));
2235        } else if sun_dot > 0.94 {
2236            let halo: f32 = ((sun_dot - 0.94) * (1.0 / 0.06)).clamp(0.0, 1.0);
2237            let h2: f32 = halo * halo;
2238            col = col.add(sun.get_color().scale(h2 * h2 * 0.65));
2239        }
2240        col
2241    }
2242
2243    /// Reconstructs exact world-space position for pixel `(px, py)` at camera depth `depth`.
2244    ///
2245    /// # Arguments
2246    ///
2247    /// - `&DeferredFrameContext` - Shared per-frame camera basis.
2248    /// - `usize` - Pixel X coordinate.
2249    /// - `usize` - Pixel Y coordinate.
2250    /// - `f32` - Linear camera-space depth (`1 / inv_w`).
2251    ///
2252    /// # Returns
2253    ///
2254    /// - `(Vec3, Vec3)` - `(world_pos, unnormalized_view_ray_dir)`.
2255    #[inline(always)]
2256    #[must_use]
2257    fn pixel_world_pos(
2258        frame_context: &DeferredFrameContext,
2259        px: usize,
2260        py: usize,
2261        depth: f32,
2262    ) -> (Vec3, Vec3) {
2263        let ndc_x: f32 = 2.0 * (((px as f32) + 0.5) * frame_context.inv_width) - 1.0;
2264        let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * frame_context.inv_height);
2265        let ray_vec: Vec3 = frame_context
2266            .camera_forward
2267            .add(frame_context.camera_right_scaled.scale(ndc_x))
2268            .add(frame_context.camera_up_scaled.scale(ndc_y));
2269        (
2270            frame_context.camera_position.add(ray_vec.scale(depth)),
2271            ray_vec,
2272        )
2273    }
2274
2275    /// Shades a single BVH closest-hit surface given its world-space normal and PBR material.
2276    ///
2277    /// # Arguments
2278    ///
2279    /// - `Vec3` - Hit world-space unit surface normal.
2280    /// - `PbrMaterial` - Hit surface PBR material.
2281    /// - `&DirectionalLight3D` - Active directional sun light.
2282    /// - `bool` - Enables secondary hemisphere sky energy conservation for multi-bounce Lumen GI.
2283    ///
2284    /// # Returns
2285    ///
2286    /// - `Vec3` - Linear HDR hit radiance.
2287    #[inline(always)]
2288    #[must_use]
2289    fn shade_surface_hit(
2290        hit_n: Vec3,
2291        mat: PbrMaterial,
2292        sun: &DirectionalLight3D,
2293        multi_bounce: bool,
2294    ) -> Vec3 {
2295        let h_nl: f32 = hit_n.dot(sun.get_direction()).abs().max(0.18);
2296        let mut col: Vec3 = mat
2297            .get_base_color()
2298            .mul(sun.get_color().scale(h_nl))
2299            .add(mat.get_emissive());
2300        if multi_bounce {
2301            let sky_hemi: Vec3 = sun.get_sky_horizon().lerp(
2302                sun.get_sky_zenith(),
2303                (hit_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
2304            );
2305            col = col.add(mat.get_base_color().mul(sky_hemi.scale(0.32)));
2306        }
2307        col
2308    }
2309
2310    /// Computes four blue-noise-rotated hemisphere Lumen GI/AO `(dir, inv_dir)` rays for a triangle normal.
2311    ///
2312    /// # Arguments
2313    ///
2314    /// - `Vec3` - Camera-facing unit surface normal.
2315    /// - `usize` - Starting slot offset inside `GI_HEMI_RING_16` rotated per frame.
2316    ///
2317    /// # Returns
2318    ///
2319    /// - `[(Vec3, Vec3); 4]` - Four `(gi_dir, inv_gi_dir)` ray tuples.
2320    #[cfg_attr(not(target_arch = "wasm32"), inline)]
2321    #[must_use]
2322    fn compute_gi_ray_quad(vec_value: Vec3, ring_offset: usize) -> [(Vec3, Vec3); 4] {
2323        let mut dirs: [(Vec3, Vec3); 4] = [(vec_value, vec_value); 4];
2324        for (idx, slot) in dirs.iter_mut().enumerate() {
2325            let jit_arr: [f32; 3] = GI_HEMI_RING_16[(ring_offset + idx) & 15];
2326            let base_jit: Vec3 = Vec3::new(jit_arr[0], jit_arr[1], jit_arr[2]);
2327            let jit: Vec3 = if vec_value.dot(base_jit) < -0.15 {
2328                base_jit.scale(-1.0)
2329            } else {
2330                base_jit
2331            };
2332            let gi_dir: Vec3 = vec_value.add(jit).normalize();
2333            *slot = (gi_dir, Ray3D::safe_inv_vec(gi_dir));
2334        }
2335        dirs
2336    }
2337
2338    /// Performs branchless 4-wide SIMD reverse-Z depth testing and G-Buffer triangle ID updates across a contiguous horizontal span inside a tile-local L1 buffer.
2339    ///
2340    /// # Arguments
2341    ///
2342    /// - `&mut [f32]` - Contiguous tile-local reverse-Z depth span.
2343    /// - `&mut [u32]` - Contiguous tile-local G-Buffer triangle ID span.
2344    /// - `f32` - Starting `1/w` depth at the left edge of the span.
2345    /// - `f32` - Per-pixel `1/w` derivative `d_inv_w_dx`.
2346    /// - `u32` - Triangle ID to write on depth pass.
2347    ///
2348    /// # Returns
2349    ///
2350    /// - `bool` - `true` when at least one pixel in this span passed the depth test.
2351    #[inline(always)]
2352    fn raster_span_simd(
2353        d_span: &mut [f32],
2354        g_span: &mut [u32],
2355        mut inv_w: f32,
2356        d_inv_w_dx: f32,
2357        tri_id: u32,
2358    ) -> bool {
2359        let len: usize = d_span.len();
2360        let mut wrote: bool = false;
2361        let mut idx: usize = 0;
2362        #[cfg(target_arch = "aarch64")]
2363        if len >= 4 {
2364            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; NEON is mandatory on `aarch64`.
2365            unsafe {
2366                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2367                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2368                let init: [f32; 4] = [
2369                    inv_w,
2370                    inv_w + d_inv_w_dx,
2371                    inv_w + d_inv_w_dx * 2.0,
2372                    inv_w + d_inv_w_dx * 3.0,
2373                ];
2374                let mut v_w: core::arch::aarch64::float32x4_t =
2375                    core::arch::aarch64::vld1q_f32(init.as_ptr());
2376                let v_step: core::arch::aarch64::float32x4_t =
2377                    core::arch::aarch64::vdupq_n_f32(d_inv_w_dx * 4.0);
2378                let v_tid: core::arch::aarch64::uint32x4_t =
2379                    core::arch::aarch64::vdupq_n_u32(tri_id);
2380                let mut any_hit: core::arch::aarch64::uint32x4_t =
2381                    core::arch::aarch64::vdupq_n_u32(0);
2382                while idx + 4 <= len {
2383                    let cur_d: core::arch::aarch64::float32x4_t =
2384                        core::arch::aarch64::vld1q_f32(d_ptr.add(idx));
2385                    let cmp: core::arch::aarch64::uint32x4_t =
2386                        core::arch::aarch64::vcgtq_f32(v_w, cur_d);
2387                    let cur_g: core::arch::aarch64::uint32x4_t =
2388                        core::arch::aarch64::vld1q_u32(g_ptr.add(idx));
2389                    let next_d: core::arch::aarch64::float32x4_t =
2390                        core::arch::aarch64::vbslq_f32(cmp, v_w, cur_d);
2391                    let next_g: core::arch::aarch64::uint32x4_t =
2392                        core::arch::aarch64::vbslq_u32(cmp, v_tid, cur_g);
2393                    core::arch::aarch64::vst1q_f32(d_ptr.add(idx), next_d);
2394                    core::arch::aarch64::vst1q_u32(g_ptr.add(idx), next_g);
2395                    any_hit = core::arch::aarch64::vorrq_u32(any_hit, cmp);
2396                    v_w = core::arch::aarch64::vaddq_f32(v_w, v_step);
2397                    idx += 4;
2398                }
2399                if core::arch::aarch64::vmaxvq_u32(any_hit) != 0 {
2400                    wrote = true;
2401                }
2402                inv_w += d_inv_w_dx * (idx as f32);
2403            }
2404        }
2405        #[cfg(target_arch = "x86_64")]
2406        if len >= 4 {
2407            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; SSE2 is mandatory on `x86_64`.
2408            unsafe {
2409                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2410                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2411                let init: [f32; 4] = [
2412                    inv_w,
2413                    inv_w + d_inv_w_dx,
2414                    inv_w + d_inv_w_dx * 2.0,
2415                    inv_w + d_inv_w_dx * 3.0,
2416                ];
2417                let mut v_w: core::arch::x86_64::__m128 =
2418                    core::arch::x86_64::_mm_loadu_ps(init.as_ptr());
2419                let v_step: core::arch::x86_64::__m128 =
2420                    core::arch::x86_64::_mm_set1_ps(d_inv_w_dx * 4.0);
2421                let v_tid: core::arch::x86_64::__m128i =
2422                    core::arch::x86_64::_mm_set1_epi32(tri_id as i32);
2423                let mut any_mask: i32 = 0;
2424                while idx + 4 <= len {
2425                    let cur_d: core::arch::x86_64::__m128 =
2426                        core::arch::x86_64::_mm_loadu_ps(d_ptr.add(idx));
2427                    let cmp: core::arch::x86_64::__m128 =
2428                        core::arch::x86_64::_mm_cmpgt_ps(v_w, cur_d);
2429                    let matrix_elems: i32 = core::arch::x86_64::_mm_movemask_ps(cmp);
2430                    if matrix_elems != 0 {
2431                        any_mask |= matrix_elems;
2432                        let next_d: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
2433                            core::arch::x86_64::_mm_and_ps(cmp, v_w),
2434                            core::arch::x86_64::_mm_andnot_ps(cmp, cur_d),
2435                        );
2436                        core::arch::x86_64::_mm_storeu_ps(d_ptr.add(idx), next_d);
2437                        let cmp_i: core::arch::x86_64::__m128i =
2438                            core::arch::x86_64::_mm_castps_si128(cmp);
2439                        let cur_g: core::arch::x86_64::__m128i =
2440                            core::arch::x86_64::_mm_loadu_si128(
2441                                g_ptr.add(idx).cast::<core::arch::x86_64::__m128i>(),
2442                            );
2443                        let next_g: core::arch::x86_64::__m128i = core::arch::x86_64::_mm_or_si128(
2444                            core::arch::x86_64::_mm_and_si128(cmp_i, v_tid),
2445                            core::arch::x86_64::_mm_andnot_si128(cmp_i, cur_g),
2446                        );
2447                        core::arch::x86_64::_mm_storeu_si128(
2448                            g_ptr.add(idx).cast::<core::arch::x86_64::__m128i>(),
2449                            next_g,
2450                        );
2451                    }
2452                    v_w = core::arch::x86_64::_mm_add_ps(v_w, v_step);
2453                    idx += 4;
2454                }
2455                if any_mask != 0 {
2456                    wrote = true;
2457                }
2458                inv_w += d_inv_w_dx * (idx as f32);
2459            }
2460        }
2461        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
2462        if len >= 4 {
2463            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; `simd128` is enabled on `wasm32`.
2464            unsafe {
2465                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2466                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2467                let init: [f32; 4] = [
2468                    inv_w,
2469                    inv_w + d_inv_w_dx,
2470                    inv_w + d_inv_w_dx * 2.0,
2471                    inv_w + d_inv_w_dx * 3.0,
2472                ];
2473                let mut v_w: core::arch::wasm32::v128 =
2474                    core::arch::wasm32::v128_load(init.as_ptr().cast());
2475                let v_step: core::arch::wasm32::v128 =
2476                    core::arch::wasm32::f32x4_splat(d_inv_w_dx * 4.0);
2477                let v_tid: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(tri_id);
2478                let mut any_hit: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0);
2479                while idx + 4 <= len {
2480                    let cur_d: core::arch::wasm32::v128 =
2481                        core::arch::wasm32::v128_load(d_ptr.add(idx).cast());
2482                    let cmp: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_gt(v_w, cur_d);
2483                    let cur_g: core::arch::wasm32::v128 =
2484                        core::arch::wasm32::v128_load(g_ptr.add(idx).cast());
2485                    let next_d: core::arch::wasm32::v128 =
2486                        core::arch::wasm32::v128_bitselect(v_w, cur_d, cmp);
2487                    let next_g: core::arch::wasm32::v128 =
2488                        core::arch::wasm32::v128_bitselect(v_tid, cur_g, cmp);
2489                    core::arch::wasm32::v128_store(d_ptr.add(idx).cast(), next_d);
2490                    core::arch::wasm32::v128_store(g_ptr.add(idx).cast(), next_g);
2491                    any_hit = core::arch::wasm32::v128_or(any_hit, cmp);
2492                    v_w = core::arch::wasm32::f32x4_add(v_w, v_step);
2493                    idx += 4;
2494                }
2495                if core::arch::wasm32::v128_any_true(any_hit) {
2496                    wrote = true;
2497                }
2498                inv_w += d_inv_w_dx * (idx as f32);
2499            }
2500        }
2501        while idx < len {
2502            if inv_w > d_span[idx] {
2503                d_span[idx] = inv_w;
2504                g_span[idx] = tri_id;
2505                wrote = true;
2506            }
2507            inv_w += d_inv_w_dx;
2508            idx += 1;
2509        }
2510        wrote
2511    }
2512
2513    /// Fused Barrier 1 worker executing L1-hot `64x64` tiled G-Buffer clear, binned SIMD triangle rasterization, visible-tri bitset marking, and coherent 2x2 probe packet raytracing.
2514    ///
2515    /// # Arguments
2516    ///
2517    /// - `&DeferredFrameContext` - Immutable per-frame camera, sun, and RT parameters.
2518    /// - `&TileRasterProbeInputs<'_>` - Read-only binned triangles, shading records, BVH4/BVH8, and object-space dynamic instances.
2519    /// - `usize` - Inclusive start tile index.
2520    /// - `usize` - Exclusive end tile index.
2521    /// - `(usize, usize, RtProbeGridMutPtrs)` - Writable base addresses `(depth_base, gtri_base, probe_ptrs)`.
2522    ///
2523    /// # Returns
2524    ///
2525    /// - `(usize, usize)` - `(total_rays, probe_reproj_hits)` traced and reused across `[tile_start..tile_end)`.
2526    unsafe fn raster_and_trace_tiles(
2527        frame_context: &DeferredFrameContext,
2528        inputs: &TileRasterProbeInputs<'_>,
2529        tile_start: usize,
2530        tile_end: usize,
2531        outputs: (usize, usize, RtProbeGridMutPtrs),
2532    ) -> (usize, usize) {
2533        let (depth_base, gtri_base, probe_ptrs): (usize, usize, RtProbeGridMutPtrs) = outputs;
2534        let width_val: usize = frame_context.width;
2535        let height_val: usize = frame_context.height;
2536        let gw: usize = frame_context.grid_width;
2537        let gh: usize = frame_context.grid_height;
2538        let step: usize = frame_context.raytrace_step;
2539        let half_step: usize = step / 2;
2540        let tile_px: usize = inputs.tile_px;
2541        let tiles_x: usize = inputs.tiles_x;
2542        let use_soft_shadows: bool =
2543            frame_context.raytrace_mode == RayTracingMode::FullPathTracedGi;
2544        let multi_bounce_refl: bool = frame_context.reflection_bounces >= 2;
2545        let sun_dir: Vec3 = frame_context.sun.get_direction();
2546        let inv_sun: Vec3 = frame_context.inv_sun_dir;
2547        let soft_rays: [(Vec3, Vec3); 16] = frame_context.soft_shadow_rays;
2548        let frame_idx_cur: usize = frame_context.frame_index;
2549        let _: usize = frame_idx_cur;
2550        let gi_ring_offset: usize = 0;
2551        let mut local_depth_uninit: [MaybeUninit<f32>;
2552            ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX] =
2553            [const { MaybeUninit::uninit() }; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX];
2554        let mut local_gtri_uninit: [MaybeUninit<u32>; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX] =
2555            [const { MaybeUninit::uninit() }; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX];
2556        let mut static_shadow_cache: u32 = u32::MAX;
2557        let mut dyn_shadow_cache: u32 = u32::MAX;
2558        let mut gi_cache: [(u32, [(Vec3, Vec3); 4]); 4] =
2559            [(u32::MAX, [(Vec3::zero(), Vec3::zero()); 4]); 4];
2560        let mut gi_cache_cursor: usize = 0;
2561        let mut total_rays: usize = 0;
2562        let mut reproj_hits: usize = 0;
2563        for tile_id in tile_start..tile_end {
2564            let tx: usize = tile_id % tiles_x;
2565            let ty: usize = tile_id / tiles_x;
2566            let px0: usize = tx * tile_px;
2567            let py0: usize = ty * tile_px;
2568            let px1: usize = (px0 + tile_px).min(width_val);
2569            let py1: usize = (py0 + tile_px).min(height_val);
2570            let tw: usize = px1 - px0;
2571            let th: usize = py1 - py0;
2572            let t_pixels: usize = tw * th;
2573            if t_pixels == 0 {
2574                continue;
2575            }
2576            // SAFETY: Immediately fills all `t_pixels` elements with `0.0` / `u32::MAX` before creating initialized slices.
2577            let (local_depth, local_gtri): (&mut [f32], &mut [u32]) = unsafe {
2578                let dp: *mut f32 = local_depth_uninit.as_mut_ptr().cast::<f32>();
2579                let gp: *mut u32 = local_gtri_uninit.as_mut_ptr().cast::<u32>();
2580                let ds: &mut [f32] = from_raw_parts_mut(dp, t_pixels);
2581                let gs: &mut [u32] = from_raw_parts_mut(gp, t_pixels);
2582                ds.fill(0.0);
2583                gs.fill(u32::MAX);
2584                (ds, gs)
2585            };
2586            let bin_start: usize = inputs.tile_offsets[tile_id] as usize;
2587            let bin_end: usize = inputs.tile_offsets[tile_id + 1] as usize;
2588            let px0_i: i32 = px0 as i32;
2589            let px1_last_i: i32 = (px1 - 1) as i32;
2590            let py0_i: i32 = py0 as i32;
2591            let py1_last_i: i32 = (py1 - 1) as i32;
2592            for &tri_slot in inputs.tile_tri_indices[bin_start..bin_end].iter() {
2593                let tri: &RasterTri2D = &inputs.raster_tris[tri_slot as usize];
2594                let py_start: i32 = tri.min_y.max(py0_i);
2595                let py_end: i32 = tri.max_y.min(py1_last_i);
2596                if py_start > py_end {
2597                    continue;
2598                }
2599                let dy: f32 = (py_start - tri.min_y) as f32;
2600                let mut w0_row: f32 = tri.dw_dy[0].mul_add(dy, tri.w_start[0]);
2601                let mut w1_row: f32 = tri.dw_dy[1].mul_add(dy, tri.w_start[1]);
2602                let mut w2_row: f32 = tri.dw_dy[2].mul_add(dy, tri.w_start[2]);
2603                let mut inv_w_row: f32 = tri.d_inv_w_dy.mul_add(dy, tri.inv_w_start);
2604                let mut row_off: usize = ((py_start - py0_i) as usize) * tw;
2605                let min_x: i32 = tri.min_x;
2606                let k_tile_min: i32 = (px0_i - min_x).max(0);
2607                let k_tile_max: i32 = (px1_last_i - min_x).min(tri.span_max);
2608                if k_tile_min > k_tile_max {
2609                    continue;
2610                }
2611                let k_tile_min_f: f32 = k_tile_min as f32;
2612                let k_tile_max_f: f32 = k_tile_max as f32;
2613                let tri_id: u32 = tri.tri_id;
2614                let slopes: [f32; 3] = tri.slopes;
2615                let neg_inv_slopes: [f32; 3] = tri.neg_inv_slopes;
2616                let d_inv_w_dx: f32 = tri.d_inv_w_dx;
2617                for _py in py_start..=py_end {
2618                    let vals: [f32; 3] = [w0_row + 1e-5, w1_row + 1e-5, w2_row + 1e-5];
2619                    let mut k_lo: f32 = k_tile_min_f;
2620                    let mut k_hi: f32 = k_tile_max_f;
2621                    let mut valid_span: bool = true;
2622                    for event_ref in 0..3 {
2623                        let slope: f32 = slopes[event_ref];
2624                        let val: f32 = vals[event_ref];
2625                        if slope > 1e-9 {
2626                            k_lo = k_lo.max((val * neg_inv_slopes[event_ref]).ceil());
2627                        } else if slope < -1e-9 {
2628                            k_hi = k_hi.min((val * neg_inv_slopes[event_ref]).floor());
2629                        } else if val < 0.0 {
2630                            valid_span = false;
2631                            break;
2632                        }
2633                    }
2634                    if valid_span && k_lo <= k_hi {
2635                        let start_k: i32 = (k_lo as i32).max(k_tile_min);
2636                        let end_k: i32 = (k_hi as i32).min(k_tile_max);
2637                        if start_k <= end_k {
2638                            let inv_w_start_k: f32 = d_inv_w_dx.mul_add(start_k as f32, inv_w_row);
2639                            let lx0: usize = (min_x + start_k - px0_i) as usize;
2640                            let lx1: usize = (min_x + end_k - px0_i) as usize;
2641                            let _: bool = Self::raster_span_simd(
2642                                &mut local_depth[(row_off + lx0)..=(row_off + lx1)],
2643                                &mut local_gtri[(row_off + lx0)..=(row_off + lx1)],
2644                                inv_w_start_k,
2645                                d_inv_w_dx,
2646                                tri_id,
2647                            );
2648                        }
2649                    }
2650                    w0_row += tri.dw_dy[0];
2651                    w1_row += tri.dw_dy[1];
2652                    w2_row += tri.dw_dy[2];
2653                    inv_w_row += tri.d_inv_w_dy;
2654                    row_off += tw;
2655                }
2656            }
2657            for ly in 0..th {
2658                let dst_off: usize = (py0 + ly) * width_val + px0;
2659                let src_off: usize = ly * tw;
2660                // SAFETY: Tiles cover strictly disjoint `(px0..px1) x (py0..py1)` rectangles inside the global G-Buffer.
2661                unsafe {
2662                    (depth_base as *mut f32)
2663                        .add(dst_off)
2664                        .copy_from_nonoverlapping(local_depth.as_ptr().add(src_off), tw);
2665                    (gtri_base as *mut u32)
2666                        .add(dst_off)
2667                        .copy_from_nonoverlapping(local_gtri.as_ptr().add(src_off), tw);
2668                }
2669            }
2670            if step == 0 {
2671                continue;
2672            }
2673            let gx0: usize = px0 / step;
2674            let gx1: usize = px1.div_ceil(step).min(gw);
2675            let gy0: usize = py0 / step;
2676            let gy1: usize = py1.div_ceil(step).min(gh);
2677            let mut gy_base: usize = gy0;
2678            while gy_base < gy1 {
2679                let mut gx_base: usize = gx0;
2680                while gx_base < gx1 {
2681                    let coords: [(usize, usize); 4] = [
2682                        (gx_base, gy_base),
2683                        (gx_base + 1, gy_base),
2684                        (gx_base, gy_base + 1),
2685                        (gx_base + 1, gy_base + 1),
2686                    ];
2687                    let mut valid_mask: u8 = 0;
2688                    let mut shadow_mask: u8 = 0;
2689                    let mut refl_mask: u8 = 0;
2690                    let mut gi_mask: u8 = 0;
2691                    let mut p_idx_4: [usize; 4] = [0; 4];
2692                    let mut tid_4: [usize; 4] = [0; 4];
2693                    let mut depth_4: [f32; 4] = [0.0; 4];
2694                    let mut world_p_4: [Vec3; 4] = [Vec3::zero(); 4];
2695                    let mut origin_4: [Vec3; 4] = [Vec3::zero(); 4];
2696                    let mut normal_4: [Vec3; 4] = [Vec3::zero(); 4];
2697                    let mut ray_vec_4: [Vec3; 4] = [Vec3::zero(); 4];
2698                    let reuse_block: bool = inputs.prev_probes.is_some()
2699                        && (((gx_base >> 1) + (gy_base >> 1) + inputs.probe_checker_parity) & 1)
2700                            != 0;
2701                    let mut sh_pkt: RayPacket4 = RayPacket4 {
2702                        ox: [0.0; 4],
2703                        oy: [0.0; 4],
2704                        oz: [0.0; 4],
2705                        dx: [sun_dir.get_x(); 4],
2706                        dy: [sun_dir.get_y(); 4],
2707                        dz: [sun_dir.get_z(); 4],
2708                        ix: [inv_sun.get_x(); 4],
2709                        iy: [inv_sun.get_y(); 4],
2710                        iz: [inv_sun.get_z(); 4],
2711                    };
2712                    let mut refl_dir_4: [Vec3; 4] = [Vec3::zero(); 4];
2713                    let mut refl_pkt: RayPacket4 = sh_pkt;
2714                    let mut gi_dir_4: [Vec3; 4] = [Vec3::zero(); 4];
2715                    let mut gi_pkt: RayPacket4 = sh_pkt;
2716                    let mut out_shadow: [f32; 4] = [1.0; 4];
2717                    let mut out_refl: [Vec3; 4] = [frame_context.sun.get_sky_horizon(); 4];
2718                    let mut out_gi: [Vec3; 4] = [Vec3::zero(); 4];
2719                    let mut out_ao: [f32; 4] = [1.0; 4];
2720                    let mut prev_valid_mask: u8 = 0;
2721                    let mut prev_shadow_4: [f32; 4] = [1.0; 4];
2722                    let mut prev_refl_4: [Vec3; 4] = [frame_context.sun.get_sky_horizon(); 4];
2723                    let mut prev_gi_4: [Vec3; 4] = [Vec3::zero(); 4];
2724                    let mut prev_ao_4: [f32; 4] = [1.0; 4];
2725                    for lane in 0..4 {
2726                        let (gx, gy): (usize, usize) = coords[lane];
2727                        if gx >= gx1 || gy >= gy1 {
2728                            continue;
2729                        }
2730                        let pidx: usize = gy * gw + gx;
2731                        p_idx_4[lane] = pidx;
2732                        let px: usize = (gx * step + half_step).min(width_val - 1);
2733                        let py: usize = (gy * step + half_step).min(height_val - 1);
2734                        let l_off: usize = (py - py0) * tw + (px - px0);
2735                        let tid: u32 = local_gtri[l_off];
2736                        if tid == u32::MAX {
2737                            // SAFETY: Probe index `(gx, gy)` belongs exclusively to this tile.
2738                            unsafe {
2739                                probe_ptrs.write_invalid(pidx);
2740                            }
2741                            continue;
2742                        }
2743                        let inv_w: f32 = local_depth[l_off];
2744                        let depth: f32 = 1.0 / inv_w.max(1e-6);
2745                        let tri_idx: usize = tid as usize;
2746                        let tri: &GShadeTri = &inputs.shaded_tris[tri_idx];
2747                        let (world_p, ray_vec): (Vec3, Vec3) =
2748                            Self::pixel_world_pos(frame_context, px, py, depth);
2749                        let origin: Vec3 = world_p.add(tri.shade_n.scale(0.08));
2750                        let bit: u8 = 1_u8 << lane;
2751                        valid_mask |= bit;
2752                        tid_4[lane] = tri_idx;
2753                        depth_4[lane] = depth;
2754                        world_p_4[lane] = world_p;
2755                        origin_4[lane] = origin;
2756                        normal_4[lane] = tri.shade_n;
2757                        ray_vec_4[lane] = ray_vec;
2758                        if (reuse_block || inputs.same_camera_pose)
2759                            && let Some(prev) = inputs.prev_probes
2760                        {
2761                            let reproj_cand: Option<(usize, f32)> = if inputs.same_camera_pose {
2762                                Some((pidx, depth))
2763                            } else {
2764                                LumenRadianceCache::reproject_world_to_prev_probe(
2765                                    world_p,
2766                                    &inputs.prev_view_proj,
2767                                    inputs.prev_render_dims,
2768                                    (inputs.prev_rt_step, inputs.prev_gw, inputs.prev_gh),
2769                                )
2770                                .map(
2771                                    |reproj: LumenReprojectedProbe| {
2772                                        (reproj.get_prev_index(), reproj.get_prev_depth())
2773                                    },
2774                                )
2775                            };
2776                            if let Some((prev_idx, reproj_depth)) = reproj_cand
2777                                && prev_idx < prev.valid.len()
2778                                && prev.valid[prev_idx] != 0
2779                            {
2780                                let wdx: f32 = world_p.get_x() - prev.world_x[prev_idx];
2781                                let wdy: f32 = world_p.get_y() - prev.world_y[prev_idx];
2782                                let wdz: f32 = world_p.get_z() - prev.world_z[prev_idx];
2783                                let wdist_sq: f32 = wdx.mul_add(wdx, wdy.mul_add(wdy, wdz * wdz));
2784                                let ndot: f32 = tri.shade_n.get_x().mul_add(
2785                                    prev.nx[prev_idx],
2786                                    tri.shade_n.get_y().mul_add(
2787                                        prev.ny[prev_idx],
2788                                        tri.shade_n.get_z() * prev.nz[prev_idx],
2789                                    ),
2790                                );
2791                                let max_wdist: f32 = depth.mul_add(0.018, 0.30);
2792                                let d_tol: f32 = reproj_depth.mul_add(0.08, 0.25);
2793                                if wdist_sq <= max_wdist * max_wdist
2794                                    && ndot >= 0.94
2795                                    && (reproj_depth - prev.depth[prev_idx]).abs() <= d_tol
2796                                {
2797                                    let p_sh: f32 = prev.shadow[prev_idx];
2798                                    let p_rf: Vec3 = Vec3::new(
2799                                        prev.refl_r[prev_idx],
2800                                        prev.refl_g[prev_idx],
2801                                        prev.refl_b[prev_idx],
2802                                    );
2803                                    let p_gi: Vec3 = Vec3::new(
2804                                        prev.gi_r[prev_idx],
2805                                        prev.gi_g[prev_idx],
2806                                        prev.gi_b[prev_idx],
2807                                    );
2808                                    let p_ao: f32 = prev.ao[prev_idx];
2809                                    if reuse_block {
2810                                        out_shadow[lane] = p_sh;
2811                                        out_refl[lane] = p_rf;
2812                                        out_gi[lane] = p_gi;
2813                                        out_ao[lane] = p_ao;
2814                                        reproj_hits += 1;
2815                                        continue;
2816                                    }
2817                                    prev_valid_mask |= bit;
2818                                    prev_shadow_4[lane] = p_sh;
2819                                    prev_refl_4[lane] = p_rf;
2820                                    prev_gi_4[lane] = p_gi;
2821                                    prev_ao_4[lane] = p_ao;
2822                                }
2823                            }
2824                        }
2825                        if let Some(clusters) = inputs.light_clusters {
2826                            let uv_x: f32 = ((px as f32) + 0.5) * frame_context.inv_width;
2827                            let uv_y: f32 = ((py as f32) + 0.5) * frame_context.inv_height;
2828                            let local_irrad: Vec3 = clusters.evaluate_irradiance_fast(
2829                                world_p,
2830                                tri.shade_n,
2831                                (uv_x, uv_y, depth),
2832                            );
2833                            out_gi[lane] = out_gi[lane].add(local_irrad);
2834                        }
2835                        let pattern: usize = (gx & 1) | ((gy & 1) << 1);
2836                        let blue_slot: usize = (gx.wrapping_mul(73) ^ gy.wrapping_mul(151)) & 15;
2837                        if tri.n_dot_l > 0.02 {
2838                            if inputs.use_vsm_far_shadows
2839                                && depth > 42.0
2840                                && let Some(vsm) = inputs.vsm
2841                            {
2842                                out_shadow[lane] =
2843                                    vsm.sample_visibility(world_p, tri.shade_n, sun_dir);
2844                            } else {
2845                                shadow_mask |= bit;
2846                                total_rays += 1;
2847                                let (s_dir, s_inv): (Vec3, Vec3) = if use_soft_shadows {
2848                                    soft_rays[blue_slot]
2849                                } else {
2850                                    (sun_dir, inv_sun)
2851                                };
2852                                sh_pkt.ox[lane] = origin.get_x();
2853                                sh_pkt.oy[lane] = origin.get_y();
2854                                sh_pkt.oz[lane] = origin.get_z();
2855                                sh_pkt.dx[lane] = s_dir.get_x();
2856                                sh_pkt.dy[lane] = s_dir.get_y();
2857                                sh_pkt.dz[lane] = s_dir.get_z();
2858                                sh_pkt.ix[lane] = s_inv.get_x();
2859                                sh_pkt.iy[lane] = s_inv.get_y();
2860                                sh_pkt.iz[lane] = s_inv.get_z();
2861                            }
2862                        }
2863                        if tri.do_refl {
2864                            let view_in: Vec3 = ray_vec.normalize();
2865                            let rdir: Vec3 = view_in.reflect(tri.shade_n).normalize();
2866                            refl_dir_4[lane] = rdir;
2867                            if depth > 52.0 || (tri.mat_refl < 0.30 && depth > 34.0) {
2868                                out_refl[lane] =
2869                                    Self::sample_sky_lut(inputs.sky_lut, rdir, &frame_context.sun);
2870                            } else {
2871                                let rinv: Vec3 = Ray3D::safe_inv_vec(rdir);
2872                                refl_mask |= bit;
2873                                total_rays += 1;
2874                                refl_pkt.ox[lane] = origin.get_x();
2875                                refl_pkt.oy[lane] = origin.get_y();
2876                                refl_pkt.oz[lane] = origin.get_z();
2877                                refl_pkt.dx[lane] = rdir.get_x();
2878                                refl_pkt.dy[lane] = rdir.get_y();
2879                                refl_pkt.dz[lane] = rdir.get_z();
2880                                refl_pkt.ix[lane] = rinv.get_x();
2881                                refl_pkt.iy[lane] = rinv.get_y();
2882                                refl_pkt.iz[lane] = rinv.get_z();
2883                            }
2884                        }
2885                        if use_soft_shadows {
2886                            if depth > 48.0 {
2887                                out_gi[lane] = out_gi[lane]
2888                                    .add(frame_context.sun.get_sky_horizon().scale(0.18));
2889                                out_ao[lane] = 0.88;
2890                            } else if depth > 22.0
2891                                && let Some(cache) = inputs.lumen_cache
2892                                && let Some((cached_irrad, cached_ao, _)) = cache.lookup(
2893                                    world_p,
2894                                    tri.shade_n,
2895                                    frame_context.camera_position,
2896                                )
2897                            {
2898                                out_gi[lane] = out_gi[lane].add(cached_irrad.scale(0.36));
2899                                out_ao[lane] = cached_ao;
2900                            } else {
2901                                let quad: [(Vec3, Vec3); 4] = if gi_cache[0].0 == tid {
2902                                    gi_cache[0].1
2903                                } else if gi_cache[1].0 == tid {
2904                                    gi_cache[1].1
2905                                } else if gi_cache[2].0 == tid {
2906                                    gi_cache[2].1
2907                                } else if gi_cache[3].0 == tid {
2908                                    gi_cache[3].1
2909                                } else {
2910                                    let computed: [(Vec3, Vec3); 4] =
2911                                        Self::compute_gi_ray_quad(tri.shade_n, gi_ring_offset);
2912                                    gi_cache[gi_cache_cursor] = (tid, computed);
2913                                    gi_cache_cursor = (gi_cache_cursor + 1) & 3;
2914                                    computed
2915                                };
2916                                let (gdir, ginv): (Vec3, Vec3) = quad[pattern];
2917                                gi_dir_4[lane] = gdir;
2918                                gi_mask |= bit;
2919                                total_rays += 1;
2920                                gi_pkt.ox[lane] = origin.get_x();
2921                                gi_pkt.oy[lane] = origin.get_y();
2922                                gi_pkt.oz[lane] = origin.get_z();
2923                                gi_pkt.dx[lane] = gdir.get_x();
2924                                gi_pkt.dy[lane] = gdir.get_y();
2925                                gi_pkt.dz[lane] = gdir.get_z();
2926                                gi_pkt.ix[lane] = ginv.get_x();
2927                                gi_pkt.iy[lane] = ginv.get_y();
2928                                gi_pkt.iz[lane] = ginv.get_z();
2929                            }
2930                        }
2931                    }
2932                    if shadow_mask != 0 {
2933                        let occ: u8 = World3D::trace_any_shadow_packet4_with_instances(
2934                            inputs.static_bvh,
2935                            inputs.dyn_instances,
2936                            inputs.local_bvhs,
2937                            &sh_pkt,
2938                            shadow_mask,
2939                            (0.05, 140.0),
2940                            (&mut static_shadow_cache, &mut dyn_shadow_cache),
2941                        );
2942                        let mut matrix_elems: u8 = occ;
2943                        while matrix_elems != 0 {
2944                            let lane: usize = matrix_elems.trailing_zeros() as usize;
2945                            matrix_elems &= matrix_elems - 1;
2946                            out_shadow[lane] = 0.22;
2947                        }
2948                    }
2949                    if refl_mask != 0 {
2950                        let refl_hits: [Option<(f32, Vec3, PbrMaterial)>; 4] = if refl_mask
2951                            .count_ones()
2952                            >= 2
2953                        {
2954                            World3D::trace_closest_packet4_with_instances(
2955                                inputs.static_bvh,
2956                                inputs.dyn_instances,
2957                                inputs.local_bvhs,
2958                                &refl_pkt,
2959                                refl_mask,
2960                                (0.08, 100.0),
2961                            )
2962                        } else {
2963                            let lane: usize = refl_mask.trailing_zeros() as usize;
2964                            let rdir: Vec3 = refl_dir_4[lane];
2965                            let rinv: Vec3 =
2966                                Vec3::new(refl_pkt.ix[lane], refl_pkt.iy[lane], refl_pkt.iz[lane]);
2967                            let mut single: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2968                            single[lane] = World3D::trace_closest_with_instances(
2969                                inputs.static_bvh,
2970                                inputs.dyn_instances,
2971                                inputs.local_bvhs,
2972                                (origin_4[lane], rdir, rinv),
2973                                (0.08, 100.0),
2974                            );
2975                            single
2976                        };
2977                        let mut rm: u8 = refl_mask;
2978                        while rm != 0 {
2979                            let lane: usize = rm.trailing_zeros() as usize;
2980                            rm &= rm - 1;
2981                            let rdir: Vec3 = refl_dir_4[lane];
2982                            out_refl[lane] = match refl_hits[lane] {
2983                                Some((hit_t, hit_n, hit_mat)) => {
2984                                    let mut hit_rad: Vec3 = Self::shade_surface_hit(
2985                                        hit_n,
2986                                        hit_mat,
2987                                        &frame_context.sun,
2988                                        use_soft_shadows,
2989                                    );
2990                                    if multi_bounce_refl
2991                                        && hit_t < 30.0
2992                                        && depth_4[lane] < 32.0
2993                                        && hit_mat.get_reflectivity() > 0.55
2994                                    {
2995                                        let p2: Vec3 = origin_4[lane]
2996                                            .add(rdir.scale(hit_t))
2997                                            .add(hit_n.scale(0.08));
2998                                        let r2: Vec3 = rdir.reflect(hit_n).normalize();
2999                                        let inv_r2: Vec3 = Ray3D::safe_inv_vec(r2);
3000                                        total_rays += 1;
3001                                        let bounce2: Vec3 =
3002                                            match World3D::trace_closest_with_instances(
3003                                                inputs.static_bvh,
3004                                                inputs.dyn_instances,
3005                                                inputs.local_bvhs,
3006                                                (p2, r2, inv_r2),
3007                                                (0.08, 56.0),
3008                                            ) {
3009                                                Some((_, n2, m2)) => Self::shade_surface_hit(
3010                                                    n2,
3011                                                    m2,
3012                                                    &frame_context.sun,
3013                                                    false,
3014                                                ),
3015                                                None => Self::sample_sky_lut(
3016                                                    inputs.sky_lut,
3017                                                    r2,
3018                                                    &frame_context.sun,
3019                                                ),
3020                                            };
3021                                        hit_rad = hit_rad.lerp(
3022                                            bounce2,
3023                                            (hit_mat.get_reflectivity() * 0.45).clamp(0.0, 0.5),
3024                                        );
3025                                    }
3026                                    hit_rad
3027                                }
3028                                None => {
3029                                    Self::sample_sky_lut(inputs.sky_lut, rdir, &frame_context.sun)
3030                                }
3031                            };
3032                        }
3033                    }
3034                    if gi_mask != 0 {
3035                        let gi_hits: [Option<(f32, Vec3, PbrMaterial)>; 4] =
3036                            if gi_mask.count_ones() >= 2 {
3037                                World3D::trace_closest_packet4_with_instances(
3038                                    inputs.static_bvh,
3039                                    inputs.dyn_instances,
3040                                    inputs.local_bvhs,
3041                                    &gi_pkt,
3042                                    gi_mask,
3043                                    (0.06, 20.0),
3044                                )
3045                            } else {
3046                                let lane: usize = gi_mask.trailing_zeros() as usize;
3047                                let gdir: Vec3 = gi_dir_4[lane];
3048                                let ginv: Vec3 =
3049                                    Vec3::new(gi_pkt.ix[lane], gi_pkt.iy[lane], gi_pkt.iz[lane]);
3050                                let mut single: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
3051                                single[lane] = World3D::trace_closest_with_instances(
3052                                    inputs.static_bvh,
3053                                    inputs.dyn_instances,
3054                                    inputs.local_bvhs,
3055                                    (origin_4[lane], gdir, ginv),
3056                                    (0.06, 20.0),
3057                                );
3058                                single
3059                            };
3060                        let mut gm: u8 = gi_mask;
3061                        while gm != 0 {
3062                            let lane: usize = gm.trailing_zeros() as usize;
3063                            gm &= gm - 1;
3064                            let gdir: Vec3 = gi_dir_4[lane];
3065                            match gi_hits[lane] {
3066                                Some((dist, hit_n, hit_mat)) => {
3067                                    let mut bounce: Vec3 = Self::shade_surface_hit(
3068                                        hit_n,
3069                                        hit_mat,
3070                                        &frame_context.sun,
3071                                        true,
3072                                    );
3073                                    if let Some(cache) = inputs.lumen_cache {
3074                                        let hit_pos: Vec3 = origin_4[lane].add(gdir.scale(dist));
3075                                        if let Some((cached_irrad, _, _)) = cache.lookup(
3076                                            hit_pos,
3077                                            hit_n,
3078                                            frame_context.camera_position,
3079                                        ) {
3080                                            bounce = bounce.add(
3081                                                hit_mat
3082                                                    .get_base_color()
3083                                                    .mul(cached_irrad.scale(0.55)),
3084                                            );
3085                                        }
3086                                    }
3087                                    let falloff: f32 = (1.0 - dist / 20.0).clamp(0.14, 1.0);
3088                                    out_gi[lane] = out_gi[lane].add(bounce.scale(0.36 * falloff));
3089                                    out_ao[lane] = 0.42 + 0.58 * (dist / 14.0).clamp(0.0, 1.0);
3090                                }
3091                                None => {
3092                                    out_gi[lane] = out_gi[lane].add(
3093                                        Self::sample_sky_lut(
3094                                            inputs.sky_lut,
3095                                            gdir,
3096                                            &frame_context.sun,
3097                                        )
3098                                        .scale(0.20),
3099                                    );
3100                                    out_ao[lane] = 1.0;
3101                                }
3102                            }
3103                        }
3104                    }
3105                    let mut blend_m: u8 = prev_valid_mask;
3106                    while blend_m != 0 {
3107                        let lane: usize = blend_m.trailing_zeros() as usize;
3108                        blend_m &= blend_m - 1;
3109                        let sh_diff: f32 = (out_shadow[lane] - prev_shadow_4[lane]).abs();
3110                        let sh_w: f32 = if sh_diff > 0.35 { 0.85 } else { 0.42 };
3111                        out_shadow[lane] =
3112                            prev_shadow_4[lane] + (out_shadow[lane] - prev_shadow_4[lane]) * sh_w;
3113                        let rf_delta: f32 = out_refl[lane].sub(prev_refl_4[lane]).length_sq();
3114                        let rf_w: f32 = if rf_delta > 0.45 { 0.85 } else { 0.45 };
3115                        out_refl[lane] = prev_refl_4[lane].lerp(out_refl[lane], rf_w);
3116                        out_gi[lane] = prev_gi_4[lane].lerp(out_gi[lane], 0.42);
3117                        out_ao[lane] = prev_ao_4[lane] + (out_ao[lane] - prev_ao_4[lane]) * 0.42;
3118                    }
3119                    let mut vm: u8 = valid_mask;
3120                    while vm != 0 {
3121                        let lane: usize = vm.trailing_zeros() as usize;
3122                        vm &= vm - 1;
3123                        let _: (usize, Vec3) = (tid_4[lane], ray_vec_4[lane]);
3124                        // SAFETY: Probe index `p_idx_4[lane]` lies within this tile's strictly disjoint probe rectangle.
3125                        unsafe {
3126                            probe_ptrs.write_valid(
3127                                p_idx_4[lane],
3128                                (out_shadow[lane], out_ao[lane], depth_4[lane]),
3129                                (out_refl[lane], out_gi[lane], normal_4[lane]),
3130                            );
3131                            probe_ptrs.write_world_pos(p_idx_4[lane], world_p_4[lane]);
3132                        }
3133                    }
3134                    gx_base += 2;
3135                }
3136                gy_base += 2;
3137            }
3138        }
3139        (total_rays, reproj_hits)
3140    }
3141
3142    /// Populates a single L1-stack SoA probe row `dst` (`gw <= 512`) for probe row `gy` with zero heap allocations, optionally skipping GI/AO 3x3 bilateral filtering when GI holds smooth analytic local lighting.
3143    ///
3144    /// # Arguments
3145    ///
3146    /// - `&RtProbeGridSoa` - Full raw probe SoA grid written by Barrier 1.
3147    /// - `usize` - Coarse probe grid width `gw <= 512`.
3148    /// - `usize` - Coarse probe grid height `gh`.
3149    /// - `usize` - Target probe row index `gy`.
3150    /// - `(bool, bool)` - `(denoise_shadow_refl, denoise_gi_ao)` bilateral flags.
3151    /// - `&mut RtProbeRowStack` - Destination L1-stack single-row SoA buffer.
3152    fn populate_probe_row_stack(
3153        raw: &RtProbeGridSoa,
3154        gw: usize,
3155        gh: usize,
3156        gy: usize,
3157        denoise_flags: (bool, bool),
3158        dst: &mut RtProbeRowStack,
3159    ) {
3160        let (denoise, denoise_gi): (bool, bool) = denoise_flags;
3161        let row_start: usize = gy * gw;
3162        let row_end: usize = row_start + gw;
3163        if !denoise {
3164            dst.shadow[..gw].copy_from_slice(&raw.shadow[row_start..row_end]);
3165            dst.refl_r[..gw].copy_from_slice(&raw.refl_r[row_start..row_end]);
3166            dst.refl_g[..gw].copy_from_slice(&raw.refl_g[row_start..row_end]);
3167            dst.refl_b[..gw].copy_from_slice(&raw.refl_b[row_start..row_end]);
3168            dst.gi_r[..gw].copy_from_slice(&raw.gi_r[row_start..row_end]);
3169            dst.gi_g[..gw].copy_from_slice(&raw.gi_g[row_start..row_end]);
3170            dst.gi_b[..gw].copy_from_slice(&raw.gi_b[row_start..row_end]);
3171            dst.ao[..gw].copy_from_slice(&raw.ao[row_start..row_end]);
3172            dst.depth[..gw].copy_from_slice(&raw.depth[row_start..row_end]);
3173            dst.nx[..gw].copy_from_slice(&raw.nx[row_start..row_end]);
3174            dst.ny[..gw].copy_from_slice(&raw.ny[row_start..row_end]);
3175            dst.nz[..gw].copy_from_slice(&raw.nz[row_start..row_end]);
3176            dst.valid[..gw].copy_from_slice(&raw.valid[row_start..row_end]);
3177            return;
3178        }
3179        let y0: usize = gy.saturating_sub(1);
3180        let y1: usize = (gy + 1).min(gh - 1);
3181        let raw_valid: &[u8] = raw.valid.as_slice();
3182        let raw_depth: &[f32] = raw.depth.as_slice();
3183        let raw_nx: &[f32] = raw.nx.as_slice();
3184        let raw_ny: &[f32] = raw.ny.as_slice();
3185        let raw_nz: &[f32] = raw.nz.as_slice();
3186        let raw_shadow: &[f32] = raw.shadow.as_slice();
3187        let raw_rr: &[f32] = raw.refl_r.as_slice();
3188        let raw_rg: &[f32] = raw.refl_g.as_slice();
3189        let raw_rb: &[f32] = raw.refl_b.as_slice();
3190        if !denoise_gi {
3191            dst.gi_r[..gw].copy_from_slice(&raw.gi_r[row_start..row_end]);
3192            dst.gi_g[..gw].copy_from_slice(&raw.gi_g[row_start..row_end]);
3193            dst.gi_b[..gw].copy_from_slice(&raw.gi_b[row_start..row_end]);
3194            dst.ao[..gw].copy_from_slice(&raw.ao[row_start..row_end]);
3195            for gx in 0..gw {
3196                let idx: usize = row_start + gx;
3197                if raw_valid[idx] == 0 {
3198                    dst.valid[gx] = 0;
3199                    continue;
3200                }
3201                let c_depth: f32 = raw_depth[idx];
3202                let c_nx: f32 = raw_nx[idx];
3203                let c_ny: f32 = raw_ny[idx];
3204                let c_nz: f32 = raw_nz[idx];
3205                let x0: usize = gx.saturating_sub(1);
3206                let x1: usize = (gx + 1).min(gw - 1);
3207                let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3208                let inv_depth_tol: f32 = 1.0 / depth_tol;
3209                let mut w_sum: f32 = 0.0;
3210                let mut s_sum: f32 = 0.0;
3211                let mut rr_sum: f32 = 0.0;
3212                let mut rg_sum: f32 = 0.0;
3213                let mut rb_sum: f32 = 0.0;
3214                for ny in y0..=y1 {
3215                    let row_off: usize = ny * gw;
3216                    let row_wt_diag: f32 = if ny == gy { 1.0 } else { 0.6 };
3217                    let row_wt_center: f32 = if ny == gy { 1.8 } else { 1.0 };
3218                    for nx in x0..=x1 {
3219                        let nb_i: usize = row_off + nx;
3220                        if raw_valid[nb_i] == 0 {
3221                            continue;
3222                        }
3223                        let ndot: f32 = c_nx.mul_add(
3224                            raw_nx[nb_i],
3225                            c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3226                        );
3227                        if ndot < 0.75 {
3228                            continue;
3229                        }
3230                        let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3231                        if d_diff > depth_tol {
3232                            continue;
3233                        }
3234                        let spatial: f32 = if nx == gx { row_wt_center } else { row_wt_diag };
3235                        let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3236                        w_sum += width_val;
3237                        s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3238                        rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3239                        rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3240                        rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3241                    }
3242                }
3243                dst.valid[gx] = 1;
3244                dst.depth[gx] = c_depth;
3245                dst.nx[gx] = c_nx;
3246                dst.ny[gx] = c_ny;
3247                dst.nz[gx] = c_nz;
3248                if w_sum > 1e-4 {
3249                    let inv_w: f32 = 1.0 / w_sum;
3250                    dst.shadow[gx] = s_sum * inv_w;
3251                    dst.refl_r[gx] = rr_sum * inv_w;
3252                    dst.refl_g[gx] = rg_sum * inv_w;
3253                    dst.refl_b[gx] = rb_sum * inv_w;
3254                } else {
3255                    dst.shadow[gx] = raw_shadow[idx];
3256                    dst.refl_r[gx] = raw_rr[idx];
3257                    dst.refl_g[gx] = raw_rg[idx];
3258                    dst.refl_b[gx] = raw_rb[idx];
3259                }
3260            }
3261            return;
3262        }
3263        let raw_gr: &[f32] = raw.gi_r.as_slice();
3264        let raw_gg: &[f32] = raw.gi_g.as_slice();
3265        let raw_gb: &[f32] = raw.gi_b.as_slice();
3266        let raw_ao: &[f32] = raw.ao.as_slice();
3267        for gx in 0..gw {
3268            let idx: usize = row_start + gx;
3269            if raw_valid[idx] == 0 {
3270                dst.valid[gx] = 0;
3271                continue;
3272            }
3273            let c_depth: f32 = raw_depth[idx];
3274            let c_nx: f32 = raw_nx[idx];
3275            let c_ny: f32 = raw_ny[idx];
3276            let c_nz: f32 = raw_nz[idx];
3277            let x0: usize = gx.saturating_sub(1);
3278            let x1: usize = (gx + 1).min(gw - 1);
3279            let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3280            let inv_depth_tol: f32 = 1.0 / depth_tol;
3281            let mut w_sum: f32 = 0.0;
3282            let mut s_sum: f32 = 0.0;
3283            let mut rr_sum: f32 = 0.0;
3284            let mut rg_sum: f32 = 0.0;
3285            let mut rb_sum: f32 = 0.0;
3286            let mut gi_r: f32 = 0.0;
3287            let mut gi_g: f32 = 0.0;
3288            let mut gi_b: f32 = 0.0;
3289            let mut ao_sum: f32 = 0.0;
3290            for ny in y0..=y1 {
3291                let row_off: usize = ny * gw;
3292                let row_wt_diag: f32 = if ny == gy { 1.0 } else { 0.6 };
3293                let row_wt_center: f32 = if ny == gy { 1.8 } else { 1.0 };
3294                for nx in x0..=x1 {
3295                    let nb_i: usize = row_off + nx;
3296                    if raw_valid[nb_i] == 0 {
3297                        continue;
3298                    }
3299                    let ndot: f32 = c_nx.mul_add(
3300                        raw_nx[nb_i],
3301                        c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3302                    );
3303                    if ndot < 0.75 {
3304                        continue;
3305                    }
3306                    let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3307                    if d_diff > depth_tol {
3308                        continue;
3309                    }
3310                    let spatial: f32 = if nx == gx { row_wt_center } else { row_wt_diag };
3311                    let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3312                    w_sum += width_val;
3313                    s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3314                    rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3315                    rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3316                    rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3317                    gi_r = raw_gr[nb_i].mul_add(width_val, gi_r);
3318                    gi_g = raw_gg[nb_i].mul_add(width_val, gi_g);
3319                    gi_b = raw_gb[nb_i].mul_add(width_val, gi_b);
3320                    ao_sum = raw_ao[nb_i].mul_add(width_val, ao_sum);
3321                }
3322            }
3323            dst.valid[gx] = 1;
3324            dst.depth[gx] = c_depth;
3325            dst.nx[gx] = c_nx;
3326            dst.ny[gx] = c_ny;
3327            dst.nz[gx] = c_nz;
3328            if w_sum > 1e-4 {
3329                let inv_w: f32 = 1.0 / w_sum;
3330                dst.shadow[gx] = s_sum * inv_w;
3331                dst.refl_r[gx] = rr_sum * inv_w;
3332                dst.refl_g[gx] = rg_sum * inv_w;
3333                dst.refl_b[gx] = rb_sum * inv_w;
3334                dst.gi_r[gx] = gi_r * inv_w;
3335                dst.gi_g[gx] = gi_g * inv_w;
3336                dst.gi_b[gx] = gi_b * inv_w;
3337                dst.ao[gx] = ao_sum * inv_w;
3338            } else {
3339                dst.shadow[gx] = raw_shadow[idx];
3340                dst.refl_r[gx] = raw_rr[idx];
3341                dst.refl_g[gx] = raw_rg[idx];
3342                dst.refl_b[gx] = raw_rb[idx];
3343                dst.gi_r[gx] = raw_gr[idx];
3344                dst.gi_g[gx] = raw_gg[idx];
3345                dst.gi_b[gx] = raw_gb[idx];
3346                dst.ao[gx] = raw_ao[idx];
3347            }
3348        }
3349    }
3350
3351    /// Fallback full-grid bilateral denoiser for ultra-wide viewports (`gw > 256`, e.g. 4K).
3352    ///
3353    /// # Arguments
3354    ///
3355    /// - `&RtProbeGridSoa` - Raw input SoA probe grid.
3356    /// - `usize` - Coarse grid width `gw`.
3357    /// - `usize` - Coarse grid height `gh`.
3358    /// - `&mut RtProbeGridSoa` - Pre-allocated denoised output SoA grid.
3359    fn denoise_wide_grid(raw: &RtProbeGridSoa, gw: usize, gh: usize, dst: &mut RtProbeGridSoa) {
3360        dst.resize(gw * gh);
3361        let dst_ptrs: RtProbeGridMutPtrs = dst.mut_ptrs();
3362        let grain: usize = (gh / 24).clamp(2, 8);
3363        parallel_for_ranges(gh, grain, |gy0: usize, gy1: usize| {
3364            let raw_valid: &[u8] = raw.valid.as_slice();
3365            let raw_depth: &[f32] = raw.depth.as_slice();
3366            let raw_nx: &[f32] = raw.nx.as_slice();
3367            let raw_ny: &[f32] = raw.ny.as_slice();
3368            let raw_nz: &[f32] = raw.nz.as_slice();
3369            let raw_shadow: &[f32] = raw.shadow.as_slice();
3370            let raw_rr: &[f32] = raw.refl_r.as_slice();
3371            let raw_rg: &[f32] = raw.refl_g.as_slice();
3372            let raw_rb: &[f32] = raw.refl_b.as_slice();
3373            let raw_gr: &[f32] = raw.gi_r.as_slice();
3374            let raw_gg: &[f32] = raw.gi_g.as_slice();
3375            let raw_gb: &[f32] = raw.gi_b.as_slice();
3376            let raw_ao: &[f32] = raw.ao.as_slice();
3377            for gy in gy0..gy1 {
3378                let row_start: usize = gy * gw;
3379                let y0: usize = gy.saturating_sub(1);
3380                let y1: usize = (gy + 1).min(gh - 1);
3381                for gx in 0..gw {
3382                    let idx: usize = row_start + gx;
3383                    if raw_valid[idx] == 0 {
3384                        // SAFETY: `parallel_for_ranges` yields strictly disjoint rows `[gy0..gy1)`.
3385                        unsafe {
3386                            dst_ptrs.write_invalid(idx);
3387                        }
3388                        continue;
3389                    }
3390                    let c_depth: f32 = raw_depth[idx];
3391                    let c_nx: f32 = raw_nx[idx];
3392                    let c_ny: f32 = raw_ny[idx];
3393                    let c_nz: f32 = raw_nz[idx];
3394                    let x0: usize = gx.saturating_sub(1);
3395                    let x1: usize = (gx + 1).min(gw - 1);
3396                    let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3397                    let inv_depth_tol: f32 = 1.0 / depth_tol;
3398                    let mut w_sum: f32 = 0.0;
3399                    let mut s_sum: f32 = 0.0;
3400                    let mut rr_sum: f32 = 0.0;
3401                    let mut rg_sum: f32 = 0.0;
3402                    let mut rb_sum: f32 = 0.0;
3403                    let mut gi_r: f32 = 0.0;
3404                    let mut gi_g: f32 = 0.0;
3405                    let mut gi_b: f32 = 0.0;
3406                    let mut ao_sum: f32 = 0.0;
3407                    for ny in y0..=y1 {
3408                        let row_off: usize = ny * gw;
3409                        let same_y: bool = ny == gy;
3410                        for nx in x0..=x1 {
3411                            let nb_i: usize = row_off + nx;
3412                            if raw_valid[nb_i] == 0 {
3413                                continue;
3414                            }
3415                            let ndot: f32 = c_nx.mul_add(
3416                                raw_nx[nb_i],
3417                                c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3418                            );
3419                            if ndot < 0.75 {
3420                                continue;
3421                            }
3422                            let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3423                            if d_diff > depth_tol {
3424                                continue;
3425                            }
3426                            let spatial: f32 = if nx == gx && same_y {
3427                                1.8
3428                            } else if nx == gx || same_y {
3429                                1.0
3430                            } else {
3431                                0.6
3432                            };
3433                            let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3434                            w_sum += width_val;
3435                            s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3436                            rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3437                            rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3438                            rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3439                            gi_r = raw_gr[nb_i].mul_add(width_val, gi_r);
3440                            gi_g = raw_gg[nb_i].mul_add(width_val, gi_g);
3441                            gi_b = raw_gb[nb_i].mul_add(width_val, gi_b);
3442                            ao_sum = raw_ao[nb_i].mul_add(width_val, ao_sum);
3443                        }
3444                    }
3445                    let (sh, rr, rg, rb, gr, gg, gb, ao): (f32, f32, f32, f32, f32, f32, f32, f32) =
3446                        if w_sum > 1e-4 {
3447                            let inv_w: f32 = 1.0 / w_sum;
3448                            (
3449                                s_sum * inv_w,
3450                                rr_sum * inv_w,
3451                                rg_sum * inv_w,
3452                                rb_sum * inv_w,
3453                                gi_r * inv_w,
3454                                gi_g * inv_w,
3455                                gi_b * inv_w,
3456                                ao_sum * inv_w,
3457                            )
3458                        } else {
3459                            (
3460                                raw_shadow[idx],
3461                                raw_rr[idx],
3462                                raw_rg[idx],
3463                                raw_rb[idx],
3464                                raw_gr[idx],
3465                                raw_gg[idx],
3466                                raw_gb[idx],
3467                                raw_ao[idx],
3468                            )
3469                        };
3470                    // SAFETY: `idx` belongs exclusively to disjoint row `gy` in `[gy0..gy1)`.
3471                    unsafe {
3472                        dst_ptrs.write_valid(
3473                            idx,
3474                            (sh, ao, c_depth),
3475                            (
3476                                Vec3::new(rr, rg, rb),
3477                                Vec3::new(gr, gg, gb),
3478                                Vec3::new(c_nx, c_ny, c_nz),
3479                            ),
3480                        );
3481                    }
3482                }
3483            }
3484        });
3485    }
3486
3487    /// Evaluates a symmetric 5-tap SIMD Gaussian bloom kernel (`0.08, 0.22, 0.40, 0.22, 0.08`) on 16-byte-aligned `[f32; 4]` RGB0 taps.
3488    ///
3489    /// # Arguments
3490    ///
3491    /// - `[f32; 4]` - Tap at offset `-2`.
3492    /// - `[f32; 4]` - Tap at offset `-1`.
3493    /// - `[f32; 4]` - Center tap `0`.
3494    /// - `[f32; 4]` - Tap at offset `+1`.
3495    /// - `[f32; 4]` - Tap at offset `+2`.
3496    ///
3497    /// # Returns
3498    ///
3499    /// - `[f32; 4]` - Filtered linear HDR bloom RGB0 vector.
3500    #[inline(always)]
3501    #[must_use]
3502    fn blur_bloom_tap5(
3503        c0: [f32; 4],
3504        c1: [f32; 4],
3505        c2: [f32; 4],
3506        c3: [f32; 4],
3507        c4: [f32; 4],
3508    ) -> [f32; 4] {
3509        #[cfg(target_arch = "aarch64")]
3510        {
3511            let mut out: [f32; 4] = [0.0; 4];
3512            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; NEON is mandatory on `aarch64`.
3513            unsafe {
3514                let s04: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
3515                    core::arch::aarch64::vld1q_f32(c0.as_ptr()),
3516                    core::arch::aarch64::vld1q_f32(c4.as_ptr()),
3517                );
3518                let s13: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
3519                    core::arch::aarch64::vld1q_f32(c1.as_ptr()),
3520                    core::arch::aarch64::vld1q_f32(c3.as_ptr()),
3521                );
3522                let v2: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
3523                    core::arch::aarch64::vld1q_f32(c2.as_ptr()),
3524                    core::arch::aarch64::vdupq_n_f32(0.40),
3525                );
3526                let acc: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
3527                    core::arch::aarch64::vfmaq_f32(v2, s13, core::arch::aarch64::vdupq_n_f32(0.22)),
3528                    s04,
3529                    core::arch::aarch64::vdupq_n_f32(0.08),
3530                );
3531                core::arch::aarch64::vst1q_f32(out.as_mut_ptr(), acc);
3532            }
3533            out
3534        }
3535        #[cfg(target_arch = "x86_64")]
3536        {
3537            let mut out: [f32; 4] = [0.0; 4];
3538            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; SSE2 is mandatory on `x86_64`.
3539            unsafe {
3540                let s04: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3541                    core::arch::x86_64::_mm_loadu_ps(c0.as_ptr()),
3542                    core::arch::x86_64::_mm_loadu_ps(c4.as_ptr()),
3543                );
3544                let s13: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3545                    core::arch::x86_64::_mm_loadu_ps(c1.as_ptr()),
3546                    core::arch::x86_64::_mm_loadu_ps(c3.as_ptr()),
3547                );
3548                let v2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
3549                    core::arch::x86_64::_mm_loadu_ps(c2.as_ptr()),
3550                    core::arch::x86_64::_mm_set1_ps(0.40),
3551                );
3552                let acc: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3553                    core::arch::x86_64::_mm_add_ps(
3554                        v2,
3555                        core::arch::x86_64::_mm_mul_ps(s13, core::arch::x86_64::_mm_set1_ps(0.22)),
3556                    ),
3557                    core::arch::x86_64::_mm_mul_ps(s04, core::arch::x86_64::_mm_set1_ps(0.08)),
3558                );
3559                core::arch::x86_64::_mm_storeu_ps(out.as_mut_ptr(), acc);
3560            }
3561            out
3562        }
3563        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
3564        {
3565            let mut out: [f32; 4] = [0.0; 4];
3566            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; `simd128` is enabled on `wasm32`.
3567            unsafe {
3568                let s04: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3569                    core::arch::wasm32::v128_load(c0.as_ptr().cast()),
3570                    core::arch::wasm32::v128_load(c4.as_ptr().cast()),
3571                );
3572                let s13: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3573                    core::arch::wasm32::v128_load(c1.as_ptr().cast()),
3574                    core::arch::wasm32::v128_load(c3.as_ptr().cast()),
3575                );
3576                let v2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
3577                    core::arch::wasm32::v128_load(c2.as_ptr().cast()),
3578                    core::arch::wasm32::f32x4_splat(0.40),
3579                );
3580                let acc: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3581                    core::arch::wasm32::f32x4_add(
3582                        v2,
3583                        core::arch::wasm32::f32x4_mul(s13, core::arch::wasm32::f32x4_splat(0.22)),
3584                    ),
3585                    core::arch::wasm32::f32x4_mul(s04, core::arch::wasm32::f32x4_splat(0.08)),
3586                );
3587                core::arch::wasm32::v128_store(out.as_mut_ptr().cast(), acc);
3588            }
3589            out
3590        }
3591        #[cfg(not(target_arch = "aarch64"))]
3592        #[cfg(not(target_arch = "x86_64"))]
3593        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
3594        {
3595            [
3596                (c0[0] + c4[0]).mul_add(0.08, (c1[0] + c3[0]).mul_add(0.22, c2[0] * 0.40)),
3597                (c0[1] + c4[1]).mul_add(0.08, (c1[1] + c3[1]).mul_add(0.22, c2[1] * 0.40)),
3598                (c0[2] + c4[2]).mul_add(0.08, (c1[2] + c3[2]).mul_add(0.22, c2[2] * 0.40)),
3599                0.0,
3600            ]
3601        }
3602    }
3603
3604    /// Runs the horizontal 5-tap Gaussian bloom blur plus wide anamorphic horizontal neon streak taps over a band of active rows.
3605    ///
3606    /// # Arguments
3607    ///
3608    /// - `usize` - Quarter-res bloom width `bw` (`>= 3`).
3609    /// - `&[[f32; 4]]` - Full source bloom buffer.
3610    /// - `usize` - Inclusive starting row `y_start`.
3611    /// - `&mut [[f32; 4]]` - Disjoint mutable output row band.
3612    fn blur_bloom_horiz_band(
3613        border_width: usize,
3614        src: &[[f32; 4]],
3615        y_start: usize,
3616        dst_band: &mut [[f32; 4]],
3617    ) {
3618        let band_rows: usize = dst_band.len() / border_width;
3619        let max_x: usize = border_width - 1;
3620        for local_y in 0..band_rows {
3621            let src_row_off: usize = (y_start + local_y) * border_width;
3622            let dst_row_off: usize = local_y * border_width;
3623            let src_row: &[[f32; 4]] = &src[src_row_off..(src_row_off + border_width)];
3624            let dst_row: &mut [[f32; 4]] = &mut dst_band[dst_row_off..(dst_row_off + border_width)];
3625            if border_width >= 17 {
3626                for pos_x in 0..8_usize {
3627                    let core: [f32; 4] = Self::blur_bloom_tap5(
3628                        src_row[pos_x.saturating_sub(2)],
3629                        src_row[pos_x.saturating_sub(1)],
3630                        src_row[pos_x],
3631                        src_row[(pos_x + 1).min(max_x)],
3632                        src_row[(pos_x + 2).min(max_x)],
3633                    );
3634                    let m4: [f32; 4] = src_row[pos_x.saturating_sub(4)];
3635                    let p4: [f32; 4] = src_row[(pos_x + 4).min(max_x)];
3636                    let m8: [f32; 4] = src_row[pos_x.saturating_sub(8)];
3637                    let p8: [f32; 4] = src_row[(pos_x + 8).min(max_x)];
3638                    dst_row[pos_x] = [
3639                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3640                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3641                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3642                        0.0,
3643                    ];
3644                }
3645                for pos_x in 8..(border_width - 8) {
3646                    let core: [f32; 4] = Self::blur_bloom_tap5(
3647                        src_row[pos_x - 2],
3648                        src_row[pos_x - 1],
3649                        src_row[pos_x],
3650                        src_row[pos_x + 1],
3651                        src_row[pos_x + 2],
3652                    );
3653                    let m4: [f32; 4] = src_row[pos_x - 4];
3654                    let p4: [f32; 4] = src_row[pos_x + 4];
3655                    let m8: [f32; 4] = src_row[pos_x - 8];
3656                    let p8: [f32; 4] = src_row[pos_x + 8];
3657                    dst_row[pos_x] = [
3658                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3659                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3660                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3661                        0.0,
3662                    ];
3663                }
3664                for pos_x in (border_width - 8)..border_width {
3665                    let core: [f32; 4] = Self::blur_bloom_tap5(
3666                        src_row[pos_x.saturating_sub(2)],
3667                        src_row[pos_x.saturating_sub(1)],
3668                        src_row[pos_x],
3669                        src_row[(pos_x + 1).min(max_x)],
3670                        src_row[(pos_x + 2).min(max_x)],
3671                    );
3672                    let m4: [f32; 4] = src_row[pos_x.saturating_sub(4)];
3673                    let p4: [f32; 4] = src_row[(pos_x + 4).min(max_x)];
3674                    let m8: [f32; 4] = src_row[pos_x.saturating_sub(8)];
3675                    let p8: [f32; 4] = src_row[(pos_x + 8).min(max_x)];
3676                    dst_row[pos_x] = [
3677                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3678                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3679                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3680                        0.0,
3681                    ];
3682                }
3683            } else {
3684                for pos_x in 0..border_width {
3685                    dst_row[pos_x] = Self::blur_bloom_tap5(
3686                        src_row[pos_x.saturating_sub(2)],
3687                        src_row[pos_x.saturating_sub(1)],
3688                        src_row[pos_x],
3689                        src_row[(pos_x + 1).min(max_x)],
3690                        src_row[(pos_x + 2).min(max_x)],
3691                    );
3692                }
3693            }
3694        }
3695    }
3696
3697    /// Runs the vertical 5-tap bloom blur pass over a band of rows with row-hoisted slices.
3698    ///
3699    /// # Arguments
3700    ///
3701    /// - `usize` - Quarter-res bloom width `bw`.
3702    /// - `usize` - Quarter-res bloom height `bh`.
3703    /// - `&[[f32; 4]]` - Full horizontally blurred bloom buffer.
3704    /// - `usize` - Inclusive starting row `y_start`.
3705    /// - `&mut [[f32; 4]]` - Disjoint mutable output row band.
3706    fn blur_bloom_vert_band(
3707        border_width: usize,
3708        bh: usize,
3709        src: &[[f32; 4]],
3710        y_start: usize,
3711        dst_band: &mut [[f32; 4]],
3712    ) {
3713        let band_rows: usize = dst_band.len() / border_width;
3714        let max_y: usize = bh - 1;
3715        for local_y in 0..band_rows {
3716            let coord_y: usize = y_start + local_y;
3717            let o0: usize = coord_y.saturating_sub(2) * border_width;
3718            let o1: usize = coord_y.saturating_sub(1) * border_width;
3719            let o2: usize = coord_y * border_width;
3720            let o3: usize = (coord_y + 1).min(max_y) * border_width;
3721            let o4: usize = (coord_y + 2).min(max_y) * border_width;
3722            let r0: &[[f32; 4]] = &src[o0..(o0 + border_width)];
3723            let r1: &[[f32; 4]] = &src[o1..(o1 + border_width)];
3724            let r2: &[[f32; 4]] = &src[o2..(o2 + border_width)];
3725            let r3: &[[f32; 4]] = &src[o3..(o3 + border_width)];
3726            let r4: &[[f32; 4]] = &src[o4..(o4 + border_width)];
3727            let dst_off: usize = local_y * border_width;
3728            let dst_row: &mut [[f32; 4]] = &mut dst_band[dst_off..(dst_off + border_width)];
3729            for pos_x in 0..border_width {
3730                dst_row[pos_x] =
3731                    Self::blur_bloom_tap5(r0[pos_x], r1[pos_x], r2[pos_x], r3[pos_x], r4[pos_x]);
3732            }
3733        }
3734    }
3735
3736    /// Tests whether row `by` is marked active in the 576-bit `bloom_row_bits` mask (or falls past 576 rows).
3737    ///
3738    /// # Arguments
3739    ///
3740    /// - `&[u64; 9]` - Snapshot of non-zero bloom row bitmask.
3741    /// - `usize` - Quarter-res bloom row index `by`.
3742    ///
3743    /// # Returns
3744    ///
3745    /// - `bool` - `true` when row `by` may contain non-zero HDR bloom radiance.
3746    #[inline(always)]
3747    #[must_use]
3748    fn bloom_row_is_active(bits: &[u64; 9], by: usize) -> bool {
3749        let word: usize = by >> 6;
3750        if word >= bits.len() {
3751            return true;
3752        }
3753        (bits[word] & (1_u64 << (by & 63))) != 0
3754    }
3755
3756    /// Runs a sparse-row SIMD 5-tap separable Gaussian bloom blur fused with `bloom_tile_active` generation, skipping empty rows completely.
3757    ///
3758    /// # Arguments
3759    ///
3760    /// - `usize` - Quarter-res bloom width.
3761    /// - `usize` - Quarter-res bloom height.
3762    /// - `&mut [[f32; 4]]` - Input bloom buffer (receives final blurred output).
3763    /// - `&mut [[f32; 4]]` - Intermediate horizontal scratch buffer.
3764    /// - `&mut [u8]` - Output tile-activity mask (`len >= bw * bh`).
3765    /// - `&[u64; 9]` - Active input row bitmask populated during Barrier 2.
3766    ///
3767    /// # Returns
3768    ///
3769    /// - `bool` - `true` when at least one bloom tile requires compositing in Barrier 3.
3770    #[must_use]
3771    fn blur_bloom_and_mask(
3772        border_width: usize,
3773        bh: usize,
3774        buf_a: &mut [[f32; 4]],
3775        buf_b: &mut [[f32; 4]],
3776        tile_active: &mut [u8],
3777        row_bits: &[u64; 9],
3778    ) -> bool {
3779        let min_len: usize = border_width * bh;
3780        if border_width < 3
3781            || bh < 3
3782            || buf_a.len() < min_len
3783            || buf_b.len() < min_len
3784            || tile_active.len() < min_len
3785        {
3786            return false;
3787        }
3788        if min_len >= 96_000 && bh >= 64 {
3789            let grain: usize = (bh / 16).clamp(8, 24);
3790            let src_a: &[[f32; 4]] = &buf_a[..min_len];
3791            let dst_b_base: usize = buf_b.as_mut_ptr() as usize;
3792            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
3793                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_b[..min_len]`.
3794                let out_band: &mut [[f32; 4]] = unsafe {
3795                    from_raw_parts_mut(
3796                        (dst_b_base as *mut [f32; 4]).add(y0 * border_width),
3797                        (y1 - y0) * border_width,
3798                    )
3799                };
3800                Self::blur_bloom_horiz_band(border_width, src_a, y0, out_band);
3801            });
3802            let src_b: &[[f32; 4]] = &buf_b[..min_len];
3803            let dst_a_base: usize = buf_a.as_mut_ptr() as usize;
3804            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
3805                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_a[..min_len]`.
3806                let out_band: &mut [[f32; 4]] = unsafe {
3807                    from_raw_parts_mut(
3808                        (dst_a_base as *mut [f32; 4]).add(y0 * border_width),
3809                        (y1 - y0) * border_width,
3810                    )
3811                };
3812                Self::blur_bloom_vert_band(border_width, bh, src_b, y0, out_band);
3813            });
3814            return Self::build_bloom_tile_mask(border_width, bh, &buf_a[..min_len], tile_active);
3815        }
3816        let max_y: usize = bh - 1;
3817        let max_x: usize = border_width - 1;
3818        for coord_y in 0..bh {
3819            let r_off: usize = coord_y * border_width;
3820            if Self::bloom_row_is_active(row_bits, coord_y) {
3821                Self::blur_bloom_horiz_band(
3822                    border_width,
3823                    &buf_a[..min_len],
3824                    coord_y,
3825                    &mut buf_b[r_off..(r_off + border_width)],
3826                );
3827            } else {
3828                let near_active: bool =
3829                    Self::bloom_row_is_active(row_bits, coord_y.saturating_sub(2))
3830                        || Self::bloom_row_is_active(row_bits, coord_y.saturating_sub(1))
3831                        || Self::bloom_row_is_active(row_bits, (coord_y + 1).min(max_y))
3832                        || Self::bloom_row_is_active(row_bits, (coord_y + 2).min(max_y));
3833                if near_active {
3834                    buf_b[r_off..(r_off + border_width)].fill([0.0; 4]);
3835                }
3836            }
3837        }
3838        let mut any_active: bool = false;
3839        let mut row_cell_hot: [u8; 1024] = [0; 1024];
3840        let mut prev_cell_hot: [u8; 1024] = [0; 1024];
3841        let use_fused_mask: bool = border_width <= 1024;
3842        for sample_y in 0..bh {
3843            let y_m2: usize = sample_y.saturating_sub(2);
3844            let y_m1: usize = sample_y.saturating_sub(1);
3845            let y_p1: usize = (sample_y + 1).min(max_y);
3846            let y_p2: usize = (sample_y + 2).min(max_y);
3847            let vert_active: bool = Self::bloom_row_is_active(row_bits, y_m2)
3848                || Self::bloom_row_is_active(row_bits, y_m1)
3849                || Self::bloom_row_is_active(row_bits, sample_y)
3850                || Self::bloom_row_is_active(row_bits, y_p1)
3851                || Self::bloom_row_is_active(row_bits, y_p2);
3852            let dst_off: usize = sample_y * border_width;
3853            if !vert_active {
3854                let adj_active: bool = sample_y > 0
3855                    && (Self::bloom_row_is_active(row_bits, sample_y.saturating_sub(3))
3856                        || Self::bloom_row_is_active(row_bits, y_m2)
3857                        || Self::bloom_row_is_active(row_bits, y_m1));
3858                if adj_active || !use_fused_mask {
3859                    buf_a[dst_off..(dst_off + border_width)].fill([0.0; 4]);
3860                }
3861                if use_fused_mask {
3862                    row_cell_hot[..border_width].fill(0);
3863                }
3864            } else {
3865                let r0: &[[f32; 4]] =
3866                    &buf_b[(y_m2 * border_width)..(y_m2 * border_width + border_width)];
3867                let r1: &[[f32; 4]] =
3868                    &buf_b[(y_m1 * border_width)..(y_m1 * border_width + border_width)];
3869                let r2: &[[f32; 4]] =
3870                    &buf_b[(sample_y * border_width)..(sample_y * border_width + border_width)];
3871                let r3: &[[f32; 4]] =
3872                    &buf_b[(y_p1 * border_width)..(y_p1 * border_width + border_width)];
3873                let r4: &[[f32; 4]] =
3874                    &buf_b[(y_p2 * border_width)..(y_p2 * border_width + border_width)];
3875                let dst_row: &mut [[f32; 4]] = &mut buf_a[dst_off..(dst_off + border_width)];
3876                for pos_x in 0..border_width {
3877                    let item_val: [f32; 4] = Self::blur_bloom_tap5(
3878                        r0[pos_x], r1[pos_x], r2[pos_x], r3[pos_x], r4[pos_x],
3879                    );
3880                    dst_row[pos_x] = item_val;
3881                    if use_fused_mask {
3882                        let hot: bool = item_val[0].max(item_val[1]).max(item_val[2]) >= 0.015;
3883                        row_cell_hot[pos_x] = u8::from(hot);
3884                    }
3885                }
3886            }
3887            if use_fused_mask && sample_y > 0 {
3888                let prev_off: usize = (sample_y - 1) * border_width;
3889                let mask_row: &mut [u8] = &mut tile_active[prev_off..(prev_off + border_width)];
3890                for bx in 0..border_width {
3891                    let bx1: usize = (bx + 1).min(max_x);
3892                    let active: u8 = prev_cell_hot[bx]
3893                        | prev_cell_hot[bx1]
3894                        | row_cell_hot[bx]
3895                        | row_cell_hot[bx1];
3896                    mask_row[bx] = active;
3897                    if active != 0 {
3898                        any_active = true;
3899                    }
3900                }
3901            }
3902            if use_fused_mask {
3903                prev_cell_hot[..border_width].copy_from_slice(&row_cell_hot[..border_width]);
3904            }
3905        }
3906        if use_fused_mask {
3907            let last_off: usize = max_y * border_width;
3908            let mask_row: &mut [u8] = &mut tile_active[last_off..(last_off + border_width)];
3909            for bx in 0..border_width {
3910                let bx1: usize = (bx + 1).min(max_x);
3911                let active: u8 = prev_cell_hot[bx] | prev_cell_hot[bx1];
3912                mask_row[bx] = active;
3913                if active != 0 {
3914                    any_active = true;
3915                }
3916            }
3917            any_active
3918        } else {
3919            Self::build_bloom_tile_mask(border_width, bh, &buf_a[..min_len], tile_active)
3920        }
3921    }
3922
3923    /// Computes 4-lane reciprocal square root `1 / sqrt(max(v, 1e-12))` via SSE2/scalar Newton-Raphson refinement.
3924    ///
3925    /// # Arguments
3926    ///
3927    /// - `[f32; 4]` - Four non-negative squared lengths.
3928    ///
3929    /// # Returns
3930    ///
3931    /// - `[f32; 4]` - 23-bit accurate reciprocal square roots.
3932    #[cfg(not(target_arch = "aarch64"))]
3933    #[cfg(not(target_arch = "x86_64"))]
3934    #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
3935    #[inline(always)]
3936    #[must_use]
3937    fn rsqrt_4x(item_val: [f32; 4]) -> [f32; 4] {
3938        [
3939            1.0 / item_val[0].max(1e-12).sqrt(),
3940            1.0 / item_val[1].max(1e-12).sqrt(),
3941            1.0 / item_val[2].max(1e-12).sqrt(),
3942            1.0 / item_val[3].max(1e-12).sqrt(),
3943        ]
3944    }
3945
3946    /// Computes 4-lane reciprocal `1.0 / max(v, 1e-6)` using NEON/SSE2/WASM SIMD128 vector division.
3947    ///
3948    /// # Arguments
3949    ///
3950    /// - `[f32; 4]` - Four denominator values.
3951    ///
3952    /// # Returns
3953    ///
3954    /// - `[f32; 4]` - Four reciprocals.
3955    #[inline(always)]
3956    #[must_use]
3957    fn recip_4x(item_val: [f32; 4]) -> [f32; 4] {
3958        #[cfg(target_arch = "aarch64")]
3959        {
3960            let mut out: [f32; 4] = [0.0; 4];
3961            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; NEON is mandatory on `aarch64`.
3962            unsafe {
3963                let pos_x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
3964                    core::arch::aarch64::vld1q_f32(item_val.as_ptr()),
3965                    core::arch::aarch64::vdupq_n_f32(1e-6),
3966                );
3967                let inv: core::arch::aarch64::float32x4_t = Self::neon_rcp_4x(pos_x);
3968                core::arch::aarch64::vst1q_f32(out.as_mut_ptr(), inv);
3969            }
3970            out
3971        }
3972        #[cfg(target_arch = "x86_64")]
3973        {
3974            let mut out: [f32; 4] = [0.0; 4];
3975            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; SSE2 is mandatory on `x86_64`.
3976            unsafe {
3977                let coord_x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
3978                    core::arch::x86_64::_mm_loadu_ps(item_val.as_ptr()),
3979                    core::arch::x86_64::_mm_set1_ps(1e-6),
3980                );
3981                let inv: core::arch::x86_64::__m128 =
3982                    core::arch::x86_64::_mm_div_ps(core::arch::x86_64::_mm_set1_ps(1.0), coord_x);
3983                core::arch::x86_64::_mm_storeu_ps(out.as_mut_ptr(), inv);
3984            }
3985            out
3986        }
3987        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
3988        {
3989            let mut out: [f32; 4] = [0.0; 4];
3990            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; `simd128` is enabled on `wasm32`.
3991            unsafe {
3992                let sample_x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
3993                    core::arch::wasm32::v128_load(item_val.as_ptr().cast()),
3994                    core::arch::wasm32::f32x4_splat(1e-6),
3995                );
3996                let inv: core::arch::wasm32::v128 =
3997                    core::arch::wasm32::f32x4_div(core::arch::wasm32::f32x4_splat(1.0), sample_x);
3998                core::arch::wasm32::v128_store(out.as_mut_ptr().cast(), inv);
3999            }
4000            out
4001        }
4002        #[cfg(not(target_arch = "aarch64"))]
4003        #[cfg(not(target_arch = "x86_64"))]
4004        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
4005        {
4006            [
4007                1.0 / item_val[0].max(1e-6),
4008                1.0 / item_val[1].max(1e-6),
4009                1.0 / item_val[2].max(1e-6),
4010                1.0 / item_val[3].max(1e-6),
4011            ]
4012        }
4013    }
4014
4015    /// Computes horizontal sum across all 4 SSE2 `f32` lanes.
4016    ///
4017    /// # Arguments
4018    ///
4019    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4020    ///
4021    /// # Returns
4022    ///
4023    /// - `f32` - Sum of all four lanes.
4024    #[cfg(target_arch = "x86_64")]
4025    #[inline(always)]
4026    pub(crate) unsafe fn sse_hsum_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4027        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4028        unsafe {
4029            let hi: core::arch::x86_64::__m128 =
4030                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4031            let s1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(item_val, hi);
4032            let s2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ss(
4033                s1,
4034                core::arch::x86_64::_mm_shuffle_ps::<0x55>(s1, s1),
4035            );
4036            core::arch::x86_64::_mm_cvtss_f32(s2)
4037        }
4038    }
4039
4040    /// Computes horizontal minimum across all 4 SSE2 `f32` lanes.
4041    ///
4042    /// # Arguments
4043    ///
4044    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4045    ///
4046    /// # Returns
4047    ///
4048    /// - `f32` - Minimum lane value.
4049    #[cfg(target_arch = "x86_64")]
4050    #[inline(always)]
4051    pub(crate) unsafe fn sse_hmin_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4052        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4053        unsafe {
4054            let hi: core::arch::x86_64::__m128 =
4055                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4056            let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(item_val, hi);
4057            let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ss(
4058                m1,
4059                core::arch::x86_64::_mm_shuffle_ps::<0x55>(m1, m1),
4060            );
4061            core::arch::x86_64::_mm_cvtss_f32(m2)
4062        }
4063    }
4064
4065    /// Computes horizontal maximum across all 4 SSE2 `f32` lanes.
4066    ///
4067    /// # Arguments
4068    ///
4069    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4070    ///
4071    /// # Returns
4072    ///
4073    /// - `f32` - Maximum lane value.
4074    #[cfg(target_arch = "x86_64")]
4075    #[inline(always)]
4076    pub(crate) unsafe fn sse_hmax_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4077        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4078        unsafe {
4079            let hi: core::arch::x86_64::__m128 =
4080                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4081            let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(item_val, hi);
4082            let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ss(
4083                m1,
4084                core::arch::x86_64::_mm_shuffle_ps::<0x55>(m1, m1),
4085            );
4086            core::arch::x86_64::_mm_cvtss_f32(m2)
4087        }
4088    }
4089
4090    /// Evaluates linear interpolation `a + (b - a) * t` across 4 SSE2 lanes.
4091    ///
4092    /// # Arguments
4093    ///
4094    /// - `core::arch::x86_64::__m128` - Start vector `a`.
4095    /// - `core::arch::x86_64::__m128` - End vector `b`.
4096    /// - `core::arch::x86_64::__m128` - Blend factor `t`.
4097    ///
4098    /// # Returns
4099    ///
4100    /// - `core::arch::x86_64::__m128` - Interpolated vector.
4101    #[cfg(target_arch = "x86_64")]
4102    #[inline(always)]
4103    unsafe fn sse_lerp_4x(
4104        alpha_val: core::arch::x86_64::__m128,
4105        blue_val: core::arch::x86_64::__m128,
4106        blend_factor: core::arch::x86_64::__m128,
4107    ) -> core::arch::x86_64::__m128 {
4108        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4109        unsafe {
4110            core::arch::x86_64::_mm_add_ps(
4111                alpha_val,
4112                core::arch::x86_64::_mm_mul_ps(
4113                    core::arch::x86_64::_mm_sub_ps(blue_val, alpha_val),
4114                    blend_factor,
4115                ),
4116            )
4117        }
4118    }
4119
4120    /// Computes horizontal sum across all 4 WebAssembly SIMD128 `f32` lanes.
4121    ///
4122    /// # Arguments
4123    ///
4124    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4125    ///
4126    /// # Returns
4127    ///
4128    /// - `f32` - Sum of all four lanes.
4129    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4130    #[inline(always)]
4131    pub(crate) fn wasm_hsum_4x(item_val: core::arch::wasm32::v128) -> f32 {
4132        (core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4133            + core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4134            + (core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4135                + core::arch::wasm32::f32x4_extract_lane::<3>(item_val))
4136    }
4137
4138    /// Computes horizontal minimum across all 4 WebAssembly SIMD128 `f32` lanes.
4139    ///
4140    /// # Arguments
4141    ///
4142    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4143    ///
4144    /// # Returns
4145    ///
4146    /// - `f32` - Minimum lane value.
4147    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4148    #[inline(always)]
4149    pub(crate) fn wasm_hmin_4x(item_val: core::arch::wasm32::v128) -> f32 {
4150        core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4151            .min(core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4152            .min(
4153                core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4154                    .min(core::arch::wasm32::f32x4_extract_lane::<3>(item_val)),
4155            )
4156    }
4157
4158    /// Computes horizontal maximum across all 4 WebAssembly SIMD128 `f32` lanes.
4159    ///
4160    /// # Arguments
4161    ///
4162    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4163    ///
4164    /// # Returns
4165    ///
4166    /// - `f32` - Maximum lane value.
4167    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4168    #[inline(always)]
4169    pub(crate) fn wasm_hmax_4x(item_val: core::arch::wasm32::v128) -> f32 {
4170        core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4171            .max(core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4172            .max(
4173                core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4174                    .max(core::arch::wasm32::f32x4_extract_lane::<3>(item_val)),
4175            )
4176    }
4177
4178    /// Evaluates linear interpolation `a + (b - a) * t` across 4 WebAssembly SIMD128 lanes.
4179    ///
4180    /// # Arguments
4181    ///
4182    /// - `core::arch::wasm32::v128` - Start vector `a`.
4183    /// - `core::arch::wasm32::v128` - End vector `b`.
4184    /// - `core::arch::wasm32::v128` - Blend factor `t`.
4185    ///
4186    /// # Returns
4187    ///
4188    /// - `core::arch::wasm32::v128` - Interpolated vector.
4189    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4190    #[inline(always)]
4191    fn wasm_lerp_4x(
4192        alpha_val: core::arch::wasm32::v128,
4193        blue_val: core::arch::wasm32::v128,
4194        blend_factor: core::arch::wasm32::v128,
4195    ) -> core::arch::wasm32::v128 {
4196        core::arch::wasm32::f32x4_add(
4197            alpha_val,
4198            core::arch::wasm32::f32x4_mul(
4199                core::arch::wasm32::f32x4_sub(blue_val, alpha_val),
4200                blend_factor,
4201            ),
4202        )
4203    }
4204
4205    /// Evaluates linear interpolation `a + (b - a) * t` across 4 NEON lanes.
4206    ///
4207    /// # Arguments
4208    ///
4209    /// - `core::arch::aarch64::float32x4_t` - Start vector `a`.
4210    /// - `core::arch::aarch64::float32x4_t` - End vector `b`.
4211    /// - `core::arch::aarch64::float32x4_t` - Blend factor `t`.
4212    ///
4213    /// # Returns
4214    ///
4215    /// - `core::arch::aarch64::float32x4_t` - Interpolated vector.
4216    #[cfg(target_arch = "aarch64")]
4217    #[inline(always)]
4218    unsafe fn neon_lerp_4x(
4219        alpha_val: core::arch::aarch64::float32x4_t,
4220        blue_val: core::arch::aarch64::float32x4_t,
4221        blend_factor: core::arch::aarch64::float32x4_t,
4222    ) -> core::arch::aarch64::float32x4_t {
4223        // SAFETY: Caller guarantees ARM64 NEON execution context.
4224        unsafe {
4225            core::arch::aarch64::vfmaq_f32(
4226                alpha_val,
4227                core::arch::aarch64::vsubq_f32(blue_val, alpha_val),
4228                blend_factor,
4229            )
4230        }
4231    }
4232
4233    /// Evaluates architectural curtain-wall mullions, multi-hue interior office depth gradients, and illuminated ground-floor retail storefronts for one world point.
4234    ///
4235    /// Analytically integrates a periodic unit-period pulse `[edge_a, edge_b)` over a pixel footprint `filter_w` so high-frequency stripes and window grids converge smoothly to their exact average coverage `edge_b - edge_a` at Nyquist without shimmering.
4236    ///
4237    /// # Arguments
4238    ///
4239    /// - `f32` - Continuous periodic pattern coordinate.
4240    /// - `f32` - Pulse rising edge inside `[0.0, 1.0)`.
4241    /// - `f32` - Pulse falling edge inside `(edge_a, 1.0]`.
4242    /// - `f32` - Screen-space derivative width in pattern-space units.
4243    ///
4244    /// # Returns
4245    ///
4246    /// - `f32` - Analytical box-filtered coverage in `[0.0, 1.0]`.
4247    #[inline(always)]
4248    #[must_use]
4249    fn box_pulse(coord: f32, edge_a: f32, edge_b: f32, filter_w: f32) -> f32 {
4250        let width: f32 = edge_b - edge_a;
4251        let fw: f32 = filter_w.max(1.0e-4);
4252        let x0: f32 = coord - 0.5 * fw;
4253        let x1: f32 = coord + 0.5 * fw;
4254        let f0: f32 = x0.floor();
4255        let f1: f32 = x1.floor();
4256        let i0: f32 = f0 * width + (x0 - f0 - edge_a).clamp(0.0, width);
4257        let i1: f32 = f1 * width + (x1 - f1 - edge_a).clamp(0.0, width);
4258        ((i1 - i0) / fw).clamp(0.0, 1.0)
4259    }
4260
4261    /// Analytically integrates a single non-periodic interval `[lo, hi]` over a pixel footprint `filter_w`.
4262    ///
4263    /// # Arguments
4264    ///
4265    /// - `f32` - Continuous coordinate.
4266    /// - `f32` - Interval lower bound.
4267    /// - `f32` - Interval upper bound.
4268    /// - `f32` - Pixel footprint width in coordinate units.
4269    ///
4270    /// # Returns
4271    ///
4272    /// - `f32` - Analytical box-filtered interval coverage in `[0.0, 1.0]`.
4273    #[inline(always)]
4274    #[must_use]
4275    fn box_band(coord: f32, lo: f32, hi: f32, filter_w: f32) -> f32 {
4276        let fw: f32 = filter_w.max(1.0e-4);
4277        let x0: f32 = coord - 0.5 * fw;
4278        let x1: f32 = coord + 0.5 * fw;
4279        ((x1.min(hi) - x0.max(lo)) / fw).clamp(0.0, 1.0)
4280    }
4281
4282    /// Analytically integrates a step transition at `edge` over a pixel footprint `filter_w`.
4283    ///
4284    /// # Arguments
4285    ///
4286    /// - `f32` - Continuous coordinate.
4287    /// - `f32` - Step transition position.
4288    /// - `f32` - Pixel footprint width in coordinate units.
4289    ///
4290    /// # Returns
4291    ///
4292    /// - `f32` - Analytical box-filtered step coverage in `[0.0, 1.0]`.
4293    #[inline(always)]
4294    #[must_use]
4295    fn box_step(coord: f32, edge: f32, filter_w: f32) -> f32 {
4296        let fw: f32 = filter_w.max(1.0e-4);
4297        ((coord - edge) / fw + 0.5).clamp(0.0, 1.0)
4298    }
4299
4300    /// Computes the continuous unit horizontal wall tangent `(-nz, nx) / hypot(nx, nz)` eliminating 45-degree axis flips on chamfered, twisted, cylindrical, and rotated facades.
4301    ///
4302    /// # Arguments
4303    ///
4304    /// - `Vec3` - World-space shading normal of the building wall facet.
4305    ///
4306    /// # Returns
4307    ///
4308    /// - `(f32, f32)` - Normalized horizontal tangent `(tangent_x, tangent_z)` along the wall plane.
4309    #[inline(always)]
4310    #[must_use]
4311    fn facade_wall_tangent(shade_normal: Vec3) -> (f32, f32) {
4312        let horiz_len: f32 = shade_normal.get_x().hypot(shade_normal.get_z()).max(1.0e-4);
4313        (
4314            -shade_normal.get_z() / horiz_len,
4315            shade_normal.get_x() / horiz_len,
4316        )
4317    }
4318
4319    /// Evaluates architectural curtain-wall glazing, sunlit office interiors, metallic mullions, and warm storefront bays with analytical Nyquist box-filter anti-aliasing and per-cell coherence blending.
4320    ///
4321    /// # Arguments
4322    ///
4323    /// - `(f32, f32, f32, f32)` - `(u_coord, world_y, depth, inv_height)`.
4324    /// - `(Vec3, Vec3, f32)` - Base `(albedo, emissive, reflectivity)`.
4325    ///
4326    /// # Returns
4327    ///
4328    /// - `(Vec3, Vec3, f32)` - Updated `(albedo, emissive, reflectivity)`.
4329    #[inline(always)]
4330    #[must_use]
4331    fn eval_facade_detail(
4332        coords: (f32, f32, f32, f32),
4333        surf: (Vec3, Vec3, f32),
4334    ) -> (Vec3, Vec3, f32) {
4335        let (u_coord, world_y, depth, inv_height): (f32, f32, f32, f32) = coords;
4336        let (base, emissive, refl): (Vec3, Vec3, f32) = surf;
4337        let world_px_size: f32 = (depth * inv_height * 2.10).max(0.015);
4338        let spec_aa_damp: f32 = (1.0 - world_px_size * 0.22).clamp(0.45, 1.0);
4339        if world_y > 0.25 && world_y < 3.25 {
4340            let su: f32 = u_coord * 0.34;
4341            let su_fl: f32 = su.floor();
4342            let fy: f32 = (world_y - 0.25) * (1.0 / 3.0);
4343            let fw_su: f32 = world_px_size * 0.34;
4344            let fw_fy: f32 = world_px_size * (1.0 / 3.0);
4345            let pu: f32 = Self::box_pulse(su, 0.08, 0.92, fw_su);
4346            let pv: f32 = Self::box_band(fy, 0.08, 0.92, fw_fy);
4347            let pane_w: f32 = (pu * pv).clamp(0.0, 1.0);
4348            let frame_col: Vec3 = base.scale(0.55);
4349            if pane_w > 0.01 {
4350                let shop_h: u32 = ((su_fl as i32).wrapping_mul(73_856_093)) as u32;
4351                let shop_t: f32 = ((fw_su.max(fw_fy) - 0.08) * (1.0 / 0.14)).clamp(0.0, 1.0);
4352                let cell_coh: f32 = 1.0 - shop_t * shop_t * (3.0 - 2.0 * shop_t);
4353                let raw_grad: f32 = (1.12 - fy * 0.52).clamp(0.45, 1.15);
4354                let grad: f32 = 0.84 + (raw_grad - 0.84) * cell_coh;
4355                let shop_glow: Vec3 = match shop_h % 5 {
4356                    0 | 1 => Vec3::new(1.18, 0.78, 0.36),
4357                    2 => Vec3::new(0.28, 0.88, 1.18),
4358                    3 => Vec3::new(1.12, 0.32, 0.68),
4359                    _ => Vec3::new(0.0, 0.0, 0.0),
4360                };
4361                let avg_shop: Vec3 = Vec3::new(0.75, 0.55, 0.52);
4362                let eff_glow: Vec3 = avg_shop.lerp(shop_glow, cell_coh);
4363                let next_base: Vec3 = frame_col.lerp(base.scale(0.42), pane_w);
4364                let next_em: Vec3 = emissive.add(eff_glow.scale(pane_w * grad * 0.92));
4365                return (
4366                    next_base,
4367                    next_em,
4368                    ((refl + 0.34 * pane_w) * spec_aa_damp).min(0.92),
4369                );
4370            }
4371            return (frame_col, emissive, refl * 0.65 * spec_aa_damp);
4372        }
4373        if world_y < 3.45 {
4374            return (base.scale(0.68), emissive, refl * 0.75 * spec_aa_damp);
4375        }
4376        let su: f32 = u_coord * 0.48;
4377        let su_fl: f32 = su.floor();
4378        let sy: f32 = world_y * 0.33;
4379        let sy_fl: f32 = sy.floor();
4380        let fy_win: f32 = sy - sy_fl;
4381        let fw_su: f32 = world_px_size * 0.48;
4382        let fw_sy: f32 = world_px_size * 0.33;
4383        let pane_u: f32 = Self::box_pulse(su, 0.14, 0.86, fw_su);
4384        let pane_v: f32 = Self::box_pulse(sy, 0.18, 0.84, fw_sy);
4385        let pane_w: f32 = (pane_u * pane_v).clamp(0.0, 1.0);
4386        let spandrel_cov: f32 = Self::box_pulse(sy, 0.14, 0.88, fw_sy);
4387        let spandrel_shade: f32 = 0.70 + 0.14 * spandrel_cov;
4388        let wall_base: Vec3 = base.scale(spandrel_shade);
4389        if pane_w <= 0.01 {
4390            return (wall_base, emissive, refl * 0.72 * spec_aa_damp);
4391        }
4392        let cell_fw: f32 = fw_su.max(fw_sy);
4393        let ct: f32 = ((cell_fw - 0.10) * (1.0 / 0.18)).clamp(0.0, 1.0);
4394        let cell_coh: f32 = 1.0 - ct * ct * (3.0 - 2.0 * ct);
4395        let cell_x: i32 = su_fl as i32;
4396        let cell_y: i32 = sy_fl as i32;
4397        let h_bits: u32 = ((cell_x.wrapping_mul(73_856_093))
4398            ^ (cell_y.wrapping_mul(19_349_663))
4399            ^ ((cell_x.wrapping_add(cell_y)).wrapping_mul(83_492_791)))
4400            as u32;
4401        let bucket: u32 = h_bits % 11;
4402        let room_level: f32 = 0.68 + (((h_bits >> 8) & 15) as f32) * 0.032;
4403        let blind_grad: f32 = (0.48 + 0.66 * (1.0 - fy_win)).clamp(0.38, 1.14);
4404        let room_scale: f32 = room_level * (0.78 + (blind_grad - 0.78) * cell_coh);
4405        let (cell_tint, cell_em, cell_refl_add): (f32, Vec3, f32) = match bucket {
4406            0 | 4 => (0.86, Vec3::new(1.24, 0.86, 0.42).scale(room_scale), 0.14),
4407            1 => (0.84, Vec3::new(0.28, 0.86, 1.24).scale(room_scale), 0.18),
4408            2 => (
4409                0.88,
4410                Vec3::new(0.96, 0.94, 0.88).scale(room_scale * 0.82),
4411                0.16,
4412            ),
4413            3 => (
4414                0.84,
4415                Vec3::new(1.06, 0.34, 0.72).scale(room_scale * 0.86),
4416                0.18,
4417            ),
4418            _ => (
4419                (0.36 + 0.22 * fy_win).clamp(0.32, 0.62),
4420                Vec3::new(0.0, 0.0, 0.0),
4421                0.36,
4422            ),
4423        };
4424        let avg_tint: f32 = 0.64;
4425        let avg_em: Vec3 = Vec3::new(0.32, 0.27, 0.24);
4426        let avg_refl_add: f32 = 0.27;
4427        let eff_tint: f32 = avg_tint + (cell_tint - avg_tint) * cell_coh;
4428        let eff_em: Vec3 = avg_em.lerp(cell_em, cell_coh);
4429        let eff_refl_add: f32 = avg_refl_add + (cell_refl_add - avg_refl_add) * cell_coh;
4430        (
4431            wall_base.lerp(base.scale(eff_tint), pane_w),
4432            emissive.add(eff_em.scale(pane_w)),
4433            ((refl + eff_refl_add * pane_w) * spec_aa_damp).min(0.92),
4434        )
4435    }
4436
4437    /// Evaluates continuous closed-loop stadium arc length for boulevard markings and streetlights.
4438    ///
4439    /// # Arguments
4440    ///
4441    /// - `f32` - World X coordinate in meters.
4442    /// - `f32` - World Z coordinate in meters.
4443    ///
4444    /// # Returns
4445    ///
4446    /// - `f32` - Continuous arc-length coordinate `road_s` along the 962.12m closed loop.
4447    #[inline(always)]
4448    #[must_use]
4449    fn eval_loop_arc_s(wpx: f32, wpz: f32) -> f32 {
4450        if wpz < -140.0 {
4451            let ry: f32 = -(wpz + 140.0);
4452            let rx: f32 = -(wpx - 64.0);
4453            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4454                1.0
4455            } else {
4456                rx
4457            };
4458            return 140.0 + 64.0 * ry.atan2(rx_safe);
4459        }
4460        if wpz > 140.0 {
4461            let ry: f32 = wpz - 140.0;
4462            let rx: f32 = wpx - 64.0;
4463            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4464                1.0
4465            } else {
4466                rx
4467            };
4468            return 621.06193 + 64.0 * ry.atan2(rx_safe);
4469        }
4470        if wpx <= 64.0 { -wpz } else { 481.06193 + wpz }
4471    }
4472
4473    /// Evaluates physically-based closed-loop wet boulevard asphalt with a 3-zone wetness model (dry matte aggregate, capillary-darkened porous damp halo, and crisp meniscus standing water with Beer-Lambert depth tint, Snell refraction parallax, animated micro-ripples, and physical `F0 = 0.02` Schlick Fresnel), seamless stadium markings, tiled sidewalks, and the eastern sunlit coastal ocean bay.
4474    ///
4475    /// # Arguments
4476    ///
4477    /// - `(f32, f32, f32, f32)` - `(world_x, world_z, depth, inv_height)`.
4478    /// - `(Vec3, f32, f32, f32)` - `(view_dir, fresnel_t, metallic, world_time_secs)`.
4479    /// - `Vec3` - Base road material albedo.
4480    ///
4481    /// # Returns
4482    ///
4483    /// - `(Vec3, f32)` - Updated `(albedo, calibrated_reflectivity)`.
4484    #[inline(always)]
4485    #[must_use]
4486    fn eval_road_detail(
4487        coords: (f32, f32, f32, f32),
4488        optics: (Vec3, f32, f32, f32),
4489        base: Vec3,
4490    ) -> (Vec3, f32) {
4491        let (wpx, wpz, depth, inv_height): (f32, f32, f32, f32) = coords;
4492        let (view_dir, fresnel_t, metallic, world_time): (Vec3, f32, f32, f32) = optics;
4493        let world_px_size: f32 = (depth * inv_height * 2.10).max(0.018);
4494        let fw_x: f32 = world_px_size * 1.15;
4495        let fw_z: f32 = world_px_size * 2.35;
4496        let fw_xz: f32 = fw_x.hypot(fw_z);
4497        let spine_z: f32 = wpz.clamp(-140.0, 140.0);
4498        let rel_x: f32 = wpx - 64.0;
4499        let rel_z: f32 = wpz - spine_z;
4500        let d_spine: f32 = rel_x.hypot(rel_z);
4501        let road_u: f32 = d_spine - 64.0;
4502        let abs_u: f32 = road_u.abs();
4503        let (rad_x, rad_z): (f32, f32) = if d_spine > 1.0e-4 {
4504            (rel_x / d_spine, rel_z / d_spine)
4505        } else {
4506            (-1.0, 0.0)
4507        };
4508        let tan_x: f32 = -rad_z;
4509        let tan_z: f32 = rad_x;
4510        let fw_u: f32 = (rad_x.abs() * fw_x + rad_z.abs() * fw_z).max(0.015);
4511        let arc_scale: f32 = if wpz.abs() > 140.0 {
4512            64.0 / d_spine.max(16.0)
4513        } else {
4514            1.0
4515        };
4516        let fw_s: f32 = ((tan_x.abs() * fw_x + tan_z.abs() * fw_z) * arc_scale).max(0.015);
4517        let refl_fresnel: f32 = (0.18 + 0.82 * fresnel_t + metallic * 0.25).clamp(0.18, 0.95);
4518        let inv_refl_f: f32 = 1.0 / refl_fresnel;
4519        let f_water: f32 = 0.02 + 0.98 * fresnel_t;
4520        let d_bay_t: f32 = ((d_spine - 77.8) * (1.0 / 0.6)).clamp(0.0, 1.0);
4521        let bay_w: f32 =
4522            Self::box_step(wpx, 144.0, fw_x) * (d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t));
4523        if bay_w >= 0.999 {
4524            let shore_d: f32 = (wpx - 144.0).max(0.0);
4525            let shallow_t: f32 = Self::fast_exp_neg_3d(shore_d * 0.055);
4526            let deep_col: Vec3 = Vec3::new(0.005, 0.044, 0.118);
4527            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4528            let warp_a: f32 = Self::sky_value_noise(
4529                wpx * 0.075 - world_time * 0.14,
4530                wpz * 0.065 + world_time * 0.09,
4531            ) * 2.4;
4532            let wave_p: f32 =
4533                (wpx * 0.23 + wpz * 0.11 + warp_a - world_time * 1.35).sin() * 0.5 + 0.5;
4534            let cloud_var: f32 = 0.84
4535                + 0.24
4536                    * Self::sky_value_noise(
4537                        wpx * 0.018 - world_time * 0.025,
4538                        wpz * 0.018 + world_time * 0.015,
4539                    );
4540            let sw_t: f32 = (shore_d * (1.0 / 1.8)).clamp(0.0, 1.0);
4541            let seawall_shadow: f32 = 0.46 + 0.54 * (sw_t * sw_t * (3.0 - 2.0 * sw_t));
4542            let body_col: Vec3 = deep_col
4543                .lerp(shallow_col, shallow_t)
4544                .scale((0.92 + 0.16 * wave_p) * cloud_var * seawall_shadow);
4545            let surf_n: f32 = Self::sky_value_noise(
4546                wpx * 0.48 - world_time * 0.55,
4547                wpz * 0.34 + world_time * 0.18,
4548            );
4549            let surf_n2: f32 =
4550                Self::sky_value_noise(wpx * 1.35 + 3.1, wpz * 1.15 - world_time * 0.40);
4551            let surf_wave: f32 =
4552                (shore_d * 1.65 - world_time * 1.95 + surf_n * 3.4).sin() * 0.5 + 0.5;
4553            let shore_band: f32 = Self::fast_exp_neg_3d(shore_d * 0.38);
4554            let lace_t: f32 =
4555                ((surf_n * 0.62 + surf_n2 * 0.38 + shore_band * 0.42 - 0.32) * 2.5).clamp(0.0, 1.0);
4556            let lace: f32 = lace_t * lace_t * (3.0 - 2.0 * lace_t);
4557            let foam_aa: f32 = 1.0 - ((fw_xz - 0.25) * 1.0).clamp(0.0, 1.0);
4558            let foam_w: f32 = ((shore_band * (0.45 + 0.55 * surf_wave) * lace
4559                + Self::fast_exp_neg_3d(shore_d * 2.2) * 0.65)
4560                * foam_aa)
4561                .clamp(0.0, 0.94);
4562            let ocean_col: Vec3 = body_col.lerp(Vec3::new(0.84, 0.90, 0.94), foam_w);
4563            let ocean_refl: f32 = ((f_water * (1.0 - foam_w)) * inv_refl_f).clamp(0.0, 1.0);
4564            return (ocean_col, ocean_refl);
4565        }
4566        let tm: f32 = ((depth - 14.0) * (1.0 / 34.0)).clamp(0.0, 1.0);
4567        let micro_fade: f32 = (1.0 - tm * tm * (3.0 - 2.0 * tm))
4568            * (1.0 - ((fw_xz - 0.05) * (1.0 / 0.17)).clamp(0.0, 1.0));
4569        let agg_h: f32 = if micro_fade > 0.005 {
4570            let a0: f32 = Self::sky_value_noise(wpx * 8.5, wpz * 8.5);
4571            let a1: f32 = Self::sky_value_noise(wpx * 24.0 + 7.3, wpz * 24.0 - 4.1);
4572            a0.mul_add(0.48, a1 * 0.52)
4573        } else {
4574            0.5
4575        };
4576        let grain_n: f32 = agg_h - 0.5;
4577        let seam_u: f32 = Self::box_pulse(wpx * 0.45, 0.0, 0.045, fw_x * 0.45);
4578        let seam_v: f32 = Self::box_pulse(wpz * 0.45, 0.0, 0.045, fw_z * 0.45);
4579        let seam_cov: f32 = (seam_u + seam_v - seam_u * seam_v).clamp(0.0, 1.0);
4580        let tile_seam: f32 = 1.0 - 0.26 * seam_cov;
4581        if abs_u > 14.2 {
4582            let plaza_base: Vec3 = if d_spine < 64.0 {
4583                Vec3::new(0.32, 0.34, 0.37)
4584            } else {
4585                Vec3::new(0.26, 0.28, 0.32)
4586            };
4587            let east_mask: f32 = d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t);
4588            let seawall_coping: f32 = Self::box_band(wpx, 142.4, 144.0, fw_x) * east_mask;
4589            let seawall_lip: f32 = Self::box_band(wpx, 143.65, 144.0, fw_x) * east_mask;
4590            let sea_spray: f32 = Self::fast_exp_neg_3d((144.0 - wpx).max(0.0) * 0.65) * east_mask;
4591            let coping_col: Vec3 = Vec3::new(0.42, 0.44, 0.46)
4592                .lerp(Vec3::new(0.22, 0.24, 0.27), seawall_lip)
4593                .scale(1.0 - 0.28 * sea_spray);
4594            let land_col: Vec3 = plaza_base
4595                .scale(tile_seam)
4596                .lerp(coping_col, seawall_coping)
4597                .scale(1.0 + grain_n * 0.10 * micro_fade);
4598            let land_refl: f32 = ((0.025 + 0.04 * fresnel_t) * inv_refl_f).clamp(0.0, 1.0);
4599            if bay_w <= 1.0e-4 {
4600                return (land_col, land_refl);
4601            }
4602            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4603            let ocean_refl: f32 = (f_water * inv_refl_f).clamp(0.0, 1.0);
4604            return (
4605                land_col.lerp(shallow_col, bay_w),
4606                land_refl * (1.0 - bay_w) + ocean_refl * bay_w,
4607            );
4608        }
4609        let road_s: f32 = Self::eval_loop_arc_s(wpx, wpz);
4610        let curb_w: f32 = Self::box_step(abs_u, 10.2, fw_u);
4611        let walk_w: f32 = Self::box_step(abs_u, 10.8, fw_u);
4612        let om_curb: f32 = 1.0 - curb_w;
4613        let inner_lin: f32 = 1.0 - ((abs_u - 3.65).abs() * 0.85).clamp(0.0, 1.0);
4614        let outer_lin: f32 = 1.0 - ((abs_u - 6.85).abs() * 0.95).clamp(0.0, 1.0);
4615        let tire_wear: f32 =
4616            (inner_lin * inner_lin + outer_lin * outer_lin).clamp(0.0, 1.0) * om_curb;
4617        let gutter_band: f32 = (1.0 - ((abs_u - 9.55).abs() * 2.2).clamp(0.0, 1.0)) * om_curb;
4618        let cpg_t: f32 = ((10.18 - abs_u) * (1.0 / 0.46)).clamp(0.0, 1.0);
4619        let curb_pool_guard: f32 = cpg_t * cpg_t * (3.0 - 2.0 * cpg_t);
4620        let center_crown: f32 = (1.0 - (abs_u * 0.65).clamp(0.0, 1.0)) * om_curb;
4621        let tp_fade: f32 = ((depth - 54.0) * (1.0 / 86.0)).clamp(0.0, 1.0);
4622        let puddle_fade: f32 = 1.0 - tp_fade * tp_fade * (3.0 - 2.0 * tp_fade);
4623        let (wet_porosity, water_mask, water_depth): (f32, f32, f32) =
4624            if puddle_fade > 1.0e-3 && om_curb > 1.0e-3 {
4625                let n0: f32 = Self::sky_value_noise(wpx * 0.13 + 3.1, wpz * 0.075 - 1.7);
4626                let n1: f32 = Self::sky_value_noise(wpx * 0.38 - 5.4, wpz * 0.22 + 2.9);
4627                let n2: f32 = Self::sky_value_noise(wpx * 1.45 + 8.7, wpz * 1.05 - 4.3);
4628                let wet_field: f32 =
4629                    n0 * 0.56 + n1 * 0.28 + n2 * 0.16 + tire_wear * 0.13 + gutter_band * 0.17
4630                        - center_crown * 0.22;
4631                let wp_t: f32 = ((wet_field - 0.45) * (1.0 / 0.15)).clamp(0.0, 1.0);
4632                let wp_val: f32 = wp_t * wp_t * (3.0 - 2.0 * wp_t) * om_curb * puddle_fade;
4633                let shore_micro: f32 =
4634                    grain_n * 0.058 * (0.28 + 0.72 * micro_fade) + (n2 - 0.5) * 0.045;
4635                let puddle_h: f32 = wet_field + shore_micro;
4636                let shore_w: f32 = (0.020 + fw_xz * 0.042).clamp(0.020, 0.095);
4637                let wm_t: f32 = ((puddle_h - (0.60 - shore_w)) / (2.0 * shore_w)).clamp(0.0, 1.0);
4638                let wm_val: f32 =
4639                    wm_t * wm_t * (3.0 - 2.0 * wm_t) * om_curb * curb_pool_guard * puddle_fade;
4640                let wd_val: f32 = ((wet_field - 0.58) * 3.8).clamp(0.0, 1.0) * wm_val;
4641                (wp_val, wm_val, wd_val)
4642            } else {
4643                (0.0, 0.0, 0.0)
4644            };
4645        let dry_base: Vec3 = Vec3::new(
4646            base.get_x().mul_add(1.38, 0.036),
4647            base.get_y().mul_add(1.38, 0.038),
4648            base.get_z().mul_add(1.38, 0.042),
4649        );
4650        let dry_scale: f32 = (1.0 + grain_n * 0.34 * micro_fade)
4651            * (1.0 - 0.14 * tire_wear)
4652            * (1.0 - 0.22 * gutter_band);
4653        let mut road_col: Vec3 = dry_base.scale(dry_scale);
4654        let yellow_w: f32 = Self::box_band(abs_u, 0.135, 0.305, fw_u) * om_curb;
4655        if yellow_w > 0.005 {
4656            let paint_vis: f32 = 0.94 + grain_n * 0.16 * micro_fade;
4657            road_col = road_col.lerp(
4658                Vec3::new(0.92, 0.65, 0.10).scale(paint_vis),
4659                yellow_w * 0.95,
4660            );
4661        }
4662        let dash_on: f32 = Self::box_pulse(road_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4663        let lane_w: f32 = Self::box_band(abs_u, 4.565, 4.735, fw_u) * dash_on * om_curb;
4664        let shoulder_w: f32 = Self::box_band(abs_u, 9.15, 9.35, fw_u) * om_curb;
4665        let straight_t: f32 = ((134.0 - wpz.abs()) * 0.125).clamp(0.0, 1.0);
4666        let straight_w: f32 = straight_t * straight_t * (3.0 - 2.0 * straight_t);
4667        let cross_z_w: f32 = Self::box_pulse(
4668            (road_s + 18.0) * 0.02494481,
4669            0.455,
4670            0.545,
4671            fw_s * 0.02494481,
4672        ) * straight_w;
4673        let cross_x_w: f32 = Self::box_band(abs_u, 0.55, 8.65, fw_u);
4674        let cross_bar: f32 = Self::box_pulse(road_u * 0.85, 0.0, 0.50, fw_u * 0.85);
4675        let cross_w: f32 = cross_z_w * cross_x_w * cross_bar * 0.88 * om_curb;
4676        let white_w: f32 = shoulder_w.max(lane_w).max(cross_w);
4677        if white_w > 0.005 {
4678            let paint_vis: f32 = 0.92 + grain_n * 0.14 * micro_fade;
4679            road_col = road_col.lerp(Vec3::new(0.82, 0.85, 0.90).scale(paint_vis), white_w * 0.92);
4680        }
4681        let damp_col: Vec3 = Vec3::new(
4682            road_col.get_x().max(1.0e-4).powf(1.35) * 0.60,
4683            road_col.get_y().max(1.0e-4).powf(1.35) * 0.60,
4684            road_col.get_z().max(1.0e-4).powf(1.35) * 0.60,
4685        );
4686        let mut final_road_col: Vec3 = road_col.lerp(damp_col, wet_porosity);
4687        let mut ripple_mod: f32 = 0.0;
4688        if water_mask > 0.005 {
4689            let rf_d: f32 = 1.0 - ((depth - 24.0) * (1.0 / 48.0)).clamp(0.0, 1.0);
4690            let rf_w: f32 = ((water_depth - 0.03) * (1.0 / 0.23)).clamp(0.0, 1.0);
4691            let ripple_fade: f32 = rf_d * rf_d * (3.0 - 2.0 * rf_d) * rf_w;
4692            let (rx_rip, rz_rip): (f32, f32) = if ripple_fade > 0.005 {
4693                let rw1: f32 = wpx * 2.4 + wpz * 1.5 - world_time * 1.85;
4694                let rw2: f32 = -wpx * 1.8 + wpz * 3.1 - world_time * 2.35;
4695                let gx: f32 = ((rw1.cos() * 2.4 - rw2.cos() * 1.8) * 0.0028 * ripple_fade)
4696                    .clamp(-0.018, 0.018);
4697                let gz: f32 = ((rw1.cos() * 1.5 + rw2.cos() * 3.1) * 0.0028 * ripple_fade)
4698                    .clamp(-0.018, 0.018);
4699                ripple_mod = (gx + gz) * 1.6;
4700                (gx, gz)
4701            } else {
4702                (0.0, 0.0)
4703            };
4704            let inv_vy: f32 = 1.0 / (view_dir.get_y() + 0.35).max(0.35);
4705            let sh_x: f32 =
4706                -view_dir.get_x() * inv_vy * (water_depth * 0.032) + rx_rip * (water_depth * 1.65);
4707            let sh_z: f32 =
4708                -view_dir.get_z() * inv_vy * (water_depth * 0.032) + rz_rip * (water_depth * 1.65);
4709            let sub_u: f32 = road_u + sh_x * rad_x + sh_z * rad_z;
4710            let sub_abs_u: f32 = sub_u.abs();
4711            let sub_s: f32 = road_s + sh_x * tan_x + sh_z * tan_z;
4712            let mut sub_base: Vec3 = dry_base.scale(dry_scale);
4713            let sy_w: f32 = Self::box_band(sub_abs_u, 0.135, 0.305, fw_u) * om_curb;
4714            if sy_w > 0.005 {
4715                sub_base = sub_base.lerp(
4716                    Vec3::new(0.92, 0.65, 0.10).scale(0.92 + grain_n * 0.14 * micro_fade),
4717                    sy_w * 0.95,
4718                );
4719            }
4720            let sd_on: f32 = Self::box_pulse(sub_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4721            let sl_w: f32 = Self::box_band(sub_abs_u, 4.565, 4.735, fw_u) * sd_on * om_curb;
4722            let ss_w: f32 = Self::box_band(sub_abs_u, 9.15, 9.35, fw_u) * om_curb;
4723            let sc_z: f32 =
4724                Self::box_pulse((sub_s + 18.0) * 0.02494481, 0.455, 0.545, fw_s * 0.02494481)
4725                    * straight_w;
4726            let sc_w: f32 = sc_z
4727                * Self::box_band(sub_abs_u, 0.55, 8.65, fw_u)
4728                * Self::box_pulse(sub_u * 0.85, 0.0, 0.50, fw_u * 0.85)
4729                * 0.88
4730                * om_curb;
4731            let sw_w: f32 = ss_w.max(sl_w).max(sc_w);
4732            if sw_w > 0.005 {
4733                sub_base = sub_base.lerp(
4734                    Vec3::new(0.82, 0.85, 0.90).scale(0.90 + grain_n * 0.12 * micro_fade),
4735                    sw_w * 0.92,
4736                );
4737            }
4738            let meniscus_t: f32 = (water_depth * (1.0 / 0.22)).clamp(0.0, 1.0);
4739            let meniscus_rim: f32 =
4740                1.0 - 0.18 * (1.0 - meniscus_t * meniscus_t * (3.0 - 2.0 * meniscus_t));
4741            let sub_col: Vec3 = Vec3::new(
4742                sub_base.get_x().max(1.0e-4).powf(1.35)
4743                    * 0.58
4744                    * Self::fast_exp_neg_3d(water_depth * 1.15)
4745                    * meniscus_rim,
4746                sub_base.get_y().max(1.0e-4).powf(1.35)
4747                    * 0.58
4748                    * Self::fast_exp_neg_3d(water_depth * 0.88)
4749                    * meniscus_rim,
4750                sub_base.get_z().max(1.0e-4).powf(1.35)
4751                    * 0.58
4752                    * Self::fast_exp_neg_3d(water_depth * 0.72)
4753                    * meniscus_rim,
4754            );
4755            final_road_col = final_road_col.lerp(sub_col, water_mask);
4756        }
4757        let dry_target: f32 = 0.015 + 0.03 * fresnel_t + tire_wear * 0.015;
4758        let damp_target: f32 = 0.04 + 0.22 * fresnel_t;
4759        let water_target: f32 = (f_water + ripple_mod).clamp(0.02, 0.82);
4760        let surf_target: f32 = dry_target * (1.0 - wet_porosity) + damp_target * wet_porosity;
4761        let road_target_blend: f32 = surf_target * (1.0 - water_mask) + water_target * water_mask;
4762        let road_refl: f32 = (road_target_blend * inv_refl_f).clamp(0.0, 1.0);
4763        if curb_w <= 1.0e-4 && walk_w <= 1.0e-4 {
4764            return (final_road_col, road_refl);
4765        }
4766        let curb_col: Vec3 = Vec3::new(0.38, 0.40, 0.44).scale(1.0 + grain_n * 0.10 * micro_fade);
4767        let walk_col: Vec3 =
4768            Vec3::new(0.25, 0.27, 0.31).scale(tile_seam * (1.0 + grain_n * 0.10 * micro_fade));
4769        let final_col: Vec3 = final_road_col.lerp(curb_col, curb_w).lerp(walk_col, walk_w);
4770        let walk_refl: f32 = ((0.025 + 0.04 * fresnel_t) * inv_refl_f).clamp(0.0, 1.0);
4771        let final_refl: f32 = road_refl * om_curb + walk_refl * curb_w;
4772        (final_col, final_refl)
4773    }
4774
4775    /// Fast rational approximation of `exp(-x)` for `x >= 0.0` used in 3D coastal ocean optics.
4776    ///
4777    /// # Arguments
4778    ///
4779    /// - `f32` - Non-negative exponent magnitude `x`.
4780    ///
4781    /// # Returns
4782    ///
4783    /// - `f32` - Approximate `exp(-x)` in `(0.0, 1.0]`.
4784    #[inline(always)]
4785    #[must_use]
4786    fn fast_exp_neg_3d(pos_x: f32) -> f32 {
4787        if pos_x <= 0.0 {
4788            return 1.0;
4789        }
4790        let x2: f32 = pos_x * pos_x;
4791        1.0 / (1.0 + pos_x + 0.48 * x2 + 0.235 * x2 * pos_x)
4792    }
4793
4794    /// Branchless minimax polynomial approximation of `(sin(phase), cos(phase))` for animated 3D ocean waves.
4795    ///
4796    /// # Arguments
4797    ///
4798    /// - `f32` - Input phase angle in radians.
4799    ///
4800    /// # Returns
4801    ///
4802    /// - `(f32, f32)` - Approximate `(sin(phase), cos(phase))`.
4803    #[inline(always)]
4804    #[must_use]
4805    fn fast_sin_cos_3d(phase: f32) -> (f32, f32) {
4806        let quad_f: f32 = (phase * (2.0 / PI)).round();
4807        let rem_rad: f32 = phase - quad_f * FRAC_PI_2;
4808        let rem_sq: f32 = rem_rad * rem_rad;
4809        let sin_rem: f32 = rem_rad
4810            * (1.0 + rem_sq * (-0.166_666_57 + rem_sq * (0.008_333_026 - rem_sq * 0.000_198_074)));
4811        let cos_rem: f32 = 1.0 + rem_sq * (-0.5 + rem_sq * (0.041_666_64 - rem_sq * 0.001_388_839));
4812        match (quad_f as i32) & 3 {
4813            0 => (sin_rem, cos_rem),
4814            1 => (cos_rem, -sin_rem),
4815            2 => (-sin_rem, -cos_rem),
4816            _ => (-cos_rem, sin_rem),
4817        }
4818    }
4819
4820    /// Evaluates photorealistic animated Beer-Lambert liquid ocean radiance matching `/water` optics: 5-octave multi-directional Gerstner waves, Schlick Fresnel reflections, emerald subsurface wave-crest glow, foreground caustics, GGX sun glitter, animated shoreline sea-foam, and marine horizon mist.
4821    ///
4822    /// # Arguments
4823    ///
4824    /// - `&DeferredFrameContext` - Immutable per-frame camera, sun, and animation clock context.
4825    /// - `&[[f32; 3]]` - Pre-baked hemi-octahedral sky dome LUT.
4826    /// - `(Vec3, Vec3, f32)` - `(world_pos, unit_view_to_camera, linear_depth)`.
4827    /// - `(f32, Vec3)` - `(sun_shadow, rt_probe_reflection)`.
4828    ///
4829    /// # Returns
4830    ///
4831    /// - `Vec3` - Linear HDR ocean surface radiance prior to exposure and ACES tonemapping.
4832    #[inline(always)]
4833    #[must_use]
4834    fn eval_ocean_water_radiance(
4835        frame_context: &DeferredFrameContext,
4836        sky_lut: &[[f32; 3]],
4837        geom: (Vec3, Vec3, f32),
4838        lighting: (f32, Vec3),
4839    ) -> Vec3 {
4840        let (world_p, view_dir, depth): (Vec3, Vec3, f32) = geom;
4841        let (shadow, rt_refl): (f32, Vec3) = lighting;
4842        let sim_t: f32 = frame_context.world_time_secs;
4843        let wx_orig: f32 = world_p.get_x();
4844        let wz_orig: f32 = world_p.get_z();
4845        let pixel_foot: f32 = depth * frame_context.inv_height * 2.15;
4846        let mut wx: f32 = wx_orig;
4847        let mut wz: f32 = wz_orig;
4848        let mut wave_h: f32 = 0.0;
4849        let mut dh_dx: f32 = 0.0;
4850        let mut dh_dz: f32 = 0.0;
4851        for wave in OCEAN3D_WAVE_SPECTRUM.iter() {
4852            let freq: f32 = wave[2];
4853            let aa_arg: f32 = pixel_foot * freq * 0.30;
4854            if aa_arg > 3.8 {
4855                break;
4856            }
4857            let dir_x: f32 = wave[0];
4858            let dir_z: f32 = wave[1];
4859            let amp: f32 = wave[3];
4860            let aa_sq: f32 = aa_arg * aa_arg;
4861            let aa_w: f32 = 1.0 / (1.0 + aa_sq);
4862            let phase: f32 = (wx * dir_x + wz * dir_z) * freq + sim_t * wave[4];
4863            let (sin_p, cos_p): (f32, f32) = Self::fast_sin_cos_3d(phase);
4864            let sharp_e: f32 = Self::fast_exp_neg_3d(1.0 - sin_p);
4865            wave_h += amp * (sharp_e - 0.40) * aa_w;
4866            let slope: f32 = amp * freq * sharp_e * cos_p * aa_w;
4867            dh_dx += slope * dir_x;
4868            dh_dz += slope * dir_z;
4869            let warp_s: f32 = cos_p * amp * 0.78 * aa_w;
4870            wx += warp_s * dir_x;
4871            wz += warp_s * dir_z;
4872        }
4873        if pixel_foot < 0.90 {
4874            let cap_aa: f32 = 1.0 / (1.0 + (pixel_foot * 3.8) * (pixel_foot * 3.8));
4875            let c1: f32 = Self::fast_sin_cos_3d(wx_orig * 2.6 + wz_orig * 3.8 + sim_t * 3.4).1
4876                * 0.085
4877                * cap_aa;
4878            let c2: f32 = Self::fast_sin_cos_3d(-wx_orig * 3.4 + wz_orig * 4.2 - sim_t * 4.1).1
4879                * 0.068
4880                * cap_aa;
4881            dh_dx += c1 * 0.58 - c2 * 0.62;
4882            dh_dz += c1 * 0.81 + c2 * 0.78;
4883        }
4884        let near_steep: f32 = 1.48 + 0.58 * Self::fast_exp_neg_3d(depth * 0.015);
4885        dh_dx *= near_steep;
4886        dh_dz *= near_steep;
4887        let inv_nlen: f32 = 1.0 / (dh_dx * dh_dx + 1.0 + dh_dz * dh_dz).sqrt();
4888        let nx: f32 = -dh_dx * inv_nlen;
4889        let ny: f32 = inv_nlen;
4890        let nz: f32 = -dh_dz * inv_nlen;
4891        let vx: f32 = view_dir.get_x();
4892        let vy: f32 = view_dir.get_y();
4893        let vz: f32 = view_dir.get_z();
4894        let ndv: f32 = (nx * vx + ny * vy + nz * vz).clamp(0.004, 1.0);
4895        let om_ndv: f32 = 1.0 - ndv;
4896        let om2: f32 = om_ndv * om_ndv;
4897        let fresnel: f32 = (0.0204 + 0.9796 * om2 * om2 * om_ndv).clamp(0.024, 0.84);
4898        let two_ndv: f32 = 2.0 * ndv;
4899        let refl_dir: Vec3 = Vec3::new(
4900            two_ndv * nx - vx,
4901            (two_ndv * ny - vy).max(0.010),
4902            two_ndv * nz - vz,
4903        );
4904        let sky_raw: Vec3 = Self::sample_sky_lut(sky_lut, refl_dir, &frame_context.sun);
4905        let sun_dir: Vec3 = frame_context.sun.get_direction();
4906        let sun_col: Vec3 = frame_context.sun.get_color();
4907        let sun_luma: f32 =
4908            (sun_col.get_x() * 0.30 + sun_col.get_y() * 0.55 + sun_col.get_z() * 0.15)
4909                .clamp(0.45, 1.40);
4910        let az_dx: f32 = refl_dir.get_x() - sun_dir.get_x();
4911        let az_dz: f32 = refl_dir.get_z() - sun_dir.get_z();
4912        let az_dist_sq: f32 = az_dx * az_dx + az_dz * az_dz;
4913        let sun_az_glow: f32 = Self::fast_exp_neg_3d(az_dist_sq * 48.0);
4914        let sky_elev: f32 = (refl_dir.get_y() * 2.4).clamp(0.0, 1.0);
4915        let sky_fade: f32 = 1.0 - sky_elev * 0.72;
4916        let marine_refl: Vec3 = Vec3::new(
4917            ((0.003 * sky_fade + 0.18 * sun_az_glow) * sun_luma)
4918                + sky_raw.get_x().min(1.2) * (0.025 + 0.14 * sun_az_glow),
4919            ((0.068 * sky_fade + 0.16 * sun_az_glow) * sun_luma)
4920                + sky_raw.get_y().min(1.2) * (0.12 + 0.10 * sun_az_glow),
4921            ((0.142 * sky_fade + 0.11 * sun_az_glow) * sun_luma)
4922                + sky_raw.get_z().min(1.2) * (0.20 + 0.08 * sun_az_glow),
4923        );
4924        let near_sss: f32 = 0.24 + 0.76 * Self::fast_exp_neg_3d(depth * 0.0065);
4925        let crest_elev: f32 = ((wave_h + 0.075) * 3.35).clamp(0.0, 1.0);
4926        let sss_back: f32 =
4927            (-(vx * sun_dir.get_x() + vy * sun_dir.get_y() + vz * sun_dir.get_z()) * 0.5 + 0.5)
4928                .clamp(0.0, 1.0);
4929        let sss_term: f32 = crest_elev * crest_elev * (0.42 + 0.58 * sss_back) * near_sss;
4930        let caustic: f32 = if depth < 76.0 {
4931            let cf: f32 = Self::fast_exp_neg_3d(depth * 0.036) * (1.0 - fresnel);
4932            let c_warp: f32 =
4933                Self::sky_value_noise(wx_orig * 0.24 + sim_t * 0.18, wz_orig * 0.24 - sim_t * 0.14)
4934                    * 2.8;
4935            let ca: f32 =
4936                Self::fast_sin_cos_3d(wx_orig * 0.62 + wz_orig * 0.44 + c_warp + sim_t * 1.15).0;
4937            let cb: f32 = Self::fast_sin_cos_3d(
4938                -wx_orig * 0.48 + wz_orig * 0.78 - c_warp * 0.7 - sim_t * 0.92,
4939            )
4940            .1;
4941            let cn: f32 = (ca * 0.55 + cb * 0.45).abs();
4942            cn * cn * cf * 0.16
4943        } else {
4944            0.0
4945        };
4946        let body_col: Vec3 = Vec3::new(
4947            (0.0004 + 0.0020 * sss_term) * sun_luma,
4948            (0.052 + 0.365 * sss_term + caustic * 0.92) * sun_luma,
4949            (0.105 + 0.480 * sss_term + caustic * 1.14) * sun_luma,
4950        );
4951        let hx_u: f32 = vx + sun_dir.get_x();
4952        let hy_u: f32 = vy + sun_dir.get_y();
4953        let hz_u: f32 = vz + sun_dir.get_z();
4954        let inv_hlen: f32 = 1.0 / (hx_u * hx_u + hy_u * hy_u + hz_u * hz_u).sqrt().max(1.0e-5);
4955        let ndh: f32 = ((nx * hx_u + ny * hy_u + nz * hz_u) * inv_hlen).max(0.0);
4956        let ndh2: f32 = ndh * ndh;
4957        let a1_sq: f32 = 0.000_095;
4958        let d1_den: f32 = ndh2 * (a1_sq - 1.0) + 1.0;
4959        let ggx_tight: f32 = (a1_sq / (PI * d1_den * d1_den)).min(28.0);
4960        let a2_sq: f32 = 0.000_52;
4961        let d2_den: f32 = ndh2 * (a2_sq - 1.0) + 1.0;
4962        let ggx_mid: f32 = (a2_sq / (PI * d2_den * d2_den)).min(5.2);
4963        let glint_t: f32 = ((ndh - 0.980) * (1.0 / 0.018)).clamp(0.0, 1.0);
4964        let glint_sharp: f32 = glint_t * glint_t * (3.0 - 2.0 * glint_t);
4965        let spec_scale: f32 =
4966            (ggx_tight * 0.56 + ggx_mid * 0.12 + glint_sharp * 0.68) * (0.45 + 0.55 * shadow);
4967        let spec_col: Vec3 = sun_col.scale(spec_scale);
4968        let near_shore_rt: f32 = Self::fast_exp_neg_3d(depth * 0.026) * 0.24;
4969        let combined_refl: Vec3 = marine_refl.lerp(rt_refl, near_shore_rt);
4970        let refl_weight: f32 = (fresnel * 0.50 + 0.022).clamp(0.022, 0.58);
4971        let mut col: Vec3 = body_col.lerp(combined_refl, refl_weight).add(spec_col);
4972        let dx_shore: f32 = (wx_orig.abs() - CITY_ISLAND_HALF_X).max(0.0);
4973        let dz_shore: f32 = (CITY_ISLAND_Z_MIN - wz_orig)
4974            .max(0.0)
4975            .max((wz_orig - CITY_ISLAND_Z_MAX).max(0.0));
4976        if dx_shore < 4.8 && dz_shore < 4.8 {
4977            let shore_dist: f32 = (dx_shore * dx_shore + dz_shore * dz_shore).sqrt();
4978            if shore_dist < 4.8 {
4979                let surge: f32 =
4980                    Self::fast_sin_cos_3d(sim_t * 2.1 + wx_orig * 0.35 + wz_orig * 0.35).0 * 0.55;
4981                let eff_dist: f32 = (shore_dist + surge).max(0.0);
4982                let band_lin: f32 = 1.0 - (eff_dist * (1.0 / 3.6)).clamp(0.0, 1.0);
4983                let foam_band: f32 = band_lin * band_lin;
4984                let lacy_a: f32 = Self::sky_value_noise(wx_orig * 1.45 + 3.7, wz_orig * 1.45 - 2.1);
4985                let lacy_b: f32 = Self::sky_value_noise(
4986                    wx_orig * 3.8 - sim_t * 0.55,
4987                    wz_orig * 3.8 + sim_t * 0.42,
4988                );
4989                let foam_t: f32 = ((lacy_a * 0.55 + lacy_b * 0.45 - 0.36) * 2.4).clamp(0.0, 1.0);
4990                let foam_alpha: f32 =
4991                    (foam_band * (0.28 + 0.72 * foam_t * foam_t * (3.0 - 2.0 * foam_t)) * 0.84)
4992                        .clamp(0.0, 0.85);
4993                if foam_alpha > 0.01 {
4994                    let foam_col: Vec3 = Vec3::new(0.84, 0.90, 0.94).scale(0.65 + 0.45 * sun_luma);
4995                    col = col.lerp(foam_col, foam_alpha);
4996                }
4997            }
4998        }
4999        if frame_context.fog_on {
5000            let fog_t: f32 = (1.0 - Self::fast_exp_neg_3d(depth * 0.000_65)).clamp(0.0, 0.22);
5001            if fog_t > 0.005 {
5002                let horiz_raw: Vec3 = frame_context.sun.get_sky_horizon();
5003                let marine_mist: Vec3 = Vec3::new(
5004                    (0.010 + 0.06 * sun_az_glow) * sun_luma + horiz_raw.get_x().min(1.0) * 0.05,
5005                    (0.068 + 0.05 * sun_az_glow) * sun_luma + horiz_raw.get_y().min(1.0) * 0.12,
5006                    (0.118 + 0.04 * sun_az_glow) * sun_luma + horiz_raw.get_z().min(1.0) * 0.18,
5007                );
5008                col = col.lerp(marine_mist, fog_t);
5009            }
5010        }
5011        col
5012    }
5013
5014    /// Evaluates a pipelined 4-wide reciprocal `1.0 / x` via NEON estimate plus one Newton-Raphson refinement (~22-bit precision, eliminating divider stalls).
5015    ///
5016    /// # Arguments
5017    ///
5018    /// - `core::arch::aarch64::float32x4_t` - Strictly positive denominator vector `x`.
5019    ///
5020    /// # Returns
5021    ///
5022    /// - `core::arch::aarch64::float32x4_t` - Refined 4-wide reciprocal `1.0 / x`.
5023    #[cfg(target_arch = "aarch64")]
5024    #[inline(always)]
5025    pub(crate) unsafe fn neon_rcp_4x(
5026        pos_x: core::arch::aarch64::float32x4_t,
5027    ) -> core::arch::aarch64::float32x4_t {
5028        // SAFETY: Caller guarantees ARM64 NEON execution context and positive `x`.
5029        unsafe {
5030            let est: core::arch::aarch64::float32x4_t = core::arch::aarch64::vrecpeq_f32(pos_x);
5031            core::arch::aarch64::vmulq_f32(est, core::arch::aarch64::vrecpsq_f32(pos_x, est))
5032        }
5033    }
5034
5035    /// Const-specialized vectorized 4-pixel Cook-Torrance GGX PBR, procedural surface detail (`0=Plain`, `1=Road`, `2=Facade`), reflection, volumetric fog, and ACES tonemap kernel reading from L1 `RunScratch32` at `off`.
5036    ///
5037    /// # Arguments
5038    ///
5039    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and fog configuration.
5040    /// - `&GShadeTri` - Precomputed triangle PBR record shared by the run.
5041    /// - `(Vec3, Vec3)` - Starting unnormalized primary ray and horizontal ray step `(raw_ray, ray_dx)`.
5042    /// - `(&RunScratch32, usize)` - L1-hot run scratch and 4-pixel-aligned lane offset `off <= 28`.
5043    /// - `SpanShadeOut<'_>` - Writable 16-byte RGBA, 4-byte luma, and optional HDR bloom slot.
5044    ///
5045    /// # Returns
5046    ///
5047    /// - `bool` - `true` when the optional bloom slot received non-zero HDR excess radiance.
5048    #[inline(always)]
5049    fn shade_span_4x_specialized<const DETAIL: u8>(
5050        frame_context: &DeferredFrameContext,
5051        tri: &GShadeTri,
5052        rays: (Vec3, Vec3),
5053        src_run: (&RunScratch32, usize),
5054        dst: SpanShadeOut<'_>,
5055    ) -> bool {
5056        let (raw_ray, ray_dx): (Vec3, Vec3) = rays;
5057        let (run, off): (&RunScratch32, usize) = src_run;
5058        let SpanShadeOut {
5059            rgba: c_dst,
5060            luma: l_dst,
5061            bloom: bloom_slot,
5062        } = dst;
5063        let sun_dir: Vec3 = frame_context.sun.get_direction();
5064        let sun_col: Vec3 = frame_context.sun.get_color();
5065        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
5066        let sn: Vec3 = tri.shade_n;
5067        let mut exp_r_arr: [f32; 4] = [0.0; 4];
5068        let mut exp_g_arr: [f32; 4] = [0.0; 4];
5069        let mut exp_b_arr: [f32; 4] = [0.0; 4];
5070        #[cfg(target_arch = "aarch64")]
5071        {
5072            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; NEON is mandatory on `aarch64`.
5073            unsafe {
5074                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
5075                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
5076                let two: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(2.0);
5077                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5078                let lane_idx: core::arch::aarch64::float32x4_t =
5079                    core::arch::aarch64::vld1q_f32(lane_idx_arr.as_ptr());
5080                let rx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5081                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_x()),
5082                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_x()),
5083                    lane_idx,
5084                );
5085                let ry: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5086                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_y()),
5087                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_y()),
5088                    lane_idx,
5089                );
5090                let rz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5091                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_z()),
5092                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_z()),
5093                    lane_idx,
5094                );
5095                let len_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5096                    core::arch::aarch64::vfmaq_f32(
5097                        core::arch::aarch64::vfmaq_f32(
5098                            core::arch::aarch64::vmulq_f32(rz, rz),
5099                            ry,
5100                            ry,
5101                        ),
5102                        rx,
5103                        rx,
5104                    ),
5105                    core::arch::aarch64::vdupq_n_f32(1e-12),
5106                );
5107                let mut inv_l: core::arch::aarch64::float32x4_t =
5108                    core::arch::aarch64::vrsqrteq_f32(len_sq);
5109                inv_l = core::arch::aarch64::vmulq_f32(
5110                    inv_l,
5111                    core::arch::aarch64::vrsqrtsq_f32(
5112                        core::arch::aarch64::vmulq_f32(len_sq, inv_l),
5113                        inv_l,
5114                    ),
5115                );
5116                let ndv_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5117                    core::arch::aarch64::vdupq_n_f32(-sn.dot(raw_ray)),
5118                    core::arch::aarch64::vdupq_n_f32(-sn.dot(ray_dx)),
5119                    lane_idx,
5120                );
5121                let ndv_raw: core::arch::aarch64::float32x4_t =
5122                    core::arch::aarch64::vmulq_f32(ndv_num, inv_l);
5123                let ndv: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5124                    core::arch::aarch64::vmaxq_f32(ndv_raw, core::arch::aarch64::vdupq_n_f32(0.02)),
5125                    one,
5126                );
5127                let f_om: core::arch::aarch64::float32x4_t =
5128                    core::arch::aarch64::vsubq_f32(one, ndv);
5129                let f_om2: core::arch::aarch64::float32x4_t =
5130                    core::arch::aarch64::vmulq_f32(f_om, f_om);
5131                let fresnel_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5132                    core::arch::aarch64::vmulq_f32(f_om2, f_om2),
5133                    f_om,
5134                );
5135                let vdl_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5136                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(raw_ray)),
5137                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(ray_dx)),
5138                    lane_idx,
5139                );
5140                let vdl: core::arch::aarch64::float32x4_t =
5141                    core::arch::aarch64::vmulq_f32(vdl_num, inv_l);
5142                let sh_v: core::arch::aarch64::float32x4_t =
5143                    core::arch::aarch64::vld1q_f32(run.shadow.as_ptr().add(off));
5144                let (spec_r, spec_g, spec_b): (
5145                    core::arch::aarch64::float32x4_t,
5146                    core::arch::aarch64::float32x4_t,
5147                    core::arch::aarch64::float32x4_t,
5148                ) = if tri.n_dot_l > 0.0 {
5149                    let ndl_v: core::arch::aarch64::float32x4_t =
5150                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l);
5151                    let ndh_u: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5152                        core::arch::aarch64::vaddq_f32(ndl_v, ndv_raw),
5153                        zero,
5154                    );
5155                    let h_lsq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5156                        core::arch::aarch64::vfmaq_f32(two, two, vdl),
5157                        core::arch::aarch64::vdupq_n_f32(1e-6),
5158                    );
5159                    let ndh_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5160                        core::arch::aarch64::vmulq_f32(ndh_u, ndh_u),
5161                        Self::neon_rcp_4x(h_lsq),
5162                    );
5163                    let ggx_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5164                        one,
5165                        ndh_sq,
5166                        core::arch::aarch64::vdupq_n_f32(tri.alpha2 - 1.0),
5167                    );
5168                    let ggx_term: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5169                        core::arch::aarch64::vdupq_n_f32(1e-4),
5170                        core::arch::aarch64::vmulq_f32(ggx_den, ggx_den),
5171                        core::arch::aarch64::vdupq_n_f32(PI),
5172                    );
5173                    let vis_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5174                        core::arch::aarch64::vdupq_n_f32(0.08),
5175                        ndv,
5176                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l.max(0.06)),
5177                    );
5178                    let spec_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5179                        core::arch::aarch64::vdupq_n_f32(0.25 * tri.alpha2 * tri.n_dot_l),
5180                        sh_v,
5181                    );
5182                    let spec_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5183                        core::arch::aarch64::vmulq_f32(
5184                            spec_num,
5185                            Self::neon_rcp_4x(core::arch::aarch64::vmulq_f32(ggx_term, vis_den)),
5186                        ),
5187                        core::arch::aarch64::vdupq_n_f32(4.5),
5188                    );
5189                    let fr_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5190                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_x()),
5191                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_x()),
5192                        fresnel_t,
5193                    );
5194                    let fr_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5195                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_y()),
5196                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_y()),
5197                        fresnel_t,
5198                    );
5199                    let fr_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5200                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_z()),
5201                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_z()),
5202                        fresnel_t,
5203                    );
5204                    (
5205                        core::arch::aarch64::vmulq_f32(
5206                            fr_r,
5207                            core::arch::aarch64::vmulq_f32(
5208                                core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5209                                spec_s,
5210                            ),
5211                        ),
5212                        core::arch::aarch64::vmulq_f32(
5213                            fr_g,
5214                            core::arch::aarch64::vmulq_f32(
5215                                core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5216                                spec_s,
5217                            ),
5218                        ),
5219                        core::arch::aarch64::vmulq_f32(
5220                            fr_b,
5221                            core::arch::aarch64::vmulq_f32(
5222                                core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5223                                spec_s,
5224                            ),
5225                        ),
5226                    )
5227                } else {
5228                    (zero, zero, zero)
5229                };
5230                let d_v: core::arch::aarch64::float32x4_t =
5231                    core::arch::aarch64::vld1q_f32(run.depths.as_ptr().add(off));
5232                let wpy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5233                    core::arch::aarch64::vdupq_n_f32(frame_context.camera_position.get_y()),
5234                    ry,
5235                    d_v,
5236                );
5237                let mut sb_r: core::arch::aarch64::float32x4_t =
5238                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_x());
5239                let mut sb_g: core::arch::aarch64::float32x4_t =
5240                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_y());
5241                let mut sb_b: core::arch::aarch64::float32x4_t =
5242                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_z());
5243                let mut em_r: core::arch::aarch64::float32x4_t =
5244                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_x());
5245                let mut em_g: core::arch::aarch64::float32x4_t =
5246                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_y());
5247                let mut em_b: core::arch::aarch64::float32x4_t =
5248                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_z());
5249                let mut s_refl: core::arch::aarch64::float32x4_t =
5250                    core::arch::aarch64::vdupq_n_f32(tri.mat_refl);
5251                if DETAIL == 2 {
5252                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
5253                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
5254                        wall_tan_x,
5255                        frame_context.camera_position.get_z() * wall_tan_z,
5256                    );
5257                    let ray_u: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5258                        core::arch::aarch64::vmulq_n_f32(rx, wall_tan_x),
5259                        rz,
5260                        core::arch::aarch64::vdupq_n_f32(wall_tan_z),
5261                    );
5262                    let u_coord_v: core::arch::aarch64::float32x4_t =
5263                        core::arch::aarch64::vfmaq_f32(
5264                            core::arch::aarch64::vdupq_n_f32(cam_u),
5265                            ray_u,
5266                            d_v,
5267                        );
5268                    let mut u_a: [f32; 4] = [0.0; 4];
5269                    let mut y_a: [f32; 4] = [0.0; 4];
5270                    let mut d_a: [f32; 4] = [0.0; 4];
5271                    core::arch::aarch64::vst1q_f32(u_a.as_mut_ptr(), u_coord_v);
5272                    core::arch::aarch64::vst1q_f32(y_a.as_mut_ptr(), wpy);
5273                    core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5274                    let mut nr_a: [f32; 4] = [0.0; 4];
5275                    let mut ng_a: [f32; 4] = [0.0; 4];
5276                    let mut nb_a: [f32; 4] = [0.0; 4];
5277                    let mut er_a: [f32; 4] = [0.0; 4];
5278                    let mut eg_a: [f32; 4] = [0.0; 4];
5279                    let mut eb_a: [f32; 4] = [0.0; 4];
5280                    let mut rf_a: [f32; 4] = [0.0; 4];
5281                    for lane in 0..4usize {
5282                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5283                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5284                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5285                        );
5286                        nr_a[lane] = sb.get_x();
5287                        ng_a[lane] = sb.get_y();
5288                        nb_a[lane] = sb.get_z();
5289                        er_a[lane] = em.get_x();
5290                        eg_a[lane] = em.get_y();
5291                        eb_a[lane] = em.get_z();
5292                        rf_a[lane] = rf;
5293                    }
5294                    sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5295                    sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5296                    sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5297                    em_r = core::arch::aarch64::vld1q_f32(er_a.as_ptr());
5298                    em_g = core::arch::aarch64::vld1q_f32(eg_a.as_ptr());
5299                    em_b = core::arch::aarch64::vld1q_f32(eb_a.as_ptr());
5300                    s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5301                } else if DETAIL == 1 {
5302                    let m_r: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
5303                        core::arch::aarch64::vabsq_f32(wpy),
5304                        core::arch::aarch64::vdupq_n_f32(0.15),
5305                    );
5306                    if core::arch::aarch64::vmaxvq_u32(m_r) != 0 {
5307                        let wpx_v: core::arch::aarch64::float32x4_t =
5308                            core::arch::aarch64::vfmaq_f32(
5309                                core::arch::aarch64::vdupq_n_f32(
5310                                    frame_context.camera_position.get_x(),
5311                                ),
5312                                rx,
5313                                d_v,
5314                            );
5315                        let wpz_v: core::arch::aarch64::float32x4_t =
5316                            core::arch::aarch64::vfmaq_f32(
5317                                core::arch::aarch64::vdupq_n_f32(
5318                                    frame_context.camera_position.get_z(),
5319                                ),
5320                                rz,
5321                                d_v,
5322                            );
5323                        let mut x_a: [f32; 4] = [0.0; 4];
5324                        let mut z_a: [f32; 4] = [0.0; 4];
5325                        let mut d_a: [f32; 4] = [0.0; 4];
5326                        let mut rx_a: [f32; 4] = [0.0; 4];
5327                        let mut ry_a: [f32; 4] = [0.0; 4];
5328                        let mut rz_a: [f32; 4] = [0.0; 4];
5329                        let mut ft_a: [f32; 4] = [0.0; 4];
5330                        let mut m_a: [u32; 4] = [0; 4];
5331                        core::arch::aarch64::vst1q_f32(x_a.as_mut_ptr(), wpx_v);
5332                        core::arch::aarch64::vst1q_f32(z_a.as_mut_ptr(), wpz_v);
5333                        core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5334                        core::arch::aarch64::vst1q_f32(rx_a.as_mut_ptr(), rx);
5335                        core::arch::aarch64::vst1q_f32(ry_a.as_mut_ptr(), ry);
5336                        core::arch::aarch64::vst1q_f32(rz_a.as_mut_ptr(), rz);
5337                        core::arch::aarch64::vst1q_f32(ft_a.as_mut_ptr(), fresnel_t);
5338                        core::arch::aarch64::vst1q_u32(m_a.as_mut_ptr(), m_r);
5339                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
5340                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
5341                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
5342                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
5343                        for lane in 0..4usize {
5344                            if m_a[lane] != 0 {
5345                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
5346                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
5347                                    (
5348                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
5349                                        ft_a[lane],
5350                                        tri.metallic,
5351                                        frame_context.world_time_secs,
5352                                    ),
5353                                    tri.mat_base,
5354                                );
5355                                nr_a[lane] = sb.get_x();
5356                                ng_a[lane] = sb.get_y();
5357                                nb_a[lane] = sb.get_z();
5358                                rf_a[lane] = rf;
5359                            }
5360                        }
5361                        sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5362                        sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5363                        sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5364                        s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5365                    }
5366                }
5367                let kd_scale: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5368                    core::arch::aarch64::vmulq_f32(
5369                        core::arch::aarch64::vdupq_n_f32(tri.diffuse_scale),
5370                        core::arch::aarch64::vfmsq_f32(
5371                            one,
5372                            fresnel_t,
5373                            core::arch::aarch64::vdupq_n_f32(0.55),
5374                        ),
5375                    ),
5376                    core::arch::aarch64::vdupq_n_f32(0.08),
5377                );
5378                let dir_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5379                    core::arch::aarch64::vmulq_f32(
5380                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l),
5381                        sh_v,
5382                    ),
5383                    kd_scale,
5384                );
5385                let ao_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5386                    core::arch::aarch64::vld1q_f32(run.ao.as_ptr().add(off)),
5387                    core::arch::aarch64::vdupq_n_f32(0.44),
5388                );
5389                let lit_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5390                    core::arch::aarch64::vfmaq_f32(
5391                        core::arch::aarch64::vld1q_f32(run.gi_r.as_ptr().add(off)),
5392                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_x()),
5393                        ao_s,
5394                    ),
5395                    core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5396                    dir_s,
5397                );
5398                let lit_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5399                    core::arch::aarch64::vfmaq_f32(
5400                        core::arch::aarch64::vld1q_f32(run.gi_g.as_ptr().add(off)),
5401                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_y()),
5402                        ao_s,
5403                    ),
5404                    core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5405                    dir_s,
5406                );
5407                let lit_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5408                    core::arch::aarch64::vfmaq_f32(
5409                        core::arch::aarch64::vld1q_f32(run.gi_b.as_ptr().add(off)),
5410                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_z()),
5411                        ao_s,
5412                    ),
5413                    core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5414                    dir_s,
5415                );
5416                let mut rad_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5417                    core::arch::aarch64::vfmaq_f32(spec_r, sb_r, lit_r),
5418                    em_r,
5419                );
5420                let mut rad_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5421                    core::arch::aarch64::vfmaq_f32(spec_g, sb_g, lit_g),
5422                    em_g,
5423                );
5424                let mut rad_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5425                    core::arch::aarch64::vfmaq_f32(spec_b, sb_b, lit_b),
5426                    em_b,
5427                );
5428                if tri.do_refl {
5429                    let refl_f: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5430                        core::arch::aarch64::vmaxq_f32(
5431                            core::arch::aarch64::vfmaq_f32(
5432                                core::arch::aarch64::vdupq_n_f32(0.18 + tri.metallic * 0.25),
5433                                fresnel_t,
5434                                core::arch::aarch64::vdupq_n_f32(0.82),
5435                            ),
5436                            core::arch::aarch64::vdupq_n_f32(0.18),
5437                        ),
5438                        core::arch::aarch64::vdupq_n_f32(0.95),
5439                    );
5440                    let refl_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5441                        core::arch::aarch64::vmaxq_f32(
5442                            core::arch::aarch64::vmulq_f32(s_refl, refl_f),
5443                            zero,
5444                        ),
5445                        core::arch::aarch64::vdupq_n_f32(0.82),
5446                    );
5447                    let rr_v: core::arch::aarch64::float32x4_t =
5448                        core::arch::aarch64::vld1q_f32(run.refl_r.as_ptr().add(off));
5449                    let rg_v: core::arch::aarch64::float32x4_t =
5450                        core::arch::aarch64::vld1q_f32(run.refl_g.as_ptr().add(off));
5451                    let rb_v: core::arch::aarch64::float32x4_t =
5452                        core::arch::aarch64::vld1q_f32(run.refl_b.as_ptr().add(off));
5453                    rad_r = Self::neon_lerp_4x(rad_r, rr_v, refl_b);
5454                    rad_g = Self::neon_lerp_4x(rad_g, rg_v, refl_b);
5455                    rad_b = Self::neon_lerp_4x(rad_b, rb_v, refl_b);
5456                }
5457                if frame_context.fog_on {
5458                    let pos_y: core::arch::aarch64::float32x4_t =
5459                        core::arch::aarch64::vmaxq_f32(wpy, zero);
5460                    let h_att: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5461                        Self::neon_rcp_4x(core::arch::aarch64::vfmaq_f32(
5462                            one,
5463                            pos_y,
5464                            core::arch::aarch64::vdupq_n_f32(0.045),
5465                        )),
5466                        core::arch::aarch64::vdupq_n_f32(0.32),
5467                    );
5468                    let fd: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5469                        core::arch::aarch64::vmulq_f32(
5470                            d_v,
5471                            core::arch::aarch64::vdupq_n_f32(frame_context.inv_fog_distance),
5472                        ),
5473                        h_att,
5474                    );
5475                    let fog_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5476                        core::arch::aarch64::vmaxq_f32(
5477                            core::arch::aarch64::vmulq_f32(
5478                                fd,
5479                                Self::neon_rcp_4x(core::arch::aarch64::vaddq_f32(one, fd)),
5480                            ),
5481                            zero,
5482                        ),
5483                        core::arch::aarch64::vdupq_n_f32(0.85),
5484                    );
5485                    let sun_align: core::arch::aarch64::float32x4_t =
5486                        core::arch::aarch64::vmaxq_f32(core::arch::aarch64::vnegq_f32(vdl), zero);
5487                    let sa2: core::arch::aarch64::float32x4_t =
5488                        core::arch::aarch64::vmulq_f32(sun_align, sun_align);
5489                    let shaft55: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5490                        core::arch::aarch64::vmulq_f32(
5491                            core::arch::aarch64::vmulq_f32(sa2, sa2),
5492                            fog_t,
5493                        ),
5494                        core::arch::aarch64::vfmaq_f32(
5495                            core::arch::aarch64::vdupq_n_f32(0.35 * 0.55),
5496                            sh_v,
5497                            core::arch::aarch64::vdupq_n_f32(0.65 * 0.55),
5498                        ),
5499                    );
5500                    let fog_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5501                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_x()),
5502                        core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5503                        shaft55,
5504                    );
5505                    let fog_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5506                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_y()),
5507                        core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5508                        shaft55,
5509                    );
5510                    let fog_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5511                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_z()),
5512                        core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5513                        shaft55,
5514                    );
5515                    rad_r = Self::neon_lerp_4x(rad_r, fog_r, fog_t);
5516                    rad_g = Self::neon_lerp_4x(rad_g, fog_g, fog_t);
5517                    rad_b = Self::neon_lerp_4x(rad_b, fog_b, fog_t);
5518                }
5519                let exp_s: core::arch::aarch64::float32x4_t =
5520                    core::arch::aarch64::vdupq_n_f32(frame_context.exposure_scale);
5521                core::arch::aarch64::vst1q_f32(
5522                    exp_r_arr.as_mut_ptr(),
5523                    core::arch::aarch64::vmulq_f32(rad_r, exp_s),
5524                );
5525                core::arch::aarch64::vst1q_f32(
5526                    exp_g_arr.as_mut_ptr(),
5527                    core::arch::aarch64::vmulq_f32(rad_g, exp_s),
5528                );
5529                core::arch::aarch64::vst1q_f32(
5530                    exp_b_arr.as_mut_ptr(),
5531                    core::arch::aarch64::vmulq_f32(rad_b, exp_s),
5532                );
5533            }
5534        }
5535        #[cfg(target_arch = "x86_64")]
5536        {
5537            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; SSE2 is mandatory on `x86_64`.
5538            unsafe {
5539                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
5540                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
5541                let two: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(2.0);
5542                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
5543                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5544                let lane_idx: core::arch::x86_64::__m128 =
5545                    core::arch::x86_64::_mm_loadu_ps(lane_idx_arr.as_ptr());
5546                let rx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5547                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_x()),
5548                    core::arch::x86_64::_mm_mul_ps(
5549                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_x()),
5550                        lane_idx,
5551                    ),
5552                );
5553                let ry: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5554                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_y()),
5555                    core::arch::x86_64::_mm_mul_ps(
5556                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_y()),
5557                        lane_idx,
5558                    ),
5559                );
5560                let rz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5561                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_z()),
5562                    core::arch::x86_64::_mm_mul_ps(
5563                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_z()),
5564                        lane_idx,
5565                    ),
5566                );
5567                let len_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5568                    core::arch::x86_64::_mm_add_ps(
5569                        core::arch::x86_64::_mm_add_ps(
5570                            core::arch::x86_64::_mm_mul_ps(rx, rx),
5571                            core::arch::x86_64::_mm_mul_ps(ry, ry),
5572                        ),
5573                        core::arch::x86_64::_mm_mul_ps(rz, rz),
5574                    ),
5575                    core::arch::x86_64::_mm_set1_ps(1e-12),
5576                );
5577                let est: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_rsqrt_ps(len_sq);
5578                let inv_l: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5579                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(0.5), est),
5580                    core::arch::x86_64::_mm_sub_ps(
5581                        core::arch::x86_64::_mm_set1_ps(3.0),
5582                        core::arch::x86_64::_mm_mul_ps(
5583                            core::arch::x86_64::_mm_mul_ps(len_sq, est),
5584                            est,
5585                        ),
5586                    ),
5587                );
5588                let ndv_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5589                    core::arch::x86_64::_mm_set1_ps(-sn.dot(raw_ray)),
5590                    core::arch::x86_64::_mm_mul_ps(
5591                        core::arch::x86_64::_mm_set1_ps(-sn.dot(ray_dx)),
5592                        lane_idx,
5593                    ),
5594                );
5595                let ndv_raw: core::arch::x86_64::__m128 =
5596                    core::arch::x86_64::_mm_mul_ps(ndv_num, inv_l);
5597                let ndv: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5598                    core::arch::x86_64::_mm_max_ps(ndv_raw, core::arch::x86_64::_mm_set1_ps(0.02)),
5599                    one,
5600                );
5601                let f_om: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(one, ndv);
5602                let f_om2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(f_om, f_om);
5603                let fresnel_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5604                    core::arch::x86_64::_mm_mul_ps(f_om2, f_om2),
5605                    f_om,
5606                );
5607                let vdl_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5608                    core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(raw_ray)),
5609                    core::arch::x86_64::_mm_mul_ps(
5610                        core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(ray_dx)),
5611                        lane_idx,
5612                    ),
5613                );
5614                let vdl: core::arch::x86_64::__m128 =
5615                    core::arch::x86_64::_mm_mul_ps(vdl_num, inv_l);
5616                let sh_v: core::arch::x86_64::__m128 =
5617                    core::arch::x86_64::_mm_loadu_ps(run.shadow.as_ptr().add(off));
5618                let (spec_r, spec_g, spec_b): (
5619                    core::arch::x86_64::__m128,
5620                    core::arch::x86_64::__m128,
5621                    core::arch::x86_64::__m128,
5622                ) = if tri.n_dot_l > 0.0 {
5623                    let ndl_v: core::arch::x86_64::__m128 =
5624                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l);
5625                    let ndh_u: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5626                        core::arch::x86_64::_mm_add_ps(ndl_v, ndv_raw),
5627                        zero,
5628                    );
5629                    let h_lsq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5630                        core::arch::x86_64::_mm_add_ps(
5631                            two,
5632                            core::arch::x86_64::_mm_mul_ps(two, vdl),
5633                        ),
5634                        core::arch::x86_64::_mm_set1_ps(1e-6),
5635                    );
5636                    let ndh_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_div_ps(
5637                        core::arch::x86_64::_mm_mul_ps(ndh_u, ndh_u),
5638                        h_lsq,
5639                    );
5640                    let ggx_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5641                        one,
5642                        core::arch::x86_64::_mm_mul_ps(
5643                            ndh_sq,
5644                            core::arch::x86_64::_mm_set1_ps(tri.alpha2 - 1.0),
5645                        ),
5646                    );
5647                    let ggx_term: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5648                        core::arch::x86_64::_mm_set1_ps(1e-4),
5649                        core::arch::x86_64::_mm_mul_ps(
5650                            core::arch::x86_64::_mm_mul_ps(ggx_den, ggx_den),
5651                            core::arch::x86_64::_mm_set1_ps(PI),
5652                        ),
5653                    );
5654                    let vis_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5655                        core::arch::x86_64::_mm_set1_ps(0.08),
5656                        core::arch::x86_64::_mm_mul_ps(
5657                            ndv,
5658                            core::arch::x86_64::_mm_set1_ps(tri.n_dot_l.max(0.06)),
5659                        ),
5660                    );
5661                    let spec_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5662                        core::arch::x86_64::_mm_set1_ps(0.25 * tri.alpha2 * tri.n_dot_l),
5663                        sh_v,
5664                    );
5665                    let spec_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5666                        core::arch::x86_64::_mm_div_ps(
5667                            spec_num,
5668                            core::arch::x86_64::_mm_mul_ps(ggx_term, vis_den),
5669                        ),
5670                        core::arch::x86_64::_mm_set1_ps(4.5),
5671                    );
5672                    let fr_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5673                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_x()),
5674                        core::arch::x86_64::_mm_mul_ps(
5675                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_x()),
5676                            fresnel_t,
5677                        ),
5678                    );
5679                    let fr_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5680                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_y()),
5681                        core::arch::x86_64::_mm_mul_ps(
5682                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_y()),
5683                            fresnel_t,
5684                        ),
5685                    );
5686                    let fr_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5687                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_z()),
5688                        core::arch::x86_64::_mm_mul_ps(
5689                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_z()),
5690                            fresnel_t,
5691                        ),
5692                    );
5693                    (
5694                        core::arch::x86_64::_mm_mul_ps(
5695                            fr_r,
5696                            core::arch::x86_64::_mm_mul_ps(
5697                                core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5698                                spec_s,
5699                            ),
5700                        ),
5701                        core::arch::x86_64::_mm_mul_ps(
5702                            fr_g,
5703                            core::arch::x86_64::_mm_mul_ps(
5704                                core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5705                                spec_s,
5706                            ),
5707                        ),
5708                        core::arch::x86_64::_mm_mul_ps(
5709                            fr_b,
5710                            core::arch::x86_64::_mm_mul_ps(
5711                                core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5712                                spec_s,
5713                            ),
5714                        ),
5715                    )
5716                } else {
5717                    (zero, zero, zero)
5718                };
5719                let d_v: core::arch::x86_64::__m128 =
5720                    core::arch::x86_64::_mm_loadu_ps(run.depths.as_ptr().add(off));
5721                let wpy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5722                    core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_y()),
5723                    core::arch::x86_64::_mm_mul_ps(ry, d_v),
5724                );
5725                let mut sb_r: core::arch::x86_64::__m128 =
5726                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_x());
5727                let mut sb_g: core::arch::x86_64::__m128 =
5728                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_y());
5729                let mut sb_b: core::arch::x86_64::__m128 =
5730                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_z());
5731                let mut em_r: core::arch::x86_64::__m128 =
5732                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_x());
5733                let mut em_g: core::arch::x86_64::__m128 =
5734                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_y());
5735                let mut em_b: core::arch::x86_64::__m128 =
5736                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_z());
5737                let mut s_refl: core::arch::x86_64::__m128 =
5738                    core::arch::x86_64::_mm_set1_ps(tri.mat_refl);
5739                if DETAIL == 2 {
5740                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
5741                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
5742                        wall_tan_x,
5743                        frame_context.camera_position.get_z() * wall_tan_z,
5744                    );
5745                    let ray_u: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5746                        core::arch::x86_64::_mm_mul_ps(
5747                            rx,
5748                            core::arch::x86_64::_mm_set1_ps(wall_tan_x),
5749                        ),
5750                        core::arch::x86_64::_mm_mul_ps(
5751                            rz,
5752                            core::arch::x86_64::_mm_set1_ps(wall_tan_z),
5753                        ),
5754                    );
5755                    let u_coord_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5756                        core::arch::x86_64::_mm_set1_ps(cam_u),
5757                        core::arch::x86_64::_mm_mul_ps(ray_u, d_v),
5758                    );
5759                    let mut u_a: [f32; 4] = [0.0; 4];
5760                    let mut y_a: [f32; 4] = [0.0; 4];
5761                    let mut d_a: [f32; 4] = [0.0; 4];
5762                    core::arch::x86_64::_mm_storeu_ps(u_a.as_mut_ptr(), u_coord_v);
5763                    core::arch::x86_64::_mm_storeu_ps(y_a.as_mut_ptr(), wpy);
5764                    core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
5765                    let mut nr_a: [f32; 4] = [0.0; 4];
5766                    let mut ng_a: [f32; 4] = [0.0; 4];
5767                    let mut nb_a: [f32; 4] = [0.0; 4];
5768                    let mut er_a: [f32; 4] = [0.0; 4];
5769                    let mut eg_a: [f32; 4] = [0.0; 4];
5770                    let mut eb_a: [f32; 4] = [0.0; 4];
5771                    let mut rf_a: [f32; 4] = [0.0; 4];
5772                    for lane in 0..4usize {
5773                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5774                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5775                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5776                        );
5777                        nr_a[lane] = sb.get_x();
5778                        ng_a[lane] = sb.get_y();
5779                        nb_a[lane] = sb.get_z();
5780                        er_a[lane] = em.get_x();
5781                        eg_a[lane] = em.get_y();
5782                        eb_a[lane] = em.get_z();
5783                        rf_a[lane] = rf;
5784                    }
5785                    sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
5786                    sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
5787                    sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
5788                    em_r = core::arch::x86_64::_mm_loadu_ps(er_a.as_ptr());
5789                    em_g = core::arch::x86_64::_mm_loadu_ps(eg_a.as_ptr());
5790                    em_b = core::arch::x86_64::_mm_loadu_ps(eb_a.as_ptr());
5791                    s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
5792                } else if DETAIL == 1 {
5793                    let m_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
5794                        core::arch::x86_64::_mm_andnot_ps(abs_mask, wpy),
5795                        core::arch::x86_64::_mm_set1_ps(0.15),
5796                    );
5797                    let m_mask: i32 = core::arch::x86_64::_mm_movemask_ps(m_r);
5798                    if m_mask != 0 {
5799                        let wpx_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5800                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_x()),
5801                            core::arch::x86_64::_mm_mul_ps(rx, d_v),
5802                        );
5803                        let wpz_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5804                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_z()),
5805                            core::arch::x86_64::_mm_mul_ps(rz, d_v),
5806                        );
5807                        let mut x_a: [f32; 4] = [0.0; 4];
5808                        let mut z_a: [f32; 4] = [0.0; 4];
5809                        let mut d_a: [f32; 4] = [0.0; 4];
5810                        let mut rx_a: [f32; 4] = [0.0; 4];
5811                        let mut ry_a: [f32; 4] = [0.0; 4];
5812                        let mut rz_a: [f32; 4] = [0.0; 4];
5813                        let mut ft_a: [f32; 4] = [0.0; 4];
5814                        core::arch::x86_64::_mm_storeu_ps(x_a.as_mut_ptr(), wpx_v);
5815                        core::arch::x86_64::_mm_storeu_ps(z_a.as_mut_ptr(), wpz_v);
5816                        core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
5817                        core::arch::x86_64::_mm_storeu_ps(rx_a.as_mut_ptr(), rx);
5818                        core::arch::x86_64::_mm_storeu_ps(ry_a.as_mut_ptr(), ry);
5819                        core::arch::x86_64::_mm_storeu_ps(rz_a.as_mut_ptr(), rz);
5820                        core::arch::x86_64::_mm_storeu_ps(ft_a.as_mut_ptr(), fresnel_t);
5821                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
5822                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
5823                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
5824                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
5825                        for lane in 0..4usize {
5826                            if (m_mask & (1 << lane)) != 0 {
5827                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
5828                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
5829                                    (
5830                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
5831                                        ft_a[lane],
5832                                        tri.metallic,
5833                                        frame_context.world_time_secs,
5834                                    ),
5835                                    tri.mat_base,
5836                                );
5837                                nr_a[lane] = sb.get_x();
5838                                ng_a[lane] = sb.get_y();
5839                                nb_a[lane] = sb.get_z();
5840                                rf_a[lane] = rf;
5841                            }
5842                        }
5843                        sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
5844                        sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
5845                        sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
5846                        s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
5847                    }
5848                }
5849                let kd_scale: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5850                    core::arch::x86_64::_mm_mul_ps(
5851                        core::arch::x86_64::_mm_set1_ps(tri.diffuse_scale),
5852                        core::arch::x86_64::_mm_sub_ps(
5853                            one,
5854                            core::arch::x86_64::_mm_mul_ps(
5855                                fresnel_t,
5856                                core::arch::x86_64::_mm_set1_ps(0.55),
5857                            ),
5858                        ),
5859                    ),
5860                    core::arch::x86_64::_mm_set1_ps(0.08),
5861                );
5862                let dir_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5863                    core::arch::x86_64::_mm_mul_ps(
5864                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l),
5865                        sh_v,
5866                    ),
5867                    kd_scale,
5868                );
5869                let ao_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5870                    core::arch::x86_64::_mm_loadu_ps(run.ao.as_ptr().add(off)),
5871                    core::arch::x86_64::_mm_set1_ps(0.44),
5872                );
5873                let lit_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5874                    core::arch::x86_64::_mm_add_ps(
5875                        core::arch::x86_64::_mm_loadu_ps(run.gi_r.as_ptr().add(off)),
5876                        core::arch::x86_64::_mm_mul_ps(
5877                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_x()),
5878                            ao_s,
5879                        ),
5880                    ),
5881                    core::arch::x86_64::_mm_mul_ps(
5882                        core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5883                        dir_s,
5884                    ),
5885                );
5886                let lit_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5887                    core::arch::x86_64::_mm_add_ps(
5888                        core::arch::x86_64::_mm_loadu_ps(run.gi_g.as_ptr().add(off)),
5889                        core::arch::x86_64::_mm_mul_ps(
5890                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_y()),
5891                            ao_s,
5892                        ),
5893                    ),
5894                    core::arch::x86_64::_mm_mul_ps(
5895                        core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5896                        dir_s,
5897                    ),
5898                );
5899                let lit_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5900                    core::arch::x86_64::_mm_add_ps(
5901                        core::arch::x86_64::_mm_loadu_ps(run.gi_b.as_ptr().add(off)),
5902                        core::arch::x86_64::_mm_mul_ps(
5903                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_z()),
5904                            ao_s,
5905                        ),
5906                    ),
5907                    core::arch::x86_64::_mm_mul_ps(
5908                        core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5909                        dir_s,
5910                    ),
5911                );
5912                let mut rad_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5913                    core::arch::x86_64::_mm_add_ps(
5914                        spec_r,
5915                        core::arch::x86_64::_mm_mul_ps(sb_r, lit_r),
5916                    ),
5917                    em_r,
5918                );
5919                let mut rad_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5920                    core::arch::x86_64::_mm_add_ps(
5921                        spec_g,
5922                        core::arch::x86_64::_mm_mul_ps(sb_g, lit_g),
5923                    ),
5924                    em_g,
5925                );
5926                let mut rad_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5927                    core::arch::x86_64::_mm_add_ps(
5928                        spec_b,
5929                        core::arch::x86_64::_mm_mul_ps(sb_b, lit_b),
5930                    ),
5931                    em_b,
5932                );
5933                if tri.do_refl {
5934                    let refl_f: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5935                        core::arch::x86_64::_mm_max_ps(
5936                            core::arch::x86_64::_mm_add_ps(
5937                                core::arch::x86_64::_mm_set1_ps(0.18 + tri.metallic * 0.25),
5938                                core::arch::x86_64::_mm_mul_ps(
5939                                    fresnel_t,
5940                                    core::arch::x86_64::_mm_set1_ps(0.82),
5941                                ),
5942                            ),
5943                            core::arch::x86_64::_mm_set1_ps(0.18),
5944                        ),
5945                        core::arch::x86_64::_mm_set1_ps(0.95),
5946                    );
5947                    let refl_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5948                        core::arch::x86_64::_mm_max_ps(
5949                            core::arch::x86_64::_mm_mul_ps(s_refl, refl_f),
5950                            zero,
5951                        ),
5952                        core::arch::x86_64::_mm_set1_ps(0.82),
5953                    );
5954                    let rr_v: core::arch::x86_64::__m128 =
5955                        core::arch::x86_64::_mm_loadu_ps(run.refl_r.as_ptr().add(off));
5956                    let rg_v: core::arch::x86_64::__m128 =
5957                        core::arch::x86_64::_mm_loadu_ps(run.refl_g.as_ptr().add(off));
5958                    let rb_v: core::arch::x86_64::__m128 =
5959                        core::arch::x86_64::_mm_loadu_ps(run.refl_b.as_ptr().add(off));
5960                    rad_r = Self::sse_lerp_4x(rad_r, rr_v, refl_b);
5961                    rad_g = Self::sse_lerp_4x(rad_g, rg_v, refl_b);
5962                    rad_b = Self::sse_lerp_4x(rad_b, rb_v, refl_b);
5963                }
5964                if frame_context.fog_on {
5965                    let pos_y: core::arch::x86_64::__m128 =
5966                        core::arch::x86_64::_mm_max_ps(wpy, zero);
5967                    let h_att: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5968                        core::arch::x86_64::_mm_div_ps(
5969                            one,
5970                            core::arch::x86_64::_mm_add_ps(
5971                                one,
5972                                core::arch::x86_64::_mm_mul_ps(
5973                                    pos_y,
5974                                    core::arch::x86_64::_mm_set1_ps(0.045),
5975                                ),
5976                            ),
5977                        ),
5978                        core::arch::x86_64::_mm_set1_ps(0.32),
5979                    );
5980                    let fd: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5981                        core::arch::x86_64::_mm_mul_ps(
5982                            d_v,
5983                            core::arch::x86_64::_mm_set1_ps(frame_context.inv_fog_distance),
5984                        ),
5985                        h_att,
5986                    );
5987                    let fog_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5988                        core::arch::x86_64::_mm_max_ps(
5989                            core::arch::x86_64::_mm_div_ps(
5990                                fd,
5991                                core::arch::x86_64::_mm_add_ps(one, fd),
5992                            ),
5993                            zero,
5994                        ),
5995                        core::arch::x86_64::_mm_set1_ps(0.85),
5996                    );
5997                    let sun_align: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5998                        core::arch::x86_64::_mm_xor_ps(vdl, abs_mask),
5999                        zero,
6000                    );
6001                    let sa2: core::arch::x86_64::__m128 =
6002                        core::arch::x86_64::_mm_mul_ps(sun_align, sun_align);
6003                    let shaft55: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
6004                        core::arch::x86_64::_mm_mul_ps(
6005                            core::arch::x86_64::_mm_mul_ps(sa2, sa2),
6006                            fog_t,
6007                        ),
6008                        core::arch::x86_64::_mm_add_ps(
6009                            core::arch::x86_64::_mm_set1_ps(0.35 * 0.55),
6010                            core::arch::x86_64::_mm_mul_ps(
6011                                sh_v,
6012                                core::arch::x86_64::_mm_set1_ps(0.65 * 0.55),
6013                            ),
6014                        ),
6015                    );
6016                    let fog_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6017                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_x()),
6018                        core::arch::x86_64::_mm_mul_ps(
6019                            core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
6020                            shaft55,
6021                        ),
6022                    );
6023                    let fog_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6024                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_y()),
6025                        core::arch::x86_64::_mm_mul_ps(
6026                            core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
6027                            shaft55,
6028                        ),
6029                    );
6030                    let fog_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6031                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_z()),
6032                        core::arch::x86_64::_mm_mul_ps(
6033                            core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
6034                            shaft55,
6035                        ),
6036                    );
6037                    rad_r = Self::sse_lerp_4x(rad_r, fog_r, fog_t);
6038                    rad_g = Self::sse_lerp_4x(rad_g, fog_g, fog_t);
6039                    rad_b = Self::sse_lerp_4x(rad_b, fog_b, fog_t);
6040                }
6041                let exp_s: core::arch::x86_64::__m128 =
6042                    core::arch::x86_64::_mm_set1_ps(frame_context.exposure_scale);
6043                core::arch::x86_64::_mm_storeu_ps(
6044                    exp_r_arr.as_mut_ptr(),
6045                    core::arch::x86_64::_mm_mul_ps(rad_r, exp_s),
6046                );
6047                core::arch::x86_64::_mm_storeu_ps(
6048                    exp_g_arr.as_mut_ptr(),
6049                    core::arch::x86_64::_mm_mul_ps(rad_g, exp_s),
6050                );
6051                core::arch::x86_64::_mm_storeu_ps(
6052                    exp_b_arr.as_mut_ptr(),
6053                    core::arch::x86_64::_mm_mul_ps(rad_b, exp_s),
6054                );
6055            }
6056        }
6057        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
6058        {
6059            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; `simd128` is enabled on `wasm32`.
6060            unsafe {
6061                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
6062                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
6063                let two: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(2.0);
6064                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
6065                let lane_idx: core::arch::wasm32::v128 =
6066                    core::arch::wasm32::v128_load(lane_idx_arr.as_ptr().cast());
6067                let rx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6068                    core::arch::wasm32::f32x4_splat(raw_ray.get_x()),
6069                    core::arch::wasm32::f32x4_mul(
6070                        core::arch::wasm32::f32x4_splat(ray_dx.get_x()),
6071                        lane_idx,
6072                    ),
6073                );
6074                let ry: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6075                    core::arch::wasm32::f32x4_splat(raw_ray.get_y()),
6076                    core::arch::wasm32::f32x4_mul(
6077                        core::arch::wasm32::f32x4_splat(ray_dx.get_y()),
6078                        lane_idx,
6079                    ),
6080                );
6081                let rz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6082                    core::arch::wasm32::f32x4_splat(raw_ray.get_z()),
6083                    core::arch::wasm32::f32x4_mul(
6084                        core::arch::wasm32::f32x4_splat(ray_dx.get_z()),
6085                        lane_idx,
6086                    ),
6087                );
6088                let len_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6089                    core::arch::wasm32::f32x4_add(
6090                        core::arch::wasm32::f32x4_add(
6091                            core::arch::wasm32::f32x4_mul(rx, rx),
6092                            core::arch::wasm32::f32x4_mul(ry, ry),
6093                        ),
6094                        core::arch::wasm32::f32x4_mul(rz, rz),
6095                    ),
6096                    core::arch::wasm32::f32x4_splat(1e-12),
6097                );
6098                let inv_l: core::arch::wasm32::v128 =
6099                    core::arch::wasm32::f32x4_div(one, core::arch::wasm32::f32x4_sqrt(len_sq));
6100                let ndv_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6101                    core::arch::wasm32::f32x4_splat(-sn.dot(raw_ray)),
6102                    core::arch::wasm32::f32x4_mul(
6103                        core::arch::wasm32::f32x4_splat(-sn.dot(ray_dx)),
6104                        lane_idx,
6105                    ),
6106                );
6107                let ndv_raw: core::arch::wasm32::v128 =
6108                    core::arch::wasm32::f32x4_mul(ndv_num, inv_l);
6109                let ndv: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6110                    core::arch::wasm32::f32x4_pmax(ndv_raw, core::arch::wasm32::f32x4_splat(0.02)),
6111                    one,
6112                );
6113                let f_om: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(one, ndv);
6114                let f_om2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(f_om, f_om);
6115                let fresnel_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6116                    core::arch::wasm32::f32x4_mul(f_om2, f_om2),
6117                    f_om,
6118                );
6119                let vdl_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6120                    core::arch::wasm32::f32x4_splat(-sun_dir.dot(raw_ray)),
6121                    core::arch::wasm32::f32x4_mul(
6122                        core::arch::wasm32::f32x4_splat(-sun_dir.dot(ray_dx)),
6123                        lane_idx,
6124                    ),
6125                );
6126                let vdl: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(vdl_num, inv_l);
6127                let sh_v: core::arch::wasm32::v128 =
6128                    core::arch::wasm32::v128_load(run.shadow.as_ptr().add(off).cast());
6129                let (spec_r, spec_g, spec_b): (
6130                    core::arch::wasm32::v128,
6131                    core::arch::wasm32::v128,
6132                    core::arch::wasm32::v128,
6133                ) = if tri.n_dot_l > 0.0 {
6134                    let ndl_v: core::arch::wasm32::v128 =
6135                        core::arch::wasm32::f32x4_splat(tri.n_dot_l);
6136                    let ndh_u: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6137                        core::arch::wasm32::f32x4_add(ndl_v, ndv_raw),
6138                        zero,
6139                    );
6140                    let h_lsq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6141                        core::arch::wasm32::f32x4_add(two, core::arch::wasm32::f32x4_mul(two, vdl)),
6142                        core::arch::wasm32::f32x4_splat(1e-6),
6143                    );
6144                    let ndh_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_div(
6145                        core::arch::wasm32::f32x4_mul(ndh_u, ndh_u),
6146                        h_lsq,
6147                    );
6148                    let ggx_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6149                        one,
6150                        core::arch::wasm32::f32x4_mul(
6151                            ndh_sq,
6152                            core::arch::wasm32::f32x4_splat(tri.alpha2 - 1.0),
6153                        ),
6154                    );
6155                    let ggx_term: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6156                        core::arch::wasm32::f32x4_splat(1e-4),
6157                        core::arch::wasm32::f32x4_mul(
6158                            core::arch::wasm32::f32x4_mul(ggx_den, ggx_den),
6159                            core::arch::wasm32::f32x4_splat(PI),
6160                        ),
6161                    );
6162                    let vis_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6163                        core::arch::wasm32::f32x4_splat(0.08),
6164                        core::arch::wasm32::f32x4_mul(
6165                            ndv,
6166                            core::arch::wasm32::f32x4_splat(tri.n_dot_l.max(0.06)),
6167                        ),
6168                    );
6169                    let spec_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6170                        core::arch::wasm32::f32x4_splat(0.25 * tri.alpha2 * tri.n_dot_l),
6171                        sh_v,
6172                    );
6173                    let spec_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6174                        core::arch::wasm32::f32x4_div(
6175                            spec_num,
6176                            core::arch::wasm32::f32x4_mul(ggx_term, vis_den),
6177                        ),
6178                        core::arch::wasm32::f32x4_splat(4.5),
6179                    );
6180                    let fr_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6181                        core::arch::wasm32::f32x4_splat(tri.f0.get_x()),
6182                        core::arch::wasm32::f32x4_mul(
6183                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_x()),
6184                            fresnel_t,
6185                        ),
6186                    );
6187                    let fr_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6188                        core::arch::wasm32::f32x4_splat(tri.f0.get_y()),
6189                        core::arch::wasm32::f32x4_mul(
6190                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_y()),
6191                            fresnel_t,
6192                        ),
6193                    );
6194                    let fr_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6195                        core::arch::wasm32::f32x4_splat(tri.f0.get_z()),
6196                        core::arch::wasm32::f32x4_mul(
6197                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_z()),
6198                            fresnel_t,
6199                        ),
6200                    );
6201                    (
6202                        core::arch::wasm32::f32x4_mul(
6203                            fr_r,
6204                            core::arch::wasm32::f32x4_mul(
6205                                core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6206                                spec_s,
6207                            ),
6208                        ),
6209                        core::arch::wasm32::f32x4_mul(
6210                            fr_g,
6211                            core::arch::wasm32::f32x4_mul(
6212                                core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6213                                spec_s,
6214                            ),
6215                        ),
6216                        core::arch::wasm32::f32x4_mul(
6217                            fr_b,
6218                            core::arch::wasm32::f32x4_mul(
6219                                core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6220                                spec_s,
6221                            ),
6222                        ),
6223                    )
6224                } else {
6225                    (zero, zero, zero)
6226                };
6227                let d_v: core::arch::wasm32::v128 =
6228                    core::arch::wasm32::v128_load(run.depths.as_ptr().add(off).cast());
6229                let wpy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6230                    core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_y()),
6231                    core::arch::wasm32::f32x4_mul(ry, d_v),
6232                );
6233                let mut sb_r: core::arch::wasm32::v128 =
6234                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_x());
6235                let mut sb_g: core::arch::wasm32::v128 =
6236                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_y());
6237                let mut sb_b: core::arch::wasm32::v128 =
6238                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_z());
6239                let mut em_r: core::arch::wasm32::v128 =
6240                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_x());
6241                let mut em_g: core::arch::wasm32::v128 =
6242                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_y());
6243                let mut em_b: core::arch::wasm32::v128 =
6244                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_z());
6245                let mut s_refl: core::arch::wasm32::v128 =
6246                    core::arch::wasm32::f32x4_splat(tri.mat_refl);
6247                if DETAIL == 2 {
6248                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
6249                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
6250                        wall_tan_x,
6251                        frame_context.camera_position.get_z() * wall_tan_z,
6252                    );
6253                    let ray_u: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6254                        core::arch::wasm32::f32x4_mul(
6255                            rx,
6256                            core::arch::wasm32::f32x4_splat(wall_tan_x),
6257                        ),
6258                        core::arch::wasm32::f32x4_mul(
6259                            rz,
6260                            core::arch::wasm32::f32x4_splat(wall_tan_z),
6261                        ),
6262                    );
6263                    let u_coord_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6264                        core::arch::wasm32::f32x4_splat(cam_u),
6265                        core::arch::wasm32::f32x4_mul(ray_u, d_v),
6266                    );
6267                    let mut u_a: [f32; 4] = [0.0; 4];
6268                    let mut y_a: [f32; 4] = [0.0; 4];
6269                    let mut d_a: [f32; 4] = [0.0; 4];
6270                    core::arch::wasm32::v128_store(u_a.as_mut_ptr().cast(), u_coord_v);
6271                    core::arch::wasm32::v128_store(y_a.as_mut_ptr().cast(), wpy);
6272                    core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6273                    let mut nr_a: [f32; 4] = [0.0; 4];
6274                    let mut ng_a: [f32; 4] = [0.0; 4];
6275                    let mut nb_a: [f32; 4] = [0.0; 4];
6276                    let mut er_a: [f32; 4] = [0.0; 4];
6277                    let mut eg_a: [f32; 4] = [0.0; 4];
6278                    let mut eb_a: [f32; 4] = [0.0; 4];
6279                    let mut rf_a: [f32; 4] = [0.0; 4];
6280                    for lane in 0..4usize {
6281                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6282                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
6283                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
6284                        );
6285                        nr_a[lane] = sb.get_x();
6286                        ng_a[lane] = sb.get_y();
6287                        nb_a[lane] = sb.get_z();
6288                        er_a[lane] = em.get_x();
6289                        eg_a[lane] = em.get_y();
6290                        eb_a[lane] = em.get_z();
6291                        rf_a[lane] = rf;
6292                    }
6293                    sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6294                    sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6295                    sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6296                    em_r = core::arch::wasm32::v128_load(er_a.as_ptr().cast());
6297                    em_g = core::arch::wasm32::v128_load(eg_a.as_ptr().cast());
6298                    em_b = core::arch::wasm32::v128_load(eb_a.as_ptr().cast());
6299                    s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6300                } else if DETAIL == 1 {
6301                    let m_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
6302                        core::arch::wasm32::f32x4_abs(wpy),
6303                        core::arch::wasm32::f32x4_splat(0.15),
6304                    );
6305                    let m_mask: u32 = core::arch::wasm32::i32x4_bitmask(m_r) as u32;
6306                    if m_mask != 0 {
6307                        let wpx_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6308                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_x()),
6309                            core::arch::wasm32::f32x4_mul(rx, d_v),
6310                        );
6311                        let wpz_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6312                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_z()),
6313                            core::arch::wasm32::f32x4_mul(rz, d_v),
6314                        );
6315                        let mut x_a: [f32; 4] = [0.0; 4];
6316                        let mut z_a: [f32; 4] = [0.0; 4];
6317                        let mut d_a: [f32; 4] = [0.0; 4];
6318                        let mut rx_a: [f32; 4] = [0.0; 4];
6319                        let mut ry_a: [f32; 4] = [0.0; 4];
6320                        let mut rz_a: [f32; 4] = [0.0; 4];
6321                        let mut ft_a: [f32; 4] = [0.0; 4];
6322                        core::arch::wasm32::v128_store(x_a.as_mut_ptr().cast(), wpx_v);
6323                        core::arch::wasm32::v128_store(z_a.as_mut_ptr().cast(), wpz_v);
6324                        core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6325                        core::arch::wasm32::v128_store(rx_a.as_mut_ptr().cast(), rx);
6326                        core::arch::wasm32::v128_store(ry_a.as_mut_ptr().cast(), ry);
6327                        core::arch::wasm32::v128_store(rz_a.as_mut_ptr().cast(), rz);
6328                        core::arch::wasm32::v128_store(ft_a.as_mut_ptr().cast(), fresnel_t);
6329                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
6330                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
6331                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
6332                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
6333                        for lane in 0..4usize {
6334                            if (m_mask & (1_u32 << lane)) != 0 {
6335                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
6336                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
6337                                    (
6338                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
6339                                        ft_a[lane],
6340                                        tri.metallic,
6341                                        frame_context.world_time_secs,
6342                                    ),
6343                                    tri.mat_base,
6344                                );
6345                                nr_a[lane] = sb.get_x();
6346                                ng_a[lane] = sb.get_y();
6347                                nb_a[lane] = sb.get_z();
6348                                rf_a[lane] = rf;
6349                            }
6350                        }
6351                        sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6352                        sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6353                        sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6354                        s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6355                    }
6356                }
6357                let kd_scale: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6358                    core::arch::wasm32::f32x4_mul(
6359                        core::arch::wasm32::f32x4_splat(tri.diffuse_scale),
6360                        core::arch::wasm32::f32x4_sub(
6361                            one,
6362                            core::arch::wasm32::f32x4_mul(
6363                                fresnel_t,
6364                                core::arch::wasm32::f32x4_splat(0.55),
6365                            ),
6366                        ),
6367                    ),
6368                    core::arch::wasm32::f32x4_splat(0.08),
6369                );
6370                let dir_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6371                    core::arch::wasm32::f32x4_mul(
6372                        core::arch::wasm32::f32x4_splat(tri.n_dot_l),
6373                        sh_v,
6374                    ),
6375                    kd_scale,
6376                );
6377                let ao_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6378                    core::arch::wasm32::v128_load(run.ao.as_ptr().add(off).cast()),
6379                    core::arch::wasm32::f32x4_splat(0.44),
6380                );
6381                let lit_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6382                    core::arch::wasm32::f32x4_add(
6383                        core::arch::wasm32::v128_load(run.gi_r.as_ptr().add(off).cast()),
6384                        core::arch::wasm32::f32x4_mul(
6385                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_x()),
6386                            ao_s,
6387                        ),
6388                    ),
6389                    core::arch::wasm32::f32x4_mul(
6390                        core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6391                        dir_s,
6392                    ),
6393                );
6394                let lit_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6395                    core::arch::wasm32::f32x4_add(
6396                        core::arch::wasm32::v128_load(run.gi_g.as_ptr().add(off).cast()),
6397                        core::arch::wasm32::f32x4_mul(
6398                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_y()),
6399                            ao_s,
6400                        ),
6401                    ),
6402                    core::arch::wasm32::f32x4_mul(
6403                        core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6404                        dir_s,
6405                    ),
6406                );
6407                let lit_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6408                    core::arch::wasm32::f32x4_add(
6409                        core::arch::wasm32::v128_load(run.gi_b.as_ptr().add(off).cast()),
6410                        core::arch::wasm32::f32x4_mul(
6411                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_z()),
6412                            ao_s,
6413                        ),
6414                    ),
6415                    core::arch::wasm32::f32x4_mul(
6416                        core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6417                        dir_s,
6418                    ),
6419                );
6420                let mut rad_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6421                    core::arch::wasm32::f32x4_add(
6422                        spec_r,
6423                        core::arch::wasm32::f32x4_mul(sb_r, lit_r),
6424                    ),
6425                    em_r,
6426                );
6427                let mut rad_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6428                    core::arch::wasm32::f32x4_add(
6429                        spec_g,
6430                        core::arch::wasm32::f32x4_mul(sb_g, lit_g),
6431                    ),
6432                    em_g,
6433                );
6434                let mut rad_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6435                    core::arch::wasm32::f32x4_add(
6436                        spec_b,
6437                        core::arch::wasm32::f32x4_mul(sb_b, lit_b),
6438                    ),
6439                    em_b,
6440                );
6441                if tri.do_refl {
6442                    let refl_f: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6443                        core::arch::wasm32::f32x4_pmax(
6444                            core::arch::wasm32::f32x4_add(
6445                                core::arch::wasm32::f32x4_splat(0.18 + tri.metallic * 0.25),
6446                                core::arch::wasm32::f32x4_mul(
6447                                    fresnel_t,
6448                                    core::arch::wasm32::f32x4_splat(0.82),
6449                                ),
6450                            ),
6451                            core::arch::wasm32::f32x4_splat(0.18),
6452                        ),
6453                        core::arch::wasm32::f32x4_splat(0.95),
6454                    );
6455                    let refl_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6456                        core::arch::wasm32::f32x4_pmax(
6457                            core::arch::wasm32::f32x4_mul(s_refl, refl_f),
6458                            zero,
6459                        ),
6460                        core::arch::wasm32::f32x4_splat(0.82),
6461                    );
6462                    let rr_v: core::arch::wasm32::v128 =
6463                        core::arch::wasm32::v128_load(run.refl_r.as_ptr().add(off).cast());
6464                    let rg_v: core::arch::wasm32::v128 =
6465                        core::arch::wasm32::v128_load(run.refl_g.as_ptr().add(off).cast());
6466                    let rb_v: core::arch::wasm32::v128 =
6467                        core::arch::wasm32::v128_load(run.refl_b.as_ptr().add(off).cast());
6468                    rad_r = Self::wasm_lerp_4x(rad_r, rr_v, refl_b);
6469                    rad_g = Self::wasm_lerp_4x(rad_g, rg_v, refl_b);
6470                    rad_b = Self::wasm_lerp_4x(rad_b, rb_v, refl_b);
6471                }
6472                if frame_context.fog_on {
6473                    let pos_y: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(wpy, zero);
6474                    let h_att: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6475                        core::arch::wasm32::f32x4_div(
6476                            one,
6477                            core::arch::wasm32::f32x4_add(
6478                                one,
6479                                core::arch::wasm32::f32x4_mul(
6480                                    pos_y,
6481                                    core::arch::wasm32::f32x4_splat(0.045),
6482                                ),
6483                            ),
6484                        ),
6485                        core::arch::wasm32::f32x4_splat(0.32),
6486                    );
6487                    let fd: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6488                        core::arch::wasm32::f32x4_mul(
6489                            d_v,
6490                            core::arch::wasm32::f32x4_splat(frame_context.inv_fog_distance),
6491                        ),
6492                        h_att,
6493                    );
6494                    let fog_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6495                        core::arch::wasm32::f32x4_pmax(
6496                            core::arch::wasm32::f32x4_div(
6497                                fd,
6498                                core::arch::wasm32::f32x4_add(one, fd),
6499                            ),
6500                            zero,
6501                        ),
6502                        core::arch::wasm32::f32x4_splat(0.85),
6503                    );
6504                    let sun_align: core::arch::wasm32::v128 =
6505                        core::arch::wasm32::f32x4_pmax(core::arch::wasm32::f32x4_neg(vdl), zero);
6506                    let sa2: core::arch::wasm32::v128 =
6507                        core::arch::wasm32::f32x4_mul(sun_align, sun_align);
6508                    let shaft55: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6509                        core::arch::wasm32::f32x4_mul(
6510                            core::arch::wasm32::f32x4_mul(sa2, sa2),
6511                            fog_t,
6512                        ),
6513                        core::arch::wasm32::f32x4_add(
6514                            core::arch::wasm32::f32x4_splat(0.35 * 0.55),
6515                            core::arch::wasm32::f32x4_mul(
6516                                sh_v,
6517                                core::arch::wasm32::f32x4_splat(0.65 * 0.55),
6518                            ),
6519                        ),
6520                    );
6521                    let fog_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6522                        core::arch::wasm32::f32x4_splat(sky_horizon.get_x()),
6523                        core::arch::wasm32::f32x4_mul(
6524                            core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6525                            shaft55,
6526                        ),
6527                    );
6528                    let fog_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6529                        core::arch::wasm32::f32x4_splat(sky_horizon.get_y()),
6530                        core::arch::wasm32::f32x4_mul(
6531                            core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6532                            shaft55,
6533                        ),
6534                    );
6535                    let fog_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6536                        core::arch::wasm32::f32x4_splat(sky_horizon.get_z()),
6537                        core::arch::wasm32::f32x4_mul(
6538                            core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6539                            shaft55,
6540                        ),
6541                    );
6542                    rad_r = Self::wasm_lerp_4x(rad_r, fog_r, fog_t);
6543                    rad_g = Self::wasm_lerp_4x(rad_g, fog_g, fog_t);
6544                    rad_b = Self::wasm_lerp_4x(rad_b, fog_b, fog_t);
6545                }
6546                let exp_s: core::arch::wasm32::v128 =
6547                    core::arch::wasm32::f32x4_splat(frame_context.exposure_scale);
6548                core::arch::wasm32::v128_store(
6549                    exp_r_arr.as_mut_ptr().cast(),
6550                    core::arch::wasm32::f32x4_mul(rad_r, exp_s),
6551                );
6552                core::arch::wasm32::v128_store(
6553                    exp_g_arr.as_mut_ptr().cast(),
6554                    core::arch::wasm32::f32x4_mul(rad_g, exp_s),
6555                );
6556                core::arch::wasm32::v128_store(
6557                    exp_b_arr.as_mut_ptr().cast(),
6558                    core::arch::wasm32::f32x4_mul(rad_b, exp_s),
6559                );
6560            }
6561        }
6562        #[cfg(not(target_arch = "aarch64"))]
6563        #[cfg(not(target_arch = "x86_64"))]
6564        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
6565        {
6566            let rx: [f32; 4] = [
6567                raw_ray.get_x(),
6568                raw_ray.get_x() + ray_dx.get_x(),
6569                raw_ray.get_x() + ray_dx.get_x() * 2.0,
6570                raw_ray.get_x() + ray_dx.get_x() * 3.0,
6571            ];
6572            let ry: [f32; 4] = [
6573                raw_ray.get_y(),
6574                raw_ray.get_y() + ray_dx.get_y(),
6575                raw_ray.get_y() + ray_dx.get_y() * 2.0,
6576                raw_ray.get_y() + ray_dx.get_y() * 3.0,
6577            ];
6578            let rz: [f32; 4] = [
6579                raw_ray.get_z(),
6580                raw_ray.get_z() + ray_dx.get_z(),
6581                raw_ray.get_z() + ray_dx.get_z() * 2.0,
6582                raw_ray.get_z() + ray_dx.get_z() * 3.0,
6583            ];
6584            let len_sq: [f32; 4] = [
6585                rx[0].mul_add(rx[0], ry[0].mul_add(ry[0], rz[0] * rz[0])),
6586                rx[1].mul_add(rx[1], ry[1].mul_add(ry[1], rz[1] * rz[1])),
6587                rx[2].mul_add(rx[2], ry[2].mul_add(ry[2], rz[2] * rz[2])),
6588                rx[3].mul_add(rx[3], ry[3].mul_add(ry[3], rz[3] * rz[3])),
6589            ];
6590            let inv_len: [f32; 4] = Self::rsqrt_4x(len_sq);
6591            let cpx: f32 = frame_context.camera_position.get_x();
6592            let cpy: f32 = frame_context.camera_position.get_y();
6593            let cpz: f32 = frame_context.camera_position.get_z();
6594            let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
6595            for lane in 0..4 {
6596                let s_i: usize = off + lane;
6597                let inv_l: f32 = inv_len[lane];
6598                let vtx: f32 = -rx[lane] * inv_l;
6599                let vty: f32 = -ry[lane] * inv_l;
6600                let vtz: f32 = -rz[lane] * inv_l;
6601                let ndv_raw: f32 = sn
6602                    .get_x()
6603                    .mul_add(vtx, sn.get_y().mul_add(vty, sn.get_z() * vtz));
6604                let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
6605                let f_om: f32 = 1.0 - ndv;
6606                let f_om2: f32 = f_om * f_om;
6607                let fresnel_t: f32 = f_om2 * f_om2 * f_om;
6608                let vdl: f32 = sun_dir
6609                    .get_x()
6610                    .mul_add(vtx, sun_dir.get_y().mul_add(vty, sun_dir.get_z() * vtz));
6611                let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
6612                    let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
6613                    let h_len_sq: f32 = 2.0_f32.mul_add(vdl, 2.0).max(1e-6);
6614                    let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
6615                    let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
6616                    let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * run.shadow[s_i];
6617                    let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
6618                    let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
6619                    let spec_s: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
6620                    let fresnel_rgb: Vec3 =
6621                        tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
6622                    fresnel_rgb.mul(sun_col.scale(spec_s))
6623                } else {
6624                    Vec3::zero()
6625                };
6626                let depth: f32 = run.depths[s_i];
6627                let wpx: f32 = rx[lane].mul_add(depth, cpx);
6628                let wpy: f32 = ry[lane].mul_add(depth, cpy);
6629                let wpz: f32 = rz[lane].mul_add(depth, cpz);
6630                let mut surf_base: Vec3 = tri.mat_base;
6631                let mut surf_emissive: Vec3 = tri.mat_emissive;
6632                let mut surf_refl: f32 = tri.mat_refl;
6633                if DETAIL == 2 {
6634                    let u_coord: f32 = wpx.mul_add(wall_tan_x, wpz * wall_tan_z);
6635                    let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6636                        (u_coord, wpy, depth, frame_context.inv_height),
6637                        (surf_base, surf_emissive, surf_refl),
6638                    );
6639                    surf_base = nb;
6640                    surf_emissive = ne;
6641                    surf_refl = nr;
6642                } else if DETAIL == 1 && wpy.abs() < 0.15 {
6643                    let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
6644                        (wpx, wpz, depth, frame_context.inv_height),
6645                        (
6646                            Vec3::new(vtx, vty, vtz),
6647                            fresnel_t,
6648                            tri.metallic,
6649                            frame_context.world_time_secs,
6650                        ),
6651                        surf_base,
6652                    );
6653                    surf_base = nb;
6654                    surf_refl = nr;
6655                }
6656                let kd_scale: f32 = (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
6657                let direct: Vec3 = sun_col.scale(tri.n_dot_l * run.shadow[s_i] * kd_scale);
6658                let indirect: Vec3 = tri.ambient_sky.scale(0.44 * run.ao[s_i]).add(Vec3::new(
6659                    run.gi_r[s_i],
6660                    run.gi_g[s_i],
6661                    run.gi_b[s_i],
6662                ));
6663                let mut radiance: Vec3 = surf_base
6664                    .mul(direct.add(indirect))
6665                    .add(spec_col)
6666                    .add(surf_emissive);
6667                if tri.do_refl {
6668                    let refl_fresnel: f32 =
6669                        (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
6670                    let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
6671                    radiance = radiance.lerp(
6672                        Vec3::new(run.refl_r[s_i], run.refl_g[s_i], run.refl_b[s_i]),
6673                        refl_blend,
6674                    );
6675                }
6676                if frame_context.fog_on {
6677                    let height_atten: f32 = if wpy > 0.0 {
6678                        (1.0 / (1.0 + wpy * 0.045)).max(0.32)
6679                    } else {
6680                        1.0
6681                    };
6682                    let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
6683                    let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
6684                    let sun_align: f32 = (-vdl).max(0.0);
6685                    let sa2: f32 = sun_align * sun_align;
6686                    let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * run.shadow[s_i]);
6687                    let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
6688                    radiance = radiance.lerp(fog_col, fog_t);
6689                }
6690                let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6691                exp_r_arr[lane] = exposed.get_x();
6692                exp_g_arr[lane] = exposed.get_y();
6693                exp_b_arr[lane] = exposed.get_z();
6694            }
6695        }
6696        let (rgba_4, luma_4): ([[u8; 4]; 4], [u8; 4]) =
6697            Vec3::aces_rgba8_luma_4x(exp_r_arr, exp_g_arr, exp_b_arr);
6698        c_dst[0..4].copy_from_slice(&rgba_4[0]);
6699        c_dst[4..8].copy_from_slice(&rgba_4[1]);
6700        c_dst[8..12].copy_from_slice(&rgba_4[2]);
6701        c_dst[12..16].copy_from_slice(&rgba_4[3]);
6702        l_dst[0..4].copy_from_slice(&luma_4);
6703        if let Some((b_lane, b_cell)) = bloom_slot {
6704            let er: f32 = (exp_r_arr[b_lane] - 1.05).max(0.0);
6705            let eg: f32 = (exp_g_arr[b_lane] - 1.05).max(0.0);
6706            let eb: f32 = (exp_b_arr[b_lane] - 1.05).max(0.0);
6707            *b_cell = [er, eg, eb, 0.0];
6708            let rg_pos: bool = er > 0.0 || eg > 0.0;
6709            rg_pos || eb > 0.0
6710        } else {
6711            false
6712        }
6713    }
6714
6715    /// Loops `shade_span_4x_specialized<DETAIL>` across up to 32 pixels of one triangle run with zero probe register pressure.
6716    ///
6717    /// # Arguments
6718    ///
6719    /// - `&DeferredFrameContext` - Per-frame shading context.
6720    /// - `&GShadeTri` - Precomputed triangle PBR record.
6721    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6722    /// - `&RunScratch32` - Pre-upsampled 32-pixel L1 probe & depth arrays.
6723    /// - `&mut RunRowOut<'_>` - Writable scanline color, luma, and bloom outputs.
6724    ///
6725    /// # Returns
6726    ///
6727    /// - `bool` - `true` when any pixel in the chunk emitted non-zero HDR bloom.
6728    #[inline(always)]
6729    fn shade_run_32_loop<const DETAIL: u8>(
6730        frame_context: &DeferredFrameContext,
6731        tri: &GShadeTri,
6732        span: (usize, usize, Vec3, Vec3),
6733        run: &RunScratch32,
6734        out: &mut RunRowOut<'_>,
6735    ) -> bool {
6736        let (px_start, count, mut raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6737        let write_bloom_row: bool = out.write_bloom;
6738        let bloom_row_off: usize = out.bloom_off;
6739        let ray_dx_4: Vec3 = ray_dx.scale(4.0);
6740        let b_lane: usize = (4 - (px_start & 3)) & 3;
6741        let mut any_bloom: bool = false;
6742        let mut off: usize = 0;
6743        while off < count {
6744            let cur_px: usize = px_start + off;
6745            let base_c: usize = cur_px * 4;
6746            let bloom_slot: Option<(usize, &mut [f32; 4])> = if write_bloom_row {
6747                let bidx: usize = bloom_row_off + ((cur_px + b_lane) >> 2);
6748                if bidx < out.bloom_band.len() {
6749                    Some((b_lane, &mut out.bloom_band[bidx]))
6750                } else {
6751                    None
6752                }
6753            } else {
6754                None
6755            };
6756            if Self::shade_span_4x_specialized::<DETAIL>(
6757                frame_context,
6758                tri,
6759                (raw_ray, ray_dx),
6760                (run, off),
6761                SpanShadeOut {
6762                    rgba: &mut out.color[base_c..(base_c + 16)],
6763                    luma: &mut out.luma[cur_px..(cur_px + 4)],
6764                    bloom: bloom_slot,
6765                },
6766            ) {
6767                any_bloom = true;
6768            }
6769            raw_ray = raw_ray.add(ray_dx_4);
6770            off += 4;
6771        }
6772        any_bloom
6773    }
6774
6775    /// Outlined zero-spill leaf kernel for plain PBR triangles (`DETAIL = 0`).
6776    ///
6777    /// # Arguments
6778    ///
6779    /// - `&DeferredFrameContext` - Per-frame shading context.
6780    /// - `&GShadeTri` - Triangle PBR record.
6781    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6782    /// - `&RunScratch32` - L1-hot run scratch.
6783    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6784    ///
6785    /// # Returns
6786    ///
6787    /// - `bool` - `true` when bloom radiance was emitted.
6788    #[inline(never)]
6789    fn shade_run_plain_32(
6790        frame_context: &DeferredFrameContext,
6791        tri: &GShadeTri,
6792        span: (usize, usize, Vec3, Vec3),
6793        run: &RunScratch32,
6794        out: &mut RunRowOut<'_>,
6795    ) -> bool {
6796        Self::shade_run_32_loop::<0>(frame_context, tri, span, run, out)
6797    }
6798
6799    /// Outlined zero-spill leaf kernel for procedural asphalt road triangles (`DETAIL = 1`).
6800    ///
6801    /// # Arguments
6802    ///
6803    /// - `&DeferredFrameContext` - Per-frame shading context.
6804    /// - `&GShadeTri` - Triangle PBR record.
6805    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6806    /// - `&RunScratch32` - L1-hot run scratch.
6807    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6808    ///
6809    /// # Returns
6810    ///
6811    /// - `bool` - `true` when bloom radiance was emitted.
6812    #[inline(never)]
6813    fn shade_run_road_32(
6814        frame_context: &DeferredFrameContext,
6815        tri: &GShadeTri,
6816        span: (usize, usize, Vec3, Vec3),
6817        run: &RunScratch32,
6818        out: &mut RunRowOut<'_>,
6819    ) -> bool {
6820        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6821        if count == 0 {
6822            return false;
6823        }
6824        let cam: Vec3 = frame_context.camera_position;
6825        let last_off: usize = count.saturating_sub(1);
6826        let p0: Vec3 = cam.add(start_raw_ray.scale(run.depths[0]));
6827        let p1: Vec3 = cam.add(
6828            start_raw_ray
6829                .add(ray_dx.scale(last_off as f32))
6830                .scale(run.depths[last_off]),
6831        );
6832        if p0.get_x() <= 143.5 && p1.get_x() <= 143.5 {
6833            return Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
6834        }
6835        let d0: f32 = (p0.get_x() - 64.0).hypot(p0.get_z() - p0.get_z().clamp(-140.0, 140.0));
6836        let d1: f32 = (p1.get_x() - 64.0).hypot(p1.get_z() - p1.get_z().clamp(-140.0, 140.0));
6837        if p0.get_x() > 144.2 && p1.get_x() > 144.2 && d0 > 78.5 && d1 > 78.5 {
6838            return Self::shade_run_ocean_32(frame_context, tri, span, run, out);
6839        }
6840        let mut any_bloom: bool = Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
6841        let mut raw_ray: Vec3 = start_raw_ray;
6842        let sky_lut: &[[f32; 3]] = out.sky_lut;
6843        let aces_lut: &[u8] = out.aces_lut;
6844        for off in 0..count {
6845            let depth: f32 = run.depths[off];
6846            let world_p: Vec3 = cam.add(raw_ray.scale(depth));
6847            let wpx: f32 = world_p.get_x();
6848            if wpx > 144.0 {
6849                let wpz: f32 = world_p.get_z();
6850                let d_spine: f32 = (wpx - 64.0).hypot(wpz - wpz.clamp(-140.0, 140.0));
6851                if d_spine > 78.2 {
6852                    let px: usize = px_start + off;
6853                    let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
6854                    let rt_refl: Vec3 =
6855                        Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
6856                    let radiance: Vec3 = Self::eval_ocean_water_radiance(
6857                        frame_context,
6858                        sky_lut,
6859                        (world_p, view_dir, depth),
6860                        (run.shadow[off], rt_refl),
6861                    );
6862                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6863                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
6864                    let cidx: usize = px * 4;
6865                    out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
6866                    out.luma[px] =
6867                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
6868                            >> 8) as u8;
6869                    if out.write_bloom && (px & 3) == 0 {
6870                        let bidx: usize = out.bloom_off + (px >> 2);
6871                        if bidx < out.bloom_band.len() {
6872                            let er: f32 = (exposed.get_x() - 1.15).max(0.0);
6873                            let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
6874                            let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
6875                            out.bloom_band[bidx] = [er, eg, eb, 0.0];
6876                            if er + eg + eb > 0.0 {
6877                                any_bloom = true;
6878                            }
6879                        }
6880                    }
6881                }
6882            }
6883            raw_ray = raw_ray.add(ray_dx);
6884        }
6885        any_bloom
6886    }
6887
6888    /// Outlined zero-spill leaf kernel for animated photorealistic ocean water triangles (`DETAIL = 3`).
6889    ///
6890    /// # Arguments
6891    ///
6892    /// - `&DeferredFrameContext` - Per-frame shading context.
6893    /// - `&GShadeTri` - Triangle PBR record.
6894    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6895    /// - `&RunScratch32` - L1-hot run scratch.
6896    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6897    ///
6898    /// # Returns
6899    ///
6900    /// - `bool` - `true` when bloom radiance was emitted.
6901    #[inline(never)]
6902    fn shade_run_ocean_32(
6903        frame_context: &DeferredFrameContext,
6904        tri: &GShadeTri,
6905        span: (usize, usize, Vec3, Vec3),
6906        run: &RunScratch32,
6907        out: &mut RunRowOut<'_>,
6908    ) -> bool {
6909        let _: &GShadeTri = tri;
6910        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6911        let mut raw_ray: Vec3 = start_raw_ray;
6912        let mut any_bloom: bool = false;
6913        let sky_lut: &[[f32; 3]] = out.sky_lut;
6914        let aces_lut: &[u8] = out.aces_lut;
6915        for off in 0..count {
6916            let px: usize = px_start + off;
6917            let depth: f32 = run.depths[off];
6918            let world_p: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
6919            let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
6920            let rt_refl: Vec3 = Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
6921            let radiance: Vec3 = Self::eval_ocean_water_radiance(
6922                frame_context,
6923                sky_lut,
6924                (world_p, view_dir, depth),
6925                (run.shadow[off], rt_refl),
6926            );
6927            let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6928            let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
6929            let cidx: usize = px * 4;
6930            out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
6931            out.luma[px] =
6932                (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29) >> 8)
6933                    as u8;
6934            if out.write_bloom && (px & 3) == 0 {
6935                let bidx: usize = out.bloom_off + (px >> 2);
6936                if bidx < out.bloom_band.len() {
6937                    let er: f32 = (exposed.get_x() - 1.15).max(0.0);
6938                    let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
6939                    let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
6940                    out.bloom_band[bidx] = [er, eg, eb, 0.0];
6941                    if er + eg + eb > 0.0 {
6942                        any_bloom = true;
6943                    }
6944                }
6945            }
6946            raw_ray = raw_ray.add(ray_dx);
6947        }
6948        any_bloom
6949    }
6950
6951    /// Outlined zero-spill leaf kernel for procedural architectural facade triangles (`DETAIL = 2`).
6952    ///
6953    /// # Arguments
6954    ///
6955    /// - `&DeferredFrameContext` - Per-frame shading context.
6956    /// - `&GShadeTri` - Triangle PBR record.
6957    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6958    /// - `&RunScratch32` - L1-hot run scratch.
6959    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6960    ///
6961    /// # Returns
6962    ///
6963    /// - `bool` - `true` when bloom radiance was emitted.
6964    #[inline(never)]
6965    fn shade_run_facade_32(
6966        frame_context: &DeferredFrameContext,
6967        tri: &GShadeTri,
6968        span: (usize, usize, Vec3, Vec3),
6969        run: &RunScratch32,
6970        out: &mut RunRowOut<'_>,
6971    ) -> bool {
6972        Self::shade_run_32_loop::<2>(frame_context, tri, span, run, out)
6973    }
6974
6975    /// Stage A probe-only leaf kernel upsampling up to 32 consecutive pixels of `tid` into L1-hot `RunScratch32` with zero PBR register pressure.
6976    ///
6977    /// # Arguments
6978    ///
6979    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
6980    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
6981    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and L1 scratch.
6982    /// - `(&[u32], &[f32], usize, usize)` - `(g_row, d_row, px_start, w)`.
6983    /// - `(&mut usize, &mut i32)` - `(gx_cur, sub_x)` updated for the upsampled count.
6984    ///
6985    /// # Returns
6986    ///
6987    /// - `usize` - Number of validated pixels (`0, 4, 8, ..., 32`) populated into `RunScratch32`.
6988    #[inline(never)]
6989    fn upsample_run_probes_32(
6990        tri_info: (&GShadeTri, u32, bool, bool),
6991        probe_ctx: &ProbeBandContext<'_>,
6992        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
6993        rows: (&[u32], &[f32], usize, usize),
6994        cursor: (&mut usize, &mut i32),
6995    ) -> usize {
6996        let (tri, tid, rt_active, gi_active): (&GShadeTri, u32, bool, bool) = tri_info;
6997        let ProbeBandContext {
6998            top_row: probe_r0,
6999            bottom_row: probe_r1,
7000            wy0,
7001            wy1,
7002            gw_max,
7003            step2_i32,
7004            fx_lut,
7005        } = *probe_ctx;
7006        let (cached_probe_key, cached_cell, run): (
7007            &mut (usize, u32),
7008            &mut CachedProbeCell,
7009            &mut RunScratch32,
7010        ) = cache;
7011        let (g_row, d_row, px_start, width_val): (&[u32], &[f32], usize, usize) = rows;
7012        let (gx_ref, sub_ref): (&mut usize, &mut i32) = cursor;
7013        let check_shadow_edge: bool = !gi_active && tri.n_dot_l > 0.02;
7014        let mut run_len: usize = 0;
7015        while run_len < 32 {
7016            let px: usize = px_start + run_len;
7017            if px + 4 > width_val
7018                || g_row[px] != tid
7019                || g_row[px + 1] != tid
7020                || g_row[px + 2] != tid
7021                || g_row[px + 3] != tid
7022            {
7023                break;
7024            }
7025            let depths: [f32; 4] =
7026                Self::recip_4x([d_row[px], d_row[px + 1], d_row[px + 2], d_row[px + 3]]);
7027            run.depths[run_len..(run_len + 4)].copy_from_slice(&depths);
7028            run_len += 4;
7029        }
7030        if run_len == 0 {
7031            return 0;
7032        }
7033        if !rt_active {
7034            let mut sub_out: i32 = *sub_ref + ((run_len as i32) * 2);
7035            let mut gx_out: usize = *gx_ref;
7036            while sub_out >= step2_i32 {
7037                sub_out -= step2_i32;
7038                gx_out += 1;
7039            }
7040            *gx_ref = gx_out;
7041            *sub_ref = sub_out;
7042            return run_len;
7043        }
7044        let mut gx_cur: usize = *gx_ref;
7045        let mut sub_x: i32 = *sub_ref;
7046        let mut item_index: usize = 0;
7047        'run: while item_index < run_len {
7048            if sub_x >= 0 && gx_cur < gw_max {
7049                let gx0: usize = gx_cur;
7050                let gx1: usize = gx_cur + 1;
7051                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7052                if *cached_probe_key != probe_key {
7053                    let prev_adj: bool =
7054                        gx0 > 0 && *cached_probe_key == ((((gx0 - 1) << 16) | gx0), tid);
7055                    *cached_probe_key = probe_key;
7056                    if prev_adj {
7057                        CachedProbeCell::shift_right_in_place(
7058                            cached_cell,
7059                            probe_r0,
7060                            probe_r1,
7061                            gx1,
7062                            tri.shade_n,
7063                            (tri.do_refl, gi_active),
7064                        );
7065                    } else {
7066                        CachedProbeCell::load_into(
7067                            cached_cell,
7068                            probe_r0,
7069                            probe_r1,
7070                            (gx0, gx1),
7071                            tri.shade_n,
7072                            (tri.do_refl, gi_active),
7073                        );
7074                    }
7075                }
7076                let rem_in_cell: usize = (((step2_i32 - 1 - sub_x) >> 1) as usize) + 1;
7077                let mut avail: usize = (run_len - item_index).min(rem_in_cell);
7078                let mut ran_4x: bool = false;
7079                while avail >= 4 {
7080                    let base_s: usize = sub_x as usize;
7081                    let fx_4: [f32; 4] = [
7082                        fx_lut[base_s.min(15)],
7083                        fx_lut[(base_s + 2).min(15)],
7084                        fx_lut[(base_s + 4).min(15)],
7085                        fx_lut[(base_s + 6).min(15)],
7086                    ];
7087                    if !CachedProbeCell::sample_4x_same_cell(
7088                        cached_cell,
7089                        fx_4,
7090                        (wy0, wy1),
7091                        (check_shadow_edge, tri.do_refl, gi_active),
7092                        (run, item_index),
7093                    ) {
7094                        break 'run;
7095                    }
7096                    item_index += 4;
7097                    sub_x += 8;
7098                    avail -= 4;
7099                    ran_4x = true;
7100                }
7101                if avail > 0 {
7102                    if ran_4x {
7103                        let back: usize = 4 - avail;
7104                        let off_back: usize = item_index - back;
7105                        let s_back: usize = (sub_x - (back as i32) * 2) as usize;
7106                        let fx_4: [f32; 4] = [
7107                            fx_lut[s_back.min(15)],
7108                            fx_lut[(s_back + 2).min(15)],
7109                            fx_lut[(s_back + 4).min(15)],
7110                            fx_lut[(s_back + 6).min(15)],
7111                        ];
7112                        if !CachedProbeCell::sample_4x_same_cell(
7113                            cached_cell,
7114                            fx_4,
7115                            (wy0, wy1),
7116                            (check_shadow_edge, tri.do_refl, gi_active),
7117                            (run, off_back),
7118                        ) {
7119                            break 'run;
7120                        }
7121                        item_index += avail;
7122                        sub_x += (avail as i32) * 2;
7123                    } else {
7124                        for _ in 0..avail {
7125                            let fx: f32 = fx_lut[(sub_x as usize).min(15)];
7126                            let wx0: f32 = 1.0 - fx;
7127                            let bws: [f32; 4] = [wx0 * wy0, fx * wy0, wx0 * wy1, fx * wy1];
7128                            let depth_i: f32 = run.depths[item_index];
7129                            let (vm, sh, s_min, s_max, rf, gi, ao): (
7130                                u32,
7131                                f32,
7132                                f32,
7133                                f32,
7134                                Vec3,
7135                                Vec3,
7136                                f32,
7137                            ) = CachedProbeCell::sample_1x(
7138                                cached_cell,
7139                                bws,
7140                                depth_i,
7141                                (tri.do_refl, gi_active),
7142                            );
7143                            let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7144                                18.0
7145                            } else {
7146                                42.0
7147                            };
7148                            if vm == 0
7149                                || (check_shadow_edge
7150                                    && depth_i < edge_max_d
7151                                    && (s_max - s_min) > 0.12)
7152                            {
7153                                break 'run;
7154                            }
7155                            run.shadow[item_index] = sh;
7156                            if tri.do_refl {
7157                                run.refl_r[item_index] = rf.get_x();
7158                                run.refl_g[item_index] = rf.get_y();
7159                                run.refl_b[item_index] = rf.get_z();
7160                            }
7161                            if gi_active {
7162                                run.gi_r[item_index] = gi.get_x();
7163                                run.gi_g[item_index] = gi.get_y();
7164                                run.gi_b[item_index] = gi.get_z();
7165                                run.ao[item_index] = ao;
7166                            }
7167                            item_index += 1;
7168                            sub_x += 2;
7169                        }
7170                    }
7171                }
7172                if sub_x >= step2_i32 {
7173                    sub_x -= step2_i32;
7174                    gx_cur += 1;
7175                }
7176            } else {
7177                let (gx0, gx1): (usize, usize) = if sub_x <= 0 && gx_cur == 0 {
7178                    (0, gw_max.min(1))
7179                } else {
7180                    (gw_max, gw_max)
7181                };
7182                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7183                if *cached_probe_key != probe_key {
7184                    *cached_probe_key = probe_key;
7185                    CachedProbeCell::load_into(
7186                        cached_cell,
7187                        probe_r0,
7188                        probe_r1,
7189                        (gx0, gx1),
7190                        tri.shade_n,
7191                        (tri.do_refl, gi_active),
7192                    );
7193                }
7194                let bws: [f32; 4] = [wy0, 0.0, wy1, 0.0];
7195                let depth_i: f32 = run.depths[item_index];
7196                let (vm, sh, s_min, s_max, rf, gi, ao): (u32, f32, f32, f32, Vec3, Vec3, f32) =
7197                    CachedProbeCell::sample_1x(cached_cell, bws, depth_i, (tri.do_refl, gi_active));
7198                let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7199                    18.0
7200                } else {
7201                    42.0
7202                };
7203                if vm == 0 || (check_shadow_edge && depth_i < edge_max_d && (s_max - s_min) > 0.12)
7204                {
7205                    break 'run;
7206                }
7207                run.shadow[item_index] = sh;
7208                if tri.do_refl {
7209                    run.refl_r[item_index] = rf.get_x();
7210                    run.refl_g[item_index] = rf.get_y();
7211                    run.refl_b[item_index] = rf.get_z();
7212                }
7213                if gi_active {
7214                    run.gi_r[item_index] = gi.get_x();
7215                    run.gi_g[item_index] = gi.get_y();
7216                    run.gi_b[item_index] = gi.get_z();
7217                    run.ao[item_index] = ao;
7218                }
7219                item_index += 1;
7220                sub_x += 2;
7221                if sub_x >= step2_i32 {
7222                    sub_x -= step2_i32;
7223                    gx_cur += 1;
7224                }
7225            }
7226        }
7227        let out_count: usize = item_index & !3;
7228        if out_count == item_index {
7229            *gx_ref = gx_cur;
7230            *sub_ref = sub_x;
7231        } else {
7232            let mut final_sub: i32 = *sub_ref + ((out_count as i32) * 2);
7233            let mut final_gx: usize = *gx_ref;
7234            while final_sub >= step2_i32 {
7235                final_sub -= step2_i32;
7236                final_gx += 1;
7237            }
7238            *gx_ref = final_gx;
7239            *sub_ref = final_sub;
7240        }
7241        out_count
7242    }
7243
7244    /// Shades an entire contiguous horizontal run of 4-pixel spans belonging to triangle `tid` in 32-pixel L1-hot decoupled stages (`upsample_run_probes_32` + const-specialized leaf shader).
7245    ///
7246    /// # Arguments
7247    ///
7248    /// - `&DeferredFrameContext` - Per-frame camera, sun, and fog configuration.
7249    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
7250    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
7251    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and 32-pixel L1 scratch.
7252    /// - `(&[u32], &[f32], RunRowOut<'_>)` - Scanline G-Buffer, depth, and writable output buffers.
7253    /// - `(&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32)` - Scanline cursor `(px, raw_ray, ray_dx, gx_cur, sub_x)`.
7254    ///
7255    /// # Returns
7256    ///
7257    /// - `bool` - `true` when any 4-pixel span in the run emitted non-zero HDR bloom radiance.
7258    #[inline(always)]
7259    fn shade_tri_run_4x(
7260        frame_context: &DeferredFrameContext,
7261        tri_info: (&GShadeTri, u32, bool, bool),
7262        probe_ctx: &ProbeBandContext<'_>,
7263        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
7264        rows: (&[u32], &[f32], RunRowOut<'_>),
7265        state: (&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32),
7266    ) -> bool {
7267        let (tri, tid, _, _): (&GShadeTri, u32, bool, bool) = tri_info;
7268        let (cached_probe_key, cached_cell, run): (
7269            &mut (usize, u32),
7270            &mut CachedProbeCell,
7271            &mut RunScratch32,
7272        ) = cache;
7273        let (g_row, d_row, mut out_row): (&[u32], &[f32], RunRowOut<'_>) = rows;
7274        let (px_ref, raw_ray_ref, ray_dx, gx_ref, sub_ref): (
7275            &mut usize,
7276            &mut Vec3,
7277            Vec3,
7278            &mut usize,
7279            &mut i32,
7280        ) = state;
7281        let width_val: usize = frame_context.width;
7282        let sn: Vec3 = tri.shade_n;
7283        let detail_kind: u8 =
7284            if tri.surface_detail == SurfaceDetailMode::OceanWater && sn.get_y() > 0.90 {
7285                3
7286            } else if tri.surface_detail == SurfaceDetailMode::ArchitecturalFacade
7287                && sn.get_y().abs() < 0.25
7288                && tri.mat_emissive.length_sq() < 0.02
7289            {
7290                2
7291            } else if tri.surface_detail == SurfaceDetailMode::RoadSurface && sn.get_y() > 0.92 {
7292                1
7293            } else {
7294                0
7295            };
7296        let mut any_bloom: bool = false;
7297        loop {
7298            let px0: usize = *px_ref;
7299            let count: usize = Self::upsample_run_probes_32(
7300                tri_info,
7301                probe_ctx,
7302                (cached_probe_key, cached_cell, run),
7303                (g_row, d_row, px0, width_val),
7304                (gx_ref, sub_ref),
7305            );
7306            if count == 0 {
7307                break;
7308            }
7309            let hit: bool = match detail_kind {
7310                3 => Self::shade_run_ocean_32(
7311                    frame_context,
7312                    tri,
7313                    (px0, count, *raw_ray_ref, ray_dx),
7314                    run,
7315                    &mut out_row,
7316                ),
7317                2 => Self::shade_run_facade_32(
7318                    frame_context,
7319                    tri,
7320                    (px0, count, *raw_ray_ref, ray_dx),
7321                    run,
7322                    &mut out_row,
7323                ),
7324                1 => Self::shade_run_road_32(
7325                    frame_context,
7326                    tri,
7327                    (px0, count, *raw_ray_ref, ray_dx),
7328                    run,
7329                    &mut out_row,
7330                ),
7331                _ => Self::shade_run_plain_32(
7332                    frame_context,
7333                    tri,
7334                    (px0, count, *raw_ray_ref, ray_dx),
7335                    run,
7336                    &mut out_row,
7337                ),
7338            };
7339            if hit {
7340                any_bloom = true;
7341            }
7342            *px_ref = px0 + count;
7343            *raw_ray_ref = raw_ray_ref.add(ray_dx.scale(count as f32));
7344            if count < 32 {
7345                break;
7346            }
7347        }
7348        let _: u32 = tid;
7349        any_bloom
7350    }
7351
7352    /// Fused Barrier 2 worker running streaming 2-row L1 joint-bilateral probe denoise plus vectorized 4-pixel SIMD Cook-Torrance GGX PBR shading, SIMD ACES tonemap, and bloom extraction.
7353    ///
7354    /// # Arguments
7355    ///
7356    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and RT settings.
7357    /// - `&ShadeBandInputs<'_>` - Read-only depth, G-Buffer IDs, shading records, raw SoA probes, static BVH, and dynamic instances.
7358    /// - `(usize, &mut [u8], &mut [u8], &mut [[f32; 4]])` - `(py_start, color band, luma band, bloom band)`.
7359    ///
7360    /// # Returns
7361    ///
7362    /// - `(usize, bool)` - `(edge_rays_traced, band_emitted_nonzero_bloom)`.
7363    fn shade_deferred_band(
7364        frame_context: &DeferredFrameContext,
7365        inputs: &ShadeBandInputs<'_>,
7366        outputs: (usize, &mut [u8], &mut [u8], &mut [[f32; 4]]),
7367    ) -> (usize, bool) {
7368        let depth_buf: &[f32] = inputs.depth_buf;
7369        let g_tri_idx: &[u32] = inputs.g_tri_idx;
7370        let shaded_tris: &[GShadeTri] = inputs.shaded_tris;
7371        let raw_probes: &RtProbeGridSoa = inputs.raw_probes;
7372        let (py_start, color_band, luma_band, bloom_band): (
7373            usize,
7374            &mut [u8],
7375            &mut [u8],
7376            &mut [[f32; 4]],
7377        ) = outputs;
7378        let width_val: usize = frame_context.width;
7379        let gw: usize = frame_context.grid_width;
7380        let gh: usize = frame_context.grid_height;
7381        let gw_max: usize = gw.saturating_sub(1);
7382        let gh_max: usize = gh.saturating_sub(1);
7383        let border_width: usize = frame_context.bloom_width;
7384        let rt_step: usize = frame_context.raytrace_step.max(1);
7385        let step_f: f32 = rt_step as f32;
7386        let inv_step: f32 = 1.0 / step_f;
7387        let step2_i32: i32 = (rt_step * 2) as i32;
7388        let init_sub_x: i32 = 1 - (rt_step as i32);
7389        let inv_step2: f32 = 0.5 * inv_step;
7390        let mut fx_lut: [f32; 16] = [0.0; 16];
7391        let lut_len: usize = (rt_step * 2).min(16);
7392        for (idx, slot) in fx_lut.iter_mut().take(lut_len).enumerate() {
7393            *slot = (idx as f32) * inv_step2;
7394        }
7395        let sun_dir: Vec3 = frame_context.sun.get_direction();
7396        let inv_sun: Vec3 = frame_context.inv_sun_dir;
7397        let sun_col: Vec3 = frame_context.sun.get_color();
7398        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
7399        let rt_active: bool = frame_context.raytrace_mode != RayTracingMode::Off
7400            && frame_context.raytrace_step > 0
7401            && !raw_probes.is_empty();
7402        let gi_active: bool = (frame_context.raytrace_mode == RayTracingMode::FullPathTracedGi
7403            || frame_context.has_clustered_lights)
7404            && rt_active;
7405        let band_rows: usize = luma_band.len() / width_val.max(1);
7406        let ray_dx: Vec3 = frame_context
7407            .camera_right_scaled
7408            .scale(2.0 * frame_context.inv_width);
7409        let ndc_x0: f32 = frame_context.inv_width - 1.0;
7410        let mut edge_rays: usize = 0;
7411        let mut bloom_emitted: bool = false;
7412        let mut static_shadow_cache: u32 = u32::MAX;
7413        let mut dyn_shadow_cache: u32 = u32::MAX;
7414        let use_stack_denoise: bool = rt_active && gw <= PROBE_ROW_STACK_CAP;
7415        let mut a_is_r0: bool = true;
7416        let mut run_scratch: RunScratch32 = RunScratch32 {
7417            depths: [1.0; 32],
7418            shadow: [1.0; 32],
7419            refl_r: [sky_horizon.get_x(); 32],
7420            refl_g: [sky_horizon.get_y(); 32],
7421            refl_b: [sky_horizon.get_z(); 32],
7422            gi_r: [0.0; 32],
7423            gi_g: [0.0; 32],
7424            gi_b: [0.0; 32],
7425            ao: [1.0; 32],
7426        };
7427        PROBE_ROW_SCRATCH.with(|cell: &RefCell<Box<RtProbeRowScratch>>| {
7428            let mut guard: RefMut<'_, Box<RtProbeRowScratch>> = cell.borrow_mut();
7429            let scratch: &mut RtProbeRowScratch = guard.as_mut();
7430            if scratch.frame_gen != frame_context.probe_frame_generation {
7431                scratch.frame_gen = frame_context.probe_frame_generation;
7432                scratch.cached_gy_a = usize::MAX;
7433                scratch.cached_gy_b = usize::MAX;
7434            }
7435            for local_y in 0..band_rows {
7436                let py: usize = py_start + local_y;
7437                let row_off: usize = py * width_val;
7438                let out_row_luma: usize = local_y * width_val;
7439                let out_row_rgba: usize = out_row_luma * 4;
7440                let write_bloom_row: bool =
7441                    frame_context.bloom_on && (py & 3) == 0 && border_width > 0;
7442                let mut row_bloom_hit: bool = false;
7443                let bloom_row_off: usize = if write_bloom_row {
7444                    (local_y / 4) * border_width
7445                } else {
7446                    0
7447                };
7448                let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * frame_context.inv_height);
7449                let row_base_dir: Vec3 = frame_context
7450                    .camera_forward
7451                    .add(frame_context.camera_up_scaled.scale(ndc_y));
7452                let gy_f: f32 = (((py as f32) + 0.5) * inv_step - 0.5).clamp(0.0, gh_max as f32);
7453                let gy0: usize = (gy_f as usize).min(gh_max);
7454                let gy1: usize = (gy0 + 1).min(gh_max);
7455                let fy: f32 = gy_f - (gy0 as f32);
7456                let wy0: f32 = 1.0 - fy;
7457                let wy1: f32 = fy;
7458                if use_stack_denoise {
7459                    if gy0 == scratch.cached_gy_a {
7460                        a_is_r0 = true;
7461                    } else if gy0 == scratch.cached_gy_b {
7462                        a_is_r0 = false;
7463                    } else {
7464                        a_is_r0 = true;
7465                        Self::populate_probe_row_stack(
7466                            raw_probes,
7467                            gw,
7468                            gh,
7469                            gy0,
7470                            (inputs.denoise_probes, inputs.denoise_gi_channels),
7471                            &mut scratch.buf_a,
7472                        );
7473                        scratch.cached_gy_a = gy0;
7474                    }
7475                    if gy1 != gy0 {
7476                        if a_is_r0 && gy1 != scratch.cached_gy_b {
7477                            Self::populate_probe_row_stack(
7478                                raw_probes,
7479                                gw,
7480                                gh,
7481                                gy1,
7482                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7483                                &mut scratch.buf_b,
7484                            );
7485                            scratch.cached_gy_b = gy1;
7486                        } else if !a_is_r0 && gy1 != scratch.cached_gy_a {
7487                            Self::populate_probe_row_stack(
7488                                raw_probes,
7489                                gw,
7490                                gh,
7491                                gy1,
7492                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7493                                &mut scratch.buf_a,
7494                            );
7495                            scratch.cached_gy_a = gy1;
7496                        }
7497                    }
7498                }
7499                let (probe_r0, probe_r1): (RtProbeRowView<'_>, RtProbeRowView<'_>) =
7500                    if use_stack_denoise {
7501                        let (v0, v_other): (RtProbeRowView<'_>, RtProbeRowView<'_>) = if a_is_r0 {
7502                            (scratch.buf_a.as_view(gw), scratch.buf_b.as_view(gw))
7503                        } else {
7504                            (scratch.buf_b.as_view(gw), scratch.buf_a.as_view(gw))
7505                        };
7506                        if gy1 == gy0 { (v0, v0) } else { (v0, v_other) }
7507                    } else if rt_active {
7508                        let grid: &RtProbeGridSoa = if !inputs.wide_denoised_probes.is_empty() {
7509                            inputs.wide_denoised_probes
7510                        } else {
7511                            raw_probes
7512                        };
7513                        (grid.row_view(gy0, gw), grid.row_view(gy1, gw))
7514                    } else {
7515                        (scratch.buf_a.as_view(0), scratch.buf_a.as_view(0))
7516                    };
7517                let mut cached_probe_key: (usize, u32) = (usize::MAX, u32::MAX);
7518                let mut cached_cell: CachedProbeCell = CachedProbeCell::empty();
7519                let mut raw_ray: Vec3 =
7520                    row_base_dir.add(frame_context.camera_right_scaled.scale(ndc_x0));
7521                let mut gx_cur: usize = 0;
7522                let mut sub_x: i32 = init_sub_x;
7523                let g_row: &[u32] = &g_tri_idx[row_off..(row_off + width_val)];
7524                let d_row: &[f32] = &depth_buf[row_off..(row_off + width_val)];
7525                let c_row: &mut [u8] =
7526                    &mut color_band[out_row_rgba..(out_row_rgba + width_val * 4)];
7527                let l_row: &mut [u8] = &mut luma_band[out_row_luma..(out_row_luma + width_val)];
7528                let mut px: usize = 0;
7529                while px < width_val {
7530                    let tid: u32 = g_row[px];
7531                    if tid == u32::MAX {
7532                        let sky_hdr: Vec3 =
7533                            Self::sample_sky_lut(inputs.sky_lut, raw_ray, &frame_context.sun);
7534                        let exposed: Vec3 = sky_hdr.scale(frame_context.exposure_scale);
7535                        let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
7536                        let luma: u8 = (((rgba[0] as u32) * 77
7537                            + (rgba[1] as u32) * 150
7538                            + (rgba[2] as u32) * 29)
7539                            >> 8) as u8;
7540                        if write_bloom_row && (px & 3) == 0 {
7541                            let bidx: usize = bloom_row_off + (px >> 2);
7542                            if bidx < bloom_band.len() {
7543                                let er: f32 = (exposed.get_x() - 1.15).max(0.0);
7544                                let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
7545                                let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
7546                                bloom_band[bidx] = [er, eg, eb, 0.0];
7547                                if er + eg + eb > 0.0 {
7548                                    bloom_emitted = true;
7549                                    row_bloom_hit = true;
7550                                }
7551                            }
7552                        }
7553                        let cidx_sky: usize = px * 4;
7554                        c_row[cidx_sky..(cidx_sky + 4)].copy_from_slice(&rgba);
7555                        l_row[px] = luma;
7556                        raw_ray = raw_ray.add(ray_dx);
7557                        sub_x += 2;
7558                        if sub_x >= step2_i32 {
7559                            sub_x -= step2_i32;
7560                            gx_cur += 1;
7561                        }
7562                        px += 1;
7563                        continue;
7564                    }
7565                    if px + 4 <= width_val
7566                        && g_row[px + 1] == tid
7567                        && g_row[px + 2] == tid
7568                        && g_row[px + 3] == tid
7569                        && shaded_tris[tid as usize].smooth_idx == u32::MAX
7570                    {
7571                        let tri: &GShadeTri = &shaded_tris[tid as usize];
7572                        let prev_px: usize = px;
7573                        let probe_band: ProbeBandContext<'_> = ProbeBandContext {
7574                            top_row: &probe_r0,
7575                            bottom_row: &probe_r1,
7576                            wy0,
7577                            wy1,
7578                            gw_max,
7579                            step2_i32,
7580                            fx_lut: &fx_lut,
7581                        };
7582                        let hit_b: bool = Self::shade_tri_run_4x(
7583                            frame_context,
7584                            (tri, tid, rt_active, gi_active),
7585                            &probe_band,
7586                            (&mut cached_probe_key, &mut cached_cell, &mut run_scratch),
7587                            (
7588                                g_row,
7589                                d_row,
7590                                RunRowOut {
7591                                    color: c_row,
7592                                    luma: l_row,
7593                                    write_bloom: write_bloom_row,
7594                                    bloom_off: bloom_row_off,
7595                                    bloom_band,
7596                                    sky_lut: inputs.sky_lut,
7597                                    aces_lut: inputs.aces_lut,
7598                                },
7599                            ),
7600                            (&mut px, &mut raw_ray, ray_dx, &mut gx_cur, &mut sub_x),
7601                        );
7602                        if hit_b {
7603                            bloom_emitted = true;
7604                            row_bloom_hit = true;
7605                        }
7606                        if px != prev_px {
7607                            continue;
7608                        }
7609                    }
7610                    let cidx: usize = px * 4;
7611                    let tri: &GShadeTri = &shaded_tris[tid as usize];
7612                    let depth: f32 = 1.0 / d_row[px].max(1e-6);
7613                    let world_p_px: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
7614                    if tri.smooth_idx != u32::MAX
7615                        && let Some(smooth_tri) = inputs.smooth_tris.get(tri.smooth_idx as usize)
7616                    {
7617                        let smooth_rgba: [u8; 4] = Self::shade_pixel_principled_smooth(
7618                            frame_context,
7619                            inputs,
7620                            tri,
7621                            smooth_tri,
7622                            (px, py),
7623                            (world_p_px, raw_ray, depth),
7624                        );
7625                        c_row[cidx..(cidx + 4)].copy_from_slice(&smooth_rgba);
7626                        l_row[px] = (((smooth_rgba[0] as u32) * 77
7627                            + (smooth_rgba[1] as u32) * 150
7628                            + (smooth_rgba[2] as u32) * 29)
7629                            >> 8) as u8;
7630                        raw_ray = raw_ray.add(ray_dx);
7631                        sub_x += 2;
7632                        if sub_x >= step2_i32 {
7633                            sub_x -= step2_i32;
7634                            gx_cur += 1;
7635                        }
7636                        px += 1;
7637                        continue;
7638                    }
7639                    let mut shadow: f32 = 1.0;
7640                    let mut refl: Vec3 = sky_horizon;
7641                    let mut gi_col: Vec3 = Vec3::zero();
7642                    let mut ao: f32 = 1.0;
7643                    if rt_active {
7644                        let (gx0, gx1, fx): (usize, usize, f32) = if sub_x <= 0 && gx_cur == 0 {
7645                            (0, gw_max.min(1), 0.0)
7646                        } else if gx_cur >= gw_max {
7647                            (gw_max, gw_max, 0.0)
7648                        } else {
7649                            (gx_cur, gx_cur + 1, fx_lut[(sub_x as usize).min(15)])
7650                        };
7651                        let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7652                        if cached_probe_key != probe_key {
7653                            cached_probe_key = probe_key;
7654                            CachedProbeCell::load_into(
7655                                &mut cached_cell,
7656                                &probe_r0,
7657                                &probe_r1,
7658                                (gx0, gx1),
7659                                tri.shade_n,
7660                                (tri.do_refl, gi_active),
7661                            );
7662                        }
7663                        let wx0: f32 = 1.0 - fx;
7664                        let wx1: f32 = fx;
7665                        let bws: [f32; 4] = [wx0 * wy0, wx1 * wy0, wx0 * wy1, wx1 * wy1];
7666                        let (valid_matches, sh_b, s_min, s_max, rf_b, gi_b, ao_b): (
7667                            u32,
7668                            f32,
7669                            f32,
7670                            f32,
7671                            Vec3,
7672                            Vec3,
7673                            f32,
7674                        ) = CachedProbeCell::sample_1x(
7675                            &cached_cell,
7676                            bws,
7677                            depth,
7678                            (tri.do_refl, gi_active),
7679                        );
7680                        let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7681                            18.0
7682                        } else {
7683                            42.0
7684                        };
7685                        let need_exact_shadow: bool = tri.n_dot_l > 0.02
7686                            && depth < edge_max_d
7687                            && (valid_matches == 0 || (!gi_active && (s_max - s_min) > 0.12));
7688                        if need_exact_shadow {
7689                            let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
7690                            edge_rays += 1;
7691                            shadow = if World3D::trace_any_shadow_with_instances(
7692                                inputs.static_bvh,
7693                                inputs.dyn_instances,
7694                                inputs.local_bvhs,
7695                                (origin, sun_dir, inv_sun),
7696                                (0.05, 140.0),
7697                                (&mut static_shadow_cache, &mut dyn_shadow_cache),
7698                            ) {
7699                                0.22
7700                            } else {
7701                                1.0
7702                            };
7703                        } else if valid_matches > 0 {
7704                            shadow = sh_b;
7705                        }
7706                        if tri.do_refl {
7707                            if valid_matches > 0 {
7708                                refl = rf_b;
7709                            } else if depth < 32.0 {
7710                                let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
7711                                let refl_dir: Vec3 =
7712                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
7713                                let inv_refl: Vec3 = Ray3D::safe_inv_vec(refl_dir);
7714                                edge_rays += 1;
7715                                refl = match World3D::trace_closest_with_instances(
7716                                    inputs.static_bvh,
7717                                    inputs.dyn_instances,
7718                                    inputs.local_bvhs,
7719                                    (origin, refl_dir, inv_refl),
7720                                    (0.08, 96.0),
7721                                ) {
7722                                    Some((_, hit_n, hit_mat)) => Self::shade_surface_hit(
7723                                        hit_n,
7724                                        hit_mat,
7725                                        &frame_context.sun,
7726                                        gi_active,
7727                                    ),
7728                                    None => Self::sample_sky_lut(
7729                                        inputs.sky_lut,
7730                                        refl_dir,
7731                                        &frame_context.sun,
7732                                    ),
7733                                };
7734                            } else {
7735                                let refl_dir: Vec3 =
7736                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
7737                                refl = Self::sample_sky_lut(
7738                                    inputs.sky_lut,
7739                                    refl_dir,
7740                                    &frame_context.sun,
7741                                );
7742                            }
7743                        }
7744                        if gi_active && valid_matches > 0 {
7745                            gi_col = gi_b;
7746                            ao = ao_b;
7747                        }
7748                    }
7749                    let view_in: Vec3 = raw_ray.normalize();
7750                    let view_to_cam: Vec3 = view_in.scale(-1.0);
7751                    let ndv_raw: f32 = tri.shade_n.dot(view_to_cam);
7752                    let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
7753                    let f_om: f32 = 1.0 - ndv;
7754                    let f_om2: f32 = f_om * f_om;
7755                    let fresnel_t: f32 = f_om2 * f_om2 * f_om;
7756                    let v_dot_l: f32 = view_to_cam.dot(sun_dir);
7757                    let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
7758                        let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
7759                        let h_len_sq: f32 = 2.0_f32.mul_add(v_dot_l, 2.0).max(1e-6);
7760                        let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
7761                        let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
7762                        let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * shadow;
7763                        let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
7764                        let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
7765                        let spec_scalar: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
7766                        let fresnel_rgb: Vec3 =
7767                            tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
7768                        fresnel_rgb.mul(sun_col.scale(spec_scalar))
7769                    } else {
7770                        Vec3::zero()
7771                    };
7772                    let mut surf_base: Vec3 = tri.mat_base;
7773                    let mut surf_emissive: Vec3 = tri.mat_emissive;
7774                    let mut surf_refl: f32 = tri.mat_refl;
7775                    match tri.surface_detail {
7776                        SurfaceDetailMode::ArchitecturalFacade
7777                            if tri.shade_n.get_y().abs() < 0.25
7778                                && surf_emissive.length_sq() < 0.02 =>
7779                        {
7780                            let (wall_tan_x, wall_tan_z): (f32, f32) =
7781                                Self::facade_wall_tangent(tri.shade_n);
7782                            let u_coord: f32 = world_p_px
7783                                .get_x()
7784                                .mul_add(wall_tan_x, world_p_px.get_z() * wall_tan_z);
7785                            let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
7786                                (u_coord, world_p_px.get_y(), depth, frame_context.inv_height),
7787                                (surf_base, surf_emissive, surf_refl),
7788                            );
7789                            surf_base = nb;
7790                            surf_emissive = ne;
7791                            surf_refl = nr;
7792                        }
7793                        SurfaceDetailMode::RoadSurface
7794                            if tri.shade_n.get_y() > 0.92 && world_p_px.get_y().abs() < 0.15 =>
7795                        {
7796                            let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
7797                                (
7798                                    world_p_px.get_x(),
7799                                    world_p_px.get_z(),
7800                                    depth,
7801                                    frame_context.inv_height,
7802                                ),
7803                                (
7804                                    view_to_cam,
7805                                    fresnel_t,
7806                                    tri.metallic,
7807                                    frame_context.world_time_secs,
7808                                ),
7809                                surf_base,
7810                            );
7811                            surf_base = nb;
7812                            surf_refl = nr;
7813                        }
7814                        _ => {}
7815                    }
7816                    let is_east_coastal_bay: bool = tri.surface_detail
7817                        == SurfaceDetailMode::RoadSurface
7818                        && tri.shade_n.get_y() > 0.92
7819                        && world_p_px.get_y().abs() < 0.15
7820                        && world_p_px.get_x() > 144.0
7821                        && {
7822                            let bay_spine_z: f32 = world_p_px.get_z().clamp(-140.0, 140.0);
7823                            (world_p_px.get_x() - 64.0).hypot(world_p_px.get_z() - bay_spine_z)
7824                                > 78.2
7825                        };
7826                    let radiance: Vec3 = if (tri.surface_detail == SurfaceDetailMode::OceanWater
7827                        && tri.shade_n.get_y() > 0.90)
7828                        || is_east_coastal_bay
7829                    {
7830                        Self::eval_ocean_water_radiance(
7831                            frame_context,
7832                            inputs.sky_lut,
7833                            (world_p_px, view_to_cam, depth),
7834                            (shadow, refl),
7835                        )
7836                    } else {
7837                        let kd_scale: f32 =
7838                            (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
7839                        let direct: Vec3 = sun_col.scale(tri.n_dot_l * shadow * kd_scale);
7840                        let indirect: Vec3 = tri.ambient_sky.scale(0.44 * ao).add(gi_col);
7841                        let mut lit: Vec3 = surf_base
7842                            .mul(direct.add(indirect))
7843                            .add(spec_col)
7844                            .add(surf_emissive);
7845                        if tri.do_refl {
7846                            let refl_fresnel: f32 =
7847                                (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
7848                            let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
7849                            lit = lit.lerp(refl, refl_blend);
7850                        }
7851                        if frame_context.fog_on {
7852                            let py_world: f32 = world_p_px.get_y();
7853                            let height_atten: f32 = if py_world > 0.0 {
7854                                (1.0 / (1.0 + py_world * 0.045)).max(0.32)
7855                            } else {
7856                                1.0
7857                            };
7858                            let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
7859                            let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
7860                            let sun_align: f32 = (-v_dot_l).max(0.0);
7861                            let sa2: f32 = sun_align * sun_align;
7862                            let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * shadow);
7863                            let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
7864                            lit = lit.lerp(fog_col, fog_t);
7865                        }
7866                        lit
7867                    };
7868                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
7869                    if write_bloom_row && (px & 3) == 0 {
7870                        let bidx: usize = bloom_row_off + (px >> 2);
7871                        if bidx < bloom_band.len() {
7872                            let er: f32 = (exposed.get_x() - 1.05).max(0.0);
7873                            let eg: f32 = (exposed.get_y() - 1.05).max(0.0);
7874                            let eb: f32 = (exposed.get_z() - 1.05).max(0.0);
7875                            bloom_band[bidx] = [er, eg, eb, 0.0];
7876                            let rg_pos: bool = er > 0.0 || eg > 0.0;
7877                            if rg_pos || eb > 0.0 {
7878                                bloom_emitted = true;
7879                                row_bloom_hit = true;
7880                            }
7881                        }
7882                    }
7883                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
7884                    c_row[cidx..(cidx + 4)].copy_from_slice(&rgba);
7885                    l_row[px] =
7886                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
7887                            >> 8) as u8;
7888                    raw_ray = raw_ray.add(ray_dx);
7889                    sub_x += 2;
7890                    if sub_x >= step2_i32 {
7891                        sub_x -= step2_i32;
7892                        gx_cur += 1;
7893                    }
7894                    px += 1;
7895                }
7896                if row_bloom_hit {
7897                    let by: usize = py >> 2;
7898                    let word: usize = by >> 6;
7899                    if word < inputs.bloom_row_bits.len() {
7900                        let _: u64 = inputs.bloom_row_bits[word]
7901                            .fetch_or(1_u64 << (by & 63), Ordering::Relaxed);
7902                    }
7903                }
7904            }
7905        });
7906        (edge_rays, bloom_emitted)
7907    }
7908
7909    /// Samples the quarter-resolution HDR bloom buffer using row-hoisted coordinates for active bloom tiles.
7910    ///
7911    /// # Arguments
7912    ///
7913    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom slice.
7914    /// - `(usize, usize, usize)` - Row offsets and max X `(bloom_r0, bloom_r1, bw_max)`.
7915    /// - `(usize, f32, f32)` - Tile column and fractional weights `(bx0, tx, ty)`.
7916    ///
7917    /// # Returns
7918    ///
7919    /// - `[f32; 3]` - Bilinearly filtered bloom RGB radiance.
7920    #[inline(always)]
7921    #[must_use]
7922    fn sample_bloom_bilinear_row(
7923        bloom: &[[f32; 4]],
7924        row_info: (usize, usize, usize),
7925        tap: (usize, f32, f32),
7926    ) -> [f32; 3] {
7927        let (r0, r1, bw_max): (usize, usize, usize) = row_info;
7928        let (bx0, tx, ty): (usize, f32, f32) = tap;
7929        let bx1: usize = (bx0 + 1).min(bw_max);
7930        let c00: [f32; 4] = bloom[r0 + bx0];
7931        let c10: [f32; 4] = bloom[r0 + bx1];
7932        let c01: [f32; 4] = bloom[r1 + bx0];
7933        let c11: [f32; 4] = bloom[r1 + bx1];
7934        let omt_x: f32 = 1.0 - tx;
7935        let omt_y: f32 = 1.0 - ty;
7936        let w00: f32 = omt_x * omt_y;
7937        let w10: f32 = tx * omt_y;
7938        let w01: f32 = omt_x * ty;
7939        let w11: f32 = tx * ty;
7940        [
7941            c00[0].mul_add(w00, c10[0].mul_add(w10, c01[0].mul_add(w01, c11[0] * w11))),
7942            c00[1].mul_add(w00, c10[1].mul_add(w10, c01[1].mul_add(w01, c11[1] * w11))),
7943            c00[2].mul_add(w00, c10[2].mul_add(w10, c01[2].mul_add(w01, c11[2] * w11))),
7944        ]
7945    }
7946
7947    /// Populates `bloom_tile_active` (`1` where any bilinear corner contributes `>= 1` RGB LSB) and returns whether any tile is active.
7948    ///
7949    /// # Arguments
7950    ///
7951    /// - `usize` - Quarter-resolution bloom grid width.
7952    /// - `usize` - Quarter-resolution bloom grid height.
7953    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom buffer.
7954    /// - `&mut [u8]` - Output tile-activity mask slice (`len >= bw * bh`).
7955    ///
7956    /// # Returns
7957    ///
7958    /// - `bool` - `true` when at least one bloom tile requires sampling in `post_process_band`.
7959    #[must_use]
7960    fn build_bloom_tile_mask(
7961        border_width: usize,
7962        bh: usize,
7963        bloom: &[[f32; 4]],
7964        tile_active: &mut [u8],
7965    ) -> bool {
7966        let len: usize = border_width * bh;
7967        let short_bloom: bool = len == 0 || bloom.len() < len;
7968        if short_bloom || tile_active.len() < len {
7969            return false;
7970        }
7971        let bw_max: usize = border_width - 1;
7972        let bh_max: usize = bh - 1;
7973        let mut any_active: bool = false;
7974        for by in 0..bh {
7975            let r0: usize = by * border_width;
7976            let r1: usize = (by + 1).min(bh_max) * border_width;
7977            for bx in 0..border_width {
7978                let bx1: usize = (bx + 1).min(bw_max);
7979                let c00: [f32; 4] = bloom[r0 + bx];
7980                let c10: [f32; 4] = bloom[r0 + bx1];
7981                let c01: [f32; 4] = bloom[r1 + bx];
7982                let c11: [f32; 4] = bloom[r1 + bx1];
7983                let max_r: f32 = c00[0].max(c10[0]).max(c01[0]).max(c11[0]);
7984                let max_g: f32 = c00[1].max(c10[1]).max(c01[1]).max(c11[1]);
7985                let max_b: f32 = c00[2].max(c10[2]).max(c01[2]).max(c11[2]);
7986                let active: bool = max_r.max(max_g).max(max_b) >= 0.015;
7987                tile_active[r0 + bx] = u8::from(active);
7988                if active {
7989                    any_active = true;
7990                }
7991            }
7992        }
7993        any_active
7994    }
7995
7996    /// Loads one 4-byte RGBA pixel at `idx` from `src` into an ARM64 NEON `uint8x8_t` duplicated vector.
7997    ///
7998    /// # Arguments
7999    ///
8000    /// - `&[u8]` - Source RGBA8 pixel buffer.
8001    /// - `usize` - Byte offset (`idx + 4 <= src.len()`).
8002    ///
8003    /// # Returns
8004    ///
8005    /// - `core::arch::aarch64::uint8x8_t` - Replicated RGBA byte vector.
8006    #[cfg(target_arch = "aarch64")]
8007    #[inline(always)]
8008    unsafe fn neon_load_px_u8(src: &[u8], idx: usize) -> core::arch::aarch64::uint8x8_t {
8009        // SAFETY: Caller guarantees `idx + 4 <= src.len()` and ARM64 NEON execution context.
8010        unsafe {
8011            let word: u32 = src.as_ptr().add(idx).cast::<u32>().read_unaligned();
8012            core::arch::aarch64::vreinterpret_u8_u32(core::arch::aarch64::vdup_n_u32(word))
8013        }
8014    }
8015
8016    /// Fused Barrier 3 post-process pass applying 16-pixel SIMD flat-span copy, Geometry-Aware FXAA 3.11 + 8-step Morphological AA, 9-tap variance-clamped TAA, and active-tile bilinear HDR Bloom directly into output memory.
8017    ///
8018    /// # Arguments
8019    ///
8020    /// - `(usize, usize, usize, usize)` - Dimensions `(w, h, bloom_w, bloom_h)`.
8021    /// - `&PostProcessInputs<'_>` - Read-only color, luma, G-Buffer IDs, bloom, bloom mask, and TAA history.
8022    /// - `(bool, bool, bool)` - Flags `(use_fxaa, use_taa, use_bloom)`.
8023    /// - `(usize, *mut u8, usize)` - `(y_start, writable band RGBA base pointer, band row count)`.
8024    unsafe fn post_process_band(
8025        dims: (usize, usize, usize, usize),
8026        inputs: &PostProcessInputs<'_>,
8027        flags: (bool, bool, bool),
8028        band: (usize, *mut u8, usize),
8029    ) {
8030        let (width_val, height_val, border_width, bh): (usize, usize, usize, usize) = dims;
8031        let src: &[u8] = inputs.color_src;
8032        let luma: &[u8] = inputs.luma;
8033        let g_tri_idx: &[u32] = inputs.g_tri_idx;
8034        let bloom: &[[f32; 4]] = inputs.bloom;
8035        let bloom_active: &[u8] = inputs.bloom_tile_active;
8036        let history: &[u8] = inputs.taa_history;
8037        let (use_fxaa, use_taa, use_bloom): (bool, bool, bool) = flags;
8038        let (y_start, dst_ptr, band_rows): (usize, *mut u8, usize) = band;
8039        let row_bytes: usize = width_val * 4;
8040        let bloom_len: usize = border_width * bh;
8041        let has_bloom: bool = use_bloom
8042            && bloom_len > 0
8043            && bloom.len() >= bloom_len
8044            && bloom_active.len() >= bloom_len;
8045        let bw_max: usize = border_width.saturating_sub(1);
8046        let bh_max: usize = bh.saturating_sub(1);
8047        let has_taa: bool = use_taa && history.len() == src.len();
8048        let w_i32: i32 = width_val as i32;
8049        let h_i32: i32 = height_val as i32;
8050        for local_y in 0..band_rows {
8051            let coord_y: usize = y_start + local_y;
8052            let src_off: usize = coord_y * row_bytes;
8053            let dst_off: usize = local_y * row_bytes;
8054            if !use_fxaa && !has_bloom && !has_taa {
8055                // SAFETY: Caller guarantees `dst_ptr` covers `band_rows * row_bytes` disjoint writable bytes,
8056                // and `src_off + row_bytes <= src.len()` since `y < h`.
8057                unsafe {
8058                    dst_ptr
8059                        .add(dst_off)
8060                        .copy_from_nonoverlapping(src.as_ptr().add(src_off), row_bytes);
8061                }
8062                continue;
8063            }
8064            let by0: usize = (coord_y >> 2).min(bh_max);
8065            let by1: usize = (by0 + 1).min(bh_max);
8066            let ty: f32 = ((coord_y & 3) as f32) * 0.25;
8067            let bloom_r0: usize = by0 * border_width;
8068            let bloom_r1: usize = by1 * border_width;
8069            let edge_row: bool = coord_y == 0 || coord_y + 1 >= height_val;
8070            let simple_row: bool = !use_fxaa || edge_row;
8071            if simple_row || width_val < 3 {
8072                for pos_x in 0..width_val {
8073                    let scale_factor: usize = src_off + pos_x * 4;
8074                    let dc: usize = dst_off + pos_x * 4;
8075                    let mut red_val: i32 = src[scale_factor] as i32;
8076                    let mut green_val: i32 = src[scale_factor + 1] as i32;
8077                    let mut blue_val: i32 = src[scale_factor + 2] as i32;
8078                    if has_bloom {
8079                        let bx0: usize = (pos_x >> 2).min(bw_max);
8080                        if bloom_active[bloom_r0 + bx0] != 0 {
8081                            let tx: f32 = ((pos_x & 3) as f32) * 0.25;
8082                            let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
8083                                bloom,
8084                                (bloom_r0, bloom_r1, bw_max),
8085                                (bx0, tx, ty),
8086                            );
8087                            red_val = (red_val + (bl[0] * 64.0) as i32).min(255);
8088                            green_val = (green_val + (bl[1] * 64.0) as i32).min(255);
8089                            blue_val = (blue_val + (bl[2] * 64.0) as i32).min(255);
8090                        }
8091                    }
8092                    // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
8093                    unsafe {
8094                        dst_ptr.add(dc).cast::<[u8; 4]>().write([
8095                            red_val as u8,
8096                            green_val as u8,
8097                            blue_val as u8,
8098                            255,
8099                        ]);
8100                    }
8101                }
8102                continue;
8103            }
8104            let last_px: usize = (width_val - 1) * 4;
8105            // SAFETY: `w >= 3`, so both first and last 4-byte pixels lie within `dst_off..dst_off + row_bytes`.
8106            unsafe {
8107                dst_ptr
8108                    .add(dst_off)
8109                    .copy_from_nonoverlapping(src.as_ptr().add(src_off), 4);
8110                dst_ptr
8111                    .add(dst_off + last_px)
8112                    .copy_from_nonoverlapping(src.as_ptr().add(src_off + last_px), 4);
8113            }
8114            let row: usize = coord_y * width_val;
8115            let row_up: usize = (coord_y - 1) * width_val;
8116            let row_dn: usize = (coord_y + 1) * width_val;
8117            let y_i32: i32 = coord_y as i32;
8118            let luma_c: &[u8] = &luma[row..(row + width_val)];
8119            let luma_u: &[u8] = &luma[row_up..(row_up + width_val)];
8120            let luma_d: &[u8] = &luma[row_dn..(row_dn + width_val)];
8121            let bloom_row_mask: &[u8] = if has_bloom {
8122                &bloom_active[bloom_r0..(bloom_r0 + border_width)]
8123            } else {
8124                &[]
8125            };
8126            let row_has_bloom: bool =
8127                has_bloom && bloom_row_mask.iter().any(|&flag: &u8| flag != 0);
8128            let mut coord_x: usize = 1;
8129            let x_end: usize = width_val - 1;
8130            while coord_x < x_end {
8131                #[cfg(target_arch = "aarch64")]
8132                if coord_x + 16 <= x_end {
8133                    let lc_u8: u8 = luma_c[coord_x];
8134                    if luma_c[coord_x + 4] == lc_u8
8135                        && luma_u[coord_x] == lc_u8
8136                        && luma_d[coord_x] == lc_u8
8137                    {
8138                        let no_bloom_16: bool = !row_has_bloom || {
8139                            let t0: usize = (coord_x >> 2).min(bw_max);
8140                            let t1: usize = (t0 + 1).min(bw_max);
8141                            let t2: usize = (t0 + 2).min(bw_max);
8142                            let t3: usize = (t0 + 3).min(bw_max);
8143                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8144                            (bloom_row_mask[t0]
8145                                | bloom_row_mask[t1]
8146                                | bloom_row_mask[t2]
8147                                | bloom_row_mask[t3]
8148                                | bloom_row_mask[t4])
8149                                == 0
8150                        };
8151                        if no_bloom_16 {
8152                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8153                            let flat_16: bool = unsafe {
8154                                let splat: core::arch::aarch64::uint8x16_t =
8155                                    core::arch::aarch64::vdupq_n_u8(lc_u8);
8156                                let c16: core::arch::aarch64::uint8x16_t =
8157                                    core::arch::aarch64::vld1q_u8(luma_c.as_ptr().add(coord_x));
8158                                let u16_v: core::arch::aarch64::uint8x16_t =
8159                                    core::arch::aarch64::vld1q_u8(luma_u.as_ptr().add(coord_x));
8160                                let d16: core::arch::aarch64::uint8x16_t =
8161                                    core::arch::aarch64::vld1q_u8(luma_d.as_ptr().add(coord_x));
8162                                let eq_all: core::arch::aarch64::uint8x16_t =
8163                                    core::arch::aarch64::vandq_u8(
8164                                        core::arch::aarch64::vandq_u8(
8165                                            core::arch::aarch64::vceqq_u8(c16, splat),
8166                                            core::arch::aarch64::vceqq_u8(u16_v, splat),
8167                                        ),
8168                                        core::arch::aarch64::vceqq_u8(d16, splat),
8169                                    );
8170                                core::arch::aarch64::vminvq_u8(eq_all) == 0xFF
8171                                    && luma_c[coord_x - 1] == lc_u8
8172                                    && luma_c[coord_x + 16] == lc_u8
8173                                    && luma_u[coord_x - 1] == lc_u8
8174                                    && luma_u[coord_x + 16] == lc_u8
8175                                    && luma_d[coord_x - 1] == lc_u8
8176                                    && luma_d[coord_x + 16] == lc_u8
8177                            };
8178                            let rgba_uniform: bool = flat_16
8179                                && (!has_taa || {
8180                                    let base_px_off: usize = (row + coord_x) * 4;
8181                                    let px0_bytes: &[u8] = &src[base_px_off..(base_px_off + 4)];
8182                                    let row_span_bytes: usize = 18 * 4;
8183                                    let up_slice: &[u8] = &src[((row_up + coord_x - 1) * 4)
8184                                        ..((row_up + coord_x - 1) * 4 + row_span_bytes)];
8185                                    let mid_slice: &[u8] = &src[((row + coord_x - 1) * 4)
8186                                        ..((row + coord_x - 1) * 4 + row_span_bytes)];
8187                                    let dn_slice: &[u8] = &src[((row_dn + coord_x - 1) * 4)
8188                                        ..((row_dn + coord_x - 1) * 4 + row_span_bytes)];
8189                                    mid_slice == up_slice
8190                                        && mid_slice == dn_slice
8191                                        && mid_slice[..68] == mid_slice[4..72]
8192                                        && &mid_slice[..4] == px0_bytes
8193                                });
8194                            if rgba_uniform {
8195                                let sc16: usize = (row + coord_x) * 4;
8196                                let dc16: usize = dst_off + coord_x * 4;
8197                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8198                                unsafe {
8199                                    dst_ptr
8200                                        .add(dc16)
8201                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8202                                }
8203                                coord_x += 16;
8204                                continue;
8205                            }
8206                        }
8207                    }
8208                }
8209                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8210                if !has_taa && coord_x + 16 <= x_end {
8211                    let no_bloom_16: bool = !row_has_bloom || {
8212                        let t0: usize = (coord_x >> 2).min(bw_max);
8213                        let t1: usize = (t0 + 1).min(bw_max);
8214                        let t2: usize = (t0 + 2).min(bw_max);
8215                        let t3: usize = (t0 + 3).min(bw_max);
8216                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8217                        (bloom_row_mask[t0]
8218                            | bloom_row_mask[t1]
8219                            | bloom_row_mask[t2]
8220                            | bloom_row_mask[t3]
8221                            | bloom_row_mask[t4])
8222                            == 0
8223                    };
8224                    if no_bloom_16 {
8225                        // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so `x - 1..x + 15`, `x..x + 16`, and `x + 1..x + 17` all lie within `0..w`.
8226                        let skip_n: usize = unsafe {
8227                            let c_w: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8228                                luma_c.as_ptr().add(coord_x - 1).cast(),
8229                            );
8230                            let c_m: core::arch::wasm32::v128 =
8231                                core::arch::wasm32::v128_load(luma_c.as_ptr().add(coord_x).cast());
8232                            let c_e: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8233                                luma_c.as_ptr().add(coord_x + 1).cast(),
8234                            );
8235                            let u_m: core::arch::wasm32::v128 =
8236                                core::arch::wasm32::v128_load(luma_u.as_ptr().add(coord_x).cast());
8237                            let d_m: core::arch::wasm32::v128 =
8238                                core::arch::wasm32::v128_load(luma_d.as_ptr().add(coord_x).cast());
8239                            let lmax: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_max(
8240                                core::arch::wasm32::u8x16_max(
8241                                    core::arch::wasm32::u8x16_max(c_m, u_m),
8242                                    core::arch::wasm32::u8x16_max(d_m, c_e),
8243                                ),
8244                                c_w,
8245                            );
8246                            let lmin: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_min(
8247                                core::arch::wasm32::u8x16_min(
8248                                    core::arch::wasm32::u8x16_min(c_m, u_m),
8249                                    core::arch::wasm32::u8x16_min(d_m, c_e),
8250                                ),
8251                                c_w,
8252                            );
8253                            let contrast: core::arch::wasm32::v128 =
8254                                core::arch::wasm32::i8x16_sub(lmax, lmin);
8255                            let ge3_mask: u32 =
8256                                core::arch::wasm32::u8x16_bitmask(core::arch::wasm32::u8x16_ge(
8257                                    contrast,
8258                                    core::arch::wasm32::u8x16_splat(3),
8259                                )) as u32;
8260                            if ge3_mask == 0 {
8261                                16
8262                            } else if (ge3_mask & 0x00FF) == 0 {
8263                                8
8264                            } else if (ge3_mask & 0x000F) == 0 {
8265                                4
8266                            } else {
8267                                0
8268                            }
8269                        };
8270                        if skip_n != 0 {
8271                            let sc_n: usize = (row + coord_x) * 4;
8272                            let dc_n: usize = dst_off + coord_x * 4;
8273                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8274                            unsafe {
8275                                dst_ptr
8276                                    .add(dc_n)
8277                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8278                            }
8279                            coord_x += skip_n;
8280                            continue;
8281                        }
8282                    }
8283                }
8284                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8285                if has_taa && coord_x + 16 <= x_end {
8286                    let lc_u8: u8 = luma_c[coord_x];
8287                    if luma_c[coord_x + 4] == lc_u8
8288                        && luma_u[coord_x] == lc_u8
8289                        && luma_d[coord_x] == lc_u8
8290                    {
8291                        let no_bloom_16: bool = !row_has_bloom || {
8292                            let t0: usize = (coord_x >> 2).min(bw_max);
8293                            let t1: usize = (t0 + 1).min(bw_max);
8294                            let t2: usize = (t0 + 2).min(bw_max);
8295                            let t3: usize = (t0 + 3).min(bw_max);
8296                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8297                            (bloom_row_mask[t0]
8298                                | bloom_row_mask[t1]
8299                                | bloom_row_mask[t2]
8300                                | bloom_row_mask[t3]
8301                                | bloom_row_mask[t4])
8302                                == 0
8303                        };
8304                        if no_bloom_16 {
8305                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8306                            let flat_16: bool = unsafe {
8307                                let splat: core::arch::wasm32::v128 =
8308                                    core::arch::wasm32::u8x16_splat(lc_u8);
8309                                let c16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8310                                    luma_c.as_ptr().add(coord_x).cast(),
8311                                );
8312                                let u16_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8313                                    luma_u.as_ptr().add(coord_x).cast(),
8314                                );
8315                                let d16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8316                                    luma_d.as_ptr().add(coord_x).cast(),
8317                                );
8318                                let eq_all: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
8319                                    core::arch::wasm32::v128_and(
8320                                        core::arch::wasm32::u8x16_eq(c16, splat),
8321                                        core::arch::wasm32::u8x16_eq(u16_v, splat),
8322                                    ),
8323                                    core::arch::wasm32::u8x16_eq(d16, splat),
8324                                );
8325                                core::arch::wasm32::u8x16_all_true(eq_all)
8326                                    && luma_c[coord_x - 1] == lc_u8
8327                                    && luma_c[coord_x + 16] == lc_u8
8328                                    && luma_u[coord_x - 1] == lc_u8
8329                                    && luma_u[coord_x + 16] == lc_u8
8330                                    && luma_d[coord_x - 1] == lc_u8
8331                                    && luma_d[coord_x + 16] == lc_u8
8332                            };
8333                            if flat_16 {
8334                                let sc16: usize = (row + coord_x) * 4;
8335                                let dc16: usize = dst_off + coord_x * 4;
8336                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8337                                unsafe {
8338                                    dst_ptr
8339                                        .add(dc16)
8340                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8341                                }
8342                                coord_x += 16;
8343                                continue;
8344                            }
8345                        }
8346                    }
8347                }
8348                #[cfg(target_arch = "x86_64")]
8349                if !has_taa && coord_x + 16 <= x_end {
8350                    let no_bloom_16: bool = !row_has_bloom || {
8351                        let t0: usize = (coord_x >> 2).min(bw_max);
8352                        let t1: usize = (t0 + 1).min(bw_max);
8353                        let t2: usize = (t0 + 2).min(bw_max);
8354                        let t3: usize = (t0 + 3).min(bw_max);
8355                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8356                        (bloom_row_mask[t0]
8357                            | bloom_row_mask[t1]
8358                            | bloom_row_mask[t2]
8359                            | bloom_row_mask[t3]
8360                            | bloom_row_mask[t4])
8361                            == 0
8362                    };
8363                    if no_bloom_16 {
8364                        // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so `x - 1..x + 15`, `x..x + 16`, and `x + 1..x + 17` all lie within `0..w`.
8365                        let skip_n: usize = unsafe {
8366                            let c_w: core::arch::x86_64::__m128i =
8367                                core::arch::x86_64::_mm_loadu_si128(
8368                                    luma_c.as_ptr().add(coord_x - 1).cast(),
8369                                );
8370                            let c_m: core::arch::x86_64::__m128i =
8371                                core::arch::x86_64::_mm_loadu_si128(
8372                                    luma_c.as_ptr().add(coord_x).cast(),
8373                                );
8374                            let c_e: core::arch::x86_64::__m128i =
8375                                core::arch::x86_64::_mm_loadu_si128(
8376                                    luma_c.as_ptr().add(coord_x + 1).cast(),
8377                                );
8378                            let u_m: core::arch::x86_64::__m128i =
8379                                core::arch::x86_64::_mm_loadu_si128(
8380                                    luma_u.as_ptr().add(coord_x).cast(),
8381                                );
8382                            let d_m: core::arch::x86_64::__m128i =
8383                                core::arch::x86_64::_mm_loadu_si128(
8384                                    luma_d.as_ptr().add(coord_x).cast(),
8385                                );
8386                            let lmax: core::arch::x86_64::__m128i =
8387                                core::arch::x86_64::_mm_max_epu8(
8388                                    core::arch::x86_64::_mm_max_epu8(
8389                                        core::arch::x86_64::_mm_max_epu8(c_m, u_m),
8390                                        core::arch::x86_64::_mm_max_epu8(d_m, c_e),
8391                                    ),
8392                                    c_w,
8393                                );
8394                            let lmin: core::arch::x86_64::__m128i =
8395                                core::arch::x86_64::_mm_min_epu8(
8396                                    core::arch::x86_64::_mm_min_epu8(
8397                                        core::arch::x86_64::_mm_min_epu8(c_m, u_m),
8398                                        core::arch::x86_64::_mm_min_epu8(d_m, c_e),
8399                                    ),
8400                                    c_w,
8401                                );
8402                            let contrast: core::arch::x86_64::__m128i =
8403                                core::arch::x86_64::_mm_subs_epu8(lmax, lmin);
8404                            let lt3: core::arch::x86_64::__m128i =
8405                                core::arch::x86_64::_mm_cmpeq_epi8(
8406                                    core::arch::x86_64::_mm_subs_epu8(
8407                                        contrast,
8408                                        core::arch::x86_64::_mm_set1_epi8(2),
8409                                    ),
8410                                    core::arch::x86_64::_mm_setzero_si128(),
8411                                );
8412                            let ge3_mask: u32 =
8413                                (!core::arch::x86_64::_mm_movemask_epi8(lt3) as u32) & 0xFFFF;
8414                            if ge3_mask == 0 {
8415                                16
8416                            } else if (ge3_mask & 0x00FF) == 0 {
8417                                8
8418                            } else if (ge3_mask & 0x000F) == 0 {
8419                                4
8420                            } else {
8421                                0
8422                            }
8423                        };
8424                        if skip_n != 0 {
8425                            let sc_n: usize = (row + coord_x) * 4;
8426                            let dc_n: usize = dst_off + coord_x * 4;
8427                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8428                            unsafe {
8429                                dst_ptr
8430                                    .add(dc_n)
8431                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8432                            }
8433                            coord_x += skip_n;
8434                            continue;
8435                        }
8436                    }
8437                }
8438                #[cfg(target_arch = "x86_64")]
8439                if has_taa && coord_x + 16 <= x_end {
8440                    let lc_u8: u8 = luma_c[coord_x];
8441                    if luma_c[coord_x + 4] == lc_u8
8442                        && luma_u[coord_x] == lc_u8
8443                        && luma_d[coord_x] == lc_u8
8444                    {
8445                        let no_bloom_16: bool = !row_has_bloom || {
8446                            let t0: usize = (coord_x >> 2).min(bw_max);
8447                            let t1: usize = (t0 + 1).min(bw_max);
8448                            let t2: usize = (t0 + 2).min(bw_max);
8449                            let t3: usize = (t0 + 3).min(bw_max);
8450                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8451                            (bloom_row_mask[t0]
8452                                | bloom_row_mask[t1]
8453                                | bloom_row_mask[t2]
8454                                | bloom_row_mask[t3]
8455                                | bloom_row_mask[t4])
8456                                == 0
8457                        };
8458                        if no_bloom_16 {
8459                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8460                            let flat_16: bool = unsafe {
8461                                let splat: core::arch::x86_64::__m128i =
8462                                    core::arch::x86_64::_mm_set1_epi8(lc_u8 as i8);
8463                                let c16: core::arch::x86_64::__m128i =
8464                                    core::arch::x86_64::_mm_loadu_si128(
8465                                        luma_c.as_ptr().add(coord_x).cast(),
8466                                    );
8467                                let u16_v: core::arch::x86_64::__m128i =
8468                                    core::arch::x86_64::_mm_loadu_si128(
8469                                        luma_u.as_ptr().add(coord_x).cast(),
8470                                    );
8471                                let d16: core::arch::x86_64::__m128i =
8472                                    core::arch::x86_64::_mm_loadu_si128(
8473                                        luma_d.as_ptr().add(coord_x).cast(),
8474                                    );
8475                                let eq_all: core::arch::x86_64::__m128i =
8476                                    core::arch::x86_64::_mm_and_si128(
8477                                        core::arch::x86_64::_mm_and_si128(
8478                                            core::arch::x86_64::_mm_cmpeq_epi8(c16, splat),
8479                                            core::arch::x86_64::_mm_cmpeq_epi8(u16_v, splat),
8480                                        ),
8481                                        core::arch::x86_64::_mm_cmpeq_epi8(d16, splat),
8482                                    );
8483                                core::arch::x86_64::_mm_movemask_epi8(eq_all) == 0xFFFF
8484                                    && luma_c[coord_x - 1] == lc_u8
8485                                    && luma_c[coord_x + 16] == lc_u8
8486                                    && luma_u[coord_x - 1] == lc_u8
8487                                    && luma_u[coord_x + 16] == lc_u8
8488                                    && luma_d[coord_x - 1] == lc_u8
8489                                    && luma_d[coord_x + 16] == lc_u8
8490                            };
8491                            if flat_16 {
8492                                let sc16: usize = (row + coord_x) * 4;
8493                                let dc16: usize = dst_off + coord_x * 4;
8494                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8495                                unsafe {
8496                                    dst_ptr
8497                                        .add(dc16)
8498                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8499                                }
8500                                coord_x += 16;
8501                                continue;
8502                            }
8503                        }
8504                    }
8505                }
8506                #[cfg(not(target_arch = "aarch64"))]
8507                #[cfg(not(target_arch = "x86_64"))]
8508                #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8509                {
8510                    let no_bloom_8: bool = coord_x + 8 <= x_end
8511                        && (!row_has_bloom
8512                            || (bloom_row_mask[(coord_x >> 2).min(bw_max)] == 0
8513                                && bloom_row_mask[((coord_x + 4) >> 2).min(bw_max)] == 0
8514                                && bloom_row_mask[((coord_x + 7) >> 2).min(bw_max)] == 0));
8515                    if no_bloom_8 {
8516                        let lc_u8: u8 = luma_c[coord_x];
8517                        let splat: u64 = (lc_u8 as u64) * 0x0101_0101_0101_0101_u64;
8518                        // SAFETY: `x >= 1` and `x + 8 <= w - 1`, so all 8-byte unaligned loads and boundary bytes are in bounds.
8519                        let flat_8: bool = unsafe {
8520                            let c8: u64 =
8521                                luma_c.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8522                            let u8_w: u64 =
8523                                luma_u.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8524                            let d8: u64 =
8525                                luma_d.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8526                            c8 == splat
8527                                && u8_w == splat
8528                                && d8 == splat
8529                                && luma_c[coord_x - 1] == lc_u8
8530                                && luma_c[coord_x + 8] == lc_u8
8531                                && luma_u[coord_x - 1] == lc_u8
8532                                && luma_u[coord_x + 8] == lc_u8
8533                                && luma_d[coord_x - 1] == lc_u8
8534                                && luma_d[coord_x + 8] == lc_u8
8535                        };
8536                        if flat_8 {
8537                            let sc8: usize = (row + coord_x) * 4;
8538                            let dc8: usize = dst_off + coord_x * 4;
8539                            // SAFETY: 32-byte range `[dc8..dc8+32]` lies strictly within this band row.
8540                            unsafe {
8541                                dst_ptr
8542                                    .add(dc8)
8543                                    .copy_from_nonoverlapping(src.as_ptr().add(sc8), 32);
8544                            }
8545                            coord_x += 8;
8546                            continue;
8547                        }
8548                    }
8549                }
8550                #[cfg(target_arch = "aarch64")]
8551                if coord_x + 6 <= x_end {
8552                    let no_bloom_4: bool = !row_has_bloom
8553                        || (bloom_row_mask[(coord_x >> 2).min(bw_max)]
8554                            | bloom_row_mask[((coord_x + 3) >> 2).min(bw_max)])
8555                            == 0;
8556                    if no_bloom_4 {
8557                        // SAFETY: `x >= 1` and `x + 6 <= w - 1`, so 8-byte luma loads at `x - 1` and 16-byte RGBA loads at `x - 1` and `x + 1` stay strictly within row bounds.
8558                        let handled_4: bool = unsafe {
8559                            let lc_w: core::arch::aarch64::uint8x8_t =
8560                                core::arch::aarch64::vld1_u8(luma_c.as_ptr().add(coord_x - 1));
8561                            let lu_w: core::arch::aarch64::uint8x8_t =
8562                                core::arch::aarch64::vld1_u8(luma_u.as_ptr().add(coord_x - 1));
8563                            let ld_w: core::arch::aarch64::uint8x8_t =
8564                                core::arch::aarch64::vld1_u8(luma_d.as_ptr().add(coord_x - 1));
8565                            let c_mid: core::arch::aarch64::uint8x8_t =
8566                                core::arch::aarch64::vext_u8::<1>(lc_w, lc_w);
8567                            let c_east: core::arch::aarch64::uint8x8_t =
8568                                core::arch::aarch64::vext_u8::<2>(lc_w, lc_w);
8569                            let u_mid: core::arch::aarch64::uint8x8_t =
8570                                core::arch::aarch64::vext_u8::<1>(lu_w, lu_w);
8571                            let d_mid: core::arch::aarch64::uint8x8_t =
8572                                core::arch::aarch64::vext_u8::<1>(ld_w, ld_w);
8573                            let lmax: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmax_u8(
8574                                core::arch::aarch64::vmax_u8(
8575                                    core::arch::aarch64::vmax_u8(c_mid, u_mid),
8576                                    core::arch::aarch64::vmax_u8(d_mid, c_east),
8577                                ),
8578                                lc_w,
8579                            );
8580                            let lmin: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmin_u8(
8581                                core::arch::aarch64::vmin_u8(
8582                                    core::arch::aarch64::vmin_u8(c_mid, u_mid),
8583                                    core::arch::aarch64::vmin_u8(d_mid, c_east),
8584                                ),
8585                                lc_w,
8586                            );
8587                            let contrast_v: core::arch::aarch64::uint8x8_t =
8588                                core::arch::aarch64::vsub_u8(lmax, lmin);
8589                            let ge3_mask: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8590                                core::arch::aarch64::vreinterpret_u32_u8(
8591                                    core::arch::aarch64::vcge_u8(
8592                                        contrast_v,
8593                                        core::arch::aarch64::vdup_n_u8(3),
8594                                    ),
8595                                ),
8596                            );
8597                            if ge3_mask == 0 {
8598                                let sc4: usize = (row + coord_x) * 4;
8599                                let dc4: usize = dst_off + coord_x * 4;
8600                                if !has_taa {
8601                                    let px4: core::arch::aarch64::uint8x16_t =
8602                                        core::arch::aarch64::vld1q_u8(src.as_ptr().add(sc4));
8603                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), px4);
8604                                } else {
8605                                    let su_a: core::arch::aarch64::uint8x16_t =
8606                                        core::arch::aarch64::vld1q_u8(
8607                                            src.as_ptr().add((row_up + coord_x - 1) * 4),
8608                                        );
8609                                    let su_b: core::arch::aarch64::uint8x16_t =
8610                                        core::arch::aarch64::vld1q_u8(
8611                                            src.as_ptr().add((row_up + coord_x + 1) * 4),
8612                                        );
8613                                    let su_m: core::arch::aarch64::uint8x16_t =
8614                                        core::arch::aarch64::vextq_u8::<4>(su_a, su_b);
8615                                    let sc_a: core::arch::aarch64::uint8x16_t =
8616                                        core::arch::aarch64::vld1q_u8(
8617                                            src.as_ptr().add((row + coord_x - 1) * 4),
8618                                        );
8619                                    let sc_b: core::arch::aarch64::uint8x16_t =
8620                                        core::arch::aarch64::vld1q_u8(
8621                                            src.as_ptr().add((row + coord_x + 1) * 4),
8622                                        );
8623                                    let sc_m: core::arch::aarch64::uint8x16_t =
8624                                        core::arch::aarch64::vextq_u8::<4>(sc_a, sc_b);
8625                                    let sd_a: core::arch::aarch64::uint8x16_t =
8626                                        core::arch::aarch64::vld1q_u8(
8627                                            src.as_ptr().add((row_dn + coord_x - 1) * 4),
8628                                        );
8629                                    let sd_b: core::arch::aarch64::uint8x16_t =
8630                                        core::arch::aarch64::vld1q_u8(
8631                                            src.as_ptr().add((row_dn + coord_x + 1) * 4),
8632                                        );
8633                                    let sd_m: core::arch::aarch64::uint8x16_t =
8634                                        core::arch::aarch64::vextq_u8::<4>(sd_a, sd_b);
8635                                    let min_u: core::arch::aarch64::uint8x16_t =
8636                                        core::arch::aarch64::vminq_u8(
8637                                            core::arch::aarch64::vminq_u8(su_a, su_m),
8638                                            su_b,
8639                                        );
8640                                    let max_u: core::arch::aarch64::uint8x16_t =
8641                                        core::arch::aarch64::vmaxq_u8(
8642                                            core::arch::aarch64::vmaxq_u8(su_a, su_m),
8643                                            su_b,
8644                                        );
8645                                    let min_c: core::arch::aarch64::uint8x16_t =
8646                                        core::arch::aarch64::vminq_u8(
8647                                            core::arch::aarch64::vminq_u8(sc_a, sc_m),
8648                                            sc_b,
8649                                        );
8650                                    let max_c: core::arch::aarch64::uint8x16_t =
8651                                        core::arch::aarch64::vmaxq_u8(
8652                                            core::arch::aarch64::vmaxq_u8(sc_a, sc_m),
8653                                            sc_b,
8654                                        );
8655                                    let min_d: core::arch::aarch64::uint8x16_t =
8656                                        core::arch::aarch64::vminq_u8(
8657                                            core::arch::aarch64::vminq_u8(sd_a, sd_m),
8658                                            sd_b,
8659                                        );
8660                                    let max_d: core::arch::aarch64::uint8x16_t =
8661                                        core::arch::aarch64::vmaxq_u8(
8662                                            core::arch::aarch64::vmaxq_u8(sd_a, sd_m),
8663                                            sd_b,
8664                                        );
8665                                    let box_min: core::arch::aarch64::uint8x16_t =
8666                                        core::arch::aarch64::vminq_u8(
8667                                            core::arch::aarch64::vminq_u8(min_u, min_c),
8668                                            min_d,
8669                                        );
8670                                    let box_max: core::arch::aarch64::uint8x16_t =
8671                                        core::arch::aarch64::vmaxq_u8(
8672                                            core::arch::aarch64::vmaxq_u8(max_u, max_c),
8673                                            max_d,
8674                                        );
8675                                    let hist_v: core::arch::aarch64::uint8x16_t =
8676                                        core::arch::aarch64::vld1q_u8(history.as_ptr().add(sc4));
8677                                    let hist_c: core::arch::aarch64::uint8x16_t =
8678                                        core::arch::aarch64::vminq_u8(
8679                                            core::arch::aarch64::vmaxq_u8(hist_v, box_min),
8680                                            box_max,
8681                                        );
8682                                    let w_cur: core::arch::aarch64::uint8x8_t =
8683                                        core::arch::aarch64::vdup_n_u8(192);
8684                                    let w_his: core::arch::aarch64::uint8x8_t =
8685                                        core::arch::aarch64::vdup_n_u8(64);
8686                                    let lo_sum: core::arch::aarch64::uint16x8_t =
8687                                        core::arch::aarch64::vmlal_u8(
8688                                            core::arch::aarch64::vmull_u8(
8689                                                core::arch::aarch64::vget_low_u8(sc_m),
8690                                                w_cur,
8691                                            ),
8692                                            core::arch::aarch64::vget_low_u8(hist_c),
8693                                            w_his,
8694                                        );
8695                                    let hi_sum: core::arch::aarch64::uint16x8_t =
8696                                        core::arch::aarch64::vmlal_u8(
8697                                            core::arch::aarch64::vmull_u8(
8698                                                core::arch::aarch64::vget_high_u8(sc_m),
8699                                                w_cur,
8700                                            ),
8701                                            core::arch::aarch64::vget_high_u8(hist_c),
8702                                            w_his,
8703                                        );
8704                                    let blended: core::arch::aarch64::uint8x16_t =
8705                                        core::arch::aarch64::vcombine_u8(
8706                                            core::arch::aarch64::vrshrn_n_u16::<8>(lo_sum),
8707                                            core::arch::aarch64::vrshrn_n_u16::<8>(hi_sum),
8708                                        );
8709                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), blended);
8710                                }
8711                                true
8712                            } else {
8713                                false
8714                            }
8715                        };
8716                        if handled_4 {
8717                            coord_x += 4;
8718                            continue;
8719                        }
8720                    }
8721                }
8722                let lc: i32 = luma_c[coord_x] as i32;
8723                let ln: i32 = luma_u[coord_x] as i32;
8724                let ls: i32 = luma_d[coord_x] as i32;
8725                let le: i32 = luma_c[coord_x + 1] as i32;
8726                let lw: i32 = luma_c[coord_x - 1] as i32;
8727                let lmax: i32 = lc.max(ln).max(ls).max(le).max(lw);
8728                let lmin: i32 = lc.min(ln).min(ls).min(le).min(lw);
8729                let contrast: i32 = lmax - lmin;
8730                let dpi_scale: usize = (row + coord_x) * 4;
8731                let dc: usize = dst_off + coord_x * 4;
8732                if contrast < 3 {
8733                    let pix_bloom: bool =
8734                        row_has_bloom && bloom_row_mask[(coord_x >> 2).min(bw_max)] != 0;
8735                    if !pix_bloom {
8736                        if !has_taa {
8737                            // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
8738                            unsafe {
8739                                dst_ptr
8740                                    .add(dc)
8741                                    .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
8742                            }
8743                            coord_x += 1;
8744                            continue;
8745                        }
8746                        if contrast == 0 {
8747                            let lc_u8: u8 = lc as u8;
8748                            if luma_u[coord_x - 1] == lc_u8
8749                                && luma_u[coord_x + 1] == lc_u8
8750                                && luma_d[coord_x - 1] == lc_u8
8751                                && luma_d[coord_x + 1] == lc_u8
8752                            {
8753                                // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
8754                                unsafe {
8755                                    dst_ptr
8756                                        .add(dc)
8757                                        .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
8758                                }
8759                                coord_x += 1;
8760                                continue;
8761                            }
8762                        }
8763                    }
8764                }
8765                let (geom_edge, run_fxaa): (bool, bool) = if contrast >= 3 {
8766                    let tid_c: u32 = g_tri_idx[row + coord_x];
8767                    let edge_v_id: bool = tid_c != g_tri_idx[row_up + coord_x]
8768                        || tid_c != g_tri_idx[row_dn + coord_x];
8769                    let edge_h_id: bool = tid_c != g_tri_idx[row + coord_x - 1]
8770                        || tid_c != g_tri_idx[row + coord_x + 1];
8771                    let ge: bool = edge_v_id || edge_h_id;
8772                    (ge, contrast >= 7 || ge)
8773                } else {
8774                    (false, false)
8775                };
8776                let mut rgb: [i32; 3] = [
8777                    src[dpi_scale] as i32,
8778                    src[dpi_scale + 1] as i32,
8779                    src[dpi_scale + 2] as i32,
8780                ];
8781                if run_fxaa {
8782                    let lnw: i32 = luma[row_up + coord_x - 1] as i32;
8783                    let lne: i32 = luma[row_up + coord_x + 1] as i32;
8784                    let lsw: i32 = luma[row_dn + coord_x - 1] as i32;
8785                    let lse: i32 = luma[row_dn + coord_x + 1] as i32;
8786                    let edge_h: i32 = (lnw + lne - 2 * ln).abs()
8787                        + 2 * (lw + le - 2 * lc).abs()
8788                        + (lsw + lse - 2 * ls).abs();
8789                    let edge_v: i32 = (lnw + lsw - 2 * lw).abs()
8790                        + 2 * (ln + ls - 2 * lc).abs()
8791                        + (lne + lse - 2 * le).abs();
8792                    let is_horiz: bool = edge_h >= edge_v;
8793                    let (l_neg, l_pos): (i32, i32) = if is_horiz { (ln, ls) } else { (lw, le) };
8794                    let grad_neg: i32 = (l_neg - lc).abs();
8795                    let grad_pos: i32 = (l_pos - lc).abs();
8796                    let step_sign: i32 = if grad_neg >= grad_pos { -1 } else { 1 };
8797                    let grad_steep: i32 = grad_neg.max(grad_pos);
8798                    let l_other: i32 = if step_sign < 0 { l_neg } else { l_pos };
8799                    let edge_avg_2: i32 = lc + l_other;
8800                    let grad_thresh_2: i32 = (grad_steep >> 1).max(3);
8801                    let (perp_dx, perp_dy, tan_dx, tan_dy): (i32, i32, i32, i32) = if is_horiz {
8802                        (0, step_sign, 1, 0)
8803                    } else {
8804                        (step_sign, 0, 0, 1)
8805                    };
8806                    let x_i32: i32 = coord_x as i32;
8807                    let mut dist_neg: i32 = MLAA_MAX_WALK_STEPS as i32;
8808                    let mut end_neg_delta: i32 = 0;
8809                    for source_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
8810                        let sx: i32 = x_i32 - tan_dx * source_val;
8811                        let sy: i32 = y_i32 - tan_dy * source_val;
8812                        let ox: i32 = sx + perp_dx;
8813                        let oy: i32 = sy + perp_dy;
8814                        let oob_sx: bool = sx < 0 || sx >= w_i32;
8815                        let oob_sy: bool = sy < 0 || sy >= h_i32;
8816                        let oob_ox: bool = ox < 0 || ox >= w_i32;
8817                        let oob_oy: bool = oy < 0 || oy >= h_i32;
8818                        let oob_a: bool = oob_sx || oob_sy;
8819                        let oob_b: bool = oob_ox || oob_oy;
8820                        if oob_a || oob_b {
8821                            dist_neg = source_val;
8822                            break;
8823                        }
8824                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
8825                            as i32)
8826                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
8827                        let delta: i32 = pair_sum - edge_avg_2;
8828                        if delta.abs() >= grad_thresh_2 {
8829                            dist_neg = source_val;
8830                            end_neg_delta = delta;
8831                            break;
8832                        }
8833                    }
8834                    let mut dist_pos: i32 = MLAA_MAX_WALK_STEPS as i32;
8835                    let mut end_pos_delta: i32 = 0;
8836                    for scale_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
8837                        let sx: i32 = x_i32 + tan_dx * scale_val;
8838                        let sy: i32 = y_i32 + tan_dy * scale_val;
8839                        let ox: i32 = sx + perp_dx;
8840                        let oy: i32 = sy + perp_dy;
8841                        let oob_sx: bool = sx < 0 || sx >= w_i32;
8842                        let oob_sy: bool = sy < 0 || sy >= h_i32;
8843                        let oob_ox: bool = ox < 0 || ox >= w_i32;
8844                        let oob_oy: bool = oy < 0 || oy >= h_i32;
8845                        let oob_a: bool = oob_sx || oob_sy;
8846                        let oob_b: bool = oob_ox || oob_oy;
8847                        if oob_a || oob_b {
8848                            dist_pos = scale_val;
8849                            break;
8850                        }
8851                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
8852                            as i32)
8853                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
8854                        let delta: i32 = pair_sum - edge_avg_2;
8855                        if delta.abs() >= grad_thresh_2 {
8856                            dist_pos = scale_val;
8857                            end_pos_delta = delta;
8858                            break;
8859                        }
8860                    }
8861                    let center_lt_avg: bool = (lc * 2) < edge_avg_2;
8862                    let (closer_dist, closer_delta): (i32, i32) = if dist_neg <= dist_pos {
8863                        (dist_neg, end_neg_delta)
8864                    } else {
8865                        (dist_pos, end_pos_delta)
8866                    };
8867                    let good_span: bool = (closer_delta < 0) != center_lt_avg;
8868                    let span_total: f32 = ((dist_neg + dist_pos).max(1)) as f32;
8869                    let morph_blend: f32 = if good_span {
8870                        (0.5 - ((closer_dist as f32) - 0.5).max(0.0) / span_total).clamp(0.0, 0.5)
8871                    } else {
8872                        0.0
8873                    };
8874                    let avg_8: i32 = ((ln + ls + le + lw) * 2 + lnw + lne + lsw + lse + 6) / 12;
8875                    let subpix_raw: f32 =
8876                        (((avg_8 - lc).abs() as f32) / (contrast.max(1) as f32)).clamp(0.0, 1.0);
8877                    let subpix_s: f32 = subpix_raw * subpix_raw * (3.0 - 2.0 * subpix_raw);
8878                    let subpix_blend: f32 =
8879                        subpix_s * subpix_s * if geom_edge { 0.52 } else { 0.32 };
8880                    let final_blend: f32 = morph_blend.max(subpix_blend).clamp(0.0, 0.58);
8881                    let blend_q8: i32 = (final_blend * 256.0).round() as i32;
8882                    if blend_q8 > 0 {
8883                        let nx: usize = (x_i32 + perp_dx).clamp(0, w_i32 - 1) as usize;
8884                        let ny: usize = (y_i32 + perp_dy).clamp(0, h_i32 - 1) as usize;
8885                        let n_sc: usize = (ny * width_val + nx) * 4;
8886                        let keep_q8: i32 = 256 - blend_q8;
8887                        for ch in 0..3 {
8888                            rgb[ch] =
8889                                ((rgb[ch] * keep_q8 + (src[n_sc + ch] as i32) * blend_q8 + 128)
8890                                    >> 8)
8891                                    .clamp(0, 255);
8892                        }
8893                    }
8894                }
8895                if has_taa {
8896                    let flat_3x3: bool = if contrast == 0 {
8897                        let lc_u8: u8 = lc as u8;
8898                        let diag_top: bool = luma[row_up + coord_x - 1] == lc_u8
8899                            && luma[row_up + coord_x + 1] == lc_u8;
8900                        let diag_bot: bool = luma[row_dn + coord_x - 1] == lc_u8
8901                            && luma[row_dn + coord_x + 1] == lc_u8;
8902                        diag_top && diag_bot
8903                    } else {
8904                        false
8905                    };
8906                    if !flat_3x3 {
8907                        let hr: i32 = history[dpi_scale] as i32;
8908                        let hg: i32 = history[dpi_scale + 1] as i32;
8909                        let hb: i32 = history[dpi_scale + 2] as i32;
8910                        let diff_rg: bool = hr != rgb[0] || hg != rgb[1];
8911                        if diff_rg || hb != rgb[2] {
8912                            #[cfg(target_arch = "aarch64")]
8913                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
8914                                i32,
8915                                i32,
8916                                i32,
8917                                i32,
8918                                i32,
8919                                i32,
8920                            ) = {
8921                                // SAFETY: `x >= 1`, `x + 1 < w`, `y >= 1`, `y + 1 < h`, so every 4-byte pixel offset lies inside `src`.
8922                                unsafe {
8923                                    let c_word: u32 = u32::from_le_bytes([
8924                                        rgb[0] as u8,
8925                                        rgb[1] as u8,
8926                                        rgb[2] as u8,
8927                                        255,
8928                                    ]);
8929                                    let c_v: core::arch::aarch64::uint8x8_t =
8930                                        core::arch::aarch64::vreinterpret_u8_u32(
8931                                            core::arch::aarch64::vdup_n_u32(c_word),
8932                                        );
8933                                    let p0: core::arch::aarch64::uint8x8_t =
8934                                        Self::neon_load_px_u8(src, (row_up + coord_x - 1) * 4);
8935                                    let p1: core::arch::aarch64::uint8x8_t =
8936                                        Self::neon_load_px_u8(src, (row_up + coord_x) * 4);
8937                                    let p2: core::arch::aarch64::uint8x8_t =
8938                                        Self::neon_load_px_u8(src, (row_up + coord_x + 1) * 4);
8939                                    let p3: core::arch::aarch64::uint8x8_t =
8940                                        Self::neon_load_px_u8(src, (row + coord_x - 1) * 4);
8941                                    let p4: core::arch::aarch64::uint8x8_t =
8942                                        Self::neon_load_px_u8(src, (row + coord_x + 1) * 4);
8943                                    let p5: core::arch::aarch64::uint8x8_t =
8944                                        Self::neon_load_px_u8(src, (row_dn + coord_x - 1) * 4);
8945                                    let p6: core::arch::aarch64::uint8x8_t =
8946                                        Self::neon_load_px_u8(src, (row_dn + coord_x) * 4);
8947                                    let p7: core::arch::aarch64::uint8x8_t =
8948                                        Self::neon_load_px_u8(src, (row_dn + coord_x + 1) * 4);
8949                                    let lo_a: core::arch::aarch64::uint8x8_t =
8950                                        core::arch::aarch64::vmin_u8(
8951                                            core::arch::aarch64::vmin_u8(p0, p1),
8952                                            core::arch::aarch64::vmin_u8(p2, p3),
8953                                        );
8954                                    let lo_b: core::arch::aarch64::uint8x8_t =
8955                                        core::arch::aarch64::vmin_u8(
8956                                            core::arch::aarch64::vmin_u8(p4, p5),
8957                                            core::arch::aarch64::vmin_u8(p6, p7),
8958                                        );
8959                                    let v_min: core::arch::aarch64::uint8x8_t =
8960                                        core::arch::aarch64::vmin_u8(
8961                                            core::arch::aarch64::vmin_u8(lo_a, lo_b),
8962                                            c_v,
8963                                        );
8964                                    let hi_a: core::arch::aarch64::uint8x8_t =
8965                                        core::arch::aarch64::vmax_u8(
8966                                            core::arch::aarch64::vmax_u8(p0, p1),
8967                                            core::arch::aarch64::vmax_u8(p2, p3),
8968                                        );
8969                                    let hi_b: core::arch::aarch64::uint8x8_t =
8970                                        core::arch::aarch64::vmax_u8(
8971                                            core::arch::aarch64::vmax_u8(p4, p5),
8972                                            core::arch::aarch64::vmax_u8(p6, p7),
8973                                        );
8974                                    let v_max: core::arch::aarch64::uint8x8_t =
8975                                        core::arch::aarch64::vmax_u8(
8976                                            core::arch::aarch64::vmax_u8(hi_a, hi_b),
8977                                            c_v,
8978                                        );
8979                                    let min_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8980                                        core::arch::aarch64::vreinterpret_u32_u8(v_min),
8981                                    );
8982                                    let max_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8983                                        core::arch::aarch64::vreinterpret_u32_u8(v_max),
8984                                    );
8985                                    let min_b: [u8; 4] = min_u32.to_le_bytes();
8986                                    let max_b: [u8; 4] = max_u32.to_le_bytes();
8987                                    (
8988                                        min_b[0] as i32,
8989                                        max_b[0] as i32,
8990                                        min_b[1] as i32,
8991                                        max_b[1] as i32,
8992                                        min_b[2] as i32,
8993                                        max_b[2] as i32,
8994                                    )
8995                                }
8996                            };
8997                            #[cfg(not(target_arch = "aarch64"))]
8998                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
8999                                i32,
9000                                i32,
9001                                i32,
9002                                i32,
9003                                i32,
9004                                i32,
9005                            ) = {
9006                                let offsets: [usize; 8] = [
9007                                    (row_up + coord_x - 1) * 4,
9008                                    (row_up + coord_x) * 4,
9009                                    (row_up + coord_x + 1) * 4,
9010                                    (row + coord_x - 1) * 4,
9011                                    (row + coord_x + 1) * 4,
9012                                    (row_dn + coord_x - 1) * 4,
9013                                    (row_dn + coord_x) * 4,
9014                                    (row_dn + coord_x + 1) * 4,
9015                                ];
9016                                let mut r_lo: i32 = rgb[0];
9017                                let mut r_hi: i32 = rgb[0];
9018                                let mut g_lo: i32 = rgb[1];
9019                                let mut g_hi: i32 = rgb[1];
9020                                let mut b_lo: i32 = rgb[2];
9021                                let mut b_hi: i32 = rgb[2];
9022                                for off in offsets.into_iter() {
9023                                    let vr: i32 = src[off] as i32;
9024                                    let vg: i32 = src[off + 1] as i32;
9025                                    let vb: i32 = src[off + 2] as i32;
9026                                    r_lo = r_lo.min(vr);
9027                                    r_hi = r_hi.max(vr);
9028                                    g_lo = g_lo.min(vg);
9029                                    g_hi = g_hi.max(vg);
9030                                    b_lo = b_lo.min(vb);
9031                                    b_hi = b_hi.max(vb);
9032                                }
9033                                (r_lo, r_hi, g_lo, g_hi, b_lo, b_hi)
9034                            };
9035                            let hr_c: i32 = hr.clamp(r_min, r_max);
9036                            let hg_c: i32 = hg.clamp(g_min, g_max);
9037                            let hb_c: i32 = hb.clamp(b_min, b_max);
9038                            rgb[0] = ((rgb[0] * 192 + hr_c * 64 + 128) >> 8).clamp(0, 255);
9039                            rgb[1] = ((rgb[1] * 192 + hg_c * 64 + 128) >> 8).clamp(0, 255);
9040                            rgb[2] = ((rgb[2] * 192 + hb_c * 64 + 128) >> 8).clamp(0, 255);
9041                        }
9042                    }
9043                }
9044                if !geom_edge && (4..=56).contains(&contrast) {
9045                    let off_u: usize = (row_up + coord_x) * 4;
9046                    let off_d: usize = (row_dn + coord_x) * 4;
9047                    let off_l: usize = (row + coord_x - 1) * 4;
9048                    let off_r: usize = (row + coord_x + 1) * 4;
9049                    for ch in 0..3usize {
9050                        let cu: i32 = src[off_u + ch] as i32;
9051                        let cd: i32 = src[off_d + ch] as i32;
9052                        let cl: i32 = src[off_l + ch] as i32;
9053                        let cr: i32 = src[off_r + ch] as i32;
9054                        let nbr_min: i32 = cu.min(cd).min(cl).min(cr).min(rgb[ch]);
9055                        let nbr_max: i32 = cu.max(cd).max(cl).max(cr).max(rgb[ch]);
9056                        let lap: i32 = rgb[ch] * 4 - (cu + cd + cl + cr);
9057                        rgb[ch] = (rgb[ch] + ((lap * 56) >> 10)).clamp(nbr_min, nbr_max);
9058                    }
9059                }
9060                if row_has_bloom {
9061                    let bx0: usize = (coord_x >> 2).min(bw_max);
9062                    if bloom_row_mask[bx0] != 0 {
9063                        let tx: f32 = ((coord_x & 3) as f32) * 0.25;
9064                        let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
9065                            bloom,
9066                            (bloom_r0, bloom_r1, bw_max),
9067                            (bx0, tx, ty),
9068                        );
9069                        rgb[0] = (rgb[0] + (bl[0] * 78.0) as i32).min(255);
9070                        rgb[1] = (rgb[1] + (bl[1] * 78.0) as i32).min(255);
9071                        rgb[2] = (rgb[2] + (bl[2] * 78.0) as i32).min(255);
9072                    }
9073                }
9074                // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
9075                unsafe {
9076                    dst_ptr.add(dc).cast::<[u8; 4]>().write([
9077                        rgb[0] as u8,
9078                        rgb[1] as u8,
9079                        rgb[2] as u8,
9080                        255,
9081                    ]);
9082                }
9083                coord_x += 1;
9084            }
9085            if use_fxaa || has_bloom {
9086                let v_norm: f32 = (((coord_y as f32) + 0.5) / (height_val.max(1) as f32)) - 0.5;
9087                let v_sq: f32 = v_norm * v_norm;
9088                let inv_wf: f32 = 1.0 / (width_val.max(1) as f32);
9089                for vig_x in 0..width_val {
9090                    let u_norm: f32 = (((vig_x as f32) + 0.5) * inv_wf) - 0.5;
9091                    let r2: f32 = u_norm * u_norm + v_sq;
9092                    if r2 > 0.16 {
9093                        let vig_q8: u32 =
9094                            ((1.0 - (r2 - 0.16) * 0.44).clamp(0.82, 1.0) * 256.0) as u32;
9095                        let px_off: usize = dst_off + vig_x * 4;
9096                        // SAFETY: `px_off + 4 <= band_rows * row_bytes`.
9097                        unsafe {
9098                            let p_ptr: *mut u8 = dst_ptr.add(px_off);
9099                            *p_ptr = (((*p_ptr as u32) * vig_q8) >> 8) as u8;
9100                            *p_ptr.add(1) = (((*p_ptr.add(1) as u32) * vig_q8) >> 8) as u8;
9101                            *p_ptr.add(2) = (((*p_ptr.add(2) as u32) * vig_q8) >> 8) as u8;
9102                        }
9103                    }
9104                }
9105            }
9106        }
9107    }
9108
9109    /// Projects, culls, clips, and builds screen-space setup records for one frustum-visible object with smooth 3-vertex normal averaging.
9110    ///
9111    /// # Arguments
9112    ///
9113    /// - `&GeomPassContext<'_>` - Immutable per-frame frustum, Hi-Z, camera, and sky parameters.
9114    /// - `usize` - Index inside `visible_scratch` for Hi-Z pre-pass flag lookup.
9115    /// - `f32` - Squared distance from camera to object bounds center.
9116    /// - `usize` - Object index inside `ctx.objects`.
9117    /// - `&mut GeomPassOut<'_>` - Mutable per-chunk or sequential geometry output buffers and counters.
9118    fn process_visible_object_geom(
9119        ctx: &GeomPassContext<'_>,
9120        vis_slot: usize,
9121        dist_sq: f32,
9122        obj_idx: usize,
9123        out: &mut GeomPassOut<'_>,
9124    ) {
9125        let obj: &SceneObject3D = &ctx.objects[obj_idx];
9126        let skip_hiz_obj: bool = obj.get_is_dynamic()
9127            || obj.get_material().get_emissive().length_sq() > 0.05
9128            || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater;
9129        if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 && !skip_hiz_obj {
9130            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
9131            let area_px: f32 = HiZPyramid::projected_screen_area_px(
9132                obj_bounds,
9133                &ctx.view_proj,
9134                ctx.w_f,
9135                ctx.h_f,
9136                ctx.near_plane,
9137            );
9138            if area_px < NANITE_MIN_SCREEN_AREA_PX
9139                || ctx
9140                    .hiz_pyramid
9141                    .is_bounds_occluded(obj_bounds, &ctx.view_proj, ctx.near_plane)
9142            {
9143                out.hiz_culled_objects += 1;
9144                return;
9145            }
9146        }
9147        let Some(chain) = ctx.mesh_lib.get(obj.get_mesh_id()) else {
9148            return;
9149        };
9150        out.visible_objects += 1;
9151        if let Some(unique_set) = out.unique_meshes.as_deref_mut() {
9152            let _: bool = unique_set.insert(obj.get_mesh_id());
9153        } else if let Some(mesh_ids) = out.mesh_ids.as_deref_mut() {
9154            mesh_ids.push(obj.get_mesh_id());
9155        }
9156        let dist: f32 = dist_sq.sqrt();
9157        let obj_radius: f32 = obj.get_world_bounds().radius();
9158        let deformed_mesh: Option<&Mesh3D> =
9159            ctx.deformed_meshes.get(obj_idx).and_then(Option::as_ref);
9160        let (mesh, lod_idx): (&Mesh3D, usize) = if let Some(deformed) = deformed_mesh {
9161            (deformed, 0)
9162        } else {
9163            chain.select_screen_error(dist, obj_radius, ctx.focal_px, ctx.lod_bias)
9164        };
9165        if lod_idx > 0 {
9166            out.lod_simplified_objects += 1;
9167        }
9168        let transform_val: Transform3D = obj.get_transform();
9169        let model_mat4: Mat4 = transform_val.to_mat4();
9170        let mvp_mat4: Mat4 = ctx.view_proj.mul(model_mat4);
9171        let normal_mat3: [Vec3; 3] = transform_val.normal_mat3();
9172        let tr_scale: Vec3 = transform_val.get_scale();
9173        let det_scale: f32 = tr_scale.get_x() * tr_scale.get_y() * tr_scale.get_z();
9174        let principled_id: Option<u32> = obj.try_get_principled_material_id();
9175        let double_sided: bool = principled_id
9176            .and_then(|mat_idx: u32| ctx.principled_materials.get(mat_idx as usize))
9177            .is_some_and(PrincipledMaterial3D::get_double_sided);
9178        let cull_backface: bool = mesh.get_is_closed() && det_scale > 0.0 && !double_sided;
9179        let obj_mat: PbrMaterial = obj.get_material();
9180        let has_sub_mats: bool = !mesh.get_tri_materials().is_empty();
9181        let base_mat_base: Vec3 = obj_mat.get_base_color();
9182        let base_mat_emissive: Vec3 = obj_mat.get_emissive();
9183        let base_mat_refl: f32 = obj_mat.get_reflectivity();
9184        let base_metallic: f32 = obj_mat.get_metallic();
9185        let base_rough: f32 = obj_mat.get_roughness();
9186        let base_alpha: f32 = (base_rough * base_rough).max(0.018);
9187        let base_alpha2: f32 = base_alpha * base_alpha;
9188        let base_f0: Vec3 = Vec3::splat(0.04).lerp(base_mat_base, base_metallic);
9189        let base_diffuse_scale: f32 = 1.0 - base_metallic;
9190        let base_do_refl: bool = ctx.use_rt_refl && base_mat_refl > 0.25;
9191        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
9192        let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
9193        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
9194        out.cluster_ranges.clear();
9195        if deformed_mesh.is_none()
9196            && lod_idx == 0
9197            && ctx.frustum_on
9198            && let Some(nanite_dag) = ctx
9199                .nanite_dags
9200                .get(obj.get_mesh_id())
9201                .and_then(Option::as_ref)
9202        {
9203            let hiz_opt: Option<&HiZPyramid> =
9204                if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 {
9205                    Some(ctx.hiz_pyramid)
9206                } else {
9207                    None
9208                };
9209            let cut_ctx: NaniteCutContext<'_> = NaniteCutContext {
9210                camera_position: ctx.cam_pos,
9211                model_matrix: model_mat4,
9212                view_projection: ctx.view_proj,
9213                normal_basis: normal_mat3,
9214                frustum: ctx.frustum,
9215                hiz_pyramid: hiz_opt,
9216                cull_backface,
9217                focal_px: ctx.focal_px,
9218                error_threshold_px: (1.5 * ctx.lod_bias.max(0.25)).clamp(0.5, 8.0),
9219                near_plane: ctx.near_plane,
9220                viewport_width: ctx.w_f,
9221                viewport_height: ctx.h_f,
9222                total_triangles: indices.len(),
9223            };
9224            let cut_stats: NaniteCutStats = nanite_dag.select_cut(&cut_ctx, out.cluster_ranges);
9225            out.meshlets_drawn += cut_stats.get_clusters_drawn();
9226            out.meshlets_culled += cut_stats.get_clusters_frustum_culled()
9227                + cut_stats.get_clusters_cone_culled()
9228                + cut_stats.get_clusters_micro_culled()
9229                + cut_stats.get_clusters_hiz_culled();
9230        } else if deformed_mesh.is_none() && meshlets.len() > 1 && ctx.frustum_on {
9231            for mlet in meshlets.iter() {
9232                let wb: AxisAlignedBox3D = model_mat4.transform_bounds(mlet.get_bounds());
9233                if !ctx.frustum.intersects_bounds(&wb) {
9234                    out.meshlets_culled += 1;
9235                    continue;
9236                }
9237                if ctx.hiz_active
9238                    && ctx.hiz_occluder_flags[vis_slot] == 0
9239                    && ctx
9240                        .hiz_pyramid
9241                        .is_bounds_occluded(wb, &ctx.view_proj, ctx.near_plane)
9242                {
9243                    out.meshlets_culled += 1;
9244                    continue;
9245                }
9246                let cutoff: f32 = mlet.get_cone_cutoff();
9247                if cull_backface && cutoff > 0.05 {
9248                    let world_axis: Vec3 =
9249                        Mat4::transform_normal_with_basis(mlet.get_cone_axis(), normal_mat3);
9250                    let v_cam: Vec3 = wb.center().sub(ctx.cam_pos);
9251                    let v_len: f32 = v_cam.length();
9252                    let sin_alpha: f32 = (1.0 - cutoff * cutoff).max(0.0).sqrt();
9253                    if v_cam.dot(world_axis) > v_len * sin_alpha + wb.radius() {
9254                        out.meshlets_culled += 1;
9255                        continue;
9256                    }
9257                }
9258                out.meshlets_drawn += 1;
9259                let s0: usize = mlet.get_first_tri() as usize;
9260                let s1: usize = (s0 + (mlet.get_tri_count() as usize)).min(indices.len());
9261                out.cluster_ranges.push((s0, s1));
9262            }
9263        } else {
9264            out.meshlets_drawn += meshlets.len().max(1);
9265            out.cluster_ranges.push((0, indices.len()));
9266        }
9267        if out.cluster_ranges.is_empty() {
9268            return;
9269        }
9270        out.projected_verts.clear();
9271        out.projected_verts.reserve(verts.len());
9272        for item_val in verts.iter() {
9273            let lp: Vec3 = item_val.get_position();
9274            let cp: [f32; 4] = mvp_mat4.mul_point4(lp);
9275            let wp: Vec3 = model_mat4.mul_point3(lp);
9276            out.projected_verts.push((cp, wp));
9277        }
9278        let vert_count: usize = out.projected_verts.len();
9279        for &(tri_start, tri_end) in out.cluster_ranges.iter() {
9280            for (local_offset, tri) in indices[tri_start..tri_end].iter().enumerate() {
9281                let global_tri_idx: usize = tri_start + local_offset;
9282                let (i0, i1, i2): (usize, usize, usize) =
9283                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
9284                let oob_01: bool = i0 >= vert_count || i1 >= vert_count;
9285                if oob_01 || i2 >= vert_count {
9286                    continue;
9287                }
9288                let (c0, wp0): ([f32; 4], Vec3) = out.projected_verts[i0];
9289                let (c1, wp1): ([f32; 4], Vec3) = out.projected_verts[i1];
9290                let (c2, wp2): ([f32; 4], Vec3) = out.projected_verts[i2];
9291                if c0[3] < ctx.near_plane && c1[3] < ctx.near_plane && c2[3] < ctx.near_plane {
9292                    continue;
9293                }
9294                let out_l: bool = c0[0] < -c0[3] && c1[0] < -c1[3] && c2[0] < -c2[3];
9295                let out_r: bool = c0[0] > c0[3] && c1[0] > c1[3] && c2[0] > c2[3];
9296                let out_b: bool = c0[1] < -c0[3] && c1[1] < -c1[3] && c2[1] < -c2[3];
9297                let out_t: bool = c0[1] > c0[3] && c1[1] > c1[3] && c2[1] > c2[3];
9298                let out_x: bool = out_l || out_r;
9299                let out_y: bool = out_b || out_t;
9300                if out_x || out_y {
9301                    continue;
9302                }
9303                let (clipped_tris, clipped_count): ([ClippedBaryVert; 6], usize) = if c0[3]
9304                    >= ctx.near_plane
9305                    && c1[3] >= ctx.near_plane
9306                    && c2[3] >= ctx.near_plane
9307                {
9308                    let zero_clip: ClippedBaryVert = ClippedBaryVert {
9309                        clip_pos: [0.0; 4],
9310                        world_pos: Vec3::zero(),
9311                        bary: [0.0; 3],
9312                    };
9313                    (
9314                        [
9315                            ClippedBaryVert {
9316                                clip_pos: c0,
9317                                world_pos: wp0,
9318                                bary: [1.0, 0.0, 0.0],
9319                            },
9320                            ClippedBaryVert {
9321                                clip_pos: c1,
9322                                world_pos: wp1,
9323                                bary: [0.0, 1.0, 0.0],
9324                            },
9325                            ClippedBaryVert {
9326                                clip_pos: c2,
9327                                world_pos: wp2,
9328                                bary: [0.0, 0.0, 1.0],
9329                            },
9330                            zero_clip,
9331                            zero_clip,
9332                            zero_clip,
9333                        ],
9334                        1,
9335                    )
9336                } else {
9337                    Self::clip_triangle_near_bary((c0, wp0), (c1, wp1), (c2, wp2), ctx.near_plane)
9338                };
9339                if clipped_count == 0 {
9340                    continue;
9341                }
9342                let vert0: Vertex3D = verts[i0];
9343                let vert1: Vertex3D = verts[i1];
9344                let vert2: Vertex3D = verts[i2];
9345                let local_n0: Vec3 = vert0.get_normal();
9346                let local_n1: Vec3 = vert1.get_normal();
9347                let local_n2: Vec3 = vert2.get_normal();
9348                let has_varied_normals: bool = local_n0.sub(local_n1).length_sq() > 1.0e-4
9349                    || local_n0.sub(local_n2).length_sq() > 1.0e-4;
9350                let has_extra_attrs: bool =
9351                    ((vert0.get_flags() | vert1.get_flags() | vert2.get_flags()) & 9) != 0;
9352                let mut cached_wn: Option<Vec3> = None;
9353                for ci in 0..clipped_count {
9354                    let base_ci: usize = ci * 3;
9355                    let cv0: ClippedBaryVert = clipped_tris[base_ci];
9356                    let cv1: ClippedBaryVert = clipped_tris[base_ci + 1];
9357                    let cv2: ClippedBaryVert = clipped_tris[base_ci + 2];
9358                    let (tc0, tw0, tb0): ([f32; 4], Vec3, [f32; 3]) =
9359                        (cv0.clip_pos, cv0.world_pos, cv0.bary);
9360                    let (tc1, tw1, tb1): ([f32; 4], Vec3, [f32; 3]) =
9361                        (cv1.clip_pos, cv1.world_pos, cv1.bary);
9362                    let (tc2, tw2, tb2): ([f32; 4], Vec3, [f32; 3]) =
9363                        (cv2.clip_pos, cv2.world_pos, cv2.bary);
9364                    let inv_w0: f32 = 1.0 / tc0[3];
9365                    let inv_w1: f32 = 1.0 / tc1[3];
9366                    let inv_w2: f32 = 1.0 / tc2[3];
9367                    let sx0: f32 = (tc0[0] * inv_w0 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9368                    let sy0: f32 = (0.5 - tc0[1] * inv_w0 * 0.5) * ctx.h_f + ctx.jitter_y;
9369                    let sx1: f32 = (tc1[0] * inv_w1 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9370                    let sy1: f32 = (0.5 - tc1[1] * inv_w1 * 0.5) * ctx.h_f + ctx.jitter_y;
9371                    let sx2: f32 = (tc2[0] * inv_w2 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9372                    let sy2: f32 = (0.5 - tc2[1] * inv_w2 * 0.5) * ctx.h_f + ctx.jitter_y;
9373                    let area: f32 = (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0);
9374                    if cull_backface {
9375                        if area >= -0.25 {
9376                            continue;
9377                        }
9378                    } else if area.abs() < 0.25 {
9379                        continue;
9380                    }
9381                    let min_x: i32 = (sx0.min(sx1).min(sx2).floor() as i32).max(0);
9382                    let max_x: i32 = (sx0.max(sx1).max(sx2).ceil() as i32).min(ctx.w_max_i);
9383                    let min_y: i32 = (sy0.min(sy1).min(sy2).floor() as i32).max(0);
9384                    let max_y: i32 = (sy0.max(sy1).max(sy2).ceil() as i32).min(ctx.h_max_i);
9385                    if min_x > max_x || min_y > max_y {
9386                        continue;
9387                    }
9388                    let wn: Vec3 = match cached_wn {
9389                        Some(item_count) => item_count,
9390                        None => {
9391                            let n_avg_local: Vec3 = local_n0.add(local_n1).add(local_n2);
9392                            let n_local: Vec3 = if n_avg_local.length_sq() > 1.0e-6 {
9393                                n_avg_local.normalize()
9394                            } else {
9395                                local_n0
9396                            };
9397                            let computed: Vec3 =
9398                                Mat4::transform_normal_with_basis(n_local, normal_mat3);
9399                            cached_wn = Some(computed);
9400                            computed
9401                        }
9402                    };
9403                    let tri_id: u32 = out.shaded_tris.len() as u32;
9404                    let shade_n: Vec3 = if cull_backface {
9405                        wn
9406                    } else {
9407                        let tri_center: Vec3 = tw0.add(tw1).add(tw2).scale(1.0 / 3.0);
9408                        let tri_view: Vec3 = ctx.cam_pos.sub(tri_center);
9409                        if wn.dot(tri_view) < 0.0 {
9410                            wn.scale(-1.0)
9411                        } else {
9412                            wn
9413                        }
9414                    };
9415                    let n_dot_l: f32 = shade_n.dot(ctx.sun_dir).max(0.0);
9416                    let ambient_sky: Vec3 = ctx.sky_horizon.lerp(
9417                        ctx.sky_zenith,
9418                        (shade_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
9419                    );
9420                    let (
9421                        tri_base,
9422                        tri_emissive,
9423                        tri_f0,
9424                        tri_alpha2,
9425                        tri_diffuse_scale,
9426                        tri_refl,
9427                        tri_metallic,
9428                        tri_do_refl,
9429                        tri_surface_detail,
9430                    ): (
9431                        Vec3,
9432                        Vec3,
9433                        Vec3,
9434                        f32,
9435                        f32,
9436                        f32,
9437                        f32,
9438                        bool,
9439                        SurfaceDetailMode,
9440                    ) = if !has_sub_mats {
9441                        (
9442                            base_mat_base,
9443                            base_mat_emissive,
9444                            base_f0,
9445                            base_alpha2,
9446                            base_diffuse_scale,
9447                            base_mat_refl,
9448                            base_metallic,
9449                            base_do_refl,
9450                            obj_mat.get_surface_detail(),
9451                        )
9452                    } else {
9453                        let (resolved, _): (PbrMaterial, u16) =
9454                            mesh.resolve_triangle_material(global_tri_idx, obj_mat);
9455                        let sub_base: Vec3 = resolved.get_base_color();
9456                        let sub_metal: f32 = resolved.get_metallic();
9457                        let sub_rough: f32 = resolved.get_roughness();
9458                        let sub_alpha: f32 = (sub_rough * sub_rough).max(0.018);
9459                        let sub_refl: f32 = resolved.get_reflectivity();
9460                        (
9461                            sub_base,
9462                            resolved.get_emissive(),
9463                            Vec3::splat(0.04).lerp(sub_base, sub_metal),
9464                            sub_alpha * sub_alpha,
9465                            1.0 - sub_metal,
9466                            sub_refl,
9467                            sub_metal,
9468                            ctx.use_rt_refl && sub_refl > 0.25,
9469                            resolved.get_surface_detail(),
9470                        )
9471                    };
9472                    let inv_area: f32 = 1.0 / area;
9473                    let smooth_attrs: bool = has_varied_normals || has_extra_attrs;
9474                    let smooth_legacy: bool = smooth_attrs || ctx.use_agx_tonemap;
9475                    let use_smooth: bool = principled_id.is_some()
9476                        || (tri_surface_detail == SurfaceDetailMode::None && smooth_legacy);
9477                    let smooth_idx: u32 = if use_smooth {
9478                        let world_n0: Vec3 =
9479                            Mat4::transform_normal_with_basis(local_n0, normal_mat3);
9480                        let world_n1: Vec3 =
9481                            Mat4::transform_normal_with_basis(local_n1, normal_mat3);
9482                        let world_n2: Vec3 =
9483                            Mat4::transform_normal_with_basis(local_n2, normal_mat3);
9484                        let tan_raw0: [f32; 4] = vert0.get_tangent();
9485                        let tan_raw1: [f32; 4] = vert1.get_tangent();
9486                        let tan_raw2: [f32; 4] = vert2.get_tangent();
9487                        let world_t0_v: Vec3 = Mat4::transform_normal_with_basis(
9488                            Vec3::new(tan_raw0[0], tan_raw0[1], tan_raw0[2]),
9489                            normal_mat3,
9490                        );
9491                        let world_t1_v: Vec3 = Mat4::transform_normal_with_basis(
9492                            Vec3::new(tan_raw1[0], tan_raw1[1], tan_raw1[2]),
9493                            normal_mat3,
9494                        );
9495                        let world_t2_v: Vec3 = Mat4::transform_normal_with_basis(
9496                            Vec3::new(tan_raw2[0], tan_raw2[1], tan_raw2[2]),
9497                            normal_mat3,
9498                        );
9499                        let uv0_orig: [[f32; 2]; 3] =
9500                            [vert0.get_uv0(), vert1.get_uv0(), vert2.get_uv0()];
9501                        let uv1_orig: [[f32; 2]; 3] =
9502                            [vert0.get_uv1(), vert1.get_uv1(), vert2.get_uv1()];
9503                        let unpack_col: fn([u8; 4]) -> [f32; 4] = |rgba_u8: [u8; 4]| -> [f32; 4] {
9504                            [
9505                                srgb_u8_to_linear(rgba_u8[0]),
9506                                srgb_u8_to_linear(rgba_u8[1]),
9507                                srgb_u8_to_linear(rgba_u8[2]),
9508                                f32::from(rgba_u8[3]) / 255.0,
9509                            ]
9510                        };
9511                        let col_orig: [[f32; 4]; 3] = [
9512                            unpack_col(vert0.get_color0()),
9513                            unpack_col(vert1.get_color0()),
9514                            unpack_col(vert2.get_color0()),
9515                        ];
9516                        let bary_list: [[f32; 3]; 3] = [tb0, tb1, tb2];
9517                        let mut interp_normals: [Vec3; 3] = [Vec3::zero(); 3];
9518                        let mut interp_tangents: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 1.0]; 3];
9519                        let mut interp_uv0: [[f32; 2]; 3] = [[0.0; 2]; 3];
9520                        let mut interp_uv1: [[f32; 2]; 3] = [[0.0; 2]; 3];
9521                        let mut interp_col: [[f32; 4]; 3] = [[1.0; 4]; 3];
9522                        for corner_idx in 0..3usize {
9523                            let b_w: [f32; 3] = bary_list[corner_idx];
9524                            let n_mix: Vec3 = world_n0
9525                                .scale(b_w[0])
9526                                .add(world_n1.scale(b_w[1]))
9527                                .add(world_n2.scale(b_w[2]));
9528                            interp_normals[corner_idx] = if n_mix.length_sq() > 1.0e-8 {
9529                                n_mix.normalize()
9530                            } else {
9531                                shade_n
9532                            };
9533                            let t_mix: Vec3 = world_t0_v
9534                                .scale(b_w[0])
9535                                .add(world_t1_v.scale(b_w[1]))
9536                                .add(world_t2_v.scale(b_w[2]));
9537                            let t_unit: Vec3 = if t_mix.length_sq() > 1.0e-8 {
9538                                t_mix.normalize()
9539                            } else {
9540                                Vec3::new(1.0, 0.0, 0.0)
9541                            };
9542                            let t_hand: f32 =
9543                                tan_raw0[3] * b_w[0] + tan_raw1[3] * b_w[1] + tan_raw2[3] * b_w[2];
9544                            interp_tangents[corner_idx] = [
9545                                t_unit.get_x(),
9546                                t_unit.get_y(),
9547                                t_unit.get_z(),
9548                                if t_hand < 0.0 { -1.0 } else { 1.0 },
9549                            ];
9550                            interp_uv0[corner_idx] = [
9551                                uv0_orig[0][0] * b_w[0]
9552                                    + uv0_orig[1][0] * b_w[1]
9553                                    + uv0_orig[2][0] * b_w[2],
9554                                uv0_orig[0][1] * b_w[0]
9555                                    + uv0_orig[1][1] * b_w[1]
9556                                    + uv0_orig[2][1] * b_w[2],
9557                            ];
9558                            interp_uv1[corner_idx] = [
9559                                uv1_orig[0][0] * b_w[0]
9560                                    + uv1_orig[1][0] * b_w[1]
9561                                    + uv1_orig[2][0] * b_w[2],
9562                                uv1_orig[0][1] * b_w[0]
9563                                    + uv1_orig[1][1] * b_w[1]
9564                                    + uv1_orig[2][1] * b_w[2],
9565                            ];
9566                            for ch_idx in 0..4usize {
9567                                interp_col[corner_idx][ch_idx] = col_orig[0][ch_idx] * b_w[0]
9568                                    + col_orig[1][ch_idx] * b_w[1]
9569                                    + col_orig[2][ch_idx] * b_w[2];
9570                            }
9571                        }
9572                        let new_smooth_id: u32 = out.smooth_tris.len() as u32;
9573                        out.smooth_tris.push(GSmoothTri {
9574                            screen_x: [sx0, sx1, sx2],
9575                            screen_y: [sy0, sy1, sy2],
9576                            inv_w: [inv_w0, inv_w1, inv_w2],
9577                            inv_area,
9578                            normals: interp_normals,
9579                            tangents: interp_tangents,
9580                            uv0: interp_uv0,
9581                            uv1: interp_uv1,
9582                            color0: interp_col,
9583                            principled_material_id: principled_id.unwrap_or(u32::MAX),
9584                            double_sided: !cull_backface,
9585                        });
9586                        new_smooth_id
9587                    } else {
9588                        u32::MAX
9589                    };
9590                    out.shaded_tris.push(GShadeTri {
9591                        shade_n,
9592                        mat_base: tri_base,
9593                        mat_emissive: tri_emissive,
9594                        ambient_sky,
9595                        f0: tri_f0,
9596                        n_dot_l,
9597                        alpha2: tri_alpha2,
9598                        diffuse_scale: tri_diffuse_scale,
9599                        mat_refl: tri_refl,
9600                        metallic: tri_metallic,
9601                        do_refl: tri_do_refl,
9602                        surface_detail: tri_surface_detail,
9603                        smooth_idx,
9604                    });
9605                    let dw0_dx: f32 = (sy1 - sy2) * inv_area;
9606                    let dw1_dx: f32 = (sy2 - sy0) * inv_area;
9607                    let dw2_dx: f32 = -(dw0_dx + dw1_dx);
9608                    let dw0_dy: f32 = (sx2 - sx1) * inv_area;
9609                    let dw1_dy: f32 = (sx0 - sx2) * inv_area;
9610                    let dw2_dy: f32 = -(dw0_dy + dw1_dy);
9611                    let d_inv_w_dx: f32 = dw0_dx * inv_w0 + dw1_dx * inv_w1 + dw2_dx * inv_w2;
9612                    let d_inv_w_dy: f32 = dw0_dy * inv_w0 + dw1_dy * inv_w1 + dw2_dy * inv_w2;
9613                    let neg_inv_slopes: [f32; 3] = [
9614                        if dw0_dx.abs() > 1e-9 {
9615                            -1.0 / dw0_dx
9616                        } else {
9617                            0.0
9618                        },
9619                        if dw1_dx.abs() > 1e-9 {
9620                            -1.0 / dw1_dx
9621                        } else {
9622                            0.0
9623                        },
9624                        if dw2_dx.abs() > 1e-9 {
9625                            -1.0 / dw2_dx
9626                        } else {
9627                            0.0
9628                        },
9629                    ];
9630                    let slopes: [f32; 3] = [dw0_dx, dw1_dx, dw2_dx];
9631                    let span_max: i32 = max_x - min_x;
9632                    let fx_start: f32 = (min_x as f32) + 0.5;
9633                    let fy_start: f32 = (min_y as f32) + 0.5;
9634                    let w0_row: f32 = ((sx1 - fx_start) * (sy2 - fy_start)
9635                        - (sy1 - fy_start) * (sx2 - fx_start))
9636                        * inv_area;
9637                    let w1_row: f32 = ((sx2 - fx_start) * (sy0 - fy_start)
9638                        - (sy2 - fy_start) * (sx0 - fx_start))
9639                        * inv_area;
9640                    let w2_row: f32 = 1.0 - w0_row - w1_row;
9641                    let inv_w_row: f32 = w0_row * inv_w0 + w1_row * inv_w1 + w2_row * inv_w2;
9642                    out.raster_tris.push(RasterTri2D {
9643                        min_y,
9644                        max_y,
9645                        min_x,
9646                        span_max,
9647                        tri_id,
9648                        slopes,
9649                        neg_inv_slopes,
9650                        dw_dy: [dw0_dy, dw1_dy, dw2_dy],
9651                        w_start: [w0_row, w1_row, w2_row],
9652                        inv_w_start: inv_w_row,
9653                        d_inv_w_dx,
9654                        d_inv_w_dy,
9655                    });
9656                }
9657            }
9658        }
9659    }
9660
9661    /// Renders `world` at runtime-configured `quality` directly into `out_pixels` without zero-filling, returning internal `(width, height)`.
9662    ///
9663    /// # Arguments
9664    ///
9665    /// - `&Self` - Mutable 3D renderer.
9666    /// - `&mut World3D` - Open-world 3D scene graph.
9667    /// - `u32` - Target viewport width in logical pixels.
9668    /// - `u32` - Target viewport height in logical pixels.
9669    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
9670    /// - `&mut Vec<u8>` - Destination RGBA8 byte buffer resized without zero-fill and populated completely.
9671    ///
9672    /// # Returns
9673    ///
9674    /// - `(u32, u32)` - Internal rasterized framebuffer `(width, height)`.
9675    fn render_world_into_vec(
9676        &mut self,
9677        world: &mut World3D,
9678        viewport_w: u32,
9679        viewport_h: u32,
9680        quality: &RenderQualityConfig,
9681        out_pixels: &mut Vec<u8>,
9682    ) -> (u32, u32) {
9683        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
9684        let min_width: u32 = viewport_w.clamp(1, 240);
9685        let min_height: u32 = viewport_h.clamp(1, 144);
9686        let span_width: u32 = (((viewport_w as f32) * scale).round() as u32).max(min_width);
9687        let span_height: u32 = (((viewport_h as f32) * scale).round() as u32).max(min_height);
9688        let w_usize: usize = span_width as usize;
9689        let h_usize: usize = span_height as usize;
9690        let pixel_count: usize = w_usize * h_usize;
9691        let border_width: usize = w_usize.div_ceil(4);
9692        let bh: usize = h_usize.div_ceil(4);
9693        if self.get_width() != span_width || self.get_height() != span_height {
9694            self.set_width(span_width);
9695            self.set_height(span_height);
9696            let Self {
9697                color_buffer,
9698                aa_buffer,
9699                depth_buffer,
9700                g_tri_idx,
9701                luma_buffer,
9702                bloom_a,
9703                bloom_b,
9704                bloom_tile_active,
9705                hiz_pyramid,
9706                tsr_internal_scratch,
9707                has_taa_history,
9708                has_probe_history,
9709                ..
9710            } = self;
9711            let rgba_bytes: usize = pixel_count * 4;
9712            let bloom_cells: usize = border_width * bh;
9713            color_buffer.resize(rgba_bytes, 0);
9714            aa_buffer.resize(rgba_bytes, 0);
9715            depth_buffer.resize(pixel_count, 0.0);
9716            g_tri_idx.resize(pixel_count, u32::MAX);
9717            luma_buffer.resize(pixel_count, 0);
9718            bloom_a.resize(bloom_cells, [0.0; 4]);
9719            bloom_b.resize(bloom_cells, [0.0; 4]);
9720            bloom_tile_active.resize(bloom_cells, 0);
9721            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
9722            tsr_internal_scratch.clear();
9723            if tsr_internal_scratch.capacity() < rgba_bytes {
9724                tsr_internal_scratch.reserve_exact(rgba_bytes);
9725            }
9726            *has_taa_history = false;
9727            *has_probe_history = false;
9728        }
9729        let rt_mode: RayTracingMode = quality.get_ray_tracing();
9730        if rt_mode != RayTracingMode::Off
9731            && (world.get_bvh_dirty()
9732                || world.get_dynamic_bvh_dirty()
9733                || (world.get_bvh().is_empty() && !world.get_objects().is_empty()))
9734        {
9735            world.ensure_bvh();
9736        }
9737        let sun: DirectionalLight3D = world.get_sun();
9738        self.ensure_sky_lut(&sun);
9739        let cam: Camera3D = world.get_camera();
9740        let aspect: f32 = (span_width as f32) / (span_height as f32).max(1.0);
9741        let matrix_value: Mat4 = world.active_view_projection(aspect);
9742        let frustum: Frustum3D = Frustum3D::from_view_proj(&matrix_value);
9743        let cam_fwd: Vec3 = cam.forward();
9744        let cam_right: Vec3 = cam.right();
9745        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
9746        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
9747        let half_h: f32 = (eff_fov_rad * 0.5).tan();
9748        let half_w: f32 = half_h * aspect;
9749        let focal_px: f32 = (span_height as f32) * 0.5 / half_h.max(0.05);
9750        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
9751        let frustum_on: bool = quality.get_frustum_culling();
9752        let chunk_on: bool = quality.get_chunk_streaming();
9753        let lod_bias: f32 = quality.get_lod_bias();
9754        let aa_mode: AntiAliasingMode = quality.get_anti_aliasing();
9755        let mut visible_objects: usize = 0;
9756        let mut culled_objects: usize = 0;
9757        let mut lod_simplified_objects: usize = 0;
9758        let mut meshlets_drawn: usize = 0;
9759        let mut meshlets_culled: usize = 0;
9760        let mut hiz_culled_objects: usize = 0;
9761        let use_vsm: bool = quality.get_virtual_shadow_maps()
9762            && (rt_mode == RayTracingMode::Off || !world.get_principled_materials().is_empty());
9763        if use_vsm {
9764            let Self {
9765                virtual_shadow_map, ..
9766            } = self;
9767            virtual_shadow_map.update_from_world(world);
9768        }
9769        let has_world_local_lights: bool = quality.get_clustered_lighting()
9770            && (!world.get_point_lights().is_empty() || !world.get_spot_lights().is_empty());
9771        let active_local_lights: usize = if has_world_local_lights {
9772            let Self { light_clusters, .. } = self;
9773            light_clusters.build_clusters(
9774                &cam,
9775                aspect,
9776                world.get_point_lights().as_slice(),
9777                world.get_spot_lights().as_slice(),
9778            );
9779            light_clusters.get_active_light_count()
9780        } else {
9781            0
9782        };
9783        let rt_stride_bias: usize = self.get_rt_stride_bias().min(2);
9784        let static_bvh: &Bvh3D = world.get_bvh();
9785        let dyn_instances: &[DynamicRayInstance] = world.dynamic_instances.as_slice();
9786        let local_bvhs: &[Option<Bvh3D>] = world.mesh_local_bvhs.as_slice();
9787        let total_bvh_nodes: usize = world.total_bvh_nodes();
9788        let world_rev: u64 = world.get_world_revision();
9789        let quality_fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
9790        {
9791            let Self {
9792                render_graph,
9793                cached_rdg_schedule,
9794                cached_rdg_key,
9795                last_executed_rdg_passes,
9796                ..
9797            } = self;
9798            if *cached_rdg_key != quality_fp || cached_rdg_schedule.get_ordered_passes().is_empty()
9799            {
9800                *render_graph =
9801                    RenderGraph3D::build_ue5_frame_graph(span_width, span_height, quality);
9802                *cached_rdg_schedule = render_graph.compile();
9803                *cached_rdg_key = quality_fp;
9804            }
9805            let executed_count: usize = render_graph.execute(
9806                cached_rdg_schedule,
9807                |_pass_kind: RenderPassKind3D, _pass_name: &str| -> u64 { 0 },
9808            );
9809            *last_executed_rdg_passes = executed_count;
9810        }
9811        let objects: &[SceneObject3D] = world.get_objects().as_slice();
9812        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
9813        let deformed_meshes_slice: &[Option<Mesh3D>] = world.deformed_meshes.as_slice();
9814        let principled_mats_slice: &[PrincipledMaterial3D] =
9815            world.get_principled_materials().as_slice();
9816        let textures_slice: &[Texture2D3D] = world.get_textures().as_slice();
9817        let area_lights_slice: &[AreaLight3D] = world.get_area_lights().as_slice();
9818        let environment_ibl_ref: Option<&EnvironmentIbl3D> = world.environment_ibl();
9819        let use_agx_tonemap: bool = world.get_use_agx_tonemap();
9820        let cam_pos: Vec3 = cam.get_position();
9821        let sun_dir: Vec3 = sun.get_direction();
9822        let sky_horizon: Vec3 = sun.get_sky_horizon();
9823        let sky_zenith: Vec3 = sun.get_sky_zenith();
9824        let use_rt_refl: bool = matches!(
9825            rt_mode,
9826            RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
9827        );
9828        let base_rt_step: usize = if rt_mode == RayTracingMode::Off {
9829            0
9830        } else if cfg!(target_arch = "wasm32") {
9831            if w_usize >= 440 {
9832                7
9833            } else if w_usize >= 300 {
9834                6
9835            } else {
9836                4
9837            }
9838        } else if w_usize >= 1120 {
9839            7
9840        } else if w_usize >= 780 {
9841            6
9842        } else if w_usize >= 460 {
9843            5
9844        } else if w_usize >= 300 {
9845            4
9846        } else {
9847            2
9848        };
9849        let rt_step: usize = if base_rt_step > 0 {
9850            (base_rt_step + rt_stride_bias).min(8)
9851        } else {
9852            0
9853        };
9854        let gw: usize = if rt_step > 0 {
9855            w_usize.div_ceil(rt_step)
9856        } else {
9857            0
9858        };
9859        let gh: usize = if rt_step > 0 {
9860            h_usize.div_ceil(rt_step)
9861        } else {
9862            0
9863        };
9864        let tile_px: usize = ENGINE3D_TILE_MAX_PX
9865            .checked_div(rt_step)
9866            .map_or(ENGINE3D_TILE_MAX_PX, |entry_index: usize| {
9867                entry_index.max(1) * rt_step
9868            });
9869        let tiles_x: usize = w_usize.div_ceil(tile_px);
9870        let tiles_y: usize = h_usize.div_ceil(tile_px);
9871        let total_tiles: usize = tiles_x * tiles_y;
9872        let Self {
9873            color_buffer,
9874            aa_buffer,
9875            depth_buffer,
9876            g_tri_idx,
9877            luma_buffer,
9878            shaded_tris,
9879            smooth_tris,
9880            nanite_dags_cache,
9881            rt_probes,
9882            prev_rt_probes,
9883            has_probe_history,
9884            prev_probe_gw,
9885            prev_probe_gh,
9886            prev_probe_rt_mode,
9887            prev_sun_dir,
9888            rt_probes_wide_denoised,
9889            bloom_a,
9890            bloom_b,
9891            bloom_tile_active,
9892            visible_scratch,
9893            cluster_ranges_scratch,
9894            projected_verts_scratch,
9895            unique_meshes_scratch,
9896            raster_tris_scratch,
9897            tile_counts_scratch,
9898            tile_offsets_scratch,
9899            tile_cursors_scratch,
9900            tile_tri_indices_scratch,
9901            has_taa_history,
9902            prev_vp_m0,
9903            prev_view_proj,
9904            has_prev_vp,
9905            prev_render_dims,
9906            prev_rt_step,
9907            hiz_pyramid,
9908            hiz_occluder_flags_scratch,
9909            lumen_cache,
9910            light_clusters,
9911            virtual_shadow_map,
9912            tsr_upscaler,
9913            tsr_internal_scratch,
9914            geom_chunks_scratch,
9915            adapted_exposure,
9916            frame_index,
9917            sky_lut,
9918            aces_lut,
9919            saved_objs_scratch,
9920            reserved_object_cap,
9921            reserved_mesh_cap,
9922            ..
9923        } = self;
9924        if nanite_dags_cache.len() < mesh_lib.len() {
9925            let start_dag_idx: usize = nanite_dags_cache.len();
9926            for chain_item in mesh_lib[start_dag_idx..].iter() {
9927                let dag_entry: Option<NaniteClusterDag> = chain_item
9928                    .get_levels()
9929                    .first()
9930                    .filter(|lod0: &&Mesh3D| lod0.get_meshlets().len() > 1)
9931                    .map(NaniteClusterDag::from_mesh);
9932                nanite_dags_cache.push(dag_entry);
9933            }
9934        }
9935        let cur_frame_idx: usize = *frame_index as usize;
9936        let (jitter_x, jitter_y): (f32, f32) = if aa_mode == AntiAliasingMode::Tsr {
9937            HALTON_JITTER_8[cur_frame_idx & 7]
9938        } else {
9939            (0.0, 0.0)
9940        };
9941        *frame_index = frame_index.wrapping_add(1);
9942        if *reserved_object_cap < objects.len()
9943            || *reserved_mesh_cap < mesh_lib.len()
9944            || shaded_tris.capacity() == 0
9945        {
9946            let mut lod0_tris_sum: usize = 0;
9947            for scene_obj in objects.iter() {
9948                if let Some(chain) = mesh_lib.get(scene_obj.get_mesh_id())
9949                    && let Some(level0) = chain.get_levels().first()
9950                {
9951                    lod0_tris_sum = lod0_tris_sum.saturating_add(level0.get_indices().len());
9952                }
9953            }
9954            let mut max_mesh_verts: usize = 1_024;
9955            let mut max_mesh_clusters: usize = 128;
9956            for chain in mesh_lib.iter() {
9957                if let Some(level0) = chain.get_levels().first() {
9958                    max_mesh_verts = max_mesh_verts.max(level0.get_vertices().len());
9959                    max_mesh_clusters = max_mesh_clusters.max(level0.get_meshlets().len());
9960                }
9961            }
9962            let obj_cap: usize = objects.len().max(128);
9963            let mesh_cap: usize = mesh_lib.len().max(64);
9964            let max_scene_tris: usize = lod0_tris_sum.saturating_mul(2).max(8_192);
9965            let chunk_tri_cap: usize = (max_scene_tris / 2).max(2_048);
9966            if visible_scratch.capacity() < obj_cap {
9967                visible_scratch.reserve(obj_cap.saturating_sub(visible_scratch.len()));
9968            }
9969            if hiz_occluder_flags_scratch.capacity() < obj_cap {
9970                hiz_occluder_flags_scratch
9971                    .reserve(obj_cap.saturating_sub(hiz_occluder_flags_scratch.len()));
9972            }
9973            if saved_objs_scratch.capacity() < obj_cap {
9974                saved_objs_scratch.reserve(obj_cap.saturating_sub(saved_objs_scratch.len()));
9975            }
9976            if unique_meshes_scratch.capacity() < mesh_cap {
9977                unique_meshes_scratch.reserve(mesh_cap.saturating_sub(unique_meshes_scratch.len()));
9978            }
9979            if shaded_tris.capacity() < max_scene_tris {
9980                shaded_tris.reserve(max_scene_tris.saturating_sub(shaded_tris.len()));
9981            }
9982            if smooth_tris.capacity() < max_scene_tris {
9983                smooth_tris.reserve(max_scene_tris.saturating_sub(smooth_tris.len()));
9984            }
9985            if raster_tris_scratch.capacity() < max_scene_tris {
9986                raster_tris_scratch
9987                    .reserve(max_scene_tris.saturating_sub(raster_tris_scratch.len()));
9988            }
9989            if projected_verts_scratch.capacity() < max_mesh_verts {
9990                projected_verts_scratch
9991                    .reserve(max_mesh_verts.saturating_sub(projected_verts_scratch.len()));
9992            }
9993            if cluster_ranges_scratch.capacity() < max_mesh_clusters {
9994                cluster_ranges_scratch
9995                    .reserve(max_mesh_clusters.saturating_sub(cluster_ranges_scratch.len()));
9996            }
9997            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
9998                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, GeomChunkScratch::default);
9999            }
10000            for chunk_buf in geom_chunks_scratch.iter_mut() {
10001                if chunk_buf.shaded_tris.capacity() < chunk_tri_cap {
10002                    chunk_buf
10003                        .shaded_tris
10004                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.shaded_tris.len()));
10005                }
10006                if chunk_buf.smooth_tris.capacity() < chunk_tri_cap {
10007                    chunk_buf
10008                        .smooth_tris
10009                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.smooth_tris.len()));
10010                }
10011                if chunk_buf.raster_tris.capacity() < chunk_tri_cap {
10012                    chunk_buf
10013                        .raster_tris
10014                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.raster_tris.len()));
10015                }
10016                if chunk_buf.projected_verts.capacity() < max_mesh_verts {
10017                    chunk_buf
10018                        .projected_verts
10019                        .reserve(max_mesh_verts.saturating_sub(chunk_buf.projected_verts.len()));
10020                }
10021                if chunk_buf.cluster_ranges.capacity() < max_mesh_clusters {
10022                    chunk_buf
10023                        .cluster_ranges
10024                        .reserve(max_mesh_clusters.saturating_sub(chunk_buf.cluster_ranges.len()));
10025                }
10026                if chunk_buf.mesh_ids.capacity() < obj_cap {
10027                    chunk_buf
10028                        .mesh_ids
10029                        .reserve(obj_cap.saturating_sub(chunk_buf.mesh_ids.len()));
10030                }
10031            }
10032            *reserved_object_cap = obj_cap;
10033            *reserved_mesh_cap = mesh_cap;
10034        }
10035        visible_scratch.clear();
10036        unique_meshes_scratch.clear();
10037        if tile_counts_scratch.capacity() < total_tiles {
10038            tile_counts_scratch.reserve(total_tiles.saturating_sub(tile_counts_scratch.len()));
10039        }
10040        if tile_offsets_scratch.capacity() < total_tiles + 1 {
10041            tile_offsets_scratch
10042                .reserve((total_tiles + 1).saturating_sub(tile_offsets_scratch.len()));
10043        }
10044        if tile_cursors_scratch.capacity() < total_tiles {
10045            tile_cursors_scratch.reserve(total_tiles.saturating_sub(tile_cursors_scratch.len()));
10046        }
10047        let min_tile_indices: usize = total_tiles
10048            .saturating_mul(256)
10049            .max(shaded_tris.capacity().saturating_mul(8));
10050        if tile_tri_indices_scratch.capacity() < min_tile_indices {
10051            tile_tri_indices_scratch
10052                .reserve(min_tile_indices.saturating_sub(tile_tri_indices_scratch.len()));
10053        }
10054        for (obj_idx, obj) in objects.iter().enumerate() {
10055            if !world.is_object_visible(obj_idx) {
10056                culled_objects += 1;
10057                continue;
10058            }
10059            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
10060            let dist_sq: f32 = bounds.center().sub(cam_pos).length_sq();
10061            if chunk_on {
10062                let bmin: Vec3 = bounds.get_min();
10063                let bmax: Vec3 = bounds.get_max();
10064                let cx: f32 = cam_pos.get_x().clamp(bmin.get_x(), bmax.get_x());
10065                let cy: f32 = cam_pos.get_y().clamp(bmin.get_y(), bmax.get_y());
10066                let cz: f32 = cam_pos.get_z().clamp(bmin.get_z(), bmax.get_z());
10067                let closest_dist_sq: f32 = Vec3::new(cx, cy, cz).sub(cam_pos).length_sq();
10068                if closest_dist_sq > draw_dist_sq {
10069                    culled_objects += 1;
10070                    continue;
10071                }
10072            }
10073            if frustum_on && !frustum.intersects_bounds(&bounds) {
10074                culled_objects += 1;
10075                continue;
10076            }
10077            visible_scratch.push((dist_sq, obj_idx));
10078        }
10079        visible_scratch.sort_unstable_by(|alpha_val: &(f32, usize), blue_val: &(f32, usize)| {
10080            alpha_val
10081                .0
10082                .total_cmp(&blue_val.0)
10083                .then_with(|| alpha_val.1.cmp(&blue_val.1))
10084        });
10085        shaded_tris.clear();
10086        smooth_tris.clear();
10087        raster_tris_scratch.clear();
10088        let near_plane: f32 = cam.get_near().max(0.15);
10089        let w_f: f32 = span_width as f32;
10090        let h_f: f32 = span_height as f32;
10091        let w_max_i: i32 = (span_width as i32) - 1;
10092        let h_max_i: i32 = (span_height as i32) - 1;
10093        let hiz_active: bool =
10094            quality.get_occlusion_culling() && objects.len() >= 220 && visible_scratch.len() >= 64;
10095        if hiz_active {
10096            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
10097            hiz_pyramid.clear_for_prepass();
10098            hiz_occluder_flags_scratch.clear();
10099            hiz_occluder_flags_scratch.resize(visible_scratch.len(), 0);
10100            let mut stamped_occluders: usize = 0;
10101            let mut stamped_tris: usize = 0;
10102            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10103                if stamped_occluders >= HIZ_MAX_PREPASS_OCCLUDERS
10104                    || stamped_tris >= HIZ_MAX_OCCLUDER_TRIS
10105                {
10106                    break;
10107                }
10108                if dist_sq < 16.0 {
10109                    continue;
10110                }
10111                let obj: &SceneObject3D = &objects[obj_idx];
10112                if !obj.get_ray_trace_caster() || obj.get_world_bounds().radius() < 4.0 {
10113                    continue;
10114                }
10115                let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
10116                    continue;
10117                };
10118                let Some(mesh) = chain.get_levels().first() else {
10119                    continue;
10120                };
10121                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
10122                let invalid_occ: bool = !mesh.get_is_closed() || indices.is_empty();
10123                if invalid_occ || indices.len() > 24 {
10124                    continue;
10125                }
10126                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
10127                let mvp_occ: Mat4 = matrix_value.mul(obj.get_transform().to_mat4());
10128                projected_verts_scratch.clear();
10129                projected_verts_scratch.reserve(verts.len());
10130                for item_val in verts.iter() {
10131                    let cp: [f32; 4] = mvp_occ.mul_point4(item_val.get_position());
10132                    projected_verts_scratch.push((cp, Vec3::zero()));
10133                }
10134                let vlen: usize = projected_verts_scratch.len();
10135                for tri in indices.iter() {
10136                    let (i0, i1, i2): (usize, usize, usize) =
10137                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
10138                    let out_01: bool = i0 >= vlen || i1 >= vlen;
10139                    if out_01 || i2 >= vlen {
10140                        continue;
10141                    }
10142                    let c0: [f32; 4] = projected_verts_scratch[i0].0;
10143                    let c1: [f32; 4] = projected_verts_scratch[i1].0;
10144                    let c2: [f32; 4] = projected_verts_scratch[i2].0;
10145                    let clipped_01: bool = c0[3] < near_plane || c1[3] < near_plane;
10146                    if clipped_01 || c2[3] < near_plane {
10147                        continue;
10148                    }
10149                    let iw0: f32 = 1.0 / c0[3];
10150                    let iw1: f32 = 1.0 / c1[3];
10151                    let iw2: f32 = 1.0 / c2[3];
10152                    let sx0: f32 = (c0[0] * iw0 * 0.5 + 0.5) * w_f;
10153                    let sy0: f32 = (0.5 - c0[1] * iw0 * 0.5) * h_f;
10154                    let sx1: f32 = (c1[0] * iw1 * 0.5 + 0.5) * w_f;
10155                    let sy1: f32 = (0.5 - c1[1] * iw1 * 0.5) * h_f;
10156                    let sx2: f32 = (c2[0] * iw2 * 0.5 + 0.5) * w_f;
10157                    let sy2: f32 = (0.5 - c2[1] * iw2 * 0.5) * h_f;
10158                    hiz_pyramid.stamp_occluder_triangle_conservative(
10159                        [sx0, sx1, sx2],
10160                        [sy0, sy1, sy2],
10161                        [iw0, iw1, iw2],
10162                    );
10163                    stamped_tris += 1;
10164                }
10165                hiz_occluder_flags_scratch[vis_slot] = 1;
10166                stamped_occluders += 1;
10167            }
10168            hiz_pyramid.rebuild_mips();
10169        }
10170        let geom_ctx: GeomPassContext<'_> = GeomPassContext {
10171            objects,
10172            mesh_lib,
10173            deformed_meshes: deformed_meshes_slice,
10174            principled_materials: principled_mats_slice,
10175            nanite_dags: nanite_dags_cache.as_slice(),
10176            hiz_pyramid: &*hiz_pyramid,
10177            hiz_occluder_flags: hiz_occluder_flags_scratch.as_slice(),
10178            frustum,
10179            view_proj: matrix_value,
10180            cam_pos,
10181            sun_dir,
10182            sky_horizon,
10183            sky_zenith,
10184            focal_px,
10185            lod_bias,
10186            near_plane,
10187            w_f,
10188            h_f,
10189            w_max_i,
10190            h_max_i,
10191            jitter_x,
10192            jitter_y,
10193            frustum_on,
10194            hiz_active,
10195            use_rt_refl,
10196            use_agx_tonemap,
10197        };
10198        let vis_len: usize = visible_scratch.len();
10199        if vis_len >= GEOM_PARALLEL_MIN_OBJECTS {
10200            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
10201                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, || GeomChunkScratch {
10202                    shaded_tris: Vec::with_capacity(512),
10203                    smooth_tris: Vec::with_capacity(512),
10204                    raster_tris: Vec::with_capacity(512),
10205                    mesh_ids: Vec::with_capacity(64),
10206                    projected_verts: Vec::with_capacity(512),
10207                    cluster_ranges: Vec::with_capacity(64),
10208                    visible_objects: 0,
10209                    hiz_culled_objects: 0,
10210                    lod_simplified_objects: 0,
10211                    meshlets_drawn: 0,
10212                    meshlets_culled: 0,
10213                });
10214            }
10215            let vis_slice: &[(f32, usize)] = visible_scratch.as_slice();
10216            let chunks_base: usize = geom_chunks_scratch.as_mut_ptr() as usize;
10217            parallel_for_ranges(GEOM_PARALLEL_CHUNKS, 1, |c0: usize, c1: usize| {
10218                for ci in c0..c1 {
10219                    // SAFETY: `parallel_for_ranges` partitions `0..GEOM_PARALLEL_CHUNKS` into strictly disjoint indices.
10220                    let chunk: &mut GeomChunkScratch =
10221                        unsafe { &mut *(chunks_base as *mut GeomChunkScratch).add(ci) };
10222                    chunk.shaded_tris.clear();
10223                    chunk.smooth_tris.clear();
10224                    chunk.raster_tris.clear();
10225                    chunk.mesh_ids.clear();
10226                    chunk.visible_objects = 0;
10227                    chunk.hiz_culled_objects = 0;
10228                    chunk.lod_simplified_objects = 0;
10229                    chunk.meshlets_drawn = 0;
10230                    chunk.meshlets_culled = 0;
10231                    let mut out_view: GeomPassOut<'_> = GeomPassOut {
10232                        shaded_tris: &mut chunk.shaded_tris,
10233                        smooth_tris: &mut chunk.smooth_tris,
10234                        raster_tris: &mut chunk.raster_tris,
10235                        projected_verts: &mut chunk.projected_verts,
10236                        cluster_ranges: &mut chunk.cluster_ranges,
10237                        mesh_ids: Some(&mut chunk.mesh_ids),
10238                        unique_meshes: None,
10239                        visible_objects: 0,
10240                        hiz_culled_objects: 0,
10241                        lod_simplified_objects: 0,
10242                        meshlets_drawn: 0,
10243                        meshlets_culled: 0,
10244                    };
10245                    let vis_start: usize = (ci * vis_len) / GEOM_PARALLEL_CHUNKS;
10246                    let vis_end: usize = ((ci + 1) * vis_len) / GEOM_PARALLEL_CHUNKS;
10247                    for (offset, &(dist_sq, obj_idx)) in
10248                        vis_slice[vis_start..vis_end].iter().enumerate()
10249                    {
10250                        let vis_slot: usize = vis_start + offset;
10251                        Self::process_visible_object_geom(
10252                            &geom_ctx,
10253                            vis_slot,
10254                            dist_sq,
10255                            obj_idx,
10256                            &mut out_view,
10257                        );
10258                    }
10259                    chunk.visible_objects = out_view.visible_objects;
10260                    chunk.hiz_culled_objects = out_view.hiz_culled_objects;
10261                    chunk.lod_simplified_objects = out_view.lod_simplified_objects;
10262                    chunk.meshlets_drawn = out_view.meshlets_drawn;
10263                    chunk.meshlets_culled = out_view.meshlets_culled;
10264                }
10265            });
10266            let mut total_chunk_tris: usize = 0;
10267            let mut total_chunk_smooth: usize = 0;
10268            for chunk in geom_chunks_scratch.iter() {
10269                total_chunk_tris += chunk.shaded_tris.len();
10270                total_chunk_smooth += chunk.smooth_tris.len();
10271            }
10272            if shaded_tris.capacity() < total_chunk_tris {
10273                shaded_tris.reserve(total_chunk_tris - shaded_tris.capacity());
10274            }
10275            if smooth_tris.capacity() < total_chunk_smooth {
10276                smooth_tris.reserve(total_chunk_smooth - smooth_tris.capacity());
10277            }
10278            if raster_tris_scratch.capacity() < total_chunk_tris {
10279                raster_tris_scratch.reserve(total_chunk_tris - raster_tris_scratch.capacity());
10280            }
10281            for chunk in geom_chunks_scratch.iter() {
10282                let base_tri_id: u32 = shaded_tris.len() as u32;
10283                let base_smooth_id: u32 = smooth_tris.len() as u32;
10284                smooth_tris.extend_from_slice(chunk.smooth_tris.as_slice());
10285                for &shaded_rec in chunk.shaded_tris.iter() {
10286                    let mut shifted_tri: GShadeTri = shaded_rec;
10287                    if shifted_tri.smooth_idx != u32::MAX {
10288                        shifted_tri.smooth_idx += base_smooth_id;
10289                    }
10290                    shaded_tris.push(shifted_tri);
10291                }
10292                for &rt in chunk.raster_tris.iter() {
10293                    let mut shifted: RasterTri2D = rt;
10294                    shifted.tri_id += base_tri_id;
10295                    raster_tris_scratch.push(shifted);
10296                }
10297                visible_objects += chunk.visible_objects;
10298                hiz_culled_objects += chunk.hiz_culled_objects;
10299                culled_objects += chunk.hiz_culled_objects;
10300                lod_simplified_objects += chunk.lod_simplified_objects;
10301                meshlets_drawn += chunk.meshlets_drawn;
10302                meshlets_culled += chunk.meshlets_culled;
10303                for &mesh_id in chunk.mesh_ids.iter() {
10304                    let _: bool = unique_meshes_scratch.insert(mesh_id);
10305                }
10306            }
10307        } else {
10308            let mut seq_out: GeomPassOut<'_> = GeomPassOut {
10309                shaded_tris,
10310                smooth_tris,
10311                raster_tris: raster_tris_scratch,
10312                projected_verts: projected_verts_scratch,
10313                cluster_ranges: cluster_ranges_scratch,
10314                mesh_ids: None,
10315                unique_meshes: Some(unique_meshes_scratch),
10316                visible_objects: 0,
10317                hiz_culled_objects: 0,
10318                lod_simplified_objects: 0,
10319                meshlets_drawn: 0,
10320                meshlets_culled: 0,
10321            };
10322            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10323                Self::process_visible_object_geom(
10324                    &geom_ctx,
10325                    vis_slot,
10326                    dist_sq,
10327                    obj_idx,
10328                    &mut seq_out,
10329                );
10330            }
10331            visible_objects += seq_out.visible_objects;
10332            hiz_culled_objects += seq_out.hiz_culled_objects;
10333            culled_objects += seq_out.hiz_culled_objects;
10334            lod_simplified_objects += seq_out.lod_simplified_objects;
10335            meshlets_drawn += seq_out.meshlets_drawn;
10336            meshlets_culled += seq_out.meshlets_culled;
10337        }
10338        let triangles_drawn: usize = shaded_tris.len();
10339        tile_counts_scratch.clear();
10340        tile_counts_scratch.resize(total_tiles, 0);
10341        let tile_px_i: i32 = tile_px as i32;
10342        let tiles_x_max: usize = tiles_x.saturating_sub(1);
10343        let tiles_y_max: usize = tiles_y.saturating_sub(1);
10344        for tri in raster_tris_scratch.iter() {
10345            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10346            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10347            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10348            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10349            for ty in ty0..=ty1 {
10350                let row_t: usize = ty * tiles_x;
10351                for tx in tx0..=tx1 {
10352                    tile_counts_scratch[row_t + tx] += 1;
10353                }
10354            }
10355        }
10356        tile_offsets_scratch.clear();
10357        tile_offsets_scratch.reserve(total_tiles + 1);
10358        let mut prefix_sum: u32 = 0;
10359        tile_offsets_scratch.push(0);
10360        for &cnt in tile_counts_scratch.iter() {
10361            prefix_sum += cnt;
10362            tile_offsets_scratch.push(prefix_sum);
10363        }
10364        tile_cursors_scratch.clear();
10365        tile_cursors_scratch.extend_from_slice(&tile_offsets_scratch[..total_tiles]);
10366        tile_tri_indices_scratch.resize(prefix_sum as usize, 0);
10367        for (slot, tri) in raster_tris_scratch.iter().enumerate() {
10368            let slot_u32: u32 = slot as u32;
10369            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10370            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10371            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10372            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10373            for ty in ty0..=ty1 {
10374                let row_t: usize = ty * tiles_x;
10375                for tx in tx0..=tx1 {
10376                    let t_idx: usize = row_t + tx;
10377                    let dst_pos: usize = tile_cursors_scratch[t_idx] as usize;
10378                    tile_cursors_scratch[t_idx] = (dst_pos as u32) + 1;
10379                    tile_tri_indices_scratch[dst_pos] = slot_u32;
10380                }
10381            }
10382        }
10383        let bloom_on: bool = matches!(
10384            quality.get_preset(),
10385            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
10386        );
10387        if bloom_on {
10388            let bloom_cells: usize = border_width * bh;
10389            if bloom_a.len() != bloom_cells {
10390                bloom_a.resize(bloom_cells, [0.0; 4]);
10391                bloom_b.resize(bloom_cells, [0.0; 4]);
10392                bloom_tile_active.resize(bloom_cells, 0);
10393            }
10394        }
10395        let sun_inv_dir: Vec3 = Ray3D::safe_inv_vec(sun_dir);
10396        let soft_shadow_rays: [(Vec3, Vec3); 16] = if rt_mode == RayTracingMode::FullPathTracedGi {
10397            let sun_t1: Vec3 = sun_dir.cross(Vec3::new(0.0, 1.0, 0.0)).normalize();
10398            let sun_t2: Vec3 = sun_dir.cross(sun_t1).normalize();
10399            let mut table: [(Vec3, Vec3); 16] = [(sun_dir, sun_inv_dir); 16];
10400            for (slot, &(ox, oy)) in table.iter_mut().zip(SOFT_SHADOW_RING_16.iter()) {
10401                let jittered: Vec3 = sun_dir
10402                    .add(sun_t1.scale(ox))
10403                    .add(sun_t2.scale(oy))
10404                    .normalize();
10405                *slot = (jittered, Ray3D::safe_inv_vec(jittered));
10406            }
10407            table
10408        } else {
10409            [(sun_dir, sun_inv_dir); 16]
10410        };
10411        let frame_context: DeferredFrameContext = DeferredFrameContext {
10412            width: w_usize,
10413            height: h_usize,
10414            grid_width: gw,
10415            grid_height: gh,
10416            bloom_width: border_width,
10417            raytrace_step: rt_step,
10418            inv_width: 1.0 / (span_width as f32).max(1.0),
10419            inv_height: 1.0 / (span_height as f32).max(1.0),
10420            camera_position: cam_pos,
10421            camera_forward: cam_fwd,
10422            camera_right_scaled: cam_right.scale(half_w),
10423            camera_up_scaled: cam_up.scale(half_h),
10424            sun,
10425            inv_sun_dir: sun_inv_dir,
10426            soft_shadow_rays,
10427            frame_index: cur_frame_idx,
10428            raytrace_mode: rt_mode,
10429            reflection_bounces: quality.get_reflection_bounces(),
10430            fog_on: quality.get_volumetric_fog(),
10431            inv_fog_distance: 0.92 / quality.get_draw_distance().max(40.0),
10432            exposure_scale: *adapted_exposure,
10433            bloom_on,
10434            has_clustered_lights: active_local_lights > 0,
10435            probe_frame_generation: PROBE_SCRATCH_FRAME_GEN.fetch_add(1, Ordering::Relaxed),
10436            world_time_secs: world.get_world_time_secs(),
10437        };
10438        let vp_m0: f32 = matrix_value.get_elements()[0]
10439            + matrix_value.get_elements()[12] * 0.01
10440            + matrix_value.get_elements()[14] * 0.01;
10441        let cam_stable: bool = (*prev_vp_m0 - vp_m0).abs() < 0.35;
10442        let sun_stable: bool = prev_sun_dir.dot(sun_dir) > 0.9999;
10443        let probe_hist_valid: bool = *has_probe_history
10444            && *has_prev_vp
10445            && rt_step > 0
10446            && *prev_probe_rt_mode == rt_mode
10447            && sun_stable;
10448        if rt_step > 0 {
10449            rt_probes.resize(gw * gh);
10450            prev_rt_probes.resize(gw * gh);
10451        }
10452        let use_lumen_cache: bool = quality.get_lumen_radiance_cache()
10453            && rt_step > 0
10454            && rt_mode == RayTracingMode::FullPathTracedGi;
10455        if use_lumen_cache && !sun_stable {
10456            lumen_cache.invalidate();
10457        }
10458        let rays_atom: AtomicUsize = AtomicUsize::new(0);
10459        let reproj_hits_atom: AtomicUsize = AtomicUsize::new(0);
10460        {
10461            let prev_probes_ref: Option<&RtProbeGridSoa> = if probe_hist_valid {
10462                Some(&*prev_rt_probes)
10463            } else {
10464                None
10465            };
10466            let lumen_ref: Option<&LumenRadianceCache> =
10467                if use_lumen_cache && lumen_cache.get_active_cells() > 0 {
10468                    Some(&*lumen_cache)
10469                } else {
10470                    None
10471                };
10472            let clusters_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
10473                Some(&*light_clusters)
10474            } else {
10475                None
10476            };
10477            let vsm_ref: Option<&VirtualShadowMap> = if use_vsm {
10478                Some(&*virtual_shadow_map)
10479            } else {
10480                None
10481            };
10482            let same_camera_pose: bool = probe_hist_valid
10483                && *prev_render_dims == (w_usize, h_usize)
10484                && *prev_rt_step == rt_step
10485                && *prev_probe_gw == gw
10486                && *prev_probe_gh == gh
10487                && prev_view_proj.get_elements() == matrix_value.get_elements();
10488            let tile_inputs: TileRasterProbeInputs<'_> = TileRasterProbeInputs {
10489                raster_tris: raster_tris_scratch.as_slice(),
10490                tile_offsets: tile_offsets_scratch.as_slice(),
10491                tile_tri_indices: tile_tri_indices_scratch.as_slice(),
10492                shaded_tris: shaded_tris.as_slice(),
10493                static_bvh,
10494                dyn_instances,
10495                local_bvhs,
10496                prev_probes: prev_probes_ref,
10497                prev_view_proj: *prev_view_proj,
10498                prev_render_dims: *prev_render_dims,
10499                prev_rt_step: *prev_rt_step,
10500                prev_gw: *prev_probe_gw,
10501                prev_gh: *prev_probe_gh,
10502                lumen_cache: lumen_ref,
10503                light_clusters: clusters_ref,
10504                vsm: vsm_ref,
10505                use_vsm_far_shadows: use_vsm,
10506                probe_checker_parity: cur_frame_idx & 1,
10507                same_camera_pose,
10508                tile_px,
10509                tiles_x,
10510                sky_lut: sky_lut.as_slice(),
10511            };
10512            let depth_base: usize = depth_buffer.as_mut_ptr() as usize;
10513            let gtri_base: usize = g_tri_idx.as_mut_ptr() as usize;
10514            let probe_ptrs: RtProbeGridMutPtrs = rt_probes.mut_ptrs();
10515            let tile_grain: usize = 1;
10516            parallel_for_ranges(total_tiles, tile_grain, |t0: usize, t1: usize| {
10517                // SAFETY: `parallel_for_ranges` partitions `0..total_tiles` into strictly disjoint screen tiles and probe blocks.
10518                let (red_val, hit_val): (usize, usize) = unsafe {
10519                    Self::raster_and_trace_tiles(
10520                        &frame_context,
10521                        &tile_inputs,
10522                        t0,
10523                        t1,
10524                        (depth_base, gtri_base, probe_ptrs),
10525                    )
10526                };
10527                if red_val > 0 {
10528                    let _: usize = rays_atom.fetch_add(red_val, Ordering::Relaxed);
10529                }
10530                if hit_val > 0 {
10531                    let _: usize = reproj_hits_atom.fetch_add(hit_val, Ordering::Relaxed);
10532                }
10533            });
10534        }
10535        if use_lumen_cache {
10536            lumen_cache.begin_frame(sun_dir);
10537            let total_probes: usize = gw * gh;
10538            let probe_stride: usize = (total_probes / 384).max(1).next_power_of_two();
10539            let mut p_cursor: usize = cur_frame_idx & (probe_stride - 1);
10540            while p_cursor < total_probes {
10541                if rt_probes.valid[p_cursor] != 0 {
10542                    lumen_cache.accumulate_sample(
10543                        Vec3::new(
10544                            rt_probes.world_x[p_cursor],
10545                            rt_probes.world_y[p_cursor],
10546                            rt_probes.world_z[p_cursor],
10547                        ),
10548                        Vec3::new(
10549                            rt_probes.nx[p_cursor],
10550                            rt_probes.ny[p_cursor],
10551                            rt_probes.nz[p_cursor],
10552                        ),
10553                        cam_pos,
10554                        Vec3::new(
10555                            rt_probes.gi_r[p_cursor],
10556                            rt_probes.gi_g[p_cursor],
10557                            rt_probes.gi_b[p_cursor],
10558                        ),
10559                        rt_probes.ao[p_cursor],
10560                        rt_probes.shadow[p_cursor],
10561                    );
10562                }
10563                p_cursor += probe_stride;
10564            }
10565        }
10566        let lumen_cache_cells: usize = lumen_cache.get_active_cells();
10567        let probe_reproj_hits: usize = reproj_hits_atom.load(Ordering::Relaxed);
10568        let denoise_probes: bool = rt_step > 0
10569            && matches!(
10570                rt_mode,
10571                RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
10572            );
10573        if denoise_probes && gw > PROBE_ROW_STACK_CAP {
10574            Self::denoise_wide_grid(rt_probes, gw, gh, rt_probes_wide_denoised);
10575        }
10576        let bloom_any_atom: AtomicUsize = AtomicUsize::new(0);
10577        let bloom_row_bits: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9];
10578        {
10579            let clusters_shade_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
10580                Some(&*light_clusters)
10581            } else {
10582                None
10583            };
10584            let vsm_shade_ref: Option<&VirtualShadowMap> = if use_vsm {
10585                Some(&*virtual_shadow_map)
10586            } else {
10587                None
10588            };
10589            let shade_inputs: ShadeBandInputs<'_> = ShadeBandInputs {
10590                depth_buf: depth_buffer.as_slice(),
10591                g_tri_idx: g_tri_idx.as_slice(),
10592                shaded_tris: shaded_tris.as_slice(),
10593                smooth_tris: smooth_tris.as_slice(),
10594                principled_materials: principled_mats_slice,
10595                textures: textures_slice,
10596                area_lights: area_lights_slice,
10597                light_clusters: clusters_shade_ref,
10598                vsm: vsm_shade_ref,
10599                environment_ibl: environment_ibl_ref,
10600                use_agx_tonemap,
10601                raw_probes: rt_probes,
10602                wide_denoised_probes: rt_probes_wide_denoised,
10603                denoise_probes,
10604                denoise_gi_channels: rt_mode == RayTracingMode::FullPathTracedGi,
10605                static_bvh,
10606                dyn_instances,
10607                local_bvhs,
10608                bloom_row_bits: &bloom_row_bits,
10609                sky_lut: sky_lut.as_slice(),
10610                aces_lut: aces_lut.as_slice(),
10611            };
10612            let color_base: usize = color_buffer.as_mut_ptr() as usize;
10613            let luma_base: usize = luma_buffer.as_mut_ptr() as usize;
10614            let bloom_base: usize = bloom_a.as_mut_ptr() as usize;
10615            let bloom_total_len: usize = bloom_a.len();
10616            let shade_grain: usize = 4;
10617            parallel_for_ranges(h_usize, shade_grain, |y0: usize, y1: usize| {
10618                let rows: usize = y1 - y0;
10619                // SAFETY: `shade_grain` is a multiple of 4 and `parallel_for_ranges` yields disjoint row bands.
10620                let c_band: &mut [u8] = unsafe {
10621                    from_raw_parts_mut(
10622                        (color_base as *mut u8).add(y0 * w_usize * 4),
10623                        rows * w_usize * 4,
10624                    )
10625                };
10626                // SAFETY: Disjoint luma row band for `[y0, y1)`.
10627                let l_band: &mut [u8] = unsafe {
10628                    from_raw_parts_mut((luma_base as *mut u8).add(y0 * w_usize), rows * w_usize)
10629                };
10630                let b_start: usize = (y0 / 4) * border_width;
10631                let b_end: usize = ((y1.div_ceil(4)) * border_width).min(bloom_total_len);
10632                let b_band: &mut [[f32; 4]] = if b_start < b_end {
10633                    // SAFETY: Since `y0` and non-final `y1` are multiples of 4, `[b_start, b_end)` ranges are disjoint.
10634                    unsafe {
10635                        from_raw_parts_mut(
10636                            (bloom_base as *mut [f32; 4]).add(b_start),
10637                            b_end - b_start,
10638                        )
10639                    }
10640                } else {
10641                    &mut []
10642                };
10643                let (radius_val, has_bloom_band): (usize, bool) = Self::shade_deferred_band(
10644                    &frame_context,
10645                    &shade_inputs,
10646                    (y0, c_band, l_band, b_band),
10647                );
10648                if radius_val > 0 {
10649                    let _: usize = rays_atom.fetch_add(radius_val, Ordering::Relaxed);
10650                }
10651                if has_bloom_band {
10652                    bloom_any_atom.store(1, Ordering::Relaxed);
10653                }
10654            });
10655        }
10656        let rays_traced: usize = rays_atom.load(Ordering::Relaxed);
10657        let luma_len: usize = luma_buffer.len();
10658        if luma_len >= 64 {
10659            let sample_stride: usize = (luma_len / 1024).max(1);
10660            let mut luma_sum: u32 = 0;
10661            let mut sample_cnt: u32 = 0;
10662            let mut sample_idx: usize = sample_stride >> 1;
10663            while sample_idx < luma_len {
10664                luma_sum += luma_buffer[sample_idx] as u32;
10665                sample_cnt += 1;
10666                sample_idx += sample_stride;
10667            }
10668            if sample_cnt > 0 {
10669                let avg_luma: f32 = ((luma_sum as f32) / ((sample_cnt as f32) * 255.0)).max(0.06);
10670                let desired_exp: f32 = ((*adapted_exposure)
10671                    * (AUTO_EXPOSURE_TARGET_LUMA / avg_luma))
10672                    .clamp(AUTO_EXPOSURE_MIN, AUTO_EXPOSURE_MAX);
10673                let exp_delta: f32 = desired_exp - *adapted_exposure;
10674                if exp_delta.abs() > 0.015 {
10675                    *adapted_exposure += exp_delta * AUTO_EXPOSURE_ADAPT_RATE;
10676                }
10677            }
10678        }
10679        let particles_drawn: usize = if world.get_niagara().get_active_count() > 0 {
10680            world.get_niagara().composite_depth_tested(
10681                &matrix_value,
10682                focal_px,
10683                (w_usize, h_usize),
10684                depth_buffer.as_slice(),
10685                color_buffer.as_mut_slice(),
10686            )
10687        } else {
10688            0
10689        };
10690        let bloom_effective: bool = if bloom_on && bloom_any_atom.load(Ordering::Relaxed) != 0 {
10691            let mut row_bits_snap: [u64; 9] = [0; 9];
10692            for (dst, src_atom) in row_bits_snap.iter_mut().zip(bloom_row_bits.iter()) {
10693                *dst = src_atom.load(Ordering::Relaxed);
10694            }
10695            Self::blur_bloom_and_mask(
10696                border_width,
10697                bh,
10698                bloom_a.as_mut_slice(),
10699                bloom_b.as_mut_slice(),
10700                bloom_tile_active.as_mut_slice(),
10701                &row_bits_snap,
10702            )
10703        } else {
10704            false
10705        };
10706        let byte_len: usize = pixel_count * 4;
10707        if aa_mode == AntiAliasingMode::Tsr {
10708            let tsr_params: TsrFrameParams = TsrFrameParams {
10709                src_width: w_usize,
10710                src_height: h_usize,
10711                dst_width: w_usize,
10712                dst_height: h_usize,
10713                camera_position: cam_pos,
10714                camera_forward: cam_fwd,
10715                camera_right_scaled: cam_right.scale(half_w),
10716                camera_up_scaled: cam_up.scale(half_h),
10717                view_projection: matrix_value,
10718                jitter_offset: (jitter_x, jitter_y),
10719                sharpness: TSR_DEFAULT_SHARPNESS,
10720            };
10721            if bloom_effective {
10722                tsr_internal_scratch.clear();
10723                if tsr_internal_scratch.capacity() < byte_len {
10724                    tsr_internal_scratch.reserve_exact(byte_len);
10725                }
10726                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
10727                    color_src: color_buffer.as_slice(),
10728                    luma: luma_buffer.as_slice(),
10729                    g_tri_idx: g_tri_idx.as_slice(),
10730                    bloom: bloom_a.as_slice(),
10731                    bloom_tile_active: bloom_tile_active.as_slice(),
10732                    taa_history: aa_buffer.as_slice(),
10733                };
10734                let tmp_base: usize = tsr_internal_scratch.as_mut_ptr() as usize;
10735                let post_grain: usize = 8;
10736                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
10737                    // SAFETY: `tsr_internal_scratch` has capacity `>= byte_len` and row ranges are disjoint.
10738                    unsafe {
10739                        let band_ptr: *mut u8 = (tmp_base as *mut u8).add(y0 * w_usize * 4);
10740                        Self::post_process_band(
10741                            (w_usize, h_usize, border_width, bh),
10742                            &post_inputs,
10743                            (false, false, true),
10744                            (y0, band_ptr, y1 - y0),
10745                        );
10746                    }
10747                });
10748                // SAFETY: `parallel_for_ranges` initialized every byte in `0..byte_len`.
10749                unsafe {
10750                    tsr_internal_scratch.set_len(byte_len);
10751                }
10752                tsr_upscaler.upscale_rgba(
10753                    tsr_internal_scratch.as_slice(),
10754                    depth_buffer.as_slice(),
10755                    &tsr_params,
10756                    out_pixels,
10757                );
10758            } else {
10759                tsr_upscaler.upscale_rgba(
10760                    color_buffer.as_slice(),
10761                    depth_buffer.as_slice(),
10762                    &tsr_params,
10763                    out_pixels,
10764                );
10765            }
10766        } else {
10767            let use_fxaa: bool = aa_mode != AntiAliasingMode::Off;
10768            let use_taa: bool = aa_mode == AntiAliasingMode::Taa && *has_taa_history && cam_stable;
10769            out_pixels.clear();
10770            if out_pixels.capacity() < byte_len {
10771                out_pixels.reserve_exact(byte_len);
10772            }
10773            {
10774                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
10775                    color_src: color_buffer.as_slice(),
10776                    luma: luma_buffer.as_slice(),
10777                    g_tri_idx: g_tri_idx.as_slice(),
10778                    bloom: bloom_a.as_slice(),
10779                    bloom_tile_active: bloom_tile_active.as_slice(),
10780                    taa_history: aa_buffer.as_slice(),
10781                };
10782                let out_base: usize = out_pixels.as_mut_ptr() as usize;
10783                let post_grain: usize = 8;
10784                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
10785                    // SAFETY: `out_pixels` has capacity `>= byte_len`, `parallel_for_ranges` partitions `0..h_usize`
10786                    // into disjoint row ranges, and `post_process_band` writes all `(y1 - y0) * w_usize * 4` bytes.
10787                    unsafe {
10788                        let band_ptr: *mut u8 = (out_base as *mut u8).add(y0 * w_usize * 4);
10789                        Self::post_process_band(
10790                            (w_usize, h_usize, border_width, bh),
10791                            &post_inputs,
10792                            (use_fxaa, use_taa, bloom_effective),
10793                            (y0, band_ptr, y1 - y0),
10794                        );
10795                    }
10796                });
10797            }
10798            // SAFETY: `parallel_for_ranges` has joined and initialized every byte in `0..byte_len`.
10799            unsafe {
10800                out_pixels.set_len(byte_len);
10801            }
10802        }
10803        if rt_step > 0 {
10804            swap(rt_probes, prev_rt_probes);
10805            *has_probe_history = true;
10806            *prev_probe_gw = gw;
10807            *prev_probe_gh = gh;
10808            *prev_probe_rt_mode = rt_mode;
10809            *prev_sun_dir = sun_dir;
10810        } else {
10811            *has_probe_history = false;
10812        }
10813        *prev_vp_m0 = vp_m0;
10814        *prev_view_proj = matrix_value;
10815        *has_prev_vp = true;
10816        *prev_render_dims = (w_usize, h_usize);
10817        *prev_rt_step = rt_step;
10818        if aa_mode == AntiAliasingMode::Taa {
10819            if aa_buffer.len() != byte_len {
10820                aa_buffer.resize(byte_len, 0);
10821            }
10822            swap(aa_buffer, color_buffer);
10823            *has_taa_history = true;
10824        } else {
10825            *has_taa_history = false;
10826        }
10827        let instanced_batches: usize = if quality.get_gpu_instancing() {
10828            unique_meshes_scratch.len()
10829        } else {
10830            visible_objects
10831        };
10832        let stats: RenderStats3D = RenderStats3D {
10833            render_width: span_width,
10834            render_height: span_height,
10835            visible_objects,
10836            culled_objects,
10837            instanced_batches,
10838            triangles_drawn,
10839            rays_traced,
10840            bvh_nodes: total_bvh_nodes,
10841            lod_simplified_objects,
10842            meshlets_drawn,
10843            meshlets_culled,
10844            hiz_culled_objects,
10845            lumen_cache_cells,
10846            active_local_lights,
10847            particles_drawn,
10848            probe_reproj_hits,
10849        };
10850        let same_world_and_cfg: bool = self.get_last_world_revision() == world_rev && {
10851            let Self {
10852                last_quality_fingerprint,
10853                ..
10854            } = self;
10855            *last_quality_fingerprint == quality_fp
10856        };
10857        let next_taa_count: u32 =
10858            if matches!(aa_mode, AntiAliasingMode::Taa | AntiAliasingMode::Tsr) {
10859                if same_world_and_cfg {
10860                    self.get_taa_accumulated_frames().saturating_add(1).min(8)
10861                } else {
10862                    1
10863                }
10864            } else {
10865                0
10866            };
10867        self.set_taa_accumulated_frames(next_taa_count);
10868        self.set_last_world_revision(world_rev);
10869        let Self {
10870            last_quality_fingerprint,
10871            ..
10872        } = self;
10873        *last_quality_fingerprint = quality_fp;
10874        self.set_last_stats(stats);
10875        (span_width, span_height)
10876    }
10877
10878    /// Computes a stable configuration fingerprint covering viewport dimensions and visual quality knobs.
10879    ///
10880    /// # Arguments
10881    ///
10882    /// - `u32` - Target viewport width.
10883    /// - `u32` - Target viewport height.
10884    /// - `&RenderQualityConfig` - Active quality settings.
10885    ///
10886    /// # Returns
10887    ///
10888    /// - `u64` - Combined configuration fingerprint.
10889    #[must_use]
10890    fn quality_fingerprint(viewport_w: u32, viewport_h: u32, quality: &RenderQualityConfig) -> u64 {
10891        let mut height_val: u64 = 0xCBF2_9CE4_8422_2325;
10892        let parts: [u64; 8] = [
10893            viewport_w as u64,
10894            viewport_h as u64,
10895            quality.get_resolution_scale().to_bits() as u64,
10896            quality.get_draw_distance().to_bits() as u64,
10897            quality.get_lod_bias().to_bits() as u64,
10898            quality.get_reflection_bounces() as u64,
10899            (quality.get_ray_tracing() as u64)
10900                | ((quality.get_anti_aliasing() as u64) << 8)
10901                | ((quality.get_preset() as u64) << 16)
10902                | ((quality.get_upscaler() as u64) << 24),
10903            u64::from(quality.get_volumetric_fog())
10904                | (u64::from(quality.get_frustum_culling()) << 1)
10905                | (u64::from(quality.get_chunk_streaming()) << 2)
10906                | (u64::from(quality.get_occlusion_culling()) << 3)
10907                | (u64::from(quality.get_virtual_shadow_maps()) << 4)
10908                | (u64::from(quality.get_clustered_lighting()) << 5)
10909                | (u64::from(quality.get_lumen_radiance_cache()) << 6),
10910        ];
10911        for point_val in parts.into_iter() {
10912            height_val ^= point_val;
10913            height_val = height_val.wrapping_mul(0x0100_0000_01B3);
10914        }
10915        height_val
10916    }
10917
10918    /// Attaches a shared-device GPU 3D render target texture handle for zero-readback single-pass UI+3D compositing.
10919    ///
10920    /// # Arguments
10921    ///
10922    /// - `&Self` - Mutable 3D renderer.
10923    /// - `GpuTextureHandle` - Shared-device GPU texture backing the 3D render target.
10924    /// - `Rect` - Viewport rectangle in logical UI pixels.
10925    pub fn attach_gpu_target(&mut self, handle: GpuTextureHandle, rect: Rect) {
10926        let Self { gpu_target, .. } = self;
10927        gpu_target.attach_handle(handle, rect);
10928    }
10929
10930    /// Prepares a `GpuCompositeDescriptor` referencing the attached shared-device GPU 3D render target for single-pass UI+3D compositing.
10931    ///
10932    /// # Arguments
10933    ///
10934    /// - `&Self` - Mutable 3D renderer.
10935    /// - `u64` - Monotonic compositor frame index.
10936    ///
10937    /// # Returns
10938    ///
10939    /// - `Option<GpuCompositeDescriptor>` - Single-pass composite descriptor when a GPU target is attached.
10940    #[must_use]
10941    pub fn prepare_gpu_composite_descriptor(
10942        &mut self,
10943        frame_index: u64,
10944    ) -> Option<GpuCompositeDescriptor> {
10945        let Self { gpu_target, .. } = self;
10946        gpu_target.record_composite_present(frame_index)
10947    }
10948
10949    /// Explicitly resets temporal anti-aliasing history on camera cuts or world teleports without touching unrelated HUD state.
10950    ///
10951    /// # Arguments
10952    ///
10953    /// - `&Self` - Mutable 3D renderer.
10954    pub fn invalidate_taa_history(&mut self) {
10955        let Self {
10956            has_taa_history,
10957            has_probe_history,
10958            has_prev_vp,
10959            tsr_upscaler,
10960            lumen_cache,
10961            adapted_exposure,
10962            ..
10963        } = self;
10964        *has_taa_history = false;
10965        *has_probe_history = false;
10966        *has_prev_vp = false;
10967        *adapted_exposure = 1.0;
10968        tsr_upscaler.invalidate_history();
10969        lumen_cache.invalidate();
10970        self.set_taa_accumulated_frames(0);
10971    }
10972
10973    /// Returns `true` when the cached 3D framebuffer can be reused across a HUD-only dirty frame without re-running 3D rasterization or starving TAA accumulation.
10974    ///
10975    /// # Arguments
10976    ///
10977    /// - `&Self` - 3D renderer reference.
10978    /// - `&World3D` - Active 3D world.
10979    /// - `u32` - Viewport width in pixels.
10980    /// - `u32` - Viewport height in pixels.
10981    /// - `&RenderQualityConfig` - Active quality settings.
10982    ///
10983    /// # Returns
10984    ///
10985    /// - `bool` - `true` when the cached 3D frame is valid and TAA accumulation does not require another sample.
10986    #[must_use]
10987    pub fn can_reuse_cached_world(
10988        &self,
10989        world: &World3D,
10990        viewport_w: u32,
10991        viewport_h: u32,
10992        quality: &RenderQualityConfig,
10993    ) -> bool {
10994        let Self {
10995            rgba_scratch,
10996            last_quality_fingerprint,
10997            ..
10998        } = self;
10999        if rgba_scratch.is_empty() {
11000            return false;
11001        }
11002        let fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
11003        if self.get_last_world_revision() != world.get_world_revision()
11004            || *last_quality_fingerprint != fp
11005        {
11006            return false;
11007        }
11008        if matches!(
11009            quality.get_anti_aliasing(),
11010            AntiAliasingMode::Taa | AntiAliasingMode::Tsr
11011        ) {
11012            self.get_taa_accumulated_frames() >= 8
11013        } else {
11014            true
11015        }
11016    }
11017
11018    /// Renders `world` into `rgba_scratch` only when 3D state changed or TAA needs another temporal sample, otherwise reusing the cached 3D buffer across HUD-only dirty updates.
11019    ///
11020    /// # Arguments
11021    ///
11022    /// - `&Self` - Mutable 3D renderer.
11023    /// - `&mut World3D` - Open-world 3D scene graph.
11024    /// - `u32` - Target viewport width in logical pixels.
11025    /// - `u32` - Target viewport height in logical pixels.
11026    /// - `&RenderQualityConfig` - Runtime quality settings.
11027    ///
11028    /// # Returns
11029    ///
11030    /// - `(&[u8], bool)` - Borrowed RGBA8 pixel slice and `true` if satisfied from cache without re-rasterization.
11031    #[must_use]
11032    pub fn render_world_or_reuse_cached(
11033        &mut self,
11034        world: &mut World3D,
11035        viewport_w: u32,
11036        viewport_h: u32,
11037        quality: &RenderQualityConfig,
11038    ) -> (&[u8], bool) {
11039        if self.can_reuse_cached_world(world, viewport_w, viewport_h, quality) {
11040            let next_reuses: u64 = self.get_cached_world_reuses().saturating_add(1);
11041            self.set_cached_world_reuses(next_reuses);
11042            let Self { rgba_scratch, .. } = self;
11043            return (rgba_scratch.as_slice(), true);
11044        }
11045        let pixels: &[u8] = self.render_world_rgba(world, viewport_w, viewport_h, quality);
11046        (pixels, false)
11047    }
11048
11049    /// Renders `world` directly into a bounded zero-allocation `RenderBufferPool` slot tagged with `fence_id`.
11050    ///
11051    /// # Arguments
11052    ///
11053    /// - `&Self` - Mutable 3D renderer.
11054    /// - `&mut World3D` - Open-world 3D scene graph.
11055    /// - `u32` - Target viewport width in logical pixels.
11056    /// - `u32` - Target viewport height in logical pixels.
11057    /// - `&RenderQualityConfig` - Runtime quality settings.
11058    /// - `&RenderBufferPool` - Bounded CPU output buffer pool.
11059    /// - `u64` - Submission fence value guarding reclamation.
11060    ///
11061    /// # Returns
11062    ///
11063    /// - `Option<PooledFrameLease>` - Populated pooled RGBA8 lease, or `None` if all bounded pool slots are in flight.
11064    #[must_use]
11065    pub fn render_world_into_pool(
11066        &mut self,
11067        world: &mut World3D,
11068        viewport_w: u32,
11069        viewport_h: u32,
11070        quality: &RenderQualityConfig,
11071        pool: &RenderBufferPool,
11072        fence_id: u64,
11073    ) -> Option<PooledFrameLease> {
11074        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
11075        let min_width: u32 = viewport_w.clamp(1, 240);
11076        let min_height: u32 = viewport_h.clamp(1, 144);
11077        let width_val: u32 = ((viewport_w as f32 * scale).round() as u32).max(min_width);
11078        let height_val: u32 = ((viewport_h as f32 * scale).round() as u32).max(min_height);
11079        let mut lease: PooledFrameLease = pool.acquire(width_val, height_val, fence_id)?;
11080        let (rw, rh): (u32, u32) = self.render_world_into_vec(
11081            world,
11082            viewport_w,
11083            viewport_h,
11084            quality,
11085            lease.get_mut_pixels(),
11086        );
11087        lease.set_dimensions(rw, rh);
11088        Some(lease)
11089    }
11090
11091    /// Renders `world` using a discontinuity-safe interpolated `World3DSnapshot` sampled at `alpha` with object-space inverse-interpolated dynamic RT (zero `dynamic_bvh` rebuilds per VSync).
11092    ///
11093    /// # Arguments
11094    ///
11095    /// - `&Self` - Mutable 3D renderer.
11096    /// - `&mut World3D` - 3D world holding shared mesh library, lighting, and BVH acceleration structures.
11097    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Immutable `(prev_state, curr_state)` snapshot buffer.
11098    /// - `f32` - Normalized interpolation alpha in `[0.0, 1.0]`.
11099    /// - `(u32, u32)` - Target viewport `(width, height)` in logical pixels.
11100    /// - `&RenderQualityConfig` - Runtime quality settings.
11101    /// - `(&RenderBufferPool, u64)` - Bounded CPU output buffer pool and submission fence value.
11102    ///
11103    /// # Returns
11104    ///
11105    /// - `Option<PooledFrameLease>` - Rendered interpolated frame lease, or `None` under pool backpressure.
11106    #[must_use]
11107    pub fn render_world_interpolated_into_pool(
11108        &mut self,
11109        world: &mut World3D,
11110        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
11111        alpha: f32,
11112        viewport: (u32, u32),
11113        quality: &RenderQualityConfig,
11114        target_pool: (&RenderBufferPool, u64),
11115    ) -> Option<PooledFrameLease> {
11116        let (viewport_w, viewport_h): (u32, u32) = viewport;
11117        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11118        if quality.get_ray_tracing() != RayTracingMode::Off
11119            && (world.get_bvh_dirty() || world.get_dynamic_bvh_dirty())
11120        {
11121            world.ensure_bvh();
11122        }
11123        let entry_index: f32 = alpha.clamp(0.0, 1.0);
11124        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
11125        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
11126        let cam_cut: bool = curr_snap.get_camera_cut();
11127        if cam_cut {
11128            self.invalidate_taa_history();
11129        }
11130        let interp_cam: Camera3D = if cam_cut {
11131            curr_snap.get_camera()
11132        } else {
11133            prev_snap
11134                .get_camera()
11135                .lerp(curr_snap.get_camera(), entry_index)
11136        };
11137        let saved_cam: Camera3D = world.get_camera();
11138        let mut saved_objs: Vec<(usize, Transform3D, AxisAlignedBox3D)> = {
11139            let Self {
11140                saved_objs_scratch, ..
11141            } = self;
11142            take(saved_objs_scratch)
11143        };
11144        saved_objs.clear();
11145        world.set_camera(interp_cam);
11146        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
11147        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
11148        if saved_objs.capacity() < next_objs.len() {
11149            saved_objs.reserve(next_objs.len());
11150        }
11151        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
11152            let obj_idx: usize = curr.get_object_index();
11153            let mut blended_tr: Transform3D = curr.get_transform();
11154            if curr.get_visible()
11155                && let Some(prev) = prev_objs.get(slot_idx).copied()
11156            {
11157                let continuous: bool = prev.get_visible()
11158                    && prev.get_object_index() == obj_idx
11159                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
11160                if continuous {
11161                    blended_tr = prev
11162                        .get_transform()
11163                        .lerp_shortest_angle(curr.get_transform(), entry_index);
11164                }
11165            }
11166            let Some((orig_tr, orig_wb, mesh_id, is_dyn)) =
11167                world
11168                    .get_objects()
11169                    .get(obj_idx)
11170                    .map(|output_val: &SceneObject3D| {
11171                        (
11172                            output_val.get_transform(),
11173                            output_val.get_world_bounds(),
11174                            output_val.get_mesh_id(),
11175                            output_val.get_is_dynamic(),
11176                        )
11177                    })
11178            else {
11179                continue;
11180            };
11181            if orig_tr == blended_tr {
11182                continue;
11183            }
11184            saved_objs.push((obj_idx, orig_tr, orig_wb));
11185            let local_bounds: AxisAlignedBox3D = world
11186                .get_mesh_library()
11187                .get(mesh_id)
11188                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
11189                .map(Mesh3D::get_bounds)
11190                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
11191            let world_b: AxisAlignedBox3D = blended_tr.transform_bounds(local_bounds);
11192            if let Some(obj_mut) = world.get_mut_objects().get_mut(obj_idx) {
11193                obj_mut.set_transform(blended_tr);
11194                obj_mut.set_world_bounds(world_b);
11195            }
11196            if is_dyn {
11197                world.override_dynamic_instance_pose(obj_idx, blended_tr, world_b);
11198            }
11199        }
11200        let result: Option<PooledFrameLease> =
11201            self.render_world_into_pool(world, viewport_w, viewport_h, quality, pool, fence_id);
11202        world.set_camera(saved_cam);
11203        for &(idx, transform_val, wb) in saved_objs.iter() {
11204            let is_dyn: bool = world
11205                .get_objects()
11206                .get(idx)
11207                .is_some_and(SceneObject3D::get_is_dynamic);
11208            if let Some(obj_mut) = world.get_mut_objects().get_mut(idx) {
11209                obj_mut.set_transform(transform_val);
11210                obj_mut.set_world_bounds(wb);
11211            }
11212            if is_dyn {
11213                world.override_dynamic_instance_pose(idx, transform_val, wb);
11214            }
11215        }
11216        saved_objs.clear();
11217        let Self {
11218            saved_objs_scratch, ..
11219        } = self;
11220        *saved_objs_scratch = saved_objs;
11221        result
11222    }
11223
11224    /// Renders `world` at runtime-configured `quality` into an `ImageBuffer` without zero-filling output memory.
11225    ///
11226    /// # Arguments
11227    ///
11228    /// - `&Self` - Mutable 3D renderer.
11229    /// - `&mut World3D` - Open-world 3D scene graph.
11230    /// - `u32` - Target viewport width in logical pixels.
11231    /// - `u32` - Target viewport height in logical pixels.
11232    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11233    ///
11234    /// # Returns
11235    ///
11236    /// - `ImageBuffer` - Ready RGBA8 rendered 3D frame for immediate presentation.
11237    pub fn render_world(
11238        &mut self,
11239        world: &mut World3D,
11240        viewport_w: u32,
11241        viewport_h: u32,
11242        quality: &RenderQualityConfig,
11243    ) -> ImageBuffer {
11244        let mut out_pixels: Vec<u8> = Vec::new();
11245        let (width_val, height_val): (u32, u32) =
11246            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11247        ImageBuffer::new(width_val, height_val, out_pixels)
11248    }
11249
11250    /// Renders `world` into the persistent internal `rgba_scratch` buffer, eliminating per-frame output heap allocations.
11251    ///
11252    /// # Arguments
11253    ///
11254    /// - `&Self` - Mutable 3D renderer.
11255    /// - `&mut World3D` - Open-world 3D scene graph.
11256    /// - `u32` - Target viewport width in logical pixels.
11257    /// - `u32` - Target viewport height in logical pixels.
11258    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11259    ///
11260    /// # Returns
11261    ///
11262    /// - `&[u8]` - Borrowed RGBA8 pixel slice of the rendered 3D frame.
11263    #[must_use]
11264    pub fn render_world_rgba(
11265        &mut self,
11266        world: &mut World3D,
11267        viewport_w: u32,
11268        viewport_h: u32,
11269        quality: &RenderQualityConfig,
11270    ) -> &[u8] {
11271        let mut scratch: Vec<u8> = {
11272            let Self { rgba_scratch, .. } = self;
11273            take(rgba_scratch)
11274        };
11275        let _: (u32, u32) =
11276            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut scratch);
11277        let Self { rgba_scratch, .. } = self;
11278        *rgba_scratch = scratch;
11279        rgba_scratch.as_slice()
11280    }
11281
11282    /// Renders `world` at sub-native resolution and reconstructs a sharp native `(viewport_w, viewport_h)` frame via UE5 Temporal Super Resolution (TSR).
11283    ///
11284    /// # Arguments
11285    ///
11286    /// - `&mut World3D` - Open-world 3D scene graph.
11287    /// - `u32` - Target native output width in pixels.
11288    /// - `u32` - Target native output height in pixels.
11289    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal `resolution_scale`.
11290    /// - `&mut Vec<u8>` - Reusable full-resolution destination RGBA8 buffer.
11291    ///
11292    /// # Returns
11293    ///
11294    /// - `(u32, u32)` - Actual reconstructed output dimensions `(dst_w, dst_h)`.
11295    pub fn render_world_tsr_into_vec(
11296        &mut self,
11297        world: &mut World3D,
11298        viewport_w: u32,
11299        viewport_h: u32,
11300        quality: &RenderQualityConfig,
11301        out_pixels: &mut Vec<u8>,
11302    ) -> (u32, u32) {
11303        let dst_w: u32 = viewport_w.max(1);
11304        let dst_h: u32 = viewport_h.max(1);
11305        let mut internal_quality: RenderQualityConfig = *quality;
11306        internal_quality.set_anti_aliasing(AntiAliasingMode::Off);
11307        let mut internal_buf: Vec<u8> = {
11308            let Self {
11309                tsr_internal_scratch,
11310                ..
11311            } = self;
11312            take(tsr_internal_scratch)
11313        };
11314        let (src_w, src_h): (u32, u32) =
11315            self.render_world_into_vec(world, dst_w, dst_h, &internal_quality, &mut internal_buf);
11316        let cam: Camera3D = world.get_camera();
11317        let aspect: f32 = (src_w as f32) / (src_h as f32).max(1.0);
11318        let view_proj: Mat4 = cam.view_projection(aspect);
11319        let cam_fwd: Vec3 = cam.forward();
11320        let cam_right: Vec3 = cam.right();
11321        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
11322        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
11323        let half_h: f32 = (eff_fov_rad * 0.5).tan();
11324        let half_w: f32 = half_h * aspect;
11325        let tsr_params: TsrFrameParams = TsrFrameParams {
11326            src_width: src_w as usize,
11327            src_height: src_h as usize,
11328            dst_width: dst_w as usize,
11329            dst_height: dst_h as usize,
11330            camera_position: cam.get_position(),
11331            camera_forward: cam_fwd,
11332            camera_right_scaled: cam_right.scale(half_w),
11333            camera_up_scaled: cam_up.scale(half_h),
11334            view_projection: view_proj,
11335            jitter_offset: (0.0, 0.0),
11336            sharpness: TSR_DEFAULT_SHARPNESS,
11337        };
11338        {
11339            let Self {
11340                depth_buffer,
11341                tsr_upscaler,
11342                ..
11343            } = self;
11344            tsr_upscaler.upscale_rgba(
11345                internal_buf.as_slice(),
11346                depth_buffer.as_slice(),
11347                &tsr_params,
11348                out_pixels,
11349            );
11350        }
11351        let Self {
11352            tsr_internal_scratch,
11353            ..
11354        } = self;
11355        *tsr_internal_scratch = internal_buf;
11356        (dst_w, dst_h)
11357    }
11358
11359    /// Renders `world` using UE5 Temporal Super Resolution (TSR) upscaling and returns a full-resolution `ImageBuffer`.
11360    ///
11361    /// # Arguments
11362    ///
11363    /// - `&mut World3D` - Open-world 3D scene graph.
11364    /// - `u32` - Target native output width in pixels.
11365    /// - `u32` - Target native output height in pixels.
11366    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal scale and RT/Lumen toggles.
11367    ///
11368    /// # Returns
11369    ///
11370    /// - `ImageBuffer` - Reconstructed native-resolution RGBA8 frame.
11371    pub fn render_world_tsr(
11372        &mut self,
11373        world: &mut World3D,
11374        viewport_w: u32,
11375        viewport_h: u32,
11376        quality: &RenderQualityConfig,
11377    ) -> ImageBuffer {
11378        let mut out_pixels: Vec<u8> = Vec::new();
11379        let (dst_w, dst_h): (u32, u32) =
11380            self.render_world_tsr_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11381        ImageBuffer::new(dst_w, dst_h, out_pixels)
11382    }
11383
11384    /// Renders `world` at sub-native resolution and writes the TSR-reconstructed native frame directly into a bounded zero-allocation `RenderBufferPool` slot.
11385    ///
11386    /// # Arguments
11387    ///
11388    /// - `&mut World3D` - Open-world 3D scene graph.
11389    /// - `(u32, u32)` - Target native output `(viewport_w, viewport_h)` in pixels.
11390    /// - `&RenderQualityConfig` - Runtime quality configuration controlling internal TSR scale.
11391    /// - `(&RenderBufferPool, u64)` - Bounded output frame pool and fence value.
11392    ///
11393    /// # Returns
11394    ///
11395    /// - `Option<PooledFrameLease>` - Populated native-resolution TSR frame lease, or `None` under pool backpressure.
11396    #[must_use]
11397    pub fn render_world_tsr_into_pool(
11398        &mut self,
11399        world: &mut World3D,
11400        viewport: (u32, u32),
11401        quality: &RenderQualityConfig,
11402        target_pool: (&RenderBufferPool, u64),
11403    ) -> Option<PooledFrameLease> {
11404        let (viewport_w, viewport_h): (u32, u32) = viewport;
11405        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11406        let dst_w: u32 = viewport_w.max(1);
11407        let dst_h: u32 = viewport_h.max(1);
11408        let mut lease: PooledFrameLease = pool.acquire(dst_w, dst_h, fence_id)?;
11409        let (rw, rh): (u32, u32) =
11410            self.render_world_tsr_into_vec(world, dst_w, dst_h, quality, lease.get_mut_pixels());
11411        lease.set_dimensions(rw, rh);
11412        Some(lease)
11413    }
11414
11415    /// Feeds measured `frame_ms` into the damped PI `AdaptiveFrameGovernor` and applies smooth DRS scale, LOD bias, and RT probe stride adjustments to `quality` without FPS oscillation.
11416    ///
11417    /// # Arguments
11418    ///
11419    /// - `f32` - Measured render duration of the most recent frame in milliseconds.
11420    /// - `&mut RenderQualityConfig` - Mutable runtime quality settings updated when `dynamic_resolution` is enabled.
11421    ///
11422    /// # Returns
11423    ///
11424    /// - `FramePacingTelemetry3D` - Updated smoothed frame-time and stability telemetry.
11425    pub fn apply_frame_pacing_feedback(
11426        &mut self,
11427        frame_ms: f32,
11428        quality: &mut RenderQualityConfig,
11429    ) -> FramePacingTelemetry3D {
11430        let target_hz: f32 = quality.get_target_fps().max(30.0);
11431        let governor: &mut AdaptiveFrameGovernor = self.get_mut_frame_governor();
11432        if (governor.get_target_hz() - target_hz).abs() > 0.5 {
11433            governor.set_target_hz(target_hz);
11434        }
11435        let telemetry: FramePacingTelemetry3D = governor.record_frame(frame_ms, quality);
11436        if quality.get_dynamic_resolution() {
11437            self.set_rt_stride_bias(telemetry.get_effective_rt_stride_bias());
11438        } else {
11439            self.set_rt_stride_bias(0);
11440        }
11441        telemetry
11442    }
11443
11444    /// Builds and compiles the UE5 Render Dependency Graph (RDG) for `(viewport_w, viewport_h)` and `quality`, reporting dead-pass culling and transient memory aliasing savings.
11445    ///
11446    /// # Arguments
11447    ///
11448    /// - `u32` - Target viewport width in pixels.
11449    /// - `u32` - Target viewport height in pixels.
11450    /// - `&RenderQualityConfig` - Active quality configuration controlling RT, Lumen, VSM, and TSR passes.
11451    ///
11452    /// # Returns
11453    ///
11454    /// - `RenderGraphSchedule3D` - Compiled pass schedule with transient memory aliasing telemetry.
11455    #[must_use]
11456    pub fn compile_frame_graph(
11457        &mut self,
11458        viewport_w: u32,
11459        viewport_h: u32,
11460        quality: &RenderQualityConfig,
11461    ) -> RenderGraphSchedule3D {
11462        let built: RenderGraph3D =
11463            RenderGraph3D::build_ue5_frame_graph(viewport_w, viewport_h, quality);
11464        let schedule: RenderGraphSchedule3D = built.compile();
11465        self.set_render_graph(built);
11466        schedule
11467    }
11468
11469    /// Clips a triangle against the camera near plane `w >= near_w` (Sutherland-Hodgman) while tracking original barycentric weights for exact attribute interpolation.
11470    ///
11471    /// # Arguments
11472    ///
11473    /// - `([f32; 4], Vec3)` - First clip-space and world-space vertex.
11474    /// - `([f32; 4], Vec3)` - Second clip-space and world-space vertex.
11475    /// - `([f32; 4], Vec3)` - Third clip-space and world-space vertex.
11476    /// - `f32` - Positive near-plane clip `w` threshold.
11477    ///
11478    /// # Returns
11479    ///
11480    /// - `([ClippedBaryVert; 6], usize)` - Packed output triangles with barycentric weights and valid triangle count (`0..=2`).
11481    #[must_use]
11482    fn clip_triangle_near_bary(
11483        vert0: ([f32; 4], Vec3),
11484        vert1: ([f32; 4], Vec3),
11485        vert2: ([f32; 4], Vec3),
11486        near_w: f32,
11487    ) -> ([ClippedBaryVert; 6], usize) {
11488        let zero_vert: ClippedBaryVert = ClippedBaryVert {
11489            clip_pos: [0.0; 4],
11490            world_pos: Vec3::zero(),
11491            bary: [0.0; 3],
11492        };
11493        let mut out_tris: [ClippedBaryVert; 6] = [zero_vert; 6];
11494        let input: [ClippedBaryVert; 3] = [
11495            ClippedBaryVert {
11496                clip_pos: vert0.0,
11497                world_pos: vert0.1,
11498                bary: [1.0, 0.0, 0.0],
11499            },
11500            ClippedBaryVert {
11501                clip_pos: vert1.0,
11502                world_pos: vert1.1,
11503                bary: [0.0, 1.0, 0.0],
11504            },
11505            ClippedBaryVert {
11506                clip_pos: vert2.0,
11507                world_pos: vert2.1,
11508                bary: [0.0, 0.0, 1.0],
11509            },
11510        ];
11511        let mut poly: [ClippedBaryVert; 4] = [zero_vert; 4];
11512        let mut count: usize = 0;
11513        for edge_idx in 0..3usize {
11514            let cur: ClippedBaryVert = input[edge_idx];
11515            let nxt: ClippedBaryVert = input[(edge_idx + 1) % 3];
11516            let cur_in: bool = cur.clip_pos[3] >= near_w;
11517            let nxt_in: bool = nxt.clip_pos[3] >= near_w;
11518            if cur_in && count < 4 {
11519                poly[count] = cur;
11520                count += 1;
11521            }
11522            if cur_in != nxt_in && count < 4 {
11523                let denom: f32 = nxt.clip_pos[3] - cur.clip_pos[3];
11524                let blend_factor: f32 = if denom.abs() > 1.0e-6 {
11525                    ((near_w - cur.clip_pos[3]) / denom).clamp(0.0, 1.0)
11526                } else {
11527                    0.5
11528                };
11529                let interp_clip: [f32; 4] = [
11530                    cur.clip_pos[0] + (nxt.clip_pos[0] - cur.clip_pos[0]) * blend_factor,
11531                    cur.clip_pos[1] + (nxt.clip_pos[1] - cur.clip_pos[1]) * blend_factor,
11532                    cur.clip_pos[2] + (nxt.clip_pos[2] - cur.clip_pos[2]) * blend_factor,
11533                    near_w,
11534                ];
11535                let interp_world: Vec3 = cur.world_pos.lerp(nxt.world_pos, blend_factor);
11536                let interp_bary: [f32; 3] = [
11537                    cur.bary[0] + (nxt.bary[0] - cur.bary[0]) * blend_factor,
11538                    cur.bary[1] + (nxt.bary[1] - cur.bary[1]) * blend_factor,
11539                    cur.bary[2] + (nxt.bary[2] - cur.bary[2]) * blend_factor,
11540                ];
11541                poly[count] = ClippedBaryVert {
11542                    clip_pos: interp_clip,
11543                    world_pos: interp_world,
11544                    bary: interp_bary,
11545                };
11546                count += 1;
11547            }
11548        }
11549        if count < 3 {
11550            return (out_tris, 0);
11551        }
11552        out_tris[0] = poly[0];
11553        out_tris[1] = poly[1];
11554        out_tris[2] = poly[2];
11555        if count == 4 {
11556            out_tris[3] = poly[0];
11557            out_tris[4] = poly[2];
11558            out_tris[5] = poly[3];
11559            (out_tris, 2)
11560        } else {
11561            (out_tris, 1)
11562        }
11563    }
11564
11565    /// Samples an optional `TextureSlot3D` with `KHR_texture_transform` and isotropic trilinear mip selection.
11566    ///
11567    /// # Arguments
11568    ///
11569    /// - `Option<TextureSlot3D>` - Optional texture binding slot.
11570    /// - `([f32; 2], [f32; 2])` - Interpolated `(uv0, uv1)` coordinates.
11571    /// - `(f32, f32, f32)` - `(uv0_area, uv1_area, screen_area_px)` for mip LOD estimation.
11572    /// - `&[Texture2D3D]` - Scene texture pool.
11573    ///
11574    /// # Returns
11575    ///
11576    /// - `Option<[f32; 4]>` - Linear RGBA sample when the slot references a valid texture.
11577    #[must_use]
11578    fn sample_principled_slot(
11579        slot_opt: Option<TextureSlot3D>,
11580        uv_pair: ([f32; 2], [f32; 2]),
11581        area_terms: (f32, f32, f32),
11582        textures: &[Texture2D3D],
11583    ) -> Option<[f32; 4]> {
11584        let slot: TextureSlot3D = slot_opt?;
11585        let texture: &Texture2D3D = textures.get(slot.get_texture_index() as usize)?;
11586        let (uv0_coord, uv1_coord): ([f32; 2], [f32; 2]) = uv_pair;
11587        let (uv0_area, uv1_area, screen_area): (f32, f32, f32) = area_terms;
11588        let (raw_uv, uv_area): ([f32; 2], f32) = if slot.get_tex_coord() == 1 {
11589            (uv1_coord, uv1_area)
11590        } else {
11591            (uv0_coord, uv0_area)
11592        };
11593        let transformed_uv: Vec2 = slot
11594            .get_transform()
11595            .apply_uv(Vec2::new(raw_uv[0], raw_uv[1]));
11596        let tex_scale: Vec2 = slot.get_transform().get_scale();
11597        let scale_area: f32 = (tex_scale.get_x() * tex_scale.get_y()).abs().max(1.0e-4);
11598        let tex_pixels: f32 =
11599            (texture.get_width().max(1) as f32) * (texture.get_height().max(1) as f32);
11600        let texels_per_px: f32 = (uv_area * scale_area * tex_pixels) / screen_area.max(1.0);
11601        let mip_lod: f32 = if texels_per_px > 1.0 {
11602            0.5 * texels_per_px.log2()
11603        } else {
11604            0.0
11605        };
11606        Some(texture.sample_trilinear(transformed_uv.get_x(), transformed_uv.get_y(), mip_lod))
11607    }
11608
11609    /// Evaluates the Estevez-Kulla Charlie sheen microfacet NDF and Ashikhmin visibility term.
11610    ///
11611    /// # Arguments
11612    ///
11613    /// - `f32` - Perceptual sheen roughness in `[0.07, 1.0]`.
11614    /// - `f32` - Clamped `N·H` cosine.
11615    /// - `f32` - Clamped `N·V` cosine.
11616    /// - `f32` - Clamped `N·L` cosine.
11617    ///
11618    /// # Returns
11619    ///
11620    /// - `f32` - Scalar Charlie sheen BRDF factor.
11621    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11622    #[must_use]
11623    fn eval_charlie_sheen(sheen_rough: f32, n_dot_h: f32, n_dot_v: f32, n_dot_l: f32) -> f32 {
11624        let clamped_r: f32 = sheen_rough.clamp(0.07, 1.0);
11625        let alpha_g: f32 = clamped_r * clamped_r;
11626        let inv_r: f32 = 1.0 / alpha_g.max(1.0e-4);
11627        let sin2_h: f32 = (1.0 - n_dot_h * n_dot_h).max(1.0e-4);
11628        let ndf_charlie: f32 = (2.0 + inv_r) * sin2_h.powf(inv_r * 0.5) / (2.0 * PI);
11629        let vis_ashikhmin: f32 = 1.0 / (4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v)).max(1.0e-3);
11630        (ndf_charlie * vis_ashikhmin).min(8.0)
11631    }
11632
11633    /// Computes Snell refraction direction for unit incident vector `incident` and outward unit `normal` at IOR ratio `eta`.
11634    ///
11635    /// # Arguments
11636    ///
11637    /// - `Vec3` - Unit incident vector pointing toward surface (`-view_dir`).
11638    /// - `Vec3` - Unit outward surface normal.
11639    /// - `f32` - Refractive index ratio `eta_i / eta_t`.
11640    ///
11641    /// # Returns
11642    ///
11643    /// - `Vec3` - Unit refracted direction (falls back to reflection on total internal reflection).
11644    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11645    #[must_use]
11646    fn refract_unit_ray(incident: Vec3, normal: Vec3, eta: f32) -> Vec3 {
11647        let cos_i: f32 = (-incident.dot(normal)).clamp(-1.0, 1.0);
11648        let sin2_t: f32 = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
11649        if sin2_t >= 1.0 {
11650            return incident.reflect(normal).normalize();
11651        }
11652        let cos_t: f32 = (1.0 - sin2_t).sqrt();
11653        incident
11654            .scale(eta)
11655            .add(normal.scale(eta * cos_i - cos_t))
11656            .normalize()
11657    }
11658
11659    /// Encodes a display-referred linear RGB `[0..1]` color into exact sRGB `[u8; 4]` RGBA bytes.
11660    ///
11661    /// # Arguments
11662    ///
11663    /// - `Vec3` - Linear RGB color in `[0.0, 1.0]`.
11664    ///
11665    /// # Returns
11666    ///
11667    /// - `[u8; 4]` - Opaque sRGB RGBA8 pixel.
11668    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11669    #[must_use]
11670    fn encode_srgb_rgba8(linear_rgb: Vec3) -> [u8; 4] {
11671        let to_srgb: fn(f32) -> u8 = |chan: f32| -> u8 {
11672            let clamped: f32 = chan.clamp(0.0, 1.0);
11673            let encoded: f32 = if clamped <= 0.003_130_8 {
11674                clamped * 12.92
11675            } else {
11676                1.055 * clamped.powf(1.0 / 2.4) - 0.055
11677            };
11678            (encoded * 255.0 + 0.5).clamp(0.0, 255.0) as u8
11679        };
11680        [
11681            to_srgb(linear_rgb.get_x()),
11682            to_srgb(linear_rgb.get_y()),
11683            to_srgb(linear_rgb.get_z()),
11684            255,
11685        ]
11686    }
11687
11688    /// Shades a single deferred pixel with perspective-correct barycentric attribute interpolation and full Blender Principled BSDF parity (IOR/specular, clearcoat, Charlie sheen, transmission+volume, normal maps, 4-cascade CSM, clustered/area lights, IBL, AgX/ACES).
11689    ///
11690    /// # Arguments
11691    ///
11692    /// - `&DeferredFrameContext` - Per-frame camera, sun, exposure, and ray-tracing settings.
11693    /// - `&ShadeBandInputs<'_>` - Read-only scene textures, Principled materials, lights, CSM, IBL, and BVH references.
11694    /// - `&GShadeTri` - Precomputed legacy fallback material record.
11695    /// - `&GSmoothTri` - Perspective-correct per-vertex normal, tangent, UV, and color record.
11696    /// - `(usize, usize)` - Pixel coordinates `(pixel_x, pixel_y)`.
11697    /// - `(Vec3, Vec3, f32)` - `(world_pos, raw_ray, linear_depth)` pixel geometry sample.
11698    ///
11699    /// # Returns
11700    ///
11701    /// - `[u8; 4]` - Tone-mapped sRGB RGBA8 output pixel.
11702    #[must_use]
11703    fn shade_pixel_principled_smooth(
11704        frame_context: &DeferredFrameContext,
11705        inputs: &ShadeBandInputs<'_>,
11706        tri: &GShadeTri,
11707        smooth_tri: &GSmoothTri,
11708        pixel_coords: (usize, usize),
11709        geom_sample: (Vec3, Vec3, f32),
11710    ) -> [u8; 4] {
11711        let (pixel_x, pixel_y): (usize, usize) = pixel_coords;
11712        let (world_pos, raw_ray, linear_depth): (Vec3, Vec3, f32) = geom_sample;
11713        let sample_x: f32 = (pixel_x as f32) + 0.5;
11714        let sample_y: f32 = (pixel_y as f32) + 0.5;
11715        let sx: [f32; 3] = smooth_tri.screen_x;
11716        let sy: [f32; 3] = smooth_tri.screen_y;
11717        let inv_area: f32 = smooth_tri.inv_area;
11718        let screen_w0: f32 = ((sx[1] - sample_x) * (sy[2] - sample_y)
11719            - (sy[1] - sample_y) * (sx[2] - sample_x))
11720            * inv_area;
11721        let screen_w1: f32 = ((sx[2] - sample_x) * (sy[0] - sample_y)
11722            - (sy[2] - sample_y) * (sx[0] - sample_x))
11723            * inv_area;
11724        let screen_w2: f32 = 1.0 - screen_w0 - screen_w1;
11725        let persp_0: f32 = screen_w0.max(0.0) * smooth_tri.inv_w[0];
11726        let persp_1: f32 = screen_w1.max(0.0) * smooth_tri.inv_w[1];
11727        let persp_2: f32 = screen_w2.max(0.0) * smooth_tri.inv_w[2];
11728        let inv_persp_sum: f32 = 1.0 / (persp_0 + persp_1 + persp_2).max(1.0e-9);
11729        let bary_0: f32 = persp_0 * inv_persp_sum;
11730        let bary_1: f32 = persp_1 * inv_persp_sum;
11731        let bary_2: f32 = persp_2 * inv_persp_sum;
11732        let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
11733        let raw_normal: Vec3 = smooth_tri.normals[0]
11734            .scale(bary_0)
11735            .add(smooth_tri.normals[1].scale(bary_1))
11736            .add(smooth_tri.normals[2].scale(bary_2));
11737        let mut geom_normal: Vec3 = if raw_normal.length_sq() > 1.0e-8 {
11738            raw_normal.normalize()
11739        } else {
11740            tri.shade_n
11741        };
11742        if smooth_tri.double_sided && geom_normal.dot(view_dir) < 0.0 {
11743            geom_normal = geom_normal.scale(-1.0);
11744        }
11745        let raw_tangent: Vec3 = Vec3::new(
11746            smooth_tri.tangents[0][0] * bary_0
11747                + smooth_tri.tangents[1][0] * bary_1
11748                + smooth_tri.tangents[2][0] * bary_2,
11749            smooth_tri.tangents[0][1] * bary_0
11750                + smooth_tri.tangents[1][1] * bary_1
11751                + smooth_tri.tangents[2][1] * bary_2,
11752            smooth_tri.tangents[0][2] * bary_0
11753                + smooth_tri.tangents[1][2] * bary_1
11754                + smooth_tri.tangents[2][2] * bary_2,
11755        );
11756        let ortho_tangent: Vec3 = raw_tangent.sub(geom_normal.scale(raw_tangent.dot(geom_normal)));
11757        let tangent_dir: Vec3 = if ortho_tangent.length_sq() > 1.0e-6 {
11758            ortho_tangent.normalize()
11759        } else {
11760            let helper_axis: Vec3 = if geom_normal.get_y().abs() < 0.9 {
11761                Vec3::new(0.0, 1.0, 0.0)
11762            } else {
11763                Vec3::new(1.0, 0.0, 0.0)
11764            };
11765            helper_axis.cross(geom_normal).normalize()
11766        };
11767        let tan_sign: f32 = if smooth_tri.tangents[0][3] < 0.0 {
11768            -1.0
11769        } else {
11770            1.0
11771        };
11772        let bitangent_dir: Vec3 = geom_normal.cross(tangent_dir).scale(tan_sign);
11773        let uv0_interp: [f32; 2] = [
11774            smooth_tri.uv0[0][0] * bary_0
11775                + smooth_tri.uv0[1][0] * bary_1
11776                + smooth_tri.uv0[2][0] * bary_2,
11777            smooth_tri.uv0[0][1] * bary_0
11778                + smooth_tri.uv0[1][1] * bary_1
11779                + smooth_tri.uv0[2][1] * bary_2,
11780        ];
11781        let uv1_interp: [f32; 2] = [
11782            smooth_tri.uv1[0][0] * bary_0
11783                + smooth_tri.uv1[1][0] * bary_1
11784                + smooth_tri.uv1[2][0] * bary_2,
11785            smooth_tri.uv1[0][1] * bary_0
11786                + smooth_tri.uv1[1][1] * bary_1
11787                + smooth_tri.uv1[2][1] * bary_2,
11788        ];
11789        let vcol_r: f32 = smooth_tri.color0[0][0] * bary_0
11790            + smooth_tri.color0[1][0] * bary_1
11791            + smooth_tri.color0[2][0] * bary_2;
11792        let vcol_g: f32 = smooth_tri.color0[0][1] * bary_0
11793            + smooth_tri.color0[1][1] * bary_1
11794            + smooth_tri.color0[2][1] * bary_2;
11795        let vcol_b: f32 = smooth_tri.color0[0][2] * bary_0
11796            + smooth_tri.color0[1][2] * bary_1
11797            + smooth_tri.color0[2][2] * bary_2;
11798        let vcol_a: f32 = smooth_tri.color0[0][3] * bary_0
11799            + smooth_tri.color0[1][3] * bary_1
11800            + smooth_tri.color0[2][3] * bary_2;
11801        let screen_area_px: f32 = 0.5 / inv_area.abs().max(1.0e-8);
11802        let uv0_area: f32 = ((smooth_tri.uv0[1][0] - smooth_tri.uv0[0][0])
11803            * (smooth_tri.uv0[2][1] - smooth_tri.uv0[0][1])
11804            - (smooth_tri.uv0[1][1] - smooth_tri.uv0[0][1])
11805                * (smooth_tri.uv0[2][0] - smooth_tri.uv0[0][0]))
11806            .abs()
11807            * 0.5;
11808        let uv1_area: f32 = ((smooth_tri.uv1[1][0] - smooth_tri.uv1[0][0])
11809            * (smooth_tri.uv1[2][1] - smooth_tri.uv1[0][1])
11810            - (smooth_tri.uv1[1][1] - smooth_tri.uv1[0][1])
11811                * (smooth_tri.uv1[2][0] - smooth_tri.uv1[0][0]))
11812            .abs()
11813            * 0.5;
11814        let area_terms: (f32, f32, f32) = (uv0_area, uv1_area, screen_area_px);
11815        let uv_pair: ([f32; 2], [f32; 2]) = (uv0_interp, uv1_interp);
11816        let mat_opt: Option<&PrincipledMaterial3D> =
11817            if smooth_tri.principled_material_id != u32::MAX {
11818                inputs
11819                    .principled_materials
11820                    .get(smooth_tri.principled_material_id as usize)
11821            } else {
11822                None
11823            };
11824        let mut albedo: Vec3 = Vec3::new(
11825            tri.mat_base.get_x() * vcol_r,
11826            tri.mat_base.get_y() * vcol_g,
11827            tri.mat_base.get_z() * vcol_b,
11828        );
11829        let mut alpha_val: f32 = vcol_a;
11830        let mut metallic: f32 = tri.metallic.clamp(0.0, 1.0);
11831        let mut roughness: f32 = tri.alpha2.sqrt().sqrt().clamp(0.04, 1.0);
11832        let mut shade_normal: Vec3 = geom_normal;
11833        let mut coat_normal: Vec3 = geom_normal;
11834        let mut ao_factor: f32 = 1.0;
11835        let mut emissive_rgb: Vec3 = tri.mat_emissive;
11836        let mut ior_val: f32 = 1.5;
11837        let mut spec_factor: f32 = 1.0;
11838        let mut spec_color: Vec3 = Vec3::splat(1.0);
11839        let mut coat_weight: f32 = 0.0;
11840        let mut coat_rough: f32 = 0.04;
11841        let mut sheen_color: Vec3 = Vec3::zero();
11842        let mut sheen_rough: f32 = 0.5;
11843        let mut transmission: f32 = 0.0;
11844        let mut thickness: f32 = 0.0;
11845        let mut atten_dist: f32 = f32::INFINITY;
11846        let mut atten_color: Vec3 = Vec3::splat(1.0);
11847        let mut is_unlit: bool = false;
11848        let mut alpha_masked: bool = false;
11849        if let Some(pmat) = mat_opt {
11850            let base_fac: [f32; 4] = pmat.get_base_color_factor();
11851            let base_tex: [f32; 4] = Self::sample_principled_slot(
11852                pmat.try_get_base_color_texture(),
11853                uv_pair,
11854                area_terms,
11855                inputs.textures,
11856            )
11857            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11858            albedo = Vec3::new(
11859                base_fac[0] * base_tex[0] * vcol_r,
11860                base_fac[1] * base_tex[1] * vcol_g,
11861                base_fac[2] * base_tex[2] * vcol_b,
11862            );
11863            alpha_val = base_fac[3] * base_tex[3] * vcol_a;
11864            if pmat.get_alpha_mode() == AlphaMode3D::Mask && alpha_val < pmat.get_alpha_cutoff() {
11865                alpha_masked = true;
11866            }
11867            is_unlit = pmat.get_unlit();
11868            let mr_tex: [f32; 4] = Self::sample_principled_slot(
11869                pmat.try_get_metallic_roughness_texture(),
11870                uv_pair,
11871                area_terms,
11872                inputs.textures,
11873            )
11874            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11875            metallic = (pmat.get_metallic_factor() * mr_tex[2]).clamp(0.0, 1.0);
11876            roughness = (pmat.get_roughness_factor() * mr_tex[1]).clamp(0.04, 1.0);
11877            if let Some(norm_tex) = Self::sample_principled_slot(
11878                pmat.try_get_normal_texture(),
11879                uv_pair,
11880                area_terms,
11881                inputs.textures,
11882            ) {
11883                let nscale: f32 = pmat.get_normal_scale();
11884                let ts_x: f32 = (norm_tex[0] * 2.0 - 1.0) * nscale;
11885                let ts_y: f32 = (norm_tex[1] * 2.0 - 1.0) * nscale;
11886                let ts_z: f32 = (norm_tex[2] * 2.0 - 1.0).max(0.05);
11887                let perturbed: Vec3 = tangent_dir
11888                    .scale(ts_x)
11889                    .add(bitangent_dir.scale(ts_y))
11890                    .add(geom_normal.scale(ts_z));
11891                if perturbed.length_sq() > 1.0e-8 {
11892                    shade_normal = perturbed.normalize();
11893                }
11894            }
11895            if let Some(occ_tex) = Self::sample_principled_slot(
11896                pmat.try_get_occlusion_texture(),
11897                uv_pair,
11898                area_terms,
11899                inputs.textures,
11900            ) {
11901                ao_factor =
11902                    (1.0 + pmat.get_occlusion_strength() * (occ_tex[0] - 1.0)).clamp(0.0, 1.0);
11903            }
11904            let em_fac: [f32; 3] = pmat.get_emissive_factor();
11905            let em_tex: [f32; 4] = Self::sample_principled_slot(
11906                pmat.try_get_emissive_texture(),
11907                uv_pair,
11908                area_terms,
11909                inputs.textures,
11910            )
11911            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11912            let em_str: f32 = pmat.get_emissive_strength().max(0.0);
11913            emissive_rgb = Vec3::new(
11914                em_fac[0] * em_tex[0] * em_str,
11915                em_fac[1] * em_tex[1] * em_str,
11916                em_fac[2] * em_tex[2] * em_str,
11917            );
11918            ior_val = pmat.get_ior().max(1.0);
11919            let sp_tex: [f32; 4] = Self::sample_principled_slot(
11920                pmat.try_get_specular_texture(),
11921                uv_pair,
11922                area_terms,
11923                inputs.textures,
11924            )
11925            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11926            spec_factor = (pmat.get_specular_factor() * sp_tex[3]).clamp(0.0, 1.0);
11927            let sp_col_fac: [f32; 3] = pmat.get_specular_color_factor();
11928            let sp_col_tex: [f32; 4] = Self::sample_principled_slot(
11929                pmat.try_get_specular_color_texture(),
11930                uv_pair,
11931                area_terms,
11932                inputs.textures,
11933            )
11934            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11935            spec_color = Vec3::new(
11936                sp_col_fac[0] * sp_col_tex[0],
11937                sp_col_fac[1] * sp_col_tex[1],
11938                sp_col_fac[2] * sp_col_tex[2],
11939            );
11940            let cc_tex: [f32; 4] = Self::sample_principled_slot(
11941                pmat.try_get_clearcoat_texture(),
11942                uv_pair,
11943                area_terms,
11944                inputs.textures,
11945            )
11946            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11947            coat_weight = (pmat.get_clearcoat_factor() * cc_tex[0]).clamp(0.0, 1.0);
11948            let cc_r_tex: [f32; 4] = Self::sample_principled_slot(
11949                pmat.try_get_clearcoat_roughness_texture(),
11950                uv_pair,
11951                area_terms,
11952                inputs.textures,
11953            )
11954            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11955            coat_rough = (pmat.get_clearcoat_roughness_factor() * cc_r_tex[1]).clamp(0.04, 1.0);
11956            if let Some(cc_norm_tex) = Self::sample_principled_slot(
11957                pmat.try_get_clearcoat_normal_texture(),
11958                uv_pair,
11959                area_terms,
11960                inputs.textures,
11961            ) {
11962                let cc_x: f32 = cc_norm_tex[0] * 2.0 - 1.0;
11963                let cc_y: f32 = cc_norm_tex[1] * 2.0 - 1.0;
11964                let cc_z: f32 = (cc_norm_tex[2] * 2.0 - 1.0).max(0.05);
11965                let cc_pert: Vec3 = tangent_dir
11966                    .scale(cc_x)
11967                    .add(bitangent_dir.scale(cc_y))
11968                    .add(geom_normal.scale(cc_z));
11969                if cc_pert.length_sq() > 1.0e-8 {
11970                    coat_normal = cc_pert.normalize();
11971                }
11972            }
11973            let sh_col_fac: [f32; 3] = pmat.get_sheen_color_factor();
11974            let sh_col_tex: [f32; 4] = Self::sample_principled_slot(
11975                pmat.try_get_sheen_color_texture(),
11976                uv_pair,
11977                area_terms,
11978                inputs.textures,
11979            )
11980            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11981            sheen_color = Vec3::new(
11982                sh_col_fac[0] * sh_col_tex[0],
11983                sh_col_fac[1] * sh_col_tex[1],
11984                sh_col_fac[2] * sh_col_tex[2],
11985            );
11986            let sh_r_tex: [f32; 4] = Self::sample_principled_slot(
11987                pmat.try_get_sheen_roughness_texture(),
11988                uv_pair,
11989                area_terms,
11990                inputs.textures,
11991            )
11992            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11993            sheen_rough = (pmat.get_sheen_roughness_factor() * sh_r_tex[3]).clamp(0.07, 1.0);
11994            let tr_tex: [f32; 4] = Self::sample_principled_slot(
11995                pmat.try_get_transmission_texture(),
11996                uv_pair,
11997                area_terms,
11998                inputs.textures,
11999            )
12000            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12001            transmission =
12002                (pmat.get_transmission_factor() * tr_tex[0]).clamp(0.0, 1.0) * (1.0 - metallic);
12003            thickness = pmat.get_thickness_factor().max(0.0);
12004            atten_dist = pmat.get_attenuation_distance();
12005            atten_color = Vec3::from_array(pmat.get_attenuation_color());
12006        }
12007        if alpha_masked {
12008            let sky_hdr: Vec3 =
12009                Self::sample_sky_lut(inputs.sky_lut, raw_ray.normalize(), &frame_context.sun)
12010                    .scale(frame_context.exposure_scale);
12011            let sky_ldr: Vec3 = if inputs.use_agx_tonemap {
12012                agx_tonemap(sky_hdr)
12013            } else {
12014                aces_filmic_tonemap(sky_hdr)
12015            };
12016            return Self::encode_srgb_rgba8(sky_ldr);
12017        }
12018        if is_unlit {
12019            let unlit_hdr: Vec3 = albedo.scale(frame_context.exposure_scale);
12020            let unlit_ldr: Vec3 = if inputs.use_agx_tonemap {
12021                agx_tonemap(unlit_hdr)
12022            } else {
12023                aces_filmic_tonemap(unlit_hdr)
12024            };
12025            return Self::encode_srgb_rgba8(unlit_ldr);
12026        }
12027        let dielectric_f0_s: f32 = dielectric_f0_from_ior(ior_val);
12028        let dielectric_f0: Vec3 = Vec3::new(
12029            (dielectric_f0_s * spec_color.get_x()).min(1.0) * spec_factor,
12030            (dielectric_f0_s * spec_color.get_y()).min(1.0) * spec_factor,
12031            (dielectric_f0_s * spec_color.get_z()).min(1.0) * spec_factor,
12032        );
12033        let f0: Vec3 = dielectric_f0.lerp(albedo, metallic);
12034        let diffuse_albedo: Vec3 = albedo.scale((1.0 - metallic) * (1.0 - transmission));
12035        let alpha_rough: f32 = roughness * roughness;
12036        let alpha2: f32 = (alpha_rough * alpha_rough).max(1.0e-4);
12037        let n_dot_v: f32 = shade_normal.dot(view_dir).max(0.001);
12038        let sun_dir: Vec3 = frame_context.sun.get_direction();
12039        let sun_color: Vec3 = frame_context.sun.get_color();
12040        let sun_vis: f32 = if let Some(vsm) = inputs.vsm {
12041            vsm.sample_visibility(world_pos, shade_normal, sun_dir)
12042        } else if frame_context.raytrace_mode != RayTracingMode::Off {
12043            let shadow_origin: Vec3 = world_pos.add(shade_normal.scale(0.05));
12044            let mut static_hint: u32 = u32::MAX;
12045            let mut dyn_hint: u32 = u32::MAX;
12046            if World3D::trace_any_shadow_with_instances(
12047                inputs.static_bvh,
12048                inputs.dyn_instances,
12049                inputs.local_bvhs,
12050                (shadow_origin, sun_dir, frame_context.inv_sun_dir),
12051                (0.04, 140.0),
12052                (&mut static_hint, &mut dyn_hint),
12053            ) {
12054                0.15
12055            } else {
12056                1.0
12057            }
12058        } else {
12059            1.0
12060        };
12061        let brdf_lut_sample: [f32; 2] = inputs
12062            .environment_ibl
12063            .map_or([0.82, 0.08], |ibl: &EnvironmentIbl3D| {
12064                ibl.sample_brdf_lut(n_dot_v, roughness)
12065            });
12066        let multi_scatter: Vec3 =
12067            kulla_conty_multiscatter_factor(f0, brdf_lut_sample[0] + brdf_lut_sample[1]);
12068        let n_dot_l: f32 = shade_normal.dot(sun_dir).max(0.0);
12069        let mut direct_rgb: Vec3 = Vec3::zero();
12070        if n_dot_l > 0.0 && sun_vis > 0.0 {
12071            let half_vec: Vec3 = sun_dir.add(view_dir).normalize();
12072            let n_dot_h: f32 = shade_normal.dot(half_vec).max(0.0);
12073            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
12074            let ggx_den: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
12075            let ggx_d: f32 = alpha2 / (PI * ggx_den * ggx_den).max(1.0e-5);
12076            let vis_v: f32 = n_dot_l * (n_dot_v * (n_dot_v - n_dot_v * alpha2) + alpha2).sqrt();
12077            let vis_l: f32 = n_dot_v * (n_dot_l * (n_dot_l - n_dot_l * alpha2) + alpha2).sqrt();
12078            let smith_vis: f32 = 0.5 / (vis_v + vis_l).max(1.0e-4);
12079            let om_vh: f32 = 1.0 - v_dot_h;
12080            let pow5_vh: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
12081            let fresnel_base: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5_vh));
12082            let base_spec: Vec3 = fresnel_base.mul(multi_scatter).scale(ggx_d * smith_vis);
12083            let base_diff: Vec3 = diffuse_albedo
12084                .mul(Vec3::splat(1.0).sub(fresnel_base))
12085                .scale(1.0 / PI);
12086            let mut layer_brdf: Vec3 = base_diff.add(base_spec);
12087            let max_sheen: f32 = sheen_color
12088                .get_x()
12089                .max(sheen_color.get_y())
12090                .max(sheen_color.get_z());
12091            if max_sheen > 1.0e-4 {
12092                let sheen_brdf: f32 =
12093                    Self::eval_charlie_sheen(sheen_rough, n_dot_h, n_dot_v, n_dot_l);
12094                let sheen_atten: f32 = (1.0 - max_sheen * 0.25).clamp(0.25, 1.0);
12095                layer_brdf = layer_brdf
12096                    .scale(sheen_atten)
12097                    .add(sheen_color.scale(sheen_brdf));
12098            }
12099            if coat_weight > 1.0e-4 {
12100                let cc_nl: f32 = coat_normal.dot(sun_dir).max(0.0);
12101                let cc_nh: f32 = coat_normal.dot(half_vec).max(0.0);
12102                let cc_a: f32 = coat_rough * coat_rough;
12103                let cc_a2: f32 = (cc_a * cc_a).max(1.0e-4);
12104                let cc_den: f32 = cc_nh * cc_nh * (cc_a2 - 1.0) + 1.0;
12105                let cc_d: f32 = cc_a2 / (PI * cc_den * cc_den).max(1.0e-5);
12106                let cc_vis: f32 = 0.25 / (v_dot_h * v_dot_h).max(0.04);
12107                let f_coat: f32 = 0.04 + 0.96 * pow5_vh;
12108                let coat_spec: f32 = (cc_d * cc_vis * f_coat * coat_weight).min(12.0);
12109                let coat_atten: f32 = (1.0 - coat_weight * f_coat).clamp(0.0, 1.0);
12110                layer_brdf = layer_brdf.scale(coat_atten).add(Vec3::splat(
12111                    coat_spec * (cc_nl / n_dot_l.max(1.0e-4)).min(1.5),
12112                ));
12113            }
12114            direct_rgb = layer_brdf.mul(sun_color).scale(n_dot_l * sun_vis);
12115        }
12116        let mut local_rgb: Vec3 = Vec3::zero();
12117        if let Some(clusters) = inputs.light_clusters {
12118            let screen_u: f32 = sample_x * frame_context.inv_width;
12119            let screen_v: f32 = sample_y * frame_context.inv_height;
12120            local_rgb = clusters.evaluate_pixel(
12121                world_pos,
12122                shade_normal,
12123                view_dir,
12124                (albedo, f0, alpha2, (1.0 - metallic) * (1.0 - transmission)),
12125                (screen_u, screen_v, linear_depth),
12126            );
12127        }
12128        for area_light in inputs.area_lights.iter() {
12129            local_rgb = local_rgb.add(area_light.evaluate_pbr(
12130                world_pos,
12131                shade_normal,
12132                view_dir,
12133                (
12134                    albedo,
12135                    f0,
12136                    roughness,
12137                    (1.0 - metallic) * (1.0 - transmission),
12138                ),
12139            ));
12140        }
12141        let refl_dir: Vec3 = view_dir.scale(-1.0).reflect(shade_normal).normalize();
12142        let om_nv: f32 = (1.0 - n_dot_v).clamp(0.0, 1.0);
12143        let pow5_nv: f32 = om_nv * om_nv * om_nv * om_nv * om_nv;
12144        let max_smooth_f0: Vec3 = Vec3::new(
12145            (1.0 - roughness).max(f0.get_x()),
12146            (1.0 - roughness).max(f0.get_y()),
12147            (1.0 - roughness).max(f0.get_z()),
12148        );
12149        let fresnel_ibl: Vec3 = f0.add(max_smooth_f0.sub(f0).scale(pow5_nv));
12150        let mut ibl_rgb: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12151            let irradiance: Vec3 = ibl.evaluate_sh_diffuse(shade_normal);
12152            let prefiltered: Vec3 = ibl.sample_specular_octahedral(refl_dir, roughness);
12153            let ibl_diff: Vec3 = irradiance
12154                .mul(diffuse_albedo)
12155                .mul(Vec3::splat(1.0).sub(fresnel_ibl));
12156            let ibl_spec: Vec3 = prefiltered
12157                .mul(
12158                    f0.scale(brdf_lut_sample[0])
12159                        .add(Vec3::splat(brdf_lut_sample[1])),
12160                )
12161                .mul(multi_scatter);
12162            let mut combined_ibl: Vec3 = ibl_diff.add(ibl_spec);
12163            if coat_weight > 1.0e-4 {
12164                let cc_nv: f32 = coat_normal.dot(view_dir).max(0.001);
12165                let cc_om: f32 = (1.0 - cc_nv).clamp(0.0, 1.0);
12166                let f_coat_v: f32 = 0.04 + 0.96 * cc_om * cc_om * cc_om * cc_om * cc_om;
12167                let cc_refl: Vec3 = view_dir.scale(-1.0).reflect(coat_normal).normalize();
12168                let cc_pref: Vec3 = ibl.sample_specular_octahedral(cc_refl, coat_rough);
12169                combined_ibl = combined_ibl
12170                    .scale(1.0 - coat_weight * f_coat_v)
12171                    .add(cc_pref.scale(coat_weight * f_coat_v));
12172            }
12173            combined_ibl.scale(ao_factor)
12174        } else {
12175            let sky_hemi: Vec3 = frame_context.sun.get_sky_horizon().lerp(
12176                frame_context.sun.get_sky_zenith(),
12177                (shade_normal.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
12178            );
12179            let sky_spec: Vec3 = Self::sample_sky_lut(inputs.sky_lut, refl_dir, &frame_context.sun);
12180            let hemi_diff: Vec3 = sky_hemi
12181                .mul(diffuse_albedo)
12182                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12183                .scale(0.45);
12184            let hemi_spec: Vec3 = sky_spec
12185                .mul(fresnel_ibl)
12186                .mul(multi_scatter)
12187                .scale((1.0 - roughness * 0.65).clamp(0.15, 1.0));
12188            hemi_diff.add(hemi_spec).scale(ao_factor)
12189        };
12190        if sheen_color.length_sq() > 1.0e-6 {
12191            let sheen_grazing: f32 = pow5_nv * (0.35 + 0.65 * sheen_rough);
12192            ibl_rgb = ibl_rgb.add(sheen_color.scale(sheen_grazing * 0.45 * ao_factor));
12193        }
12194        let transmitted_rgb: Vec3 = if transmission > 1.0e-4 {
12195            let refr_dir: Vec3 =
12196                Self::refract_unit_ray(view_dir.scale(-1.0), shade_normal, 1.0 / ior_val);
12197            let bg_radiance: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12198                ibl.sample_specular_octahedral(refr_dir, roughness)
12199            } else {
12200                Self::sample_sky_lut(inputs.sky_lut, refr_dir, &frame_context.sun)
12201            };
12202            let beer_atten: Vec3 =
12203                if thickness > 1.0e-4 && atten_dist.is_finite() && atten_dist > 1.0e-4 {
12204                    let sigma_r: f32 = -(atten_color.get_x().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12205                    let sigma_g: f32 = -(atten_color.get_y().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12206                    let sigma_b: f32 = -(atten_color.get_z().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12207                    Vec3::new(
12208                        (-sigma_r * thickness).exp(),
12209                        (-sigma_g * thickness).exp(),
12210                        (-sigma_b * thickness).exp(),
12211                    )
12212                } else {
12213                    Vec3::splat(1.0)
12214                };
12215            bg_radiance
12216                .mul(albedo)
12217                .mul(beer_atten)
12218                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12219                .scale(transmission)
12220        } else {
12221            Vec3::zero()
12222        };
12223        let _alpha_blend_guard: f32 = alpha_val;
12224        let hdr_rgb: Vec3 = direct_rgb
12225            .add(local_rgb)
12226            .add(ibl_rgb)
12227            .add(transmitted_rgb)
12228            .add(emissive_rgb)
12229            .scale(frame_context.exposure_scale);
12230        let ldr_linear: Vec3 = if inputs.use_agx_tonemap {
12231            agx_tonemap(hdr_rgb)
12232        } else {
12233            aces_filmic_tonemap(hdr_rgb)
12234        };
12235        Self::encode_srgb_rgba8(ldr_linear)
12236    }
12237}