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 is_glass: bool = refl >= 0.55;
4384        let is_brick: bool = !is_glass && base.get_x() > base.get_y() * 1.20;
4385        let is_stone: bool = !is_glass && !is_brick && base.get_x() >= base.get_z() * 1.04;
4386        let mat_t: f32 = ((depth - 45.0) * (1.0 / 120.0)).clamp(0.0, 1.0);
4387        let mat_fade: f32 = 1.0 - mat_t * mat_t * (3.0 - 2.0 * mat_t);
4388        let (win_lo_u, win_hi_u, win_lo_v, win_hi_v): (f32, f32, f32, f32) = if is_glass {
4389            (0.11, 0.89, 0.15, 0.87)
4390        } else {
4391            (0.22, 0.78, 0.24, 0.82)
4392        };
4393        let pane_u: f32 = Self::box_pulse(su, win_lo_u, win_hi_u, fw_su);
4394        let pane_v: f32 = Self::box_pulse(sy, win_lo_v, win_hi_v, fw_sy);
4395        let mullion_cut: f32 = if is_glass && mat_fade > 0.01 {
4396            1.0 - Self::box_pulse(su, 0.48, 0.52, fw_su) * mat_fade * 0.75
4397        } else {
4398            1.0
4399        };
4400        let pane_w: f32 = (pane_u * pane_v * mullion_cut).clamp(0.0, 1.0);
4401        let spandrel_cov: f32 = Self::box_pulse(sy, 0.14, 0.88, fw_sy);
4402        let spandrel_shade: f32 = 0.70 + 0.18 * spandrel_cov;
4403        let wall_base: Vec3 = if is_glass || mat_fade <= 0.01 {
4404            base.scale(spandrel_shade)
4405        } else if is_brick {
4406            let b_row: f32 = (world_y * 6.2).floor();
4407            let b_u: f32 = u_coord * 2.1 + 0.5 * (b_row * 0.5).fract();
4408            let m_u: f32 = Self::box_pulse(b_u, 0.0, 0.085, world_px_size * 2.1);
4409            let m_v: f32 = Self::box_pulse(world_y * 6.2, 0.0, 0.14, world_px_size * 6.2);
4410            let mortar: f32 = (m_u + m_v - m_u * m_v).clamp(0.0, 1.0) * mat_fade;
4411            let b_h: f32 = Self::sky_hash_2d(b_u.floor() as i32, b_row as i32);
4412            let b_ct: f32 = ((world_px_size * 6.2 - 0.14) * (1.0 / 0.22)).clamp(0.0, 1.0);
4413            let b_coh: f32 = 1.0 - b_ct * b_ct * (3.0 - 2.0 * b_ct);
4414            let brick_t: Vec3 = base.scale(0.84 + 0.32 * (0.5 + (b_h - 0.5) * b_coh));
4415            brick_t.lerp(Vec3::new(0.46, 0.43, 0.39), mortar * 0.72)
4416        } else if is_stone {
4417            let s_row: f32 = (world_y * 1.35).floor();
4418            let s_u: f32 = u_coord * 0.72 + 0.5 * (s_row * 0.5).fract();
4419            let j_u: f32 = Self::box_pulse(s_u, 0.0, 0.045, world_px_size * 0.72);
4420            let j_v: f32 = Self::box_pulse(world_y * 1.35, 0.0, 0.060, world_px_size * 1.35);
4421            let joint: f32 = (j_u + j_v - j_u * j_v).clamp(0.0, 1.0) * mat_fade;
4422            let s_h: f32 = Self::sky_hash_2d(s_u.floor() as i32, s_row as i32);
4423            let cornice: f32 = Self::box_pulse(sy, 0.0, 0.09, fw_sy) * mat_fade;
4424            let stone_c: Vec3 = base.scale(0.88 + 0.22 * s_h).scale(1.0 - 0.32 * joint);
4425            stone_c.lerp(stone_c.scale(1.18), cornice * 0.65)
4426        } else {
4427            let flute: f32 =
4428                Self::box_pulse(u_coord * 2.4, 0.0, 0.32, world_px_size * 2.4) * mat_fade;
4429            let panel_v: f32 = Self::box_pulse(sy, 0.0, 0.05, fw_sy) * mat_fade;
4430            base.scale((0.88 + 0.18 * flute) * (1.0 - 0.30 * panel_v))
4431        };
4432        if pane_w <= 0.01 {
4433            return (wall_base, emissive, refl * 0.72 * spec_aa_damp);
4434        }
4435        let cell_fw: f32 = fw_su.max(fw_sy);
4436        let ct: f32 = ((cell_fw - 0.10) * (1.0 / 0.18)).clamp(0.0, 1.0);
4437        let cell_coh: f32 = 1.0 - ct * ct * (3.0 - 2.0 * ct);
4438        let cell_x: i32 = su_fl as i32;
4439        let cell_y: i32 = sy_fl as i32;
4440        let h_bits: u32 = ((cell_x.wrapping_mul(73_856_093))
4441            ^ (cell_y.wrapping_mul(19_349_663))
4442            ^ ((cell_x.wrapping_add(cell_y)).wrapping_mul(83_492_791)))
4443            as u32;
4444        let bucket: u32 = h_bits % 11;
4445        let room_level: f32 = 0.68 + (((h_bits >> 8) & 15) as f32) * 0.032;
4446        let blind_grad: f32 = (0.48 + 0.66 * (1.0 - fy_win)).clamp(0.38, 1.14);
4447        let room_scale: f32 = room_level * (0.78 + (blind_grad - 0.78) * cell_coh);
4448        let (cell_tint, cell_em, cell_refl_add): (f32, Vec3, f32) = match bucket {
4449            0 | 4 => (0.86, Vec3::new(1.24, 0.86, 0.42).scale(room_scale), 0.14),
4450            1 => (0.84, Vec3::new(0.28, 0.86, 1.24).scale(room_scale), 0.18),
4451            2 => (
4452                0.88,
4453                Vec3::new(0.96, 0.94, 0.88).scale(room_scale * 0.82),
4454                0.16,
4455            ),
4456            3 => (
4457                0.84,
4458                Vec3::new(1.06, 0.34, 0.72).scale(room_scale * 0.86),
4459                0.18,
4460            ),
4461            _ => (
4462                (0.36 + 0.22 * fy_win).clamp(0.32, 0.62),
4463                Vec3::new(0.0, 0.0, 0.0),
4464                0.36,
4465            ),
4466        };
4467        let avg_tint: f32 = 0.64;
4468        let avg_em: Vec3 = Vec3::new(0.32, 0.27, 0.24);
4469        let avg_refl_add: f32 = 0.27;
4470        let eff_tint: f32 = avg_tint + (cell_tint - avg_tint) * cell_coh;
4471        let eff_em: Vec3 = avg_em.lerp(cell_em, cell_coh);
4472        let eff_refl_add: f32 = avg_refl_add + (cell_refl_add - avg_refl_add) * cell_coh;
4473        (
4474            wall_base.lerp(base.scale(eff_tint), pane_w),
4475            emissive.add(eff_em.scale(pane_w)),
4476            ((refl + eff_refl_add * pane_w) * spec_aa_damp).min(0.92),
4477        )
4478    }
4479
4480    /// Evaluates continuous closed-loop stadium arc length for boulevard markings and streetlights.
4481    ///
4482    /// # Arguments
4483    ///
4484    /// - `f32` - World X coordinate in meters.
4485    /// - `f32` - World Z coordinate in meters.
4486    ///
4487    /// # Returns
4488    ///
4489    /// - `f32` - Continuous arc-length coordinate `road_s` along the 962.12m closed loop.
4490    #[inline(always)]
4491    #[must_use]
4492    fn eval_loop_arc_s(wpx: f32, wpz: f32) -> f32 {
4493        if wpz < -140.0 {
4494            let ry: f32 = -(wpz + 140.0);
4495            let rx: f32 = -(wpx - 64.0);
4496            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4497                1.0
4498            } else {
4499                rx
4500            };
4501            return 140.0 + 64.0 * ry.atan2(rx_safe);
4502        }
4503        if wpz > 140.0 {
4504            let ry: f32 = wpz - 140.0;
4505            let rx: f32 = wpx - 64.0;
4506            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4507                1.0
4508            } else {
4509                rx
4510            };
4511            return 621.06193 + 64.0 * ry.atan2(rx_safe);
4512        }
4513        if wpx <= 64.0 { -wpz } else { 481.06193 + wpz }
4514    }
4515
4516    /// 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.
4517    ///
4518    /// # Arguments
4519    ///
4520    /// - `(f32, f32, f32, f32)` - `(world_x, world_z, depth, inv_height)`.
4521    /// - `(Vec3, f32, f32, f32)` - `(view_dir, fresnel_t, metallic, world_time_secs)`.
4522    /// - `Vec3` - Base road material albedo.
4523    ///
4524    /// # Returns
4525    ///
4526    /// - `(Vec3, f32)` - Updated `(albedo, calibrated_reflectivity)`.
4527    #[inline(always)]
4528    #[must_use]
4529    fn eval_road_detail(
4530        coords: (f32, f32, f32, f32),
4531        optics: (Vec3, f32, f32, f32),
4532        base: Vec3,
4533    ) -> (Vec3, f32) {
4534        let (wpx, wpz, depth, inv_height): (f32, f32, f32, f32) = coords;
4535        let (view_dir, fresnel_t, metallic, world_time): (Vec3, f32, f32, f32) = optics;
4536        let world_px_size: f32 = (depth * inv_height * 2.10).max(0.018);
4537        let fw_x: f32 = world_px_size * 1.15;
4538        let fw_z: f32 = world_px_size * 2.35;
4539        let fw_xz: f32 = fw_x.hypot(fw_z);
4540        let spine_z: f32 = wpz.clamp(-140.0, 140.0);
4541        let rel_x: f32 = wpx - 64.0;
4542        let rel_z: f32 = wpz - spine_z;
4543        let d_spine: f32 = rel_x.hypot(rel_z);
4544        let road_u: f32 = d_spine - 64.0;
4545        let abs_u: f32 = road_u.abs();
4546        let (rad_x, rad_z): (f32, f32) = if d_spine > 1.0e-4 {
4547            (rel_x / d_spine, rel_z / d_spine)
4548        } else {
4549            (-1.0, 0.0)
4550        };
4551        let tan_x: f32 = -rad_z;
4552        let tan_z: f32 = rad_x;
4553        let fw_u: f32 = (rad_x.abs() * fw_x + rad_z.abs() * fw_z).max(0.015);
4554        let arc_scale: f32 = if wpz.abs() > 140.0 {
4555            64.0 / d_spine.max(16.0)
4556        } else {
4557            1.0
4558        };
4559        let fw_s: f32 = ((tan_x.abs() * fw_x + tan_z.abs() * fw_z) * arc_scale).max(0.015);
4560        let refl_fresnel: f32 = (0.18 + 0.82 * fresnel_t + metallic * 0.25).clamp(0.18, 0.95);
4561        let inv_refl_f: f32 = 1.0 / refl_fresnel;
4562        let f_water: f32 = 0.02 + 0.98 * fresnel_t;
4563        let d_bay_t: f32 = ((d_spine - 77.8) * (1.0 / 0.6)).clamp(0.0, 1.0);
4564        let bay_w: f32 =
4565            Self::box_step(wpx, 144.0, fw_x) * (d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t));
4566        if bay_w >= 0.999 {
4567            let shore_d: f32 = (wpx - 144.0).max(0.0);
4568            let shallow_t: f32 = Self::fast_exp_neg_3d(shore_d * 0.055);
4569            let deep_col: Vec3 = Vec3::new(0.005, 0.044, 0.118);
4570            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4571            let warp_a: f32 = Self::sky_value_noise(
4572                wpx * 0.075 - world_time * 0.14,
4573                wpz * 0.065 + world_time * 0.09,
4574            ) * 2.4;
4575            let wave_p: f32 =
4576                (wpx * 0.23 + wpz * 0.11 + warp_a - world_time * 1.35).sin() * 0.5 + 0.5;
4577            let cloud_var: f32 = 0.84
4578                + 0.24
4579                    * Self::sky_value_noise(
4580                        wpx * 0.018 - world_time * 0.025,
4581                        wpz * 0.018 + world_time * 0.015,
4582                    );
4583            let sw_t: f32 = (shore_d * (1.0 / 1.8)).clamp(0.0, 1.0);
4584            let seawall_shadow: f32 = 0.46 + 0.54 * (sw_t * sw_t * (3.0 - 2.0 * sw_t));
4585            let body_col: Vec3 = deep_col
4586                .lerp(shallow_col, shallow_t)
4587                .scale((0.92 + 0.16 * wave_p) * cloud_var * seawall_shadow);
4588            let surf_n: f32 = Self::sky_value_noise(
4589                wpx * 0.48 - world_time * 0.55,
4590                wpz * 0.34 + world_time * 0.18,
4591            );
4592            let surf_n2: f32 =
4593                Self::sky_value_noise(wpx * 1.35 + 3.1, wpz * 1.15 - world_time * 0.40);
4594            let surf_wave: f32 =
4595                (shore_d * 1.65 - world_time * 1.95 + surf_n * 3.4).sin() * 0.5 + 0.5;
4596            let shore_band: f32 = Self::fast_exp_neg_3d(shore_d * 0.38);
4597            let lace_t: f32 =
4598                ((surf_n * 0.62 + surf_n2 * 0.38 + shore_band * 0.42 - 0.32) * 2.5).clamp(0.0, 1.0);
4599            let lace: f32 = lace_t * lace_t * (3.0 - 2.0 * lace_t);
4600            let foam_aa: f32 = 1.0 - ((fw_xz - 0.25) * 1.0).clamp(0.0, 1.0);
4601            let foam_w: f32 = ((shore_band * (0.45 + 0.55 * surf_wave) * lace
4602                + Self::fast_exp_neg_3d(shore_d * 2.2) * 0.65)
4603                * foam_aa)
4604                .clamp(0.0, 0.94);
4605            let ocean_col: Vec3 = body_col.lerp(Vec3::new(0.84, 0.90, 0.94), foam_w);
4606            let ocean_refl: f32 = ((f_water * (1.0 - foam_w)) * inv_refl_f).clamp(0.0, 1.0);
4607            return (ocean_col, ocean_refl);
4608        }
4609        let tm: f32 = ((depth - 14.0) * (1.0 / 34.0)).clamp(0.0, 1.0);
4610        let micro_fade: f32 = (1.0 - tm * tm * (3.0 - 2.0 * tm))
4611            * (1.0 - ((fw_xz - 0.05) * (1.0 / 0.17)).clamp(0.0, 1.0));
4612        let agg_h: f32 = if micro_fade > 0.005 {
4613            let a0: f32 = Self::sky_value_noise(wpx * 8.5, wpz * 8.5);
4614            let a1: f32 = Self::sky_value_noise(wpx * 24.0 + 7.3, wpz * 24.0 - 4.1);
4615            a0.mul_add(0.48, a1 * 0.52)
4616        } else {
4617            0.5
4618        };
4619        let grain_n: f32 = agg_h - 0.5;
4620        let seam_u: f32 = Self::box_pulse(wpx * 0.45, 0.0, 0.045, fw_x * 0.45);
4621        let seam_v: f32 = Self::box_pulse(wpz * 0.45, 0.0, 0.045, fw_z * 0.45);
4622        let seam_cov: f32 = (seam_u + seam_v - seam_u * seam_v).clamp(0.0, 1.0);
4623        let tile_seam: f32 = 1.0 - 0.26 * seam_cov;
4624        if abs_u > 14.2 {
4625            let r_cx: f32 = -92.0 + 9.0 * (wpz * 0.022).sin() + 3.5 * (wpz * 0.048).cos();
4626            let d_ns: f32 = if wpz.abs() < 274.0 {
4627                (wpx - r_cx).abs()
4628            } else {
4629                999.0
4630            };
4631            let r_est_off: f32 = 4.5 * (wpx * 0.032).sin();
4632            let d_en: f32 = if wpx >= r_cx - 6.0 && wpx <= 146.0 {
4633                (wpz - (-266.0 + r_est_off)).abs()
4634            } else {
4635                999.0
4636            };
4637            let d_es: f32 = if wpx >= r_cx - 6.0 && wpx <= 146.0 {
4638                (wpz - (266.0 + r_est_off)).abs()
4639            } else {
4640                999.0
4641            };
4642            let d_river: f32 = d_ns.min(d_en.min(d_es));
4643            let bridge_deck: f32 = if d_ns < 11.4 {
4644                Self::box_band(wpz, -122.4, -113.6, fw_z)
4645                    .max(Self::box_band(wpz, -4.4, 4.4, fw_z))
4646                    .max(Self::box_band(wpz, 113.6, 122.4, fw_z))
4647            } else {
4648                0.0
4649            };
4650            let riv_water_w: f32 =
4651                (1.0 - Self::box_step(d_river, 6.8, fw_xz)) * (1.0 - bridge_deck);
4652            if riv_water_w >= 0.995 {
4653                let rw_a: f32 = Self::sky_value_noise(
4654                    wpx * 0.25 + world_time * 0.14,
4655                    wpz * 0.15 - world_time * 0.52,
4656                ) * 2.2;
4657                let rp: f32 =
4658                    (wpx * 0.48 + wpz * 0.32 + rw_a - world_time * 1.85).sin() * 0.5 + 0.5;
4659                let caust_raw: f32 = (wpx * 1.35 + wpz * 0.95 + rw_a - world_time * 2.1).sin();
4660                let caust: f32 = (caust_raw * caust_raw)
4661                    * (1.0 - ((depth - 35.0) * (1.0 / 95.0)).clamp(0.0, 1.0));
4662                let bt: f32 = ((d_river - 1.2) * (1.0 / 5.4)).clamp(0.0, 1.0);
4663                let bank_t: f32 = bt * bt * (3.0 - 2.0 * bt);
4664                let riv_col: Vec3 = Vec3::new(0.014, 0.115, 0.148)
4665                    .lerp(Vec3::new(0.048, 0.255, 0.235), bank_t)
4666                    .scale(0.88 + 0.24 * rp)
4667                    .add(Vec3::new(0.035, 0.125, 0.110).scale(caust));
4668                let foam_t: f32 = ((d_river - 5.8) * (1.0 / 0.95)).clamp(0.0, 1.0);
4669                let foam_w: f32 = foam_t * foam_t * (3.0 - 2.0 * foam_t) * 0.55;
4670                let final_riv: Vec3 = riv_col.lerp(Vec3::new(0.84, 0.90, 0.94), foam_w);
4671                let riv_refl: f32 = ((f_water * (1.0 - foam_w)) * inv_refl_f).clamp(0.0, 1.0);
4672                return (final_riv, riv_refl);
4673            }
4674            let cob_row: f32 = (wpz * 1.65).floor();
4675            let cob_u: f32 = wpx * 1.25 + 0.5 * (cob_row * 0.5).fract();
4676            let cob_su: f32 = Self::box_pulse(cob_u, 0.0, 0.075, fw_x * 1.25);
4677            let cob_sv: f32 = Self::box_pulse(wpz * 1.65, 0.0, 0.085, fw_z * 1.65);
4678            let cob_joint: f32 = (cob_su + cob_sv - cob_su * cob_sv).clamp(0.0, 1.0);
4679            let cob_h: f32 = Self::sky_hash_2d(cob_u.floor() as i32, cob_row as i32);
4680            let cob_ct: f32 = ((fw_xz - 0.08) * (1.0 / 0.18)).clamp(0.0, 1.0);
4681            let cob_var: f32 = 0.90
4682                + 0.20 * (0.5 + (cob_h - 0.5) * (1.0 - cob_ct * cob_ct * (3.0 - 2.0 * cob_ct)));
4683            let plaza_base: Vec3 = if d_spine < 64.0 {
4684                Vec3::new(0.37, 0.36, 0.34)
4685            } else {
4686                Vec3::new(0.30, 0.31, 0.33)
4687            };
4688            let cobble_col: Vec3 = plaza_base
4689                .scale(cob_var * (1.0 - 0.34 * cob_joint) * (1.0 + grain_n * 0.14 * micro_fade));
4690            let wp_a: f32 = ((-53.0 - wpx) * (1.0 / 6.0)).clamp(0.0, 1.0);
4691            let wp_b: f32 = ((wpx + 132.0) * (1.0 / 8.0)).clamp(0.0, 1.0);
4692            let wp_c: f32 = ((286.0 - wpz.abs()) * 0.1).clamp(0.0, 1.0);
4693            let west_park: f32 = (wp_a * wp_a * (3.0 - 2.0 * wp_a))
4694                * (wp_b * wp_b * (3.0 - 2.0 * wp_b))
4695                * (wp_c * wp_c * (3.0 - 2.0 * wp_c));
4696            let est_d: f32 = (wpz + 266.0).abs().min((wpz - 266.0).abs());
4697            let ep_a: f32 = ((24.0 - est_d) * (1.0 / 7.0)).clamp(0.0, 1.0);
4698            let ep_b: f32 = ((wpx + 130.0) * 0.1).clamp(0.0, 1.0);
4699            let ep_c: f32 = ((144.0 - wpx) * (1.0 / 6.0)).clamp(0.0, 1.0);
4700            let est_park: f32 = (ep_a * ep_a * (3.0 - 2.0 * ep_a))
4701                * (ep_b * ep_b * (3.0 - 2.0 * ep_b))
4702                * (ep_c * ep_c * (3.0 - 2.0 * ep_c));
4703            let rim_x: f32 = ((-136.0 - wpx) * (1.0 / 9.0)).clamp(0.0, 1.0);
4704            let rim_z: f32 = ((wpz.abs() - 286.0) * 0.1).clamp(0.0, 1.0);
4705            let rim_green: f32 =
4706                (rim_x * rim_x * (3.0 - 2.0 * rim_x)).max(rim_z * rim_z * (3.0 - 2.0 * rim_z));
4707            let im_s: f32 = ((49.0 - d_spine) * 0.2).clamp(0.0, 1.0);
4708            let im_a: f32 = (((wpx - 38.0).abs() - 4.0) * (1.0 / 3.5)).clamp(0.0, 1.0);
4709            let im_b: f32 = (((wpx - 91.0).abs() - 4.0) * (1.0 / 3.5)).clamp(0.0, 1.0);
4710            let im_z: f32 = ((126.0 - wpz.abs()) * 0.125).clamp(0.0, 1.0);
4711            let im_n: f32 = ((Self::sky_value_noise(wpx * 0.045 + 1.2, wpz * 0.045 - 2.8) - 0.36)
4712                * (1.0 / 0.18))
4713                .clamp(0.0, 1.0);
4714            let inner_meadow: f32 = im_s * im_a * im_b * im_z * im_n;
4715            let park_w: f32 = west_park
4716                .max(est_park)
4717                .max(rim_green * 0.68)
4718                .max(inner_meadow)
4719                .clamp(0.0, 1.0)
4720                * (1.0 - bridge_deck);
4721            let grass_n1: f32 = Self::sky_value_noise(wpx * 0.085 + 3.4, wpz * 0.085 - 1.9);
4722            let grass_n2: f32 = Self::sky_value_noise(wpx * 0.42 - 7.1, wpz * 0.42 + 4.8);
4723            let grass_col: Vec3 = Vec3::new(0.068, 0.165, 0.056)
4724                .lerp(
4725                    Vec3::new(0.145, 0.255, 0.082),
4726                    grass_n1 * 0.62 + grass_n2 * 0.38,
4727                )
4728                .scale(0.92 + 0.16 * grain_n * micro_fade);
4729            let mut land_col: Vec3 = cobble_col.lerp(grass_col, park_w);
4730            let shore_t: f32 = ((8.6 - d_river) * (1.0 / 1.5)).clamp(0.0, 1.0);
4731            let shore_sand_w: f32 = shore_t
4732                * shore_t
4733                * (3.0 - 2.0 * shore_t)
4734                * (1.0 - riv_water_w)
4735                * (1.0 - bridge_deck);
4736            let emb_stone_w: f32 = Self::box_band(d_river, 8.2, 10.2, fw_xz) * (1.0 - bridge_deck);
4737            let pebble_col: Vec3 = Vec3::new(0.32, 0.29, 0.23).scale(0.78 + 0.40 * agg_h);
4738            let emb_col: Vec3 = Vec3::new(0.30, 0.31, 0.29)
4739                .lerp(
4740                    Vec3::new(0.12, 0.20, 0.10),
4741                    0.35 * cob_joint + 0.25 * grass_n2,
4742                )
4743                .scale(1.0 - 0.32 * cob_joint);
4744            land_col = land_col.lerp(pebble_col, shore_sand_w);
4745            land_col = land_col.lerp(emb_col, emb_stone_w * 0.88);
4746            if bridge_deck > 0.005 {
4747                let br_col: Vec3 =
4748                    Vec3::new(0.35, 0.34, 0.32).scale(cob_var * (1.0 - 0.28 * cob_joint));
4749                land_col = land_col.lerp(br_col, bridge_deck);
4750            }
4751            let east_mask: f32 = d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t);
4752            let seawall_coping: f32 = Self::box_band(wpx, 142.4, 144.0, fw_x) * east_mask;
4753            let seawall_lip: f32 = Self::box_band(wpx, 143.65, 144.0, fw_x) * east_mask;
4754            let sea_spray: f32 = Self::fast_exp_neg_3d((144.0 - wpx).max(0.0) * 0.65) * east_mask;
4755            let coping_col: Vec3 = Vec3::new(0.42, 0.44, 0.46)
4756                .lerp(Vec3::new(0.22, 0.24, 0.27), seawall_lip)
4757                .scale(1.0 - 0.28 * sea_spray);
4758            land_col = land_col.lerp(coping_col, seawall_coping);
4759            let land_refl: f32 =
4760                (((0.025 + 0.04 * fresnel_t) * (1.0 - park_w * 0.7)) * inv_refl_f).clamp(0.0, 1.0);
4761            if riv_water_w > 0.005 {
4762                let riv_shallow: Vec3 = Vec3::new(0.048, 0.255, 0.235);
4763                let riv_refl: f32 = (f_water * inv_refl_f).clamp(0.0, 1.0);
4764                return (
4765                    land_col.lerp(riv_shallow, riv_water_w),
4766                    land_refl * (1.0 - riv_water_w) + riv_refl * riv_water_w,
4767                );
4768            }
4769            if bay_w <= 1.0e-4 {
4770                return (land_col, land_refl);
4771            }
4772            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4773            let ocean_refl: f32 = (f_water * inv_refl_f).clamp(0.0, 1.0);
4774            return (
4775                land_col.lerp(shallow_col, bay_w),
4776                land_refl * (1.0 - bay_w) + ocean_refl * bay_w,
4777            );
4778        }
4779        let road_s: f32 = Self::eval_loop_arc_s(wpx, wpz);
4780        let curb_w: f32 = Self::box_step(abs_u, 10.2, fw_u);
4781        let walk_w: f32 = Self::box_step(abs_u, 10.8, fw_u);
4782        let om_curb: f32 = 1.0 - curb_w;
4783        let inner_lin: f32 = 1.0 - ((abs_u - 3.65).abs() * 0.85).clamp(0.0, 1.0);
4784        let outer_lin: f32 = 1.0 - ((abs_u - 6.85).abs() * 0.95).clamp(0.0, 1.0);
4785        let tire_wear: f32 =
4786            (inner_lin * inner_lin + outer_lin * outer_lin).clamp(0.0, 1.0) * om_curb;
4787        let gutter_band: f32 = (1.0 - ((abs_u - 9.55).abs() * 2.2).clamp(0.0, 1.0)) * om_curb;
4788        let cpg_t: f32 = ((10.18 - abs_u) * (1.0 / 0.46)).clamp(0.0, 1.0);
4789        let curb_pool_guard: f32 = cpg_t * cpg_t * (3.0 - 2.0 * cpg_t);
4790        let center_crown: f32 = (1.0 - (abs_u * 0.65).clamp(0.0, 1.0)) * om_curb;
4791        let tp_fade: f32 = ((depth - 54.0) * (1.0 / 86.0)).clamp(0.0, 1.0);
4792        let puddle_fade: f32 = 1.0 - tp_fade * tp_fade * (3.0 - 2.0 * tp_fade);
4793        let (wet_porosity, water_mask, water_depth): (f32, f32, f32) =
4794            if puddle_fade > 1.0e-3 && om_curb > 1.0e-3 {
4795                let n0: f32 = Self::sky_value_noise(wpx * 0.13 + 3.1, wpz * 0.075 - 1.7);
4796                let n1: f32 = Self::sky_value_noise(wpx * 0.38 - 5.4, wpz * 0.22 + 2.9);
4797                let n2: f32 = Self::sky_value_noise(wpx * 1.45 + 8.7, wpz * 1.05 - 4.3);
4798                let wet_field: f32 =
4799                    n0 * 0.56 + n1 * 0.28 + n2 * 0.16 + tire_wear * 0.13 + gutter_band * 0.17
4800                        - center_crown * 0.22;
4801                let wp_t: f32 = ((wet_field - 0.45) * (1.0 / 0.15)).clamp(0.0, 1.0);
4802                let wp_val: f32 = wp_t * wp_t * (3.0 - 2.0 * wp_t) * om_curb * puddle_fade;
4803                let shore_micro: f32 =
4804                    grain_n * 0.058 * (0.28 + 0.72 * micro_fade) + (n2 - 0.5) * 0.045;
4805                let puddle_h: f32 = wet_field + shore_micro;
4806                let shore_w: f32 = (0.020 + fw_xz * 0.042).clamp(0.020, 0.095);
4807                let wm_t: f32 = ((puddle_h - (0.60 - shore_w)) / (2.0 * shore_w)).clamp(0.0, 1.0);
4808                let wm_val: f32 =
4809                    wm_t * wm_t * (3.0 - 2.0 * wm_t) * om_curb * curb_pool_guard * puddle_fade;
4810                let wd_val: f32 = ((wet_field - 0.58) * 3.8).clamp(0.0, 1.0) * wm_val;
4811                (wp_val, wm_val, wd_val)
4812            } else {
4813                (0.0, 0.0, 0.0)
4814            };
4815        let dry_base: Vec3 = Vec3::new(
4816            base.get_x().mul_add(1.38, 0.036),
4817            base.get_y().mul_add(1.38, 0.038),
4818            base.get_z().mul_add(1.38, 0.042),
4819        );
4820        let dry_scale: f32 = (1.0 + grain_n * 0.34 * micro_fade)
4821            * (1.0 - 0.14 * tire_wear)
4822            * (1.0 - 0.22 * gutter_band);
4823        let mut road_col: Vec3 = dry_base.scale(dry_scale);
4824        let yellow_w: f32 = Self::box_band(abs_u, 0.135, 0.305, fw_u) * om_curb;
4825        if yellow_w > 0.005 {
4826            let paint_vis: f32 = 0.94 + grain_n * 0.16 * micro_fade;
4827            road_col = road_col.lerp(
4828                Vec3::new(0.92, 0.65, 0.10).scale(paint_vis),
4829                yellow_w * 0.95,
4830            );
4831        }
4832        let dash_on: f32 = Self::box_pulse(road_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4833        let lane_w: f32 = Self::box_band(abs_u, 4.565, 4.735, fw_u) * dash_on * om_curb;
4834        let shoulder_w: f32 = Self::box_band(abs_u, 9.15, 9.35, fw_u) * om_curb;
4835        let straight_t: f32 = ((134.0 - wpz.abs()) * 0.125).clamp(0.0, 1.0);
4836        let straight_w: f32 = straight_t * straight_t * (3.0 - 2.0 * straight_t);
4837        let cross_z_w: f32 = Self::box_pulse(
4838            (road_s + 18.0) * 0.02494481,
4839            0.455,
4840            0.545,
4841            fw_s * 0.02494481,
4842        ) * straight_w;
4843        let cross_x_w: f32 = Self::box_band(abs_u, 0.55, 8.65, fw_u);
4844        let cross_bar: f32 = Self::box_pulse(road_u * 0.85, 0.0, 0.50, fw_u * 0.85);
4845        let cross_w: f32 = cross_z_w * cross_x_w * cross_bar * 0.88 * om_curb;
4846        let white_w: f32 = shoulder_w.max(lane_w).max(cross_w);
4847        if white_w > 0.005 {
4848            let paint_vis: f32 = 0.92 + grain_n * 0.14 * micro_fade;
4849            road_col = road_col.lerp(Vec3::new(0.82, 0.85, 0.90).scale(paint_vis), white_w * 0.92);
4850        }
4851        let damp_col: Vec3 = Vec3::new(
4852            road_col.get_x().max(1.0e-4).powf(1.35) * 0.60,
4853            road_col.get_y().max(1.0e-4).powf(1.35) * 0.60,
4854            road_col.get_z().max(1.0e-4).powf(1.35) * 0.60,
4855        );
4856        let mut final_road_col: Vec3 = road_col.lerp(damp_col, wet_porosity);
4857        let mut ripple_mod: f32 = 0.0;
4858        if water_mask > 0.005 {
4859            let rf_d: f32 = 1.0 - ((depth - 24.0) * (1.0 / 48.0)).clamp(0.0, 1.0);
4860            let rf_w: f32 = ((water_depth - 0.03) * (1.0 / 0.23)).clamp(0.0, 1.0);
4861            let ripple_fade: f32 = rf_d * rf_d * (3.0 - 2.0 * rf_d) * rf_w;
4862            let (rx_rip, rz_rip): (f32, f32) = if ripple_fade > 0.005 {
4863                let rw1: f32 = wpx * 2.4 + wpz * 1.5 - world_time * 1.85;
4864                let rw2: f32 = -wpx * 1.8 + wpz * 3.1 - world_time * 2.35;
4865                let gx: f32 = ((rw1.cos() * 2.4 - rw2.cos() * 1.8) * 0.0028 * ripple_fade)
4866                    .clamp(-0.018, 0.018);
4867                let gz: f32 = ((rw1.cos() * 1.5 + rw2.cos() * 3.1) * 0.0028 * ripple_fade)
4868                    .clamp(-0.018, 0.018);
4869                ripple_mod = (gx + gz) * 1.6;
4870                (gx, gz)
4871            } else {
4872                (0.0, 0.0)
4873            };
4874            let inv_vy: f32 = 1.0 / (view_dir.get_y() + 0.35).max(0.35);
4875            let sh_x: f32 =
4876                -view_dir.get_x() * inv_vy * (water_depth * 0.032) + rx_rip * (water_depth * 1.65);
4877            let sh_z: f32 =
4878                -view_dir.get_z() * inv_vy * (water_depth * 0.032) + rz_rip * (water_depth * 1.65);
4879            let sub_u: f32 = road_u + sh_x * rad_x + sh_z * rad_z;
4880            let sub_abs_u: f32 = sub_u.abs();
4881            let sub_s: f32 = road_s + sh_x * tan_x + sh_z * tan_z;
4882            let mut sub_base: Vec3 = dry_base.scale(dry_scale);
4883            let sy_w: f32 = Self::box_band(sub_abs_u, 0.135, 0.305, fw_u) * om_curb;
4884            if sy_w > 0.005 {
4885                sub_base = sub_base.lerp(
4886                    Vec3::new(0.92, 0.65, 0.10).scale(0.92 + grain_n * 0.14 * micro_fade),
4887                    sy_w * 0.95,
4888                );
4889            }
4890            let sd_on: f32 = Self::box_pulse(sub_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4891            let sl_w: f32 = Self::box_band(sub_abs_u, 4.565, 4.735, fw_u) * sd_on * om_curb;
4892            let ss_w: f32 = Self::box_band(sub_abs_u, 9.15, 9.35, fw_u) * om_curb;
4893            let sc_z: f32 =
4894                Self::box_pulse((sub_s + 18.0) * 0.02494481, 0.455, 0.545, fw_s * 0.02494481)
4895                    * straight_w;
4896            let sc_w: f32 = sc_z
4897                * Self::box_band(sub_abs_u, 0.55, 8.65, fw_u)
4898                * Self::box_pulse(sub_u * 0.85, 0.0, 0.50, fw_u * 0.85)
4899                * 0.88
4900                * om_curb;
4901            let sw_w: f32 = ss_w.max(sl_w).max(sc_w);
4902            if sw_w > 0.005 {
4903                sub_base = sub_base.lerp(
4904                    Vec3::new(0.82, 0.85, 0.90).scale(0.90 + grain_n * 0.12 * micro_fade),
4905                    sw_w * 0.92,
4906                );
4907            }
4908            let meniscus_t: f32 = (water_depth * (1.0 / 0.22)).clamp(0.0, 1.0);
4909            let meniscus_rim: f32 =
4910                1.0 - 0.18 * (1.0 - meniscus_t * meniscus_t * (3.0 - 2.0 * meniscus_t));
4911            let sub_col: Vec3 = Vec3::new(
4912                sub_base.get_x().max(1.0e-4).powf(1.35)
4913                    * 0.58
4914                    * Self::fast_exp_neg_3d(water_depth * 1.15)
4915                    * meniscus_rim,
4916                sub_base.get_y().max(1.0e-4).powf(1.35)
4917                    * 0.58
4918                    * Self::fast_exp_neg_3d(water_depth * 0.88)
4919                    * meniscus_rim,
4920                sub_base.get_z().max(1.0e-4).powf(1.35)
4921                    * 0.58
4922                    * Self::fast_exp_neg_3d(water_depth * 0.72)
4923                    * meniscus_rim,
4924            );
4925            final_road_col = final_road_col.lerp(sub_col, water_mask);
4926        }
4927        let dry_target: f32 = 0.015 + 0.03 * fresnel_t + tire_wear * 0.015;
4928        let damp_target: f32 = 0.04 + 0.22 * fresnel_t;
4929        let water_target: f32 = (f_water + ripple_mod).clamp(0.02, 0.82);
4930        let surf_target: f32 = dry_target * (1.0 - wet_porosity) + damp_target * wet_porosity;
4931        let road_target_blend: f32 = surf_target * (1.0 - water_mask) + water_target * water_mask;
4932        let road_refl: f32 = (road_target_blend * inv_refl_f).clamp(0.0, 1.0);
4933        if curb_w <= 1.0e-4 && walk_w <= 1.0e-4 {
4934            return (final_road_col, road_refl);
4935        }
4936        let curb_joint: f32 = Self::box_pulse(road_s * 0.833, 0.0, 0.045, fw_s * 0.833);
4937        let curb_bevel: f32 = Self::box_band(abs_u, 10.22, 10.42, fw_u);
4938        let curb_col: Vec3 = Vec3::new(0.42, 0.43, 0.45)
4939            .lerp(Vec3::new(0.50, 0.51, 0.52), curb_bevel)
4940            .scale((1.0 - 0.28 * curb_joint) * (1.0 + grain_n * 0.14 * micro_fade));
4941        let slab_s: f32 = road_s * 0.50;
4942        let slab_u: f32 = (abs_u - 10.8) * 0.625;
4943        let slab_js: f32 = Self::box_pulse(slab_s, 0.0, 0.036, fw_s * 0.50);
4944        let slab_ju: f32 = Self::box_pulse(slab_u, 0.0, 0.045, fw_u * 0.625);
4945        let slab_joint: f32 = (slab_js + slab_ju - slab_js * slab_ju).clamp(0.0, 1.0);
4946        let slab_h: f32 = Self::sky_hash_2d(slab_s.floor() as i32, slab_u.floor() as i32);
4947        let tactile_w: f32 = Self::box_band(abs_u, 10.84, 11.16, fw_u);
4948        let walk_slab: Vec3 = Vec3::new(0.32, 0.33, 0.35)
4949            .scale(
4950                (0.92 + 0.16 * slab_h)
4951                    * (1.0 - 0.34 * slab_joint)
4952                    * (1.0 + grain_n * 0.16 * micro_fade),
4953            )
4954            .lerp(
4955                Vec3::new(0.56, 0.46, 0.24).scale(0.90 + 0.18 * grain_n * micro_fade),
4956                tactile_w * 0.58,
4957            );
4958        let walk_col: Vec3 = walk_slab.scale(tile_seam * 0.15 + 0.85);
4959        let final_col: Vec3 = final_road_col.lerp(curb_col, curb_w).lerp(walk_col, walk_w);
4960        let walk_refl: f32 = ((0.03 + 0.05 * fresnel_t) * inv_refl_f).clamp(0.0, 1.0);
4961        let final_refl: f32 = road_refl * om_curb + walk_refl * curb_w;
4962        (final_col, final_refl)
4963    }
4964
4965    /// Fast rational approximation of `exp(-x)` for `x >= 0.0` used in 3D coastal ocean optics.
4966    ///
4967    /// # Arguments
4968    ///
4969    /// - `f32` - Non-negative exponent magnitude `x`.
4970    ///
4971    /// # Returns
4972    ///
4973    /// - `f32` - Approximate `exp(-x)` in `(0.0, 1.0]`.
4974    #[inline(always)]
4975    #[must_use]
4976    fn fast_exp_neg_3d(pos_x: f32) -> f32 {
4977        if pos_x <= 0.0 {
4978            return 1.0;
4979        }
4980        let x2: f32 = pos_x * pos_x;
4981        1.0 / (1.0 + pos_x + 0.48 * x2 + 0.235 * x2 * pos_x)
4982    }
4983
4984    /// Branchless minimax polynomial approximation of `(sin(phase), cos(phase))` for animated 3D ocean waves.
4985    ///
4986    /// # Arguments
4987    ///
4988    /// - `f32` - Input phase angle in radians.
4989    ///
4990    /// # Returns
4991    ///
4992    /// - `(f32, f32)` - Approximate `(sin(phase), cos(phase))`.
4993    #[inline(always)]
4994    #[must_use]
4995    fn fast_sin_cos_3d(phase: f32) -> (f32, f32) {
4996        let quad_f: f32 = (phase * (2.0 / PI)).round();
4997        let rem_rad: f32 = phase - quad_f * FRAC_PI_2;
4998        let rem_sq: f32 = rem_rad * rem_rad;
4999        let sin_rem: f32 = rem_rad
5000            * (1.0 + rem_sq * (-0.166_666_57 + rem_sq * (0.008_333_026 - rem_sq * 0.000_198_074)));
5001        let cos_rem: f32 = 1.0 + rem_sq * (-0.5 + rem_sq * (0.041_666_64 - rem_sq * 0.001_388_839));
5002        match (quad_f as i32) & 3 {
5003            0 => (sin_rem, cos_rem),
5004            1 => (cos_rem, -sin_rem),
5005            2 => (-sin_rem, -cos_rem),
5006            _ => (-cos_rem, sin_rem),
5007        }
5008    }
5009
5010    /// 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.
5011    ///
5012    /// # Arguments
5013    ///
5014    /// - `&DeferredFrameContext` - Immutable per-frame camera, sun, and animation clock context.
5015    /// - `&[[f32; 3]]` - Pre-baked hemi-octahedral sky dome LUT.
5016    /// - `(Vec3, Vec3, f32)` - `(world_pos, unit_view_to_camera, linear_depth)`.
5017    /// - `(f32, Vec3)` - `(sun_shadow, rt_probe_reflection)`.
5018    ///
5019    /// # Returns
5020    ///
5021    /// - `Vec3` - Linear HDR ocean surface radiance prior to exposure and ACES tonemapping.
5022    #[inline(always)]
5023    #[must_use]
5024    fn eval_ocean_water_radiance(
5025        frame_context: &DeferredFrameContext,
5026        sky_lut: &[[f32; 3]],
5027        geom: (Vec3, Vec3, f32),
5028        lighting: (f32, Vec3),
5029    ) -> Vec3 {
5030        let (world_p, view_dir, depth): (Vec3, Vec3, f32) = geom;
5031        let (shadow, rt_refl): (f32, Vec3) = lighting;
5032        let sim_t: f32 = frame_context.world_time_secs;
5033        let wx_orig: f32 = world_p.get_x();
5034        let wz_orig: f32 = world_p.get_z();
5035        let pixel_foot: f32 = depth * frame_context.inv_height * 2.15;
5036        let mut wx: f32 = wx_orig;
5037        let mut wz: f32 = wz_orig;
5038        let mut wave_h: f32 = 0.0;
5039        let mut dh_dx: f32 = 0.0;
5040        let mut dh_dz: f32 = 0.0;
5041        for wave in OCEAN3D_WAVE_SPECTRUM.iter() {
5042            let freq: f32 = wave[2];
5043            let aa_arg: f32 = pixel_foot * freq * 0.30;
5044            if aa_arg > 3.8 {
5045                break;
5046            }
5047            let dir_x: f32 = wave[0];
5048            let dir_z: f32 = wave[1];
5049            let amp: f32 = wave[3];
5050            let aa_sq: f32 = aa_arg * aa_arg;
5051            let aa_w: f32 = 1.0 / (1.0 + aa_sq);
5052            let phase: f32 = (wx * dir_x + wz * dir_z) * freq + sim_t * wave[4];
5053            let (sin_p, cos_p): (f32, f32) = Self::fast_sin_cos_3d(phase);
5054            let sharp_e: f32 = Self::fast_exp_neg_3d(1.0 - sin_p);
5055            wave_h += amp * (sharp_e - 0.40) * aa_w;
5056            let slope: f32 = amp * freq * sharp_e * cos_p * aa_w;
5057            dh_dx += slope * dir_x;
5058            dh_dz += slope * dir_z;
5059            let warp_s: f32 = cos_p * amp * 0.78 * aa_w;
5060            wx += warp_s * dir_x;
5061            wz += warp_s * dir_z;
5062        }
5063        if pixel_foot < 0.90 {
5064            let cap_aa: f32 = 1.0 / (1.0 + (pixel_foot * 3.8) * (pixel_foot * 3.8));
5065            let c1: f32 = Self::fast_sin_cos_3d(wx_orig * 2.6 + wz_orig * 3.8 + sim_t * 3.4).1
5066                * 0.085
5067                * cap_aa;
5068            let c2: f32 = Self::fast_sin_cos_3d(-wx_orig * 3.4 + wz_orig * 4.2 - sim_t * 4.1).1
5069                * 0.068
5070                * cap_aa;
5071            dh_dx += c1 * 0.58 - c2 * 0.62;
5072            dh_dz += c1 * 0.81 + c2 * 0.78;
5073        }
5074        let near_steep: f32 = 1.48 + 0.58 * Self::fast_exp_neg_3d(depth * 0.015);
5075        dh_dx *= near_steep;
5076        dh_dz *= near_steep;
5077        let inv_nlen: f32 = 1.0 / (dh_dx * dh_dx + 1.0 + dh_dz * dh_dz).sqrt();
5078        let nx: f32 = -dh_dx * inv_nlen;
5079        let ny: f32 = inv_nlen;
5080        let nz: f32 = -dh_dz * inv_nlen;
5081        let vx: f32 = view_dir.get_x();
5082        let vy: f32 = view_dir.get_y();
5083        let vz: f32 = view_dir.get_z();
5084        let ndv: f32 = (nx * vx + ny * vy + nz * vz).clamp(0.004, 1.0);
5085        let om_ndv: f32 = 1.0 - ndv;
5086        let om2: f32 = om_ndv * om_ndv;
5087        let fresnel: f32 = (0.0204 + 0.9796 * om2 * om2 * om_ndv).clamp(0.024, 0.84);
5088        let two_ndv: f32 = 2.0 * ndv;
5089        let refl_dir: Vec3 = Vec3::new(
5090            two_ndv * nx - vx,
5091            (two_ndv * ny - vy).max(0.010),
5092            two_ndv * nz - vz,
5093        );
5094        let sky_raw: Vec3 = Self::sample_sky_lut(sky_lut, refl_dir, &frame_context.sun);
5095        let sun_dir: Vec3 = frame_context.sun.get_direction();
5096        let sun_col: Vec3 = frame_context.sun.get_color();
5097        let sun_luma: f32 =
5098            (sun_col.get_x() * 0.30 + sun_col.get_y() * 0.55 + sun_col.get_z() * 0.15)
5099                .clamp(0.45, 1.40);
5100        let az_dx: f32 = refl_dir.get_x() - sun_dir.get_x();
5101        let az_dz: f32 = refl_dir.get_z() - sun_dir.get_z();
5102        let az_dist_sq: f32 = az_dx * az_dx + az_dz * az_dz;
5103        let sun_az_glow: f32 = Self::fast_exp_neg_3d(az_dist_sq * 48.0);
5104        let sky_elev: f32 = (refl_dir.get_y() * 2.4).clamp(0.0, 1.0);
5105        let sky_fade: f32 = 1.0 - sky_elev * 0.72;
5106        let marine_refl: Vec3 = Vec3::new(
5107            ((0.003 * sky_fade + 0.18 * sun_az_glow) * sun_luma)
5108                + sky_raw.get_x().min(1.2) * (0.025 + 0.14 * sun_az_glow),
5109            ((0.068 * sky_fade + 0.16 * sun_az_glow) * sun_luma)
5110                + sky_raw.get_y().min(1.2) * (0.12 + 0.10 * sun_az_glow),
5111            ((0.142 * sky_fade + 0.11 * sun_az_glow) * sun_luma)
5112                + sky_raw.get_z().min(1.2) * (0.20 + 0.08 * sun_az_glow),
5113        );
5114        let near_sss: f32 = 0.24 + 0.76 * Self::fast_exp_neg_3d(depth * 0.0065);
5115        let crest_elev: f32 = ((wave_h + 0.075) * 3.35).clamp(0.0, 1.0);
5116        let sss_back: f32 =
5117            (-(vx * sun_dir.get_x() + vy * sun_dir.get_y() + vz * sun_dir.get_z()) * 0.5 + 0.5)
5118                .clamp(0.0, 1.0);
5119        let sss_term: f32 = crest_elev * crest_elev * (0.42 + 0.58 * sss_back) * near_sss;
5120        let caustic: f32 = if depth < 76.0 {
5121            let cf: f32 = Self::fast_exp_neg_3d(depth * 0.036) * (1.0 - fresnel);
5122            let c_warp: f32 =
5123                Self::sky_value_noise(wx_orig * 0.24 + sim_t * 0.18, wz_orig * 0.24 - sim_t * 0.14)
5124                    * 2.8;
5125            let ca: f32 =
5126                Self::fast_sin_cos_3d(wx_orig * 0.62 + wz_orig * 0.44 + c_warp + sim_t * 1.15).0;
5127            let cb: f32 = Self::fast_sin_cos_3d(
5128                -wx_orig * 0.48 + wz_orig * 0.78 - c_warp * 0.7 - sim_t * 0.92,
5129            )
5130            .1;
5131            let cn: f32 = (ca * 0.55 + cb * 0.45).abs();
5132            cn * cn * cf * 0.16
5133        } else {
5134            0.0
5135        };
5136        let body_col: Vec3 = Vec3::new(
5137            (0.0004 + 0.0020 * sss_term) * sun_luma,
5138            (0.052 + 0.365 * sss_term + caustic * 0.92) * sun_luma,
5139            (0.105 + 0.480 * sss_term + caustic * 1.14) * sun_luma,
5140        );
5141        let hx_u: f32 = vx + sun_dir.get_x();
5142        let hy_u: f32 = vy + sun_dir.get_y();
5143        let hz_u: f32 = vz + sun_dir.get_z();
5144        let inv_hlen: f32 = 1.0 / (hx_u * hx_u + hy_u * hy_u + hz_u * hz_u).sqrt().max(1.0e-5);
5145        let ndh: f32 = ((nx * hx_u + ny * hy_u + nz * hz_u) * inv_hlen).max(0.0);
5146        let ndh2: f32 = ndh * ndh;
5147        let a1_sq: f32 = 0.000_095;
5148        let d1_den: f32 = ndh2 * (a1_sq - 1.0) + 1.0;
5149        let ggx_tight: f32 = (a1_sq / (PI * d1_den * d1_den)).min(28.0);
5150        let a2_sq: f32 = 0.000_52;
5151        let d2_den: f32 = ndh2 * (a2_sq - 1.0) + 1.0;
5152        let ggx_mid: f32 = (a2_sq / (PI * d2_den * d2_den)).min(5.2);
5153        let glint_t: f32 = ((ndh - 0.980) * (1.0 / 0.018)).clamp(0.0, 1.0);
5154        let glint_sharp: f32 = glint_t * glint_t * (3.0 - 2.0 * glint_t);
5155        let spec_scale: f32 =
5156            (ggx_tight * 0.56 + ggx_mid * 0.12 + glint_sharp * 0.68) * (0.45 + 0.55 * shadow);
5157        let spec_col: Vec3 = sun_col.scale(spec_scale);
5158        let near_shore_rt: f32 = Self::fast_exp_neg_3d(depth * 0.026) * 0.24;
5159        let combined_refl: Vec3 = marine_refl.lerp(rt_refl, near_shore_rt);
5160        let refl_weight: f32 = (fresnel * 0.50 + 0.022).clamp(0.022, 0.58);
5161        let mut col: Vec3 = body_col.lerp(combined_refl, refl_weight).add(spec_col);
5162        let dx_shore: f32 = (wx_orig.abs() - CITY_ISLAND_HALF_X).max(0.0);
5163        let dz_shore: f32 = (CITY_ISLAND_Z_MIN - wz_orig)
5164            .max(0.0)
5165            .max((wz_orig - CITY_ISLAND_Z_MAX).max(0.0));
5166        if dx_shore < 4.8 && dz_shore < 4.8 {
5167            let shore_dist: f32 = (dx_shore * dx_shore + dz_shore * dz_shore).sqrt();
5168            if shore_dist < 4.8 {
5169                let surge: f32 =
5170                    Self::fast_sin_cos_3d(sim_t * 2.1 + wx_orig * 0.35 + wz_orig * 0.35).0 * 0.55;
5171                let eff_dist: f32 = (shore_dist + surge).max(0.0);
5172                let band_lin: f32 = 1.0 - (eff_dist * (1.0 / 3.6)).clamp(0.0, 1.0);
5173                let foam_band: f32 = band_lin * band_lin;
5174                let lacy_a: f32 = Self::sky_value_noise(wx_orig * 1.45 + 3.7, wz_orig * 1.45 - 2.1);
5175                let lacy_b: f32 = Self::sky_value_noise(
5176                    wx_orig * 3.8 - sim_t * 0.55,
5177                    wz_orig * 3.8 + sim_t * 0.42,
5178                );
5179                let foam_t: f32 = ((lacy_a * 0.55 + lacy_b * 0.45 - 0.36) * 2.4).clamp(0.0, 1.0);
5180                let foam_alpha: f32 =
5181                    (foam_band * (0.28 + 0.72 * foam_t * foam_t * (3.0 - 2.0 * foam_t)) * 0.84)
5182                        .clamp(0.0, 0.85);
5183                if foam_alpha > 0.01 {
5184                    let foam_col: Vec3 = Vec3::new(0.84, 0.90, 0.94).scale(0.65 + 0.45 * sun_luma);
5185                    col = col.lerp(foam_col, foam_alpha);
5186                }
5187            }
5188        }
5189        if frame_context.fog_on {
5190            let fog_t: f32 = (1.0 - Self::fast_exp_neg_3d(depth * 0.000_65)).clamp(0.0, 0.22);
5191            if fog_t > 0.005 {
5192                let horiz_raw: Vec3 = frame_context.sun.get_sky_horizon();
5193                let marine_mist: Vec3 = Vec3::new(
5194                    (0.010 + 0.06 * sun_az_glow) * sun_luma + horiz_raw.get_x().min(1.0) * 0.05,
5195                    (0.068 + 0.05 * sun_az_glow) * sun_luma + horiz_raw.get_y().min(1.0) * 0.12,
5196                    (0.118 + 0.04 * sun_az_glow) * sun_luma + horiz_raw.get_z().min(1.0) * 0.18,
5197                );
5198                col = col.lerp(marine_mist, fog_t);
5199            }
5200        }
5201        col
5202    }
5203
5204    /// Evaluates a pipelined 4-wide reciprocal `1.0 / x` via NEON estimate plus one Newton-Raphson refinement (~22-bit precision, eliminating divider stalls).
5205    ///
5206    /// # Arguments
5207    ///
5208    /// - `core::arch::aarch64::float32x4_t` - Strictly positive denominator vector `x`.
5209    ///
5210    /// # Returns
5211    ///
5212    /// - `core::arch::aarch64::float32x4_t` - Refined 4-wide reciprocal `1.0 / x`.
5213    #[cfg(target_arch = "aarch64")]
5214    #[inline(always)]
5215    pub(crate) unsafe fn neon_rcp_4x(
5216        pos_x: core::arch::aarch64::float32x4_t,
5217    ) -> core::arch::aarch64::float32x4_t {
5218        // SAFETY: Caller guarantees ARM64 NEON execution context and positive `x`.
5219        unsafe {
5220            let est: core::arch::aarch64::float32x4_t = core::arch::aarch64::vrecpeq_f32(pos_x);
5221            core::arch::aarch64::vmulq_f32(est, core::arch::aarch64::vrecpsq_f32(pos_x, est))
5222        }
5223    }
5224
5225    /// 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`.
5226    ///
5227    /// # Arguments
5228    ///
5229    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and fog configuration.
5230    /// - `&GShadeTri` - Precomputed triangle PBR record shared by the run.
5231    /// - `(Vec3, Vec3)` - Starting unnormalized primary ray and horizontal ray step `(raw_ray, ray_dx)`.
5232    /// - `(&RunScratch32, usize)` - L1-hot run scratch and 4-pixel-aligned lane offset `off <= 28`.
5233    /// - `SpanShadeOut<'_>` - Writable 16-byte RGBA, 4-byte luma, and optional HDR bloom slot.
5234    ///
5235    /// # Returns
5236    ///
5237    /// - `bool` - `true` when the optional bloom slot received non-zero HDR excess radiance.
5238    #[inline(always)]
5239    fn shade_span_4x_specialized<const DETAIL: u8>(
5240        frame_context: &DeferredFrameContext,
5241        tri: &GShadeTri,
5242        rays: (Vec3, Vec3),
5243        src_run: (&RunScratch32, usize),
5244        dst: SpanShadeOut<'_>,
5245    ) -> bool {
5246        let (raw_ray, ray_dx): (Vec3, Vec3) = rays;
5247        let (run, off): (&RunScratch32, usize) = src_run;
5248        let SpanShadeOut {
5249            rgba: c_dst,
5250            luma: l_dst,
5251            bloom: bloom_slot,
5252        } = dst;
5253        let sun_dir: Vec3 = frame_context.sun.get_direction();
5254        let sun_col: Vec3 = frame_context.sun.get_color();
5255        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
5256        let sn: Vec3 = tri.shade_n;
5257        let mut exp_r_arr: [f32; 4] = [0.0; 4];
5258        let mut exp_g_arr: [f32; 4] = [0.0; 4];
5259        let mut exp_b_arr: [f32; 4] = [0.0; 4];
5260        #[cfg(target_arch = "aarch64")]
5261        {
5262            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; NEON is mandatory on `aarch64`.
5263            unsafe {
5264                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
5265                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
5266                let two: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(2.0);
5267                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5268                let lane_idx: core::arch::aarch64::float32x4_t =
5269                    core::arch::aarch64::vld1q_f32(lane_idx_arr.as_ptr());
5270                let rx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5271                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_x()),
5272                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_x()),
5273                    lane_idx,
5274                );
5275                let ry: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5276                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_y()),
5277                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_y()),
5278                    lane_idx,
5279                );
5280                let rz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5281                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_z()),
5282                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_z()),
5283                    lane_idx,
5284                );
5285                let len_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5286                    core::arch::aarch64::vfmaq_f32(
5287                        core::arch::aarch64::vfmaq_f32(
5288                            core::arch::aarch64::vmulq_f32(rz, rz),
5289                            ry,
5290                            ry,
5291                        ),
5292                        rx,
5293                        rx,
5294                    ),
5295                    core::arch::aarch64::vdupq_n_f32(1e-12),
5296                );
5297                let mut inv_l: core::arch::aarch64::float32x4_t =
5298                    core::arch::aarch64::vrsqrteq_f32(len_sq);
5299                inv_l = core::arch::aarch64::vmulq_f32(
5300                    inv_l,
5301                    core::arch::aarch64::vrsqrtsq_f32(
5302                        core::arch::aarch64::vmulq_f32(len_sq, inv_l),
5303                        inv_l,
5304                    ),
5305                );
5306                let ndv_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5307                    core::arch::aarch64::vdupq_n_f32(-sn.dot(raw_ray)),
5308                    core::arch::aarch64::vdupq_n_f32(-sn.dot(ray_dx)),
5309                    lane_idx,
5310                );
5311                let ndv_raw: core::arch::aarch64::float32x4_t =
5312                    core::arch::aarch64::vmulq_f32(ndv_num, inv_l);
5313                let ndv: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5314                    core::arch::aarch64::vmaxq_f32(ndv_raw, core::arch::aarch64::vdupq_n_f32(0.02)),
5315                    one,
5316                );
5317                let f_om: core::arch::aarch64::float32x4_t =
5318                    core::arch::aarch64::vsubq_f32(one, ndv);
5319                let f_om2: core::arch::aarch64::float32x4_t =
5320                    core::arch::aarch64::vmulq_f32(f_om, f_om);
5321                let fresnel_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5322                    core::arch::aarch64::vmulq_f32(f_om2, f_om2),
5323                    f_om,
5324                );
5325                let vdl_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5326                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(raw_ray)),
5327                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(ray_dx)),
5328                    lane_idx,
5329                );
5330                let vdl: core::arch::aarch64::float32x4_t =
5331                    core::arch::aarch64::vmulq_f32(vdl_num, inv_l);
5332                let sh_v: core::arch::aarch64::float32x4_t =
5333                    core::arch::aarch64::vld1q_f32(run.shadow.as_ptr().add(off));
5334                let (spec_r, spec_g, spec_b): (
5335                    core::arch::aarch64::float32x4_t,
5336                    core::arch::aarch64::float32x4_t,
5337                    core::arch::aarch64::float32x4_t,
5338                ) = if tri.n_dot_l > 0.0 {
5339                    let ndl_v: core::arch::aarch64::float32x4_t =
5340                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l);
5341                    let ndh_u: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5342                        core::arch::aarch64::vaddq_f32(ndl_v, ndv_raw),
5343                        zero,
5344                    );
5345                    let h_lsq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5346                        core::arch::aarch64::vfmaq_f32(two, two, vdl),
5347                        core::arch::aarch64::vdupq_n_f32(1e-6),
5348                    );
5349                    let ndh_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5350                        core::arch::aarch64::vmulq_f32(ndh_u, ndh_u),
5351                        Self::neon_rcp_4x(h_lsq),
5352                    );
5353                    let ggx_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5354                        one,
5355                        ndh_sq,
5356                        core::arch::aarch64::vdupq_n_f32(tri.alpha2 - 1.0),
5357                    );
5358                    let ggx_term: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5359                        core::arch::aarch64::vdupq_n_f32(1e-4),
5360                        core::arch::aarch64::vmulq_f32(ggx_den, ggx_den),
5361                        core::arch::aarch64::vdupq_n_f32(PI),
5362                    );
5363                    let vis_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5364                        core::arch::aarch64::vdupq_n_f32(0.08),
5365                        ndv,
5366                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l.max(0.06)),
5367                    );
5368                    let spec_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5369                        core::arch::aarch64::vdupq_n_f32(0.25 * tri.alpha2 * tri.n_dot_l),
5370                        sh_v,
5371                    );
5372                    let spec_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5373                        core::arch::aarch64::vmulq_f32(
5374                            spec_num,
5375                            Self::neon_rcp_4x(core::arch::aarch64::vmulq_f32(ggx_term, vis_den)),
5376                        ),
5377                        core::arch::aarch64::vdupq_n_f32(4.5),
5378                    );
5379                    let fr_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5380                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_x()),
5381                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_x()),
5382                        fresnel_t,
5383                    );
5384                    let fr_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5385                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_y()),
5386                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_y()),
5387                        fresnel_t,
5388                    );
5389                    let fr_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5390                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_z()),
5391                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_z()),
5392                        fresnel_t,
5393                    );
5394                    (
5395                        core::arch::aarch64::vmulq_f32(
5396                            fr_r,
5397                            core::arch::aarch64::vmulq_f32(
5398                                core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5399                                spec_s,
5400                            ),
5401                        ),
5402                        core::arch::aarch64::vmulq_f32(
5403                            fr_g,
5404                            core::arch::aarch64::vmulq_f32(
5405                                core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5406                                spec_s,
5407                            ),
5408                        ),
5409                        core::arch::aarch64::vmulq_f32(
5410                            fr_b,
5411                            core::arch::aarch64::vmulq_f32(
5412                                core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5413                                spec_s,
5414                            ),
5415                        ),
5416                    )
5417                } else {
5418                    (zero, zero, zero)
5419                };
5420                let d_v: core::arch::aarch64::float32x4_t =
5421                    core::arch::aarch64::vld1q_f32(run.depths.as_ptr().add(off));
5422                let wpy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5423                    core::arch::aarch64::vdupq_n_f32(frame_context.camera_position.get_y()),
5424                    ry,
5425                    d_v,
5426                );
5427                let mut sb_r: core::arch::aarch64::float32x4_t =
5428                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_x());
5429                let mut sb_g: core::arch::aarch64::float32x4_t =
5430                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_y());
5431                let mut sb_b: core::arch::aarch64::float32x4_t =
5432                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_z());
5433                let mut em_r: core::arch::aarch64::float32x4_t =
5434                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_x());
5435                let mut em_g: core::arch::aarch64::float32x4_t =
5436                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_y());
5437                let mut em_b: core::arch::aarch64::float32x4_t =
5438                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_z());
5439                let mut s_refl: core::arch::aarch64::float32x4_t =
5440                    core::arch::aarch64::vdupq_n_f32(tri.mat_refl);
5441                if DETAIL == 2 {
5442                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
5443                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
5444                        wall_tan_x,
5445                        frame_context.camera_position.get_z() * wall_tan_z,
5446                    );
5447                    let ray_u: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5448                        core::arch::aarch64::vmulq_n_f32(rx, wall_tan_x),
5449                        rz,
5450                        core::arch::aarch64::vdupq_n_f32(wall_tan_z),
5451                    );
5452                    let u_coord_v: core::arch::aarch64::float32x4_t =
5453                        core::arch::aarch64::vfmaq_f32(
5454                            core::arch::aarch64::vdupq_n_f32(cam_u),
5455                            ray_u,
5456                            d_v,
5457                        );
5458                    let mut u_a: [f32; 4] = [0.0; 4];
5459                    let mut y_a: [f32; 4] = [0.0; 4];
5460                    let mut d_a: [f32; 4] = [0.0; 4];
5461                    core::arch::aarch64::vst1q_f32(u_a.as_mut_ptr(), u_coord_v);
5462                    core::arch::aarch64::vst1q_f32(y_a.as_mut_ptr(), wpy);
5463                    core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5464                    let mut nr_a: [f32; 4] = [0.0; 4];
5465                    let mut ng_a: [f32; 4] = [0.0; 4];
5466                    let mut nb_a: [f32; 4] = [0.0; 4];
5467                    let mut er_a: [f32; 4] = [0.0; 4];
5468                    let mut eg_a: [f32; 4] = [0.0; 4];
5469                    let mut eb_a: [f32; 4] = [0.0; 4];
5470                    let mut rf_a: [f32; 4] = [0.0; 4];
5471                    for lane in 0..4usize {
5472                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5473                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5474                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5475                        );
5476                        nr_a[lane] = sb.get_x();
5477                        ng_a[lane] = sb.get_y();
5478                        nb_a[lane] = sb.get_z();
5479                        er_a[lane] = em.get_x();
5480                        eg_a[lane] = em.get_y();
5481                        eb_a[lane] = em.get_z();
5482                        rf_a[lane] = rf;
5483                    }
5484                    sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5485                    sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5486                    sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5487                    em_r = core::arch::aarch64::vld1q_f32(er_a.as_ptr());
5488                    em_g = core::arch::aarch64::vld1q_f32(eg_a.as_ptr());
5489                    em_b = core::arch::aarch64::vld1q_f32(eb_a.as_ptr());
5490                    s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5491                } else if DETAIL == 1 {
5492                    let m_r: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
5493                        core::arch::aarch64::vabsq_f32(wpy),
5494                        core::arch::aarch64::vdupq_n_f32(0.15),
5495                    );
5496                    if core::arch::aarch64::vmaxvq_u32(m_r) != 0 {
5497                        let wpx_v: core::arch::aarch64::float32x4_t =
5498                            core::arch::aarch64::vfmaq_f32(
5499                                core::arch::aarch64::vdupq_n_f32(
5500                                    frame_context.camera_position.get_x(),
5501                                ),
5502                                rx,
5503                                d_v,
5504                            );
5505                        let wpz_v: core::arch::aarch64::float32x4_t =
5506                            core::arch::aarch64::vfmaq_f32(
5507                                core::arch::aarch64::vdupq_n_f32(
5508                                    frame_context.camera_position.get_z(),
5509                                ),
5510                                rz,
5511                                d_v,
5512                            );
5513                        let mut x_a: [f32; 4] = [0.0; 4];
5514                        let mut z_a: [f32; 4] = [0.0; 4];
5515                        let mut d_a: [f32; 4] = [0.0; 4];
5516                        let mut rx_a: [f32; 4] = [0.0; 4];
5517                        let mut ry_a: [f32; 4] = [0.0; 4];
5518                        let mut rz_a: [f32; 4] = [0.0; 4];
5519                        let mut ft_a: [f32; 4] = [0.0; 4];
5520                        let mut m_a: [u32; 4] = [0; 4];
5521                        core::arch::aarch64::vst1q_f32(x_a.as_mut_ptr(), wpx_v);
5522                        core::arch::aarch64::vst1q_f32(z_a.as_mut_ptr(), wpz_v);
5523                        core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5524                        core::arch::aarch64::vst1q_f32(rx_a.as_mut_ptr(), rx);
5525                        core::arch::aarch64::vst1q_f32(ry_a.as_mut_ptr(), ry);
5526                        core::arch::aarch64::vst1q_f32(rz_a.as_mut_ptr(), rz);
5527                        core::arch::aarch64::vst1q_f32(ft_a.as_mut_ptr(), fresnel_t);
5528                        core::arch::aarch64::vst1q_u32(m_a.as_mut_ptr(), m_r);
5529                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
5530                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
5531                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
5532                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
5533                        for lane in 0..4usize {
5534                            if m_a[lane] != 0 {
5535                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
5536                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
5537                                    (
5538                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
5539                                        ft_a[lane],
5540                                        tri.metallic,
5541                                        frame_context.world_time_secs,
5542                                    ),
5543                                    tri.mat_base,
5544                                );
5545                                nr_a[lane] = sb.get_x();
5546                                ng_a[lane] = sb.get_y();
5547                                nb_a[lane] = sb.get_z();
5548                                rf_a[lane] = rf;
5549                            }
5550                        }
5551                        sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5552                        sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5553                        sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5554                        s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5555                    }
5556                }
5557                let kd_scale: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5558                    core::arch::aarch64::vmulq_f32(
5559                        core::arch::aarch64::vdupq_n_f32(tri.diffuse_scale),
5560                        core::arch::aarch64::vfmsq_f32(
5561                            one,
5562                            fresnel_t,
5563                            core::arch::aarch64::vdupq_n_f32(0.55),
5564                        ),
5565                    ),
5566                    core::arch::aarch64::vdupq_n_f32(0.08),
5567                );
5568                let dir_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5569                    core::arch::aarch64::vmulq_f32(
5570                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l),
5571                        sh_v,
5572                    ),
5573                    kd_scale,
5574                );
5575                let ao_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5576                    core::arch::aarch64::vld1q_f32(run.ao.as_ptr().add(off)),
5577                    core::arch::aarch64::vdupq_n_f32(0.44),
5578                );
5579                let lit_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5580                    core::arch::aarch64::vfmaq_f32(
5581                        core::arch::aarch64::vld1q_f32(run.gi_r.as_ptr().add(off)),
5582                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_x()),
5583                        ao_s,
5584                    ),
5585                    core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5586                    dir_s,
5587                );
5588                let lit_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5589                    core::arch::aarch64::vfmaq_f32(
5590                        core::arch::aarch64::vld1q_f32(run.gi_g.as_ptr().add(off)),
5591                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_y()),
5592                        ao_s,
5593                    ),
5594                    core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5595                    dir_s,
5596                );
5597                let lit_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5598                    core::arch::aarch64::vfmaq_f32(
5599                        core::arch::aarch64::vld1q_f32(run.gi_b.as_ptr().add(off)),
5600                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_z()),
5601                        ao_s,
5602                    ),
5603                    core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5604                    dir_s,
5605                );
5606                let mut rad_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5607                    core::arch::aarch64::vfmaq_f32(spec_r, sb_r, lit_r),
5608                    em_r,
5609                );
5610                let mut rad_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5611                    core::arch::aarch64::vfmaq_f32(spec_g, sb_g, lit_g),
5612                    em_g,
5613                );
5614                let mut rad_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5615                    core::arch::aarch64::vfmaq_f32(spec_b, sb_b, lit_b),
5616                    em_b,
5617                );
5618                if tri.do_refl {
5619                    let refl_f: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5620                        core::arch::aarch64::vmaxq_f32(
5621                            core::arch::aarch64::vfmaq_f32(
5622                                core::arch::aarch64::vdupq_n_f32(0.18 + tri.metallic * 0.25),
5623                                fresnel_t,
5624                                core::arch::aarch64::vdupq_n_f32(0.82),
5625                            ),
5626                            core::arch::aarch64::vdupq_n_f32(0.18),
5627                        ),
5628                        core::arch::aarch64::vdupq_n_f32(0.95),
5629                    );
5630                    let refl_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5631                        core::arch::aarch64::vmaxq_f32(
5632                            core::arch::aarch64::vmulq_f32(s_refl, refl_f),
5633                            zero,
5634                        ),
5635                        core::arch::aarch64::vdupq_n_f32(0.82),
5636                    );
5637                    let rr_v: core::arch::aarch64::float32x4_t =
5638                        core::arch::aarch64::vld1q_f32(run.refl_r.as_ptr().add(off));
5639                    let rg_v: core::arch::aarch64::float32x4_t =
5640                        core::arch::aarch64::vld1q_f32(run.refl_g.as_ptr().add(off));
5641                    let rb_v: core::arch::aarch64::float32x4_t =
5642                        core::arch::aarch64::vld1q_f32(run.refl_b.as_ptr().add(off));
5643                    rad_r = Self::neon_lerp_4x(rad_r, rr_v, refl_b);
5644                    rad_g = Self::neon_lerp_4x(rad_g, rg_v, refl_b);
5645                    rad_b = Self::neon_lerp_4x(rad_b, rb_v, refl_b);
5646                }
5647                if frame_context.fog_on {
5648                    let pos_y: core::arch::aarch64::float32x4_t =
5649                        core::arch::aarch64::vmaxq_f32(wpy, zero);
5650                    let h_att: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5651                        Self::neon_rcp_4x(core::arch::aarch64::vfmaq_f32(
5652                            one,
5653                            pos_y,
5654                            core::arch::aarch64::vdupq_n_f32(0.045),
5655                        )),
5656                        core::arch::aarch64::vdupq_n_f32(0.32),
5657                    );
5658                    let fd: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5659                        core::arch::aarch64::vmulq_f32(
5660                            d_v,
5661                            core::arch::aarch64::vdupq_n_f32(frame_context.inv_fog_distance),
5662                        ),
5663                        h_att,
5664                    );
5665                    let fog_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5666                        core::arch::aarch64::vmaxq_f32(
5667                            core::arch::aarch64::vmulq_f32(
5668                                fd,
5669                                Self::neon_rcp_4x(core::arch::aarch64::vaddq_f32(one, fd)),
5670                            ),
5671                            zero,
5672                        ),
5673                        core::arch::aarch64::vdupq_n_f32(0.85),
5674                    );
5675                    let sun_align: core::arch::aarch64::float32x4_t =
5676                        core::arch::aarch64::vmaxq_f32(core::arch::aarch64::vnegq_f32(vdl), zero);
5677                    let sa2: core::arch::aarch64::float32x4_t =
5678                        core::arch::aarch64::vmulq_f32(sun_align, sun_align);
5679                    let shaft55: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5680                        core::arch::aarch64::vmulq_f32(
5681                            core::arch::aarch64::vmulq_f32(sa2, sa2),
5682                            fog_t,
5683                        ),
5684                        core::arch::aarch64::vfmaq_f32(
5685                            core::arch::aarch64::vdupq_n_f32(0.35 * 0.55),
5686                            sh_v,
5687                            core::arch::aarch64::vdupq_n_f32(0.65 * 0.55),
5688                        ),
5689                    );
5690                    let fog_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5691                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_x()),
5692                        core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5693                        shaft55,
5694                    );
5695                    let fog_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5696                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_y()),
5697                        core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5698                        shaft55,
5699                    );
5700                    let fog_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5701                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_z()),
5702                        core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5703                        shaft55,
5704                    );
5705                    rad_r = Self::neon_lerp_4x(rad_r, fog_r, fog_t);
5706                    rad_g = Self::neon_lerp_4x(rad_g, fog_g, fog_t);
5707                    rad_b = Self::neon_lerp_4x(rad_b, fog_b, fog_t);
5708                }
5709                let exp_s: core::arch::aarch64::float32x4_t =
5710                    core::arch::aarch64::vdupq_n_f32(frame_context.exposure_scale);
5711                core::arch::aarch64::vst1q_f32(
5712                    exp_r_arr.as_mut_ptr(),
5713                    core::arch::aarch64::vmulq_f32(rad_r, exp_s),
5714                );
5715                core::arch::aarch64::vst1q_f32(
5716                    exp_g_arr.as_mut_ptr(),
5717                    core::arch::aarch64::vmulq_f32(rad_g, exp_s),
5718                );
5719                core::arch::aarch64::vst1q_f32(
5720                    exp_b_arr.as_mut_ptr(),
5721                    core::arch::aarch64::vmulq_f32(rad_b, exp_s),
5722                );
5723            }
5724        }
5725        #[cfg(target_arch = "x86_64")]
5726        {
5727            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; SSE2 is mandatory on `x86_64`.
5728            unsafe {
5729                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
5730                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
5731                let two: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(2.0);
5732                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
5733                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5734                let lane_idx: core::arch::x86_64::__m128 =
5735                    core::arch::x86_64::_mm_loadu_ps(lane_idx_arr.as_ptr());
5736                let rx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5737                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_x()),
5738                    core::arch::x86_64::_mm_mul_ps(
5739                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_x()),
5740                        lane_idx,
5741                    ),
5742                );
5743                let ry: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5744                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_y()),
5745                    core::arch::x86_64::_mm_mul_ps(
5746                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_y()),
5747                        lane_idx,
5748                    ),
5749                );
5750                let rz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5751                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_z()),
5752                    core::arch::x86_64::_mm_mul_ps(
5753                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_z()),
5754                        lane_idx,
5755                    ),
5756                );
5757                let len_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5758                    core::arch::x86_64::_mm_add_ps(
5759                        core::arch::x86_64::_mm_add_ps(
5760                            core::arch::x86_64::_mm_mul_ps(rx, rx),
5761                            core::arch::x86_64::_mm_mul_ps(ry, ry),
5762                        ),
5763                        core::arch::x86_64::_mm_mul_ps(rz, rz),
5764                    ),
5765                    core::arch::x86_64::_mm_set1_ps(1e-12),
5766                );
5767                let est: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_rsqrt_ps(len_sq);
5768                let inv_l: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5769                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(0.5), est),
5770                    core::arch::x86_64::_mm_sub_ps(
5771                        core::arch::x86_64::_mm_set1_ps(3.0),
5772                        core::arch::x86_64::_mm_mul_ps(
5773                            core::arch::x86_64::_mm_mul_ps(len_sq, est),
5774                            est,
5775                        ),
5776                    ),
5777                );
5778                let ndv_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5779                    core::arch::x86_64::_mm_set1_ps(-sn.dot(raw_ray)),
5780                    core::arch::x86_64::_mm_mul_ps(
5781                        core::arch::x86_64::_mm_set1_ps(-sn.dot(ray_dx)),
5782                        lane_idx,
5783                    ),
5784                );
5785                let ndv_raw: core::arch::x86_64::__m128 =
5786                    core::arch::x86_64::_mm_mul_ps(ndv_num, inv_l);
5787                let ndv: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5788                    core::arch::x86_64::_mm_max_ps(ndv_raw, core::arch::x86_64::_mm_set1_ps(0.02)),
5789                    one,
5790                );
5791                let f_om: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(one, ndv);
5792                let f_om2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(f_om, f_om);
5793                let fresnel_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5794                    core::arch::x86_64::_mm_mul_ps(f_om2, f_om2),
5795                    f_om,
5796                );
5797                let vdl_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5798                    core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(raw_ray)),
5799                    core::arch::x86_64::_mm_mul_ps(
5800                        core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(ray_dx)),
5801                        lane_idx,
5802                    ),
5803                );
5804                let vdl: core::arch::x86_64::__m128 =
5805                    core::arch::x86_64::_mm_mul_ps(vdl_num, inv_l);
5806                let sh_v: core::arch::x86_64::__m128 =
5807                    core::arch::x86_64::_mm_loadu_ps(run.shadow.as_ptr().add(off));
5808                let (spec_r, spec_g, spec_b): (
5809                    core::arch::x86_64::__m128,
5810                    core::arch::x86_64::__m128,
5811                    core::arch::x86_64::__m128,
5812                ) = if tri.n_dot_l > 0.0 {
5813                    let ndl_v: core::arch::x86_64::__m128 =
5814                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l);
5815                    let ndh_u: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5816                        core::arch::x86_64::_mm_add_ps(ndl_v, ndv_raw),
5817                        zero,
5818                    );
5819                    let h_lsq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5820                        core::arch::x86_64::_mm_add_ps(
5821                            two,
5822                            core::arch::x86_64::_mm_mul_ps(two, vdl),
5823                        ),
5824                        core::arch::x86_64::_mm_set1_ps(1e-6),
5825                    );
5826                    let ndh_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_div_ps(
5827                        core::arch::x86_64::_mm_mul_ps(ndh_u, ndh_u),
5828                        h_lsq,
5829                    );
5830                    let ggx_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5831                        one,
5832                        core::arch::x86_64::_mm_mul_ps(
5833                            ndh_sq,
5834                            core::arch::x86_64::_mm_set1_ps(tri.alpha2 - 1.0),
5835                        ),
5836                    );
5837                    let ggx_term: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5838                        core::arch::x86_64::_mm_set1_ps(1e-4),
5839                        core::arch::x86_64::_mm_mul_ps(
5840                            core::arch::x86_64::_mm_mul_ps(ggx_den, ggx_den),
5841                            core::arch::x86_64::_mm_set1_ps(PI),
5842                        ),
5843                    );
5844                    let vis_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5845                        core::arch::x86_64::_mm_set1_ps(0.08),
5846                        core::arch::x86_64::_mm_mul_ps(
5847                            ndv,
5848                            core::arch::x86_64::_mm_set1_ps(tri.n_dot_l.max(0.06)),
5849                        ),
5850                    );
5851                    let spec_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5852                        core::arch::x86_64::_mm_set1_ps(0.25 * tri.alpha2 * tri.n_dot_l),
5853                        sh_v,
5854                    );
5855                    let spec_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5856                        core::arch::x86_64::_mm_div_ps(
5857                            spec_num,
5858                            core::arch::x86_64::_mm_mul_ps(ggx_term, vis_den),
5859                        ),
5860                        core::arch::x86_64::_mm_set1_ps(4.5),
5861                    );
5862                    let fr_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5863                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_x()),
5864                        core::arch::x86_64::_mm_mul_ps(
5865                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_x()),
5866                            fresnel_t,
5867                        ),
5868                    );
5869                    let fr_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5870                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_y()),
5871                        core::arch::x86_64::_mm_mul_ps(
5872                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_y()),
5873                            fresnel_t,
5874                        ),
5875                    );
5876                    let fr_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5877                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_z()),
5878                        core::arch::x86_64::_mm_mul_ps(
5879                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_z()),
5880                            fresnel_t,
5881                        ),
5882                    );
5883                    (
5884                        core::arch::x86_64::_mm_mul_ps(
5885                            fr_r,
5886                            core::arch::x86_64::_mm_mul_ps(
5887                                core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5888                                spec_s,
5889                            ),
5890                        ),
5891                        core::arch::x86_64::_mm_mul_ps(
5892                            fr_g,
5893                            core::arch::x86_64::_mm_mul_ps(
5894                                core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5895                                spec_s,
5896                            ),
5897                        ),
5898                        core::arch::x86_64::_mm_mul_ps(
5899                            fr_b,
5900                            core::arch::x86_64::_mm_mul_ps(
5901                                core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5902                                spec_s,
5903                            ),
5904                        ),
5905                    )
5906                } else {
5907                    (zero, zero, zero)
5908                };
5909                let d_v: core::arch::x86_64::__m128 =
5910                    core::arch::x86_64::_mm_loadu_ps(run.depths.as_ptr().add(off));
5911                let wpy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5912                    core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_y()),
5913                    core::arch::x86_64::_mm_mul_ps(ry, d_v),
5914                );
5915                let mut sb_r: core::arch::x86_64::__m128 =
5916                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_x());
5917                let mut sb_g: core::arch::x86_64::__m128 =
5918                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_y());
5919                let mut sb_b: core::arch::x86_64::__m128 =
5920                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_z());
5921                let mut em_r: core::arch::x86_64::__m128 =
5922                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_x());
5923                let mut em_g: core::arch::x86_64::__m128 =
5924                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_y());
5925                let mut em_b: core::arch::x86_64::__m128 =
5926                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_z());
5927                let mut s_refl: core::arch::x86_64::__m128 =
5928                    core::arch::x86_64::_mm_set1_ps(tri.mat_refl);
5929                if DETAIL == 2 {
5930                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
5931                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
5932                        wall_tan_x,
5933                        frame_context.camera_position.get_z() * wall_tan_z,
5934                    );
5935                    let ray_u: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5936                        core::arch::x86_64::_mm_mul_ps(
5937                            rx,
5938                            core::arch::x86_64::_mm_set1_ps(wall_tan_x),
5939                        ),
5940                        core::arch::x86_64::_mm_mul_ps(
5941                            rz,
5942                            core::arch::x86_64::_mm_set1_ps(wall_tan_z),
5943                        ),
5944                    );
5945                    let u_coord_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5946                        core::arch::x86_64::_mm_set1_ps(cam_u),
5947                        core::arch::x86_64::_mm_mul_ps(ray_u, d_v),
5948                    );
5949                    let mut u_a: [f32; 4] = [0.0; 4];
5950                    let mut y_a: [f32; 4] = [0.0; 4];
5951                    let mut d_a: [f32; 4] = [0.0; 4];
5952                    core::arch::x86_64::_mm_storeu_ps(u_a.as_mut_ptr(), u_coord_v);
5953                    core::arch::x86_64::_mm_storeu_ps(y_a.as_mut_ptr(), wpy);
5954                    core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
5955                    let mut nr_a: [f32; 4] = [0.0; 4];
5956                    let mut ng_a: [f32; 4] = [0.0; 4];
5957                    let mut nb_a: [f32; 4] = [0.0; 4];
5958                    let mut er_a: [f32; 4] = [0.0; 4];
5959                    let mut eg_a: [f32; 4] = [0.0; 4];
5960                    let mut eb_a: [f32; 4] = [0.0; 4];
5961                    let mut rf_a: [f32; 4] = [0.0; 4];
5962                    for lane in 0..4usize {
5963                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5964                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5965                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5966                        );
5967                        nr_a[lane] = sb.get_x();
5968                        ng_a[lane] = sb.get_y();
5969                        nb_a[lane] = sb.get_z();
5970                        er_a[lane] = em.get_x();
5971                        eg_a[lane] = em.get_y();
5972                        eb_a[lane] = em.get_z();
5973                        rf_a[lane] = rf;
5974                    }
5975                    sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
5976                    sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
5977                    sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
5978                    em_r = core::arch::x86_64::_mm_loadu_ps(er_a.as_ptr());
5979                    em_g = core::arch::x86_64::_mm_loadu_ps(eg_a.as_ptr());
5980                    em_b = core::arch::x86_64::_mm_loadu_ps(eb_a.as_ptr());
5981                    s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
5982                } else if DETAIL == 1 {
5983                    let m_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
5984                        core::arch::x86_64::_mm_andnot_ps(abs_mask, wpy),
5985                        core::arch::x86_64::_mm_set1_ps(0.15),
5986                    );
5987                    let m_mask: i32 = core::arch::x86_64::_mm_movemask_ps(m_r);
5988                    if m_mask != 0 {
5989                        let wpx_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5990                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_x()),
5991                            core::arch::x86_64::_mm_mul_ps(rx, d_v),
5992                        );
5993                        let wpz_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5994                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_z()),
5995                            core::arch::x86_64::_mm_mul_ps(rz, d_v),
5996                        );
5997                        let mut x_a: [f32; 4] = [0.0; 4];
5998                        let mut z_a: [f32; 4] = [0.0; 4];
5999                        let mut d_a: [f32; 4] = [0.0; 4];
6000                        let mut rx_a: [f32; 4] = [0.0; 4];
6001                        let mut ry_a: [f32; 4] = [0.0; 4];
6002                        let mut rz_a: [f32; 4] = [0.0; 4];
6003                        let mut ft_a: [f32; 4] = [0.0; 4];
6004                        core::arch::x86_64::_mm_storeu_ps(x_a.as_mut_ptr(), wpx_v);
6005                        core::arch::x86_64::_mm_storeu_ps(z_a.as_mut_ptr(), wpz_v);
6006                        core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
6007                        core::arch::x86_64::_mm_storeu_ps(rx_a.as_mut_ptr(), rx);
6008                        core::arch::x86_64::_mm_storeu_ps(ry_a.as_mut_ptr(), ry);
6009                        core::arch::x86_64::_mm_storeu_ps(rz_a.as_mut_ptr(), rz);
6010                        core::arch::x86_64::_mm_storeu_ps(ft_a.as_mut_ptr(), fresnel_t);
6011                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
6012                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
6013                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
6014                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
6015                        for lane in 0..4usize {
6016                            if (m_mask & (1 << lane)) != 0 {
6017                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
6018                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
6019                                    (
6020                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
6021                                        ft_a[lane],
6022                                        tri.metallic,
6023                                        frame_context.world_time_secs,
6024                                    ),
6025                                    tri.mat_base,
6026                                );
6027                                nr_a[lane] = sb.get_x();
6028                                ng_a[lane] = sb.get_y();
6029                                nb_a[lane] = sb.get_z();
6030                                rf_a[lane] = rf;
6031                            }
6032                        }
6033                        sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
6034                        sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
6035                        sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
6036                        s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
6037                    }
6038                }
6039                let kd_scale: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
6040                    core::arch::x86_64::_mm_mul_ps(
6041                        core::arch::x86_64::_mm_set1_ps(tri.diffuse_scale),
6042                        core::arch::x86_64::_mm_sub_ps(
6043                            one,
6044                            core::arch::x86_64::_mm_mul_ps(
6045                                fresnel_t,
6046                                core::arch::x86_64::_mm_set1_ps(0.55),
6047                            ),
6048                        ),
6049                    ),
6050                    core::arch::x86_64::_mm_set1_ps(0.08),
6051                );
6052                let dir_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
6053                    core::arch::x86_64::_mm_mul_ps(
6054                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l),
6055                        sh_v,
6056                    ),
6057                    kd_scale,
6058                );
6059                let ao_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
6060                    core::arch::x86_64::_mm_loadu_ps(run.ao.as_ptr().add(off)),
6061                    core::arch::x86_64::_mm_set1_ps(0.44),
6062                );
6063                let lit_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6064                    core::arch::x86_64::_mm_add_ps(
6065                        core::arch::x86_64::_mm_loadu_ps(run.gi_r.as_ptr().add(off)),
6066                        core::arch::x86_64::_mm_mul_ps(
6067                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_x()),
6068                            ao_s,
6069                        ),
6070                    ),
6071                    core::arch::x86_64::_mm_mul_ps(
6072                        core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
6073                        dir_s,
6074                    ),
6075                );
6076                let lit_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6077                    core::arch::x86_64::_mm_add_ps(
6078                        core::arch::x86_64::_mm_loadu_ps(run.gi_g.as_ptr().add(off)),
6079                        core::arch::x86_64::_mm_mul_ps(
6080                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_y()),
6081                            ao_s,
6082                        ),
6083                    ),
6084                    core::arch::x86_64::_mm_mul_ps(
6085                        core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
6086                        dir_s,
6087                    ),
6088                );
6089                let lit_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6090                    core::arch::x86_64::_mm_add_ps(
6091                        core::arch::x86_64::_mm_loadu_ps(run.gi_b.as_ptr().add(off)),
6092                        core::arch::x86_64::_mm_mul_ps(
6093                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_z()),
6094                            ao_s,
6095                        ),
6096                    ),
6097                    core::arch::x86_64::_mm_mul_ps(
6098                        core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
6099                        dir_s,
6100                    ),
6101                );
6102                let mut rad_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6103                    core::arch::x86_64::_mm_add_ps(
6104                        spec_r,
6105                        core::arch::x86_64::_mm_mul_ps(sb_r, lit_r),
6106                    ),
6107                    em_r,
6108                );
6109                let mut rad_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6110                    core::arch::x86_64::_mm_add_ps(
6111                        spec_g,
6112                        core::arch::x86_64::_mm_mul_ps(sb_g, lit_g),
6113                    ),
6114                    em_g,
6115                );
6116                let mut rad_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6117                    core::arch::x86_64::_mm_add_ps(
6118                        spec_b,
6119                        core::arch::x86_64::_mm_mul_ps(sb_b, lit_b),
6120                    ),
6121                    em_b,
6122                );
6123                if tri.do_refl {
6124                    let refl_f: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
6125                        core::arch::x86_64::_mm_max_ps(
6126                            core::arch::x86_64::_mm_add_ps(
6127                                core::arch::x86_64::_mm_set1_ps(0.18 + tri.metallic * 0.25),
6128                                core::arch::x86_64::_mm_mul_ps(
6129                                    fresnel_t,
6130                                    core::arch::x86_64::_mm_set1_ps(0.82),
6131                                ),
6132                            ),
6133                            core::arch::x86_64::_mm_set1_ps(0.18),
6134                        ),
6135                        core::arch::x86_64::_mm_set1_ps(0.95),
6136                    );
6137                    let refl_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
6138                        core::arch::x86_64::_mm_max_ps(
6139                            core::arch::x86_64::_mm_mul_ps(s_refl, refl_f),
6140                            zero,
6141                        ),
6142                        core::arch::x86_64::_mm_set1_ps(0.82),
6143                    );
6144                    let rr_v: core::arch::x86_64::__m128 =
6145                        core::arch::x86_64::_mm_loadu_ps(run.refl_r.as_ptr().add(off));
6146                    let rg_v: core::arch::x86_64::__m128 =
6147                        core::arch::x86_64::_mm_loadu_ps(run.refl_g.as_ptr().add(off));
6148                    let rb_v: core::arch::x86_64::__m128 =
6149                        core::arch::x86_64::_mm_loadu_ps(run.refl_b.as_ptr().add(off));
6150                    rad_r = Self::sse_lerp_4x(rad_r, rr_v, refl_b);
6151                    rad_g = Self::sse_lerp_4x(rad_g, rg_v, refl_b);
6152                    rad_b = Self::sse_lerp_4x(rad_b, rb_v, refl_b);
6153                }
6154                if frame_context.fog_on {
6155                    let pos_y: core::arch::x86_64::__m128 =
6156                        core::arch::x86_64::_mm_max_ps(wpy, zero);
6157                    let h_att: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
6158                        core::arch::x86_64::_mm_div_ps(
6159                            one,
6160                            core::arch::x86_64::_mm_add_ps(
6161                                one,
6162                                core::arch::x86_64::_mm_mul_ps(
6163                                    pos_y,
6164                                    core::arch::x86_64::_mm_set1_ps(0.045),
6165                                ),
6166                            ),
6167                        ),
6168                        core::arch::x86_64::_mm_set1_ps(0.32),
6169                    );
6170                    let fd: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
6171                        core::arch::x86_64::_mm_mul_ps(
6172                            d_v,
6173                            core::arch::x86_64::_mm_set1_ps(frame_context.inv_fog_distance),
6174                        ),
6175                        h_att,
6176                    );
6177                    let fog_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
6178                        core::arch::x86_64::_mm_max_ps(
6179                            core::arch::x86_64::_mm_div_ps(
6180                                fd,
6181                                core::arch::x86_64::_mm_add_ps(one, fd),
6182                            ),
6183                            zero,
6184                        ),
6185                        core::arch::x86_64::_mm_set1_ps(0.85),
6186                    );
6187                    let sun_align: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
6188                        core::arch::x86_64::_mm_xor_ps(vdl, abs_mask),
6189                        zero,
6190                    );
6191                    let sa2: core::arch::x86_64::__m128 =
6192                        core::arch::x86_64::_mm_mul_ps(sun_align, sun_align);
6193                    let shaft55: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
6194                        core::arch::x86_64::_mm_mul_ps(
6195                            core::arch::x86_64::_mm_mul_ps(sa2, sa2),
6196                            fog_t,
6197                        ),
6198                        core::arch::x86_64::_mm_add_ps(
6199                            core::arch::x86_64::_mm_set1_ps(0.35 * 0.55),
6200                            core::arch::x86_64::_mm_mul_ps(
6201                                sh_v,
6202                                core::arch::x86_64::_mm_set1_ps(0.65 * 0.55),
6203                            ),
6204                        ),
6205                    );
6206                    let fog_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6207                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_x()),
6208                        core::arch::x86_64::_mm_mul_ps(
6209                            core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
6210                            shaft55,
6211                        ),
6212                    );
6213                    let fog_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6214                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_y()),
6215                        core::arch::x86_64::_mm_mul_ps(
6216                            core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
6217                            shaft55,
6218                        ),
6219                    );
6220                    let fog_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
6221                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_z()),
6222                        core::arch::x86_64::_mm_mul_ps(
6223                            core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
6224                            shaft55,
6225                        ),
6226                    );
6227                    rad_r = Self::sse_lerp_4x(rad_r, fog_r, fog_t);
6228                    rad_g = Self::sse_lerp_4x(rad_g, fog_g, fog_t);
6229                    rad_b = Self::sse_lerp_4x(rad_b, fog_b, fog_t);
6230                }
6231                let exp_s: core::arch::x86_64::__m128 =
6232                    core::arch::x86_64::_mm_set1_ps(frame_context.exposure_scale);
6233                core::arch::x86_64::_mm_storeu_ps(
6234                    exp_r_arr.as_mut_ptr(),
6235                    core::arch::x86_64::_mm_mul_ps(rad_r, exp_s),
6236                );
6237                core::arch::x86_64::_mm_storeu_ps(
6238                    exp_g_arr.as_mut_ptr(),
6239                    core::arch::x86_64::_mm_mul_ps(rad_g, exp_s),
6240                );
6241                core::arch::x86_64::_mm_storeu_ps(
6242                    exp_b_arr.as_mut_ptr(),
6243                    core::arch::x86_64::_mm_mul_ps(rad_b, exp_s),
6244                );
6245            }
6246        }
6247        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
6248        {
6249            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; `simd128` is enabled on `wasm32`.
6250            unsafe {
6251                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
6252                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
6253                let two: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(2.0);
6254                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
6255                let lane_idx: core::arch::wasm32::v128 =
6256                    core::arch::wasm32::v128_load(lane_idx_arr.as_ptr().cast());
6257                let rx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6258                    core::arch::wasm32::f32x4_splat(raw_ray.get_x()),
6259                    core::arch::wasm32::f32x4_mul(
6260                        core::arch::wasm32::f32x4_splat(ray_dx.get_x()),
6261                        lane_idx,
6262                    ),
6263                );
6264                let ry: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6265                    core::arch::wasm32::f32x4_splat(raw_ray.get_y()),
6266                    core::arch::wasm32::f32x4_mul(
6267                        core::arch::wasm32::f32x4_splat(ray_dx.get_y()),
6268                        lane_idx,
6269                    ),
6270                );
6271                let rz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6272                    core::arch::wasm32::f32x4_splat(raw_ray.get_z()),
6273                    core::arch::wasm32::f32x4_mul(
6274                        core::arch::wasm32::f32x4_splat(ray_dx.get_z()),
6275                        lane_idx,
6276                    ),
6277                );
6278                let len_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6279                    core::arch::wasm32::f32x4_add(
6280                        core::arch::wasm32::f32x4_add(
6281                            core::arch::wasm32::f32x4_mul(rx, rx),
6282                            core::arch::wasm32::f32x4_mul(ry, ry),
6283                        ),
6284                        core::arch::wasm32::f32x4_mul(rz, rz),
6285                    ),
6286                    core::arch::wasm32::f32x4_splat(1e-12),
6287                );
6288                let inv_l: core::arch::wasm32::v128 =
6289                    core::arch::wasm32::f32x4_div(one, core::arch::wasm32::f32x4_sqrt(len_sq));
6290                let ndv_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6291                    core::arch::wasm32::f32x4_splat(-sn.dot(raw_ray)),
6292                    core::arch::wasm32::f32x4_mul(
6293                        core::arch::wasm32::f32x4_splat(-sn.dot(ray_dx)),
6294                        lane_idx,
6295                    ),
6296                );
6297                let ndv_raw: core::arch::wasm32::v128 =
6298                    core::arch::wasm32::f32x4_mul(ndv_num, inv_l);
6299                let ndv: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6300                    core::arch::wasm32::f32x4_pmax(ndv_raw, core::arch::wasm32::f32x4_splat(0.02)),
6301                    one,
6302                );
6303                let f_om: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(one, ndv);
6304                let f_om2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(f_om, f_om);
6305                let fresnel_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6306                    core::arch::wasm32::f32x4_mul(f_om2, f_om2),
6307                    f_om,
6308                );
6309                let vdl_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6310                    core::arch::wasm32::f32x4_splat(-sun_dir.dot(raw_ray)),
6311                    core::arch::wasm32::f32x4_mul(
6312                        core::arch::wasm32::f32x4_splat(-sun_dir.dot(ray_dx)),
6313                        lane_idx,
6314                    ),
6315                );
6316                let vdl: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(vdl_num, inv_l);
6317                let sh_v: core::arch::wasm32::v128 =
6318                    core::arch::wasm32::v128_load(run.shadow.as_ptr().add(off).cast());
6319                let (spec_r, spec_g, spec_b): (
6320                    core::arch::wasm32::v128,
6321                    core::arch::wasm32::v128,
6322                    core::arch::wasm32::v128,
6323                ) = if tri.n_dot_l > 0.0 {
6324                    let ndl_v: core::arch::wasm32::v128 =
6325                        core::arch::wasm32::f32x4_splat(tri.n_dot_l);
6326                    let ndh_u: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6327                        core::arch::wasm32::f32x4_add(ndl_v, ndv_raw),
6328                        zero,
6329                    );
6330                    let h_lsq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6331                        core::arch::wasm32::f32x4_add(two, core::arch::wasm32::f32x4_mul(two, vdl)),
6332                        core::arch::wasm32::f32x4_splat(1e-6),
6333                    );
6334                    let ndh_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_div(
6335                        core::arch::wasm32::f32x4_mul(ndh_u, ndh_u),
6336                        h_lsq,
6337                    );
6338                    let ggx_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6339                        one,
6340                        core::arch::wasm32::f32x4_mul(
6341                            ndh_sq,
6342                            core::arch::wasm32::f32x4_splat(tri.alpha2 - 1.0),
6343                        ),
6344                    );
6345                    let ggx_term: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6346                        core::arch::wasm32::f32x4_splat(1e-4),
6347                        core::arch::wasm32::f32x4_mul(
6348                            core::arch::wasm32::f32x4_mul(ggx_den, ggx_den),
6349                            core::arch::wasm32::f32x4_splat(PI),
6350                        ),
6351                    );
6352                    let vis_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6353                        core::arch::wasm32::f32x4_splat(0.08),
6354                        core::arch::wasm32::f32x4_mul(
6355                            ndv,
6356                            core::arch::wasm32::f32x4_splat(tri.n_dot_l.max(0.06)),
6357                        ),
6358                    );
6359                    let spec_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6360                        core::arch::wasm32::f32x4_splat(0.25 * tri.alpha2 * tri.n_dot_l),
6361                        sh_v,
6362                    );
6363                    let spec_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6364                        core::arch::wasm32::f32x4_div(
6365                            spec_num,
6366                            core::arch::wasm32::f32x4_mul(ggx_term, vis_den),
6367                        ),
6368                        core::arch::wasm32::f32x4_splat(4.5),
6369                    );
6370                    let fr_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6371                        core::arch::wasm32::f32x4_splat(tri.f0.get_x()),
6372                        core::arch::wasm32::f32x4_mul(
6373                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_x()),
6374                            fresnel_t,
6375                        ),
6376                    );
6377                    let fr_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6378                        core::arch::wasm32::f32x4_splat(tri.f0.get_y()),
6379                        core::arch::wasm32::f32x4_mul(
6380                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_y()),
6381                            fresnel_t,
6382                        ),
6383                    );
6384                    let fr_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6385                        core::arch::wasm32::f32x4_splat(tri.f0.get_z()),
6386                        core::arch::wasm32::f32x4_mul(
6387                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_z()),
6388                            fresnel_t,
6389                        ),
6390                    );
6391                    (
6392                        core::arch::wasm32::f32x4_mul(
6393                            fr_r,
6394                            core::arch::wasm32::f32x4_mul(
6395                                core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6396                                spec_s,
6397                            ),
6398                        ),
6399                        core::arch::wasm32::f32x4_mul(
6400                            fr_g,
6401                            core::arch::wasm32::f32x4_mul(
6402                                core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6403                                spec_s,
6404                            ),
6405                        ),
6406                        core::arch::wasm32::f32x4_mul(
6407                            fr_b,
6408                            core::arch::wasm32::f32x4_mul(
6409                                core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6410                                spec_s,
6411                            ),
6412                        ),
6413                    )
6414                } else {
6415                    (zero, zero, zero)
6416                };
6417                let d_v: core::arch::wasm32::v128 =
6418                    core::arch::wasm32::v128_load(run.depths.as_ptr().add(off).cast());
6419                let wpy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6420                    core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_y()),
6421                    core::arch::wasm32::f32x4_mul(ry, d_v),
6422                );
6423                let mut sb_r: core::arch::wasm32::v128 =
6424                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_x());
6425                let mut sb_g: core::arch::wasm32::v128 =
6426                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_y());
6427                let mut sb_b: core::arch::wasm32::v128 =
6428                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_z());
6429                let mut em_r: core::arch::wasm32::v128 =
6430                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_x());
6431                let mut em_g: core::arch::wasm32::v128 =
6432                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_y());
6433                let mut em_b: core::arch::wasm32::v128 =
6434                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_z());
6435                let mut s_refl: core::arch::wasm32::v128 =
6436                    core::arch::wasm32::f32x4_splat(tri.mat_refl);
6437                if DETAIL == 2 {
6438                    let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
6439                    let cam_u: f32 = frame_context.camera_position.get_x().mul_add(
6440                        wall_tan_x,
6441                        frame_context.camera_position.get_z() * wall_tan_z,
6442                    );
6443                    let ray_u: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6444                        core::arch::wasm32::f32x4_mul(
6445                            rx,
6446                            core::arch::wasm32::f32x4_splat(wall_tan_x),
6447                        ),
6448                        core::arch::wasm32::f32x4_mul(
6449                            rz,
6450                            core::arch::wasm32::f32x4_splat(wall_tan_z),
6451                        ),
6452                    );
6453                    let u_coord_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6454                        core::arch::wasm32::f32x4_splat(cam_u),
6455                        core::arch::wasm32::f32x4_mul(ray_u, d_v),
6456                    );
6457                    let mut u_a: [f32; 4] = [0.0; 4];
6458                    let mut y_a: [f32; 4] = [0.0; 4];
6459                    let mut d_a: [f32; 4] = [0.0; 4];
6460                    core::arch::wasm32::v128_store(u_a.as_mut_ptr().cast(), u_coord_v);
6461                    core::arch::wasm32::v128_store(y_a.as_mut_ptr().cast(), wpy);
6462                    core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6463                    let mut nr_a: [f32; 4] = [0.0; 4];
6464                    let mut ng_a: [f32; 4] = [0.0; 4];
6465                    let mut nb_a: [f32; 4] = [0.0; 4];
6466                    let mut er_a: [f32; 4] = [0.0; 4];
6467                    let mut eg_a: [f32; 4] = [0.0; 4];
6468                    let mut eb_a: [f32; 4] = [0.0; 4];
6469                    let mut rf_a: [f32; 4] = [0.0; 4];
6470                    for lane in 0..4usize {
6471                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6472                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
6473                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
6474                        );
6475                        nr_a[lane] = sb.get_x();
6476                        ng_a[lane] = sb.get_y();
6477                        nb_a[lane] = sb.get_z();
6478                        er_a[lane] = em.get_x();
6479                        eg_a[lane] = em.get_y();
6480                        eb_a[lane] = em.get_z();
6481                        rf_a[lane] = rf;
6482                    }
6483                    sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6484                    sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6485                    sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6486                    em_r = core::arch::wasm32::v128_load(er_a.as_ptr().cast());
6487                    em_g = core::arch::wasm32::v128_load(eg_a.as_ptr().cast());
6488                    em_b = core::arch::wasm32::v128_load(eb_a.as_ptr().cast());
6489                    s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6490                } else if DETAIL == 1 {
6491                    let m_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
6492                        core::arch::wasm32::f32x4_abs(wpy),
6493                        core::arch::wasm32::f32x4_splat(0.15),
6494                    );
6495                    let m_mask: u32 = core::arch::wasm32::i32x4_bitmask(m_r) as u32;
6496                    if m_mask != 0 {
6497                        let wpx_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6498                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_x()),
6499                            core::arch::wasm32::f32x4_mul(rx, d_v),
6500                        );
6501                        let wpz_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6502                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_z()),
6503                            core::arch::wasm32::f32x4_mul(rz, d_v),
6504                        );
6505                        let mut x_a: [f32; 4] = [0.0; 4];
6506                        let mut z_a: [f32; 4] = [0.0; 4];
6507                        let mut d_a: [f32; 4] = [0.0; 4];
6508                        let mut rx_a: [f32; 4] = [0.0; 4];
6509                        let mut ry_a: [f32; 4] = [0.0; 4];
6510                        let mut rz_a: [f32; 4] = [0.0; 4];
6511                        let mut ft_a: [f32; 4] = [0.0; 4];
6512                        core::arch::wasm32::v128_store(x_a.as_mut_ptr().cast(), wpx_v);
6513                        core::arch::wasm32::v128_store(z_a.as_mut_ptr().cast(), wpz_v);
6514                        core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6515                        core::arch::wasm32::v128_store(rx_a.as_mut_ptr().cast(), rx);
6516                        core::arch::wasm32::v128_store(ry_a.as_mut_ptr().cast(), ry);
6517                        core::arch::wasm32::v128_store(rz_a.as_mut_ptr().cast(), rz);
6518                        core::arch::wasm32::v128_store(ft_a.as_mut_ptr().cast(), fresnel_t);
6519                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
6520                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
6521                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
6522                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
6523                        for lane in 0..4usize {
6524                            if (m_mask & (1_u32 << lane)) != 0 {
6525                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
6526                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
6527                                    (
6528                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
6529                                        ft_a[lane],
6530                                        tri.metallic,
6531                                        frame_context.world_time_secs,
6532                                    ),
6533                                    tri.mat_base,
6534                                );
6535                                nr_a[lane] = sb.get_x();
6536                                ng_a[lane] = sb.get_y();
6537                                nb_a[lane] = sb.get_z();
6538                                rf_a[lane] = rf;
6539                            }
6540                        }
6541                        sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6542                        sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6543                        sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6544                        s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6545                    }
6546                }
6547                let kd_scale: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6548                    core::arch::wasm32::f32x4_mul(
6549                        core::arch::wasm32::f32x4_splat(tri.diffuse_scale),
6550                        core::arch::wasm32::f32x4_sub(
6551                            one,
6552                            core::arch::wasm32::f32x4_mul(
6553                                fresnel_t,
6554                                core::arch::wasm32::f32x4_splat(0.55),
6555                            ),
6556                        ),
6557                    ),
6558                    core::arch::wasm32::f32x4_splat(0.08),
6559                );
6560                let dir_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6561                    core::arch::wasm32::f32x4_mul(
6562                        core::arch::wasm32::f32x4_splat(tri.n_dot_l),
6563                        sh_v,
6564                    ),
6565                    kd_scale,
6566                );
6567                let ao_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6568                    core::arch::wasm32::v128_load(run.ao.as_ptr().add(off).cast()),
6569                    core::arch::wasm32::f32x4_splat(0.44),
6570                );
6571                let lit_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6572                    core::arch::wasm32::f32x4_add(
6573                        core::arch::wasm32::v128_load(run.gi_r.as_ptr().add(off).cast()),
6574                        core::arch::wasm32::f32x4_mul(
6575                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_x()),
6576                            ao_s,
6577                        ),
6578                    ),
6579                    core::arch::wasm32::f32x4_mul(
6580                        core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6581                        dir_s,
6582                    ),
6583                );
6584                let lit_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6585                    core::arch::wasm32::f32x4_add(
6586                        core::arch::wasm32::v128_load(run.gi_g.as_ptr().add(off).cast()),
6587                        core::arch::wasm32::f32x4_mul(
6588                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_y()),
6589                            ao_s,
6590                        ),
6591                    ),
6592                    core::arch::wasm32::f32x4_mul(
6593                        core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6594                        dir_s,
6595                    ),
6596                );
6597                let lit_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6598                    core::arch::wasm32::f32x4_add(
6599                        core::arch::wasm32::v128_load(run.gi_b.as_ptr().add(off).cast()),
6600                        core::arch::wasm32::f32x4_mul(
6601                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_z()),
6602                            ao_s,
6603                        ),
6604                    ),
6605                    core::arch::wasm32::f32x4_mul(
6606                        core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6607                        dir_s,
6608                    ),
6609                );
6610                let mut rad_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6611                    core::arch::wasm32::f32x4_add(
6612                        spec_r,
6613                        core::arch::wasm32::f32x4_mul(sb_r, lit_r),
6614                    ),
6615                    em_r,
6616                );
6617                let mut rad_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6618                    core::arch::wasm32::f32x4_add(
6619                        spec_g,
6620                        core::arch::wasm32::f32x4_mul(sb_g, lit_g),
6621                    ),
6622                    em_g,
6623                );
6624                let mut rad_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6625                    core::arch::wasm32::f32x4_add(
6626                        spec_b,
6627                        core::arch::wasm32::f32x4_mul(sb_b, lit_b),
6628                    ),
6629                    em_b,
6630                );
6631                if tri.do_refl {
6632                    let refl_f: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6633                        core::arch::wasm32::f32x4_pmax(
6634                            core::arch::wasm32::f32x4_add(
6635                                core::arch::wasm32::f32x4_splat(0.18 + tri.metallic * 0.25),
6636                                core::arch::wasm32::f32x4_mul(
6637                                    fresnel_t,
6638                                    core::arch::wasm32::f32x4_splat(0.82),
6639                                ),
6640                            ),
6641                            core::arch::wasm32::f32x4_splat(0.18),
6642                        ),
6643                        core::arch::wasm32::f32x4_splat(0.95),
6644                    );
6645                    let refl_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6646                        core::arch::wasm32::f32x4_pmax(
6647                            core::arch::wasm32::f32x4_mul(s_refl, refl_f),
6648                            zero,
6649                        ),
6650                        core::arch::wasm32::f32x4_splat(0.82),
6651                    );
6652                    let rr_v: core::arch::wasm32::v128 =
6653                        core::arch::wasm32::v128_load(run.refl_r.as_ptr().add(off).cast());
6654                    let rg_v: core::arch::wasm32::v128 =
6655                        core::arch::wasm32::v128_load(run.refl_g.as_ptr().add(off).cast());
6656                    let rb_v: core::arch::wasm32::v128 =
6657                        core::arch::wasm32::v128_load(run.refl_b.as_ptr().add(off).cast());
6658                    rad_r = Self::wasm_lerp_4x(rad_r, rr_v, refl_b);
6659                    rad_g = Self::wasm_lerp_4x(rad_g, rg_v, refl_b);
6660                    rad_b = Self::wasm_lerp_4x(rad_b, rb_v, refl_b);
6661                }
6662                if frame_context.fog_on {
6663                    let pos_y: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(wpy, zero);
6664                    let h_att: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6665                        core::arch::wasm32::f32x4_div(
6666                            one,
6667                            core::arch::wasm32::f32x4_add(
6668                                one,
6669                                core::arch::wasm32::f32x4_mul(
6670                                    pos_y,
6671                                    core::arch::wasm32::f32x4_splat(0.045),
6672                                ),
6673                            ),
6674                        ),
6675                        core::arch::wasm32::f32x4_splat(0.32),
6676                    );
6677                    let fd: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6678                        core::arch::wasm32::f32x4_mul(
6679                            d_v,
6680                            core::arch::wasm32::f32x4_splat(frame_context.inv_fog_distance),
6681                        ),
6682                        h_att,
6683                    );
6684                    let fog_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6685                        core::arch::wasm32::f32x4_pmax(
6686                            core::arch::wasm32::f32x4_div(
6687                                fd,
6688                                core::arch::wasm32::f32x4_add(one, fd),
6689                            ),
6690                            zero,
6691                        ),
6692                        core::arch::wasm32::f32x4_splat(0.85),
6693                    );
6694                    let sun_align: core::arch::wasm32::v128 =
6695                        core::arch::wasm32::f32x4_pmax(core::arch::wasm32::f32x4_neg(vdl), zero);
6696                    let sa2: core::arch::wasm32::v128 =
6697                        core::arch::wasm32::f32x4_mul(sun_align, sun_align);
6698                    let shaft55: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6699                        core::arch::wasm32::f32x4_mul(
6700                            core::arch::wasm32::f32x4_mul(sa2, sa2),
6701                            fog_t,
6702                        ),
6703                        core::arch::wasm32::f32x4_add(
6704                            core::arch::wasm32::f32x4_splat(0.35 * 0.55),
6705                            core::arch::wasm32::f32x4_mul(
6706                                sh_v,
6707                                core::arch::wasm32::f32x4_splat(0.65 * 0.55),
6708                            ),
6709                        ),
6710                    );
6711                    let fog_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6712                        core::arch::wasm32::f32x4_splat(sky_horizon.get_x()),
6713                        core::arch::wasm32::f32x4_mul(
6714                            core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6715                            shaft55,
6716                        ),
6717                    );
6718                    let fog_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6719                        core::arch::wasm32::f32x4_splat(sky_horizon.get_y()),
6720                        core::arch::wasm32::f32x4_mul(
6721                            core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6722                            shaft55,
6723                        ),
6724                    );
6725                    let fog_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6726                        core::arch::wasm32::f32x4_splat(sky_horizon.get_z()),
6727                        core::arch::wasm32::f32x4_mul(
6728                            core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6729                            shaft55,
6730                        ),
6731                    );
6732                    rad_r = Self::wasm_lerp_4x(rad_r, fog_r, fog_t);
6733                    rad_g = Self::wasm_lerp_4x(rad_g, fog_g, fog_t);
6734                    rad_b = Self::wasm_lerp_4x(rad_b, fog_b, fog_t);
6735                }
6736                let exp_s: core::arch::wasm32::v128 =
6737                    core::arch::wasm32::f32x4_splat(frame_context.exposure_scale);
6738                core::arch::wasm32::v128_store(
6739                    exp_r_arr.as_mut_ptr().cast(),
6740                    core::arch::wasm32::f32x4_mul(rad_r, exp_s),
6741                );
6742                core::arch::wasm32::v128_store(
6743                    exp_g_arr.as_mut_ptr().cast(),
6744                    core::arch::wasm32::f32x4_mul(rad_g, exp_s),
6745                );
6746                core::arch::wasm32::v128_store(
6747                    exp_b_arr.as_mut_ptr().cast(),
6748                    core::arch::wasm32::f32x4_mul(rad_b, exp_s),
6749                );
6750            }
6751        }
6752        #[cfg(not(target_arch = "aarch64"))]
6753        #[cfg(not(target_arch = "x86_64"))]
6754        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
6755        {
6756            let rx: [f32; 4] = [
6757                raw_ray.get_x(),
6758                raw_ray.get_x() + ray_dx.get_x(),
6759                raw_ray.get_x() + ray_dx.get_x() * 2.0,
6760                raw_ray.get_x() + ray_dx.get_x() * 3.0,
6761            ];
6762            let ry: [f32; 4] = [
6763                raw_ray.get_y(),
6764                raw_ray.get_y() + ray_dx.get_y(),
6765                raw_ray.get_y() + ray_dx.get_y() * 2.0,
6766                raw_ray.get_y() + ray_dx.get_y() * 3.0,
6767            ];
6768            let rz: [f32; 4] = [
6769                raw_ray.get_z(),
6770                raw_ray.get_z() + ray_dx.get_z(),
6771                raw_ray.get_z() + ray_dx.get_z() * 2.0,
6772                raw_ray.get_z() + ray_dx.get_z() * 3.0,
6773            ];
6774            let len_sq: [f32; 4] = [
6775                rx[0].mul_add(rx[0], ry[0].mul_add(ry[0], rz[0] * rz[0])),
6776                rx[1].mul_add(rx[1], ry[1].mul_add(ry[1], rz[1] * rz[1])),
6777                rx[2].mul_add(rx[2], ry[2].mul_add(ry[2], rz[2] * rz[2])),
6778                rx[3].mul_add(rx[3], ry[3].mul_add(ry[3], rz[3] * rz[3])),
6779            ];
6780            let inv_len: [f32; 4] = Self::rsqrt_4x(len_sq);
6781            let cpx: f32 = frame_context.camera_position.get_x();
6782            let cpy: f32 = frame_context.camera_position.get_y();
6783            let cpz: f32 = frame_context.camera_position.get_z();
6784            let (wall_tan_x, wall_tan_z): (f32, f32) = Self::facade_wall_tangent(sn);
6785            for lane in 0..4 {
6786                let s_i: usize = off + lane;
6787                let inv_l: f32 = inv_len[lane];
6788                let vtx: f32 = -rx[lane] * inv_l;
6789                let vty: f32 = -ry[lane] * inv_l;
6790                let vtz: f32 = -rz[lane] * inv_l;
6791                let ndv_raw: f32 = sn
6792                    .get_x()
6793                    .mul_add(vtx, sn.get_y().mul_add(vty, sn.get_z() * vtz));
6794                let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
6795                let f_om: f32 = 1.0 - ndv;
6796                let f_om2: f32 = f_om * f_om;
6797                let fresnel_t: f32 = f_om2 * f_om2 * f_om;
6798                let vdl: f32 = sun_dir
6799                    .get_x()
6800                    .mul_add(vtx, sun_dir.get_y().mul_add(vty, sun_dir.get_z() * vtz));
6801                let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
6802                    let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
6803                    let h_len_sq: f32 = 2.0_f32.mul_add(vdl, 2.0).max(1e-6);
6804                    let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
6805                    let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
6806                    let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * run.shadow[s_i];
6807                    let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
6808                    let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
6809                    let spec_s: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
6810                    let fresnel_rgb: Vec3 =
6811                        tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
6812                    fresnel_rgb.mul(sun_col.scale(spec_s))
6813                } else {
6814                    Vec3::zero()
6815                };
6816                let depth: f32 = run.depths[s_i];
6817                let wpx: f32 = rx[lane].mul_add(depth, cpx);
6818                let wpy: f32 = ry[lane].mul_add(depth, cpy);
6819                let wpz: f32 = rz[lane].mul_add(depth, cpz);
6820                let mut surf_base: Vec3 = tri.mat_base;
6821                let mut surf_emissive: Vec3 = tri.mat_emissive;
6822                let mut surf_refl: f32 = tri.mat_refl;
6823                if DETAIL == 2 {
6824                    let u_coord: f32 = wpx.mul_add(wall_tan_x, wpz * wall_tan_z);
6825                    let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6826                        (u_coord, wpy, depth, frame_context.inv_height),
6827                        (surf_base, surf_emissive, surf_refl),
6828                    );
6829                    surf_base = nb;
6830                    surf_emissive = ne;
6831                    surf_refl = nr;
6832                } else if DETAIL == 1 && wpy.abs() < 0.15 {
6833                    let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
6834                        (wpx, wpz, depth, frame_context.inv_height),
6835                        (
6836                            Vec3::new(vtx, vty, vtz),
6837                            fresnel_t,
6838                            tri.metallic,
6839                            frame_context.world_time_secs,
6840                        ),
6841                        surf_base,
6842                    );
6843                    surf_base = nb;
6844                    surf_refl = nr;
6845                }
6846                let kd_scale: f32 = (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
6847                let direct: Vec3 = sun_col.scale(tri.n_dot_l * run.shadow[s_i] * kd_scale);
6848                let indirect: Vec3 = tri.ambient_sky.scale(0.44 * run.ao[s_i]).add(Vec3::new(
6849                    run.gi_r[s_i],
6850                    run.gi_g[s_i],
6851                    run.gi_b[s_i],
6852                ));
6853                let mut radiance: Vec3 = surf_base
6854                    .mul(direct.add(indirect))
6855                    .add(spec_col)
6856                    .add(surf_emissive);
6857                if tri.do_refl {
6858                    let refl_fresnel: f32 =
6859                        (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
6860                    let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
6861                    radiance = radiance.lerp(
6862                        Vec3::new(run.refl_r[s_i], run.refl_g[s_i], run.refl_b[s_i]),
6863                        refl_blend,
6864                    );
6865                }
6866                if frame_context.fog_on {
6867                    let height_atten: f32 = if wpy > 0.0 {
6868                        (1.0 / (1.0 + wpy * 0.045)).max(0.32)
6869                    } else {
6870                        1.0
6871                    };
6872                    let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
6873                    let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
6874                    let sun_align: f32 = (-vdl).max(0.0);
6875                    let sa2: f32 = sun_align * sun_align;
6876                    let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * run.shadow[s_i]);
6877                    let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
6878                    radiance = radiance.lerp(fog_col, fog_t);
6879                }
6880                let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6881                exp_r_arr[lane] = exposed.get_x();
6882                exp_g_arr[lane] = exposed.get_y();
6883                exp_b_arr[lane] = exposed.get_z();
6884            }
6885        }
6886        let (rgba_4, luma_4): ([[u8; 4]; 4], [u8; 4]) =
6887            Vec3::aces_rgba8_luma_4x(exp_r_arr, exp_g_arr, exp_b_arr);
6888        c_dst[0..4].copy_from_slice(&rgba_4[0]);
6889        c_dst[4..8].copy_from_slice(&rgba_4[1]);
6890        c_dst[8..12].copy_from_slice(&rgba_4[2]);
6891        c_dst[12..16].copy_from_slice(&rgba_4[3]);
6892        l_dst[0..4].copy_from_slice(&luma_4);
6893        if let Some((b_lane, b_cell)) = bloom_slot {
6894            let er: f32 = (exp_r_arr[b_lane] - 1.05).max(0.0);
6895            let eg: f32 = (exp_g_arr[b_lane] - 1.05).max(0.0);
6896            let eb: f32 = (exp_b_arr[b_lane] - 1.05).max(0.0);
6897            *b_cell = [er, eg, eb, 0.0];
6898            let rg_pos: bool = er > 0.0 || eg > 0.0;
6899            rg_pos || eb > 0.0
6900        } else {
6901            false
6902        }
6903    }
6904
6905    /// Loops `shade_span_4x_specialized<DETAIL>` across up to 32 pixels of one triangle run with zero probe register pressure.
6906    ///
6907    /// # Arguments
6908    ///
6909    /// - `&DeferredFrameContext` - Per-frame shading context.
6910    /// - `&GShadeTri` - Precomputed triangle PBR record.
6911    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6912    /// - `&RunScratch32` - Pre-upsampled 32-pixel L1 probe & depth arrays.
6913    /// - `&mut RunRowOut<'_>` - Writable scanline color, luma, and bloom outputs.
6914    ///
6915    /// # Returns
6916    ///
6917    /// - `bool` - `true` when any pixel in the chunk emitted non-zero HDR bloom.
6918    #[inline(always)]
6919    fn shade_run_32_loop<const DETAIL: u8>(
6920        frame_context: &DeferredFrameContext,
6921        tri: &GShadeTri,
6922        span: (usize, usize, Vec3, Vec3),
6923        run: &RunScratch32,
6924        out: &mut RunRowOut<'_>,
6925    ) -> bool {
6926        let (px_start, count, mut raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6927        let write_bloom_row: bool = out.write_bloom;
6928        let bloom_row_off: usize = out.bloom_off;
6929        let ray_dx_4: Vec3 = ray_dx.scale(4.0);
6930        let b_lane: usize = (4 - (px_start & 3)) & 3;
6931        let mut any_bloom: bool = false;
6932        let mut off: usize = 0;
6933        while off < count {
6934            let cur_px: usize = px_start + off;
6935            let base_c: usize = cur_px * 4;
6936            let bloom_slot: Option<(usize, &mut [f32; 4])> = if write_bloom_row {
6937                let bidx: usize = bloom_row_off + ((cur_px + b_lane) >> 2);
6938                if bidx < out.bloom_band.len() {
6939                    Some((b_lane, &mut out.bloom_band[bidx]))
6940                } else {
6941                    None
6942                }
6943            } else {
6944                None
6945            };
6946            if Self::shade_span_4x_specialized::<DETAIL>(
6947                frame_context,
6948                tri,
6949                (raw_ray, ray_dx),
6950                (run, off),
6951                SpanShadeOut {
6952                    rgba: &mut out.color[base_c..(base_c + 16)],
6953                    luma: &mut out.luma[cur_px..(cur_px + 4)],
6954                    bloom: bloom_slot,
6955                },
6956            ) {
6957                any_bloom = true;
6958            }
6959            raw_ray = raw_ray.add(ray_dx_4);
6960            off += 4;
6961        }
6962        any_bloom
6963    }
6964
6965    /// Outlined zero-spill leaf kernel for plain PBR triangles (`DETAIL = 0`).
6966    ///
6967    /// # Arguments
6968    ///
6969    /// - `&DeferredFrameContext` - Per-frame shading context.
6970    /// - `&GShadeTri` - Triangle PBR record.
6971    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6972    /// - `&RunScratch32` - L1-hot run scratch.
6973    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6974    ///
6975    /// # Returns
6976    ///
6977    /// - `bool` - `true` when bloom radiance was emitted.
6978    #[inline(never)]
6979    fn shade_run_plain_32(
6980        frame_context: &DeferredFrameContext,
6981        tri: &GShadeTri,
6982        span: (usize, usize, Vec3, Vec3),
6983        run: &RunScratch32,
6984        out: &mut RunRowOut<'_>,
6985    ) -> bool {
6986        Self::shade_run_32_loop::<0>(frame_context, tri, span, run, out)
6987    }
6988
6989    /// Outlined zero-spill leaf kernel for procedural asphalt road triangles (`DETAIL = 1`).
6990    ///
6991    /// # Arguments
6992    ///
6993    /// - `&DeferredFrameContext` - Per-frame shading context.
6994    /// - `&GShadeTri` - Triangle PBR record.
6995    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6996    /// - `&RunScratch32` - L1-hot run scratch.
6997    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6998    ///
6999    /// # Returns
7000    ///
7001    /// - `bool` - `true` when bloom radiance was emitted.
7002    #[inline(never)]
7003    fn shade_run_road_32(
7004        frame_context: &DeferredFrameContext,
7005        tri: &GShadeTri,
7006        span: (usize, usize, Vec3, Vec3),
7007        run: &RunScratch32,
7008        out: &mut RunRowOut<'_>,
7009    ) -> bool {
7010        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
7011        if count == 0 {
7012            return false;
7013        }
7014        let cam: Vec3 = frame_context.camera_position;
7015        let last_off: usize = count.saturating_sub(1);
7016        let p0: Vec3 = cam.add(start_raw_ray.scale(run.depths[0]));
7017        let p1: Vec3 = cam.add(
7018            start_raw_ray
7019                .add(ray_dx.scale(last_off as f32))
7020                .scale(run.depths[last_off]),
7021        );
7022        if p0.get_x() <= 143.5 && p1.get_x() <= 143.5 {
7023            return Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
7024        }
7025        let d0: f32 = (p0.get_x() - 64.0).hypot(p0.get_z() - p0.get_z().clamp(-140.0, 140.0));
7026        let d1: f32 = (p1.get_x() - 64.0).hypot(p1.get_z() - p1.get_z().clamp(-140.0, 140.0));
7027        if p0.get_x() > 144.2 && p1.get_x() > 144.2 && d0 > 78.5 && d1 > 78.5 {
7028            return Self::shade_run_ocean_32(frame_context, tri, span, run, out);
7029        }
7030        let mut any_bloom: bool = Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
7031        let mut raw_ray: Vec3 = start_raw_ray;
7032        let sky_lut: &[[f32; 3]] = out.sky_lut;
7033        let aces_lut: &[u8] = out.aces_lut;
7034        for off in 0..count {
7035            let depth: f32 = run.depths[off];
7036            let world_p: Vec3 = cam.add(raw_ray.scale(depth));
7037            let wpx: f32 = world_p.get_x();
7038            if wpx > 144.0 {
7039                let wpz: f32 = world_p.get_z();
7040                let d_spine: f32 = (wpx - 64.0).hypot(wpz - wpz.clamp(-140.0, 140.0));
7041                if d_spine > 78.2 {
7042                    let px: usize = px_start + off;
7043                    let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
7044                    let rt_refl: Vec3 =
7045                        Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
7046                    let radiance: Vec3 = Self::eval_ocean_water_radiance(
7047                        frame_context,
7048                        sky_lut,
7049                        (world_p, view_dir, depth),
7050                        (run.shadow[off], rt_refl),
7051                    );
7052                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
7053                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
7054                    let cidx: usize = px * 4;
7055                    out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
7056                    out.luma[px] =
7057                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
7058                            >> 8) as u8;
7059                    if out.write_bloom && (px & 3) == 0 {
7060                        let bidx: usize = out.bloom_off + (px >> 2);
7061                        if bidx < out.bloom_band.len() {
7062                            let er: f32 = (exposed.get_x() - 1.15).max(0.0);
7063                            let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
7064                            let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
7065                            out.bloom_band[bidx] = [er, eg, eb, 0.0];
7066                            if er + eg + eb > 0.0 {
7067                                any_bloom = true;
7068                            }
7069                        }
7070                    }
7071                }
7072            }
7073            raw_ray = raw_ray.add(ray_dx);
7074        }
7075        any_bloom
7076    }
7077
7078    /// Outlined zero-spill leaf kernel for animated photorealistic ocean water triangles (`DETAIL = 3`).
7079    ///
7080    /// # Arguments
7081    ///
7082    /// - `&DeferredFrameContext` - Per-frame shading context.
7083    /// - `&GShadeTri` - Triangle PBR record.
7084    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
7085    /// - `&RunScratch32` - L1-hot run scratch.
7086    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
7087    ///
7088    /// # Returns
7089    ///
7090    /// - `bool` - `true` when bloom radiance was emitted.
7091    #[inline(never)]
7092    fn shade_run_ocean_32(
7093        frame_context: &DeferredFrameContext,
7094        tri: &GShadeTri,
7095        span: (usize, usize, Vec3, Vec3),
7096        run: &RunScratch32,
7097        out: &mut RunRowOut<'_>,
7098    ) -> bool {
7099        let _: &GShadeTri = tri;
7100        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
7101        let mut raw_ray: Vec3 = start_raw_ray;
7102        let mut any_bloom: bool = false;
7103        let sky_lut: &[[f32; 3]] = out.sky_lut;
7104        let aces_lut: &[u8] = out.aces_lut;
7105        for off in 0..count {
7106            let px: usize = px_start + off;
7107            let depth: f32 = run.depths[off];
7108            let world_p: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
7109            let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
7110            let rt_refl: Vec3 = Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
7111            let radiance: Vec3 = Self::eval_ocean_water_radiance(
7112                frame_context,
7113                sky_lut,
7114                (world_p, view_dir, depth),
7115                (run.shadow[off], rt_refl),
7116            );
7117            let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
7118            let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
7119            let cidx: usize = px * 4;
7120            out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
7121            out.luma[px] =
7122                (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29) >> 8)
7123                    as u8;
7124            if out.write_bloom && (px & 3) == 0 {
7125                let bidx: usize = out.bloom_off + (px >> 2);
7126                if bidx < out.bloom_band.len() {
7127                    let er: f32 = (exposed.get_x() - 1.15).max(0.0);
7128                    let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
7129                    let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
7130                    out.bloom_band[bidx] = [er, eg, eb, 0.0];
7131                    if er + eg + eb > 0.0 {
7132                        any_bloom = true;
7133                    }
7134                }
7135            }
7136            raw_ray = raw_ray.add(ray_dx);
7137        }
7138        any_bloom
7139    }
7140
7141    /// Outlined zero-spill leaf kernel for procedural architectural facade triangles (`DETAIL = 2`).
7142    ///
7143    /// # Arguments
7144    ///
7145    /// - `&DeferredFrameContext` - Per-frame shading context.
7146    /// - `&GShadeTri` - Triangle PBR record.
7147    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
7148    /// - `&RunScratch32` - L1-hot run scratch.
7149    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
7150    ///
7151    /// # Returns
7152    ///
7153    /// - `bool` - `true` when bloom radiance was emitted.
7154    #[inline(never)]
7155    fn shade_run_facade_32(
7156        frame_context: &DeferredFrameContext,
7157        tri: &GShadeTri,
7158        span: (usize, usize, Vec3, Vec3),
7159        run: &RunScratch32,
7160        out: &mut RunRowOut<'_>,
7161    ) -> bool {
7162        Self::shade_run_32_loop::<2>(frame_context, tri, span, run, out)
7163    }
7164
7165    /// Evaluates procedural PBR surface modulation for `MasonryBrick`, `StoneCobble`, `OrganicFoliage`, `VolumetricCloud`, and `RiverWater`.
7166    ///
7167    /// # Arguments
7168    ///
7169    /// - `SurfaceDetailMode` - Active procedural surface detail mode.
7170    /// - `(Vec3, Vec3, Vec3)` - `(world_pos, surface_normal, view_to_cam)`.
7171    /// - `(&DeferredFrameContext, f32)` - `(frame_context, linear_depth)`.
7172    /// - `(Vec3, Vec3, f32)` - `(base_albedo, emissive, reflectivity)`.
7173    ///
7174    /// # Returns
7175    ///
7176    /// - `(Vec3, Vec3, f32)` - Updated `(albedo, emissive, reflectivity)`.
7177    #[inline(always)]
7178    #[must_use]
7179    fn eval_eco_material_detail(
7180        mode: SurfaceDetailMode,
7181        geom: (Vec3, Vec3, Vec3),
7182        ctx: (&DeferredFrameContext, f32),
7183        surf: (Vec3, Vec3, f32),
7184    ) -> (Vec3, Vec3, f32) {
7185        let (world_p, norm, view_dir): (Vec3, Vec3, Vec3) = geom;
7186        let (frame_context, depth): (&DeferredFrameContext, f32) = ctx;
7187        let (base, emissive, refl): (Vec3, Vec3, f32) = surf;
7188        let px_size: f32 = (depth * frame_context.inv_height * 2.10).max(0.015);
7189        match mode {
7190            SurfaceDetailMode::MasonryBrick => {
7191                let (wt_x, wt_z): (f32, f32) = Self::facade_wall_tangent(norm);
7192                let is_vert: bool = norm.get_y().abs() < 0.65;
7193                let u_coord: f32 = if is_vert {
7194                    world_p.get_x() * wt_x + world_p.get_z() * wt_z
7195                } else {
7196                    world_p.get_x()
7197                };
7198                let v_coord: f32 = if is_vert {
7199                    world_p.get_y()
7200                } else {
7201                    world_p.get_z()
7202                };
7203                let mt: f32 = ((depth - 45.0) * (1.0 / 130.0)).clamp(0.0, 1.0);
7204                let m_fade: f32 = 1.0 - mt * mt * (3.0 - 2.0 * mt);
7205                let row: f32 = (v_coord * 6.0).floor();
7206                let bu: f32 = u_coord * 2.2 + 0.5 * (row * 0.5).fract();
7207                let mu: f32 = Self::box_pulse(bu, 0.0, 0.09, px_size * 2.2);
7208                let mv: f32 = Self::box_pulse(v_coord * 6.0, 0.0, 0.15, px_size * 6.0);
7209                let mortar: f32 = (mu + mv - mu * mv).clamp(0.0, 1.0) * m_fade;
7210                let bh: f32 = Self::sky_hash_2d(bu.floor() as i32, row as i32);
7211                let mut col: Vec3 = base
7212                    .scale(0.82 + 0.34 * bh)
7213                    .lerp(Vec3::new(0.48, 0.45, 0.40), mortar * 0.75);
7214                let mut out_em: Vec3 = emissive;
7215                let mut out_refl: f32 = refl * 0.5;
7216                if norm.get_y().abs() < 0.35 && world_p.get_y() > 2.4 && m_fade > 0.02 {
7217                    let wu: f32 = Self::box_pulse(u_coord * 0.38, 0.24, 0.76, px_size * 0.38);
7218                    let wv: f32 =
7219                        Self::box_pulse(world_p.get_y() * 0.31, 0.24, 0.80, px_size * 0.31);
7220                    let win_w: f32 = wu * wv * m_fade;
7221                    let wh: f32 = Self::sky_hash_2d(
7222                        (u_coord * 0.38).floor() as i32,
7223                        (world_p.get_y() * 0.31).floor() as i32,
7224                    );
7225                    let apt_em: Vec3 = if wh < 0.38 {
7226                        Vec3::new(1.12, 0.78, 0.38)
7227                    } else if wh < 0.52 {
7228                        Vec3::new(0.82, 0.86, 0.92)
7229                    } else {
7230                        Vec3::zero()
7231                    };
7232                    col = col.lerp(Vec3::new(0.08, 0.12, 0.18), win_w);
7233                    out_em = out_em.add(apt_em.scale(win_w * 0.65));
7234                    out_refl = out_refl + (0.45 - out_refl) * win_w;
7235                }
7236                (col, out_em, out_refl)
7237            }
7238            SurfaceDetailMode::StoneCobble => {
7239                let (wt_x, wt_z): (f32, f32) = Self::facade_wall_tangent(norm);
7240                let is_vert: bool = norm.get_y().abs() < 0.65;
7241                let u_coord: f32 = if is_vert {
7242                    world_p.get_x() * wt_x + world_p.get_z() * wt_z
7243                } else {
7244                    world_p.get_x()
7245                };
7246                let v_coord: f32 = if is_vert {
7247                    world_p.get_y()
7248                } else {
7249                    world_p.get_z()
7250                };
7251                let st: f32 = ((depth - 50.0) * (1.0 / 140.0)).clamp(0.0, 1.0);
7252                let s_fade: f32 = 1.0 - st * st * (3.0 - 2.0 * st);
7253                let row: f32 = (v_coord * 1.65).floor();
7254                let su: f32 = u_coord * 0.95 + 0.5 * (row * 0.5).fract();
7255                let ju: f32 = Self::box_pulse(su, 0.0, 0.06, px_size * 0.95);
7256                let jv: f32 = Self::box_pulse(v_coord * 1.65, 0.0, 0.08, px_size * 1.65);
7257                let joint: f32 = (ju + jv - ju * jv).clamp(0.0, 1.0) * s_fade;
7258                let sh: f32 = Self::sky_hash_2d(su.floor() as i32, row as i32);
7259                let sn: f32 = Self::sky_value_noise(u_coord * 3.6, v_coord * 3.6);
7260                let moss_h: f32 = ((1.35 - world_p.get_y()) * 0.8).clamp(0.0, 1.0);
7261                let moss_n: f32 = ((sn - 0.38) * (1.0 / 0.34)).clamp(0.0, 1.0);
7262                let moss: f32 = moss_h * moss_n * s_fade;
7263                let col: Vec3 = base
7264                    .scale((0.86 + 0.26 * sh + (sn - 0.5) * 0.14 * s_fade) * (1.0 - 0.36 * joint))
7265                    .lerp(Vec3::new(0.11, 0.21, 0.08), moss * 0.45);
7266                (col, emissive, refl * 0.4)
7267            }
7268            SurfaceDetailMode::OrganicFoliage => {
7269                let n1: f32 = Self::sky_value_noise(
7270                    world_p.get_x() * 2.2 + world_p.get_y() * 1.7,
7271                    world_p.get_z() * 2.2 - world_p.get_y() * 1.3,
7272                );
7273                let n2: f32 = Self::sky_value_noise(
7274                    world_p.get_x() * 6.8 - 2.1,
7275                    world_p.get_z() * 6.8 + world_p.get_y() * 4.5,
7276                );
7277                let crown_lift: f32 = (world_p.get_y() * (1.0 / 6.5)).clamp(0.0, 1.0) * 0.16;
7278                let col: Vec3 = base.scale(0.78 + 0.34 * (n1 * 0.62 + n2 * 0.38) + crown_lift);
7279                let sun_dir: Vec3 = frame_context.sun.get_direction();
7280                let back_dir: Vec3 = sun_dir.scale(-1.0).add(norm.scale(0.35)).normalize();
7281                let back_dot: f32 = view_dir.dot(back_dir).max(0.0);
7282                let sss_fol: f32 =
7283                    back_dot * back_dot * back_dot * (0.35 + 0.65 * sun_dir.get_y().max(0.0));
7284                let out_em: Vec3 =
7285                    emissive.add(col.mul(frame_context.sun.get_color()).scale(sss_fol * 0.36));
7286                (col, out_em, 0.04)
7287            }
7288            SurfaceDetailMode::VolumetricCloud => {
7289                let w_time: f32 = frame_context.world_time_secs;
7290                let puff: f32 = Self::sky_value_noise(
7291                    world_p.get_x() * 0.14 - w_time * 0.03,
7292                    world_p.get_z() * 0.14 + world_p.get_y() * 0.22,
7293                );
7294                let top_lit: f32 =
7295                    (norm.get_y() * 0.55 + 0.50 + (puff - 0.5) * 0.25).clamp(0.0, 1.0);
7296                let sun_dir: Vec3 = frame_context.sun.get_direction();
7297                let sun_col: Vec3 = frame_context.sun.get_color();
7298                let sun_fwd: f32 = view_dir.scale(-1.0).dot(sun_dir).clamp(0.0, 1.0);
7299                let silver: f32 = sun_fwd * sun_fwd * sun_fwd * sun_fwd;
7300                let sun_luma: f32 =
7301                    (sun_col.get_x() * 0.30 + sun_col.get_y() * 0.55 + sun_col.get_z() * 0.15)
7302                        .clamp(0.16, 1.45);
7303                let under_c: Vec3 = frame_context
7304                    .sun
7305                    .get_sky_zenith()
7306                    .scale(0.58)
7307                    .add(frame_context.sun.get_sky_horizon().scale(0.42))
7308                    .lerp(Vec3::new(0.48, 0.56, 0.70).scale(sun_luma), 0.52);
7309                let crown_c: Vec3 = Vec3::new(1.04, 1.03, 1.01)
7310                    .scale(sun_luma)
7311                    .add(sun_col.scale(0.16 + 0.32 * silver));
7312                let col: Vec3 = under_c.lerp(crown_c, top_lit);
7313                (col, col.scale(0.52), 0.0)
7314            }
7315            SurfaceDetailMode::RiverWater => {
7316                let w_time: f32 = frame_context.world_time_secs;
7317                let rw_a: f32 = Self::sky_value_noise(
7318                    world_p.get_x() * 0.35 + w_time * 0.22,
7319                    world_p.get_z() * 0.28 - w_time * 0.95,
7320                ) * 2.0;
7321                let caust_raw: f32 =
7322                    (world_p.get_x() * 1.2 + world_p.get_z() * 0.9 + rw_a - w_time * 1.9).sin();
7323                let caust: f32 = caust_raw * caust_raw;
7324                let col: Vec3 =
7325                    Vec3::new(0.022, 0.168, 0.185).add(Vec3::new(0.032, 0.115, 0.105).scale(caust));
7326                (col, emissive, 0.85)
7327            }
7328            _ => (base, emissive, refl),
7329        }
7330    }
7331
7332    /// Outlined leaf kernel for procedural masonry, stone, organic foliage, volumetric cloud, and river material triangles.
7333    ///
7334    /// # Arguments
7335    ///
7336    /// - `&DeferredFrameContext` - Per-frame shading context.
7337    /// - `&GShadeTri` - Triangle PBR record.
7338    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
7339    /// - `&RunScratch32` - L1-hot run scratch.
7340    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
7341    ///
7342    /// # Returns
7343    ///
7344    /// - `bool` - `true` when bloom radiance was emitted.
7345    #[inline(never)]
7346    fn shade_run_eco_material_32(
7347        frame_context: &DeferredFrameContext,
7348        tri: &GShadeTri,
7349        span: (usize, usize, Vec3, Vec3),
7350        run: &RunScratch32,
7351        out: &mut RunRowOut<'_>,
7352    ) -> bool {
7353        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
7354        let mut raw_ray: Vec3 = start_raw_ray;
7355        let mut any_bloom: bool = false;
7356        let aces_lut: &[u8] = out.aces_lut;
7357        let sun_dir: Vec3 = frame_context.sun.get_direction();
7358        let sun_col: Vec3 = frame_context.sun.get_color();
7359        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
7360        let is_cloud: bool = tri.surface_detail == SurfaceDetailMode::VolumetricCloud;
7361        for off in 0..count {
7362            let px: usize = px_start + off;
7363            let depth: f32 = run.depths[off];
7364            let world_p: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
7365            let view_to_cam: Vec3 = raw_ray.normalize().scale(-1.0);
7366            let (surf_base, surf_em, surf_refl): (Vec3, Vec3, f32) = Self::eval_eco_material_detail(
7367                tri.surface_detail,
7368                (world_p, tri.shade_n, view_to_cam),
7369                (frame_context, depth),
7370                (tri.mat_base, tri.mat_emissive, tri.mat_refl),
7371            );
7372            let ndv: f32 = tri.shade_n.dot(view_to_cam).clamp(0.02, 1.0);
7373            let om: f32 = 1.0 - ndv;
7374            let om2: f32 = om * om;
7375            let fresnel_t: f32 = om2 * om2 * om;
7376            let direct: Vec3 = if is_cloud {
7377                sun_col.scale((tri.n_dot_l * 0.45 + 0.25) * 0.42)
7378            } else {
7379                sun_col.scale(tri.n_dot_l * run.shadow[off] * tri.diffuse_scale)
7380            };
7381            let indirect: Vec3 = tri.ambient_sky.scale(0.44 * run.ao[off]).add(Vec3::new(
7382                run.gi_r[off],
7383                run.gi_g[off],
7384                run.gi_b[off],
7385            ));
7386            let mut radiance: Vec3 = surf_base.mul(direct.add(indirect)).add(surf_em);
7387            if !is_cloud && surf_refl > 0.25 && tri.do_refl {
7388                let refl: Vec3 = Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
7389                let blend: f32 = (surf_refl * (0.18 + 0.82 * fresnel_t)).clamp(0.0, 0.78);
7390                radiance = radiance.lerp(refl, blend);
7391            }
7392            if frame_context.fog_on {
7393                let py_world: f32 = world_p.get_y();
7394                let height_atten: f32 = if py_world > 0.0 {
7395                    (1.0 / (1.0 + py_world * 0.045)).max(0.32)
7396                } else {
7397                    1.0
7398                };
7399                let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
7400                let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
7401                let v_dot_l: f32 = view_to_cam.dot(sun_dir);
7402                let sa: f32 = (-v_dot_l).max(0.0);
7403                let sa2: f32 = sa * sa;
7404                let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * run.shadow[off]);
7405                let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
7406                radiance = radiance.lerp(fog_col, fog_t);
7407            }
7408            let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
7409            let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
7410            let cidx: usize = px * 4;
7411            out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
7412            out.luma[px] =
7413                (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29) >> 8)
7414                    as u8;
7415            if out.write_bloom && (px & 3) == 0 {
7416                let bidx: usize = out.bloom_off + (px >> 2);
7417                if bidx < out.bloom_band.len() {
7418                    let er: f32 = (exposed.get_x() - 1.15).max(0.0);
7419                    let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
7420                    let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
7421                    out.bloom_band[bidx] = [er, eg, eb, 0.0];
7422                    if er + eg + eb > 0.0 {
7423                        any_bloom = true;
7424                    }
7425                }
7426            }
7427            raw_ray = raw_ray.add(ray_dx);
7428        }
7429        any_bloom
7430    }
7431
7432    /// Stage A probe-only leaf kernel upsampling up to 32 consecutive pixels of `tid` into L1-hot `RunScratch32` with zero PBR register pressure.
7433    ///
7434    /// # Arguments
7435    ///
7436    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
7437    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
7438    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and L1 scratch.
7439    /// - `(&[u32], &[f32], usize, usize)` - `(g_row, d_row, px_start, w)`.
7440    /// - `(&mut usize, &mut i32)` - `(gx_cur, sub_x)` updated for the upsampled count.
7441    ///
7442    /// # Returns
7443    ///
7444    /// - `usize` - Number of validated pixels (`0, 4, 8, ..., 32`) populated into `RunScratch32`.
7445    #[inline(never)]
7446    fn upsample_run_probes_32(
7447        tri_info: (&GShadeTri, u32, bool, bool),
7448        probe_ctx: &ProbeBandContext<'_>,
7449        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
7450        rows: (&[u32], &[f32], usize, usize),
7451        cursor: (&mut usize, &mut i32),
7452    ) -> usize {
7453        let (tri, tid, rt_active, gi_active): (&GShadeTri, u32, bool, bool) = tri_info;
7454        let ProbeBandContext {
7455            top_row: probe_r0,
7456            bottom_row: probe_r1,
7457            wy0,
7458            wy1,
7459            gw_max,
7460            step2_i32,
7461            fx_lut,
7462        } = *probe_ctx;
7463        let (cached_probe_key, cached_cell, run): (
7464            &mut (usize, u32),
7465            &mut CachedProbeCell,
7466            &mut RunScratch32,
7467        ) = cache;
7468        let (g_row, d_row, px_start, width_val): (&[u32], &[f32], usize, usize) = rows;
7469        let (gx_ref, sub_ref): (&mut usize, &mut i32) = cursor;
7470        let check_shadow_edge: bool = !gi_active && tri.n_dot_l > 0.02;
7471        let mut run_len: usize = 0;
7472        while run_len < 32 {
7473            let px: usize = px_start + run_len;
7474            if px + 4 > width_val
7475                || g_row[px] != tid
7476                || g_row[px + 1] != tid
7477                || g_row[px + 2] != tid
7478                || g_row[px + 3] != tid
7479            {
7480                break;
7481            }
7482            let depths: [f32; 4] =
7483                Self::recip_4x([d_row[px], d_row[px + 1], d_row[px + 2], d_row[px + 3]]);
7484            run.depths[run_len..(run_len + 4)].copy_from_slice(&depths);
7485            run_len += 4;
7486        }
7487        if run_len == 0 {
7488            return 0;
7489        }
7490        if !rt_active {
7491            let mut sub_out: i32 = *sub_ref + ((run_len as i32) * 2);
7492            let mut gx_out: usize = *gx_ref;
7493            while sub_out >= step2_i32 {
7494                sub_out -= step2_i32;
7495                gx_out += 1;
7496            }
7497            *gx_ref = gx_out;
7498            *sub_ref = sub_out;
7499            return run_len;
7500        }
7501        let mut gx_cur: usize = *gx_ref;
7502        let mut sub_x: i32 = *sub_ref;
7503        let mut item_index: usize = 0;
7504        'run: while item_index < run_len {
7505            if sub_x >= 0 && gx_cur < gw_max {
7506                let gx0: usize = gx_cur;
7507                let gx1: usize = gx_cur + 1;
7508                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7509                if *cached_probe_key != probe_key {
7510                    let prev_adj: bool =
7511                        gx0 > 0 && *cached_probe_key == ((((gx0 - 1) << 16) | gx0), tid);
7512                    *cached_probe_key = probe_key;
7513                    if prev_adj {
7514                        CachedProbeCell::shift_right_in_place(
7515                            cached_cell,
7516                            probe_r0,
7517                            probe_r1,
7518                            gx1,
7519                            tri.shade_n,
7520                            (tri.do_refl, gi_active),
7521                        );
7522                    } else {
7523                        CachedProbeCell::load_into(
7524                            cached_cell,
7525                            probe_r0,
7526                            probe_r1,
7527                            (gx0, gx1),
7528                            tri.shade_n,
7529                            (tri.do_refl, gi_active),
7530                        );
7531                    }
7532                }
7533                let rem_in_cell: usize = (((step2_i32 - 1 - sub_x) >> 1) as usize) + 1;
7534                let mut avail: usize = (run_len - item_index).min(rem_in_cell);
7535                let mut ran_4x: bool = false;
7536                while avail >= 4 {
7537                    let base_s: usize = sub_x as usize;
7538                    let fx_4: [f32; 4] = [
7539                        fx_lut[base_s.min(15)],
7540                        fx_lut[(base_s + 2).min(15)],
7541                        fx_lut[(base_s + 4).min(15)],
7542                        fx_lut[(base_s + 6).min(15)],
7543                    ];
7544                    if !CachedProbeCell::sample_4x_same_cell(
7545                        cached_cell,
7546                        fx_4,
7547                        (wy0, wy1),
7548                        (check_shadow_edge, tri.do_refl, gi_active),
7549                        (run, item_index),
7550                    ) {
7551                        break 'run;
7552                    }
7553                    item_index += 4;
7554                    sub_x += 8;
7555                    avail -= 4;
7556                    ran_4x = true;
7557                }
7558                if avail > 0 {
7559                    if ran_4x {
7560                        let back: usize = 4 - avail;
7561                        let off_back: usize = item_index - back;
7562                        let s_back: usize = (sub_x - (back as i32) * 2) as usize;
7563                        let fx_4: [f32; 4] = [
7564                            fx_lut[s_back.min(15)],
7565                            fx_lut[(s_back + 2).min(15)],
7566                            fx_lut[(s_back + 4).min(15)],
7567                            fx_lut[(s_back + 6).min(15)],
7568                        ];
7569                        if !CachedProbeCell::sample_4x_same_cell(
7570                            cached_cell,
7571                            fx_4,
7572                            (wy0, wy1),
7573                            (check_shadow_edge, tri.do_refl, gi_active),
7574                            (run, off_back),
7575                        ) {
7576                            break 'run;
7577                        }
7578                        item_index += avail;
7579                        sub_x += (avail as i32) * 2;
7580                    } else {
7581                        for _ in 0..avail {
7582                            let fx: f32 = fx_lut[(sub_x as usize).min(15)];
7583                            let wx0: f32 = 1.0 - fx;
7584                            let bws: [f32; 4] = [wx0 * wy0, fx * wy0, wx0 * wy1, fx * wy1];
7585                            let depth_i: f32 = run.depths[item_index];
7586                            let (vm, sh, s_min, s_max, rf, gi, ao): (
7587                                u32,
7588                                f32,
7589                                f32,
7590                                f32,
7591                                Vec3,
7592                                Vec3,
7593                                f32,
7594                            ) = CachedProbeCell::sample_1x(
7595                                cached_cell,
7596                                bws,
7597                                depth_i,
7598                                (tri.do_refl, gi_active),
7599                            );
7600                            let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7601                                18.0
7602                            } else {
7603                                42.0
7604                            };
7605                            if vm == 0
7606                                || (check_shadow_edge
7607                                    && depth_i < edge_max_d
7608                                    && (s_max - s_min) > 0.12)
7609                            {
7610                                break 'run;
7611                            }
7612                            run.shadow[item_index] = sh;
7613                            if tri.do_refl {
7614                                run.refl_r[item_index] = rf.get_x();
7615                                run.refl_g[item_index] = rf.get_y();
7616                                run.refl_b[item_index] = rf.get_z();
7617                            }
7618                            if gi_active {
7619                                run.gi_r[item_index] = gi.get_x();
7620                                run.gi_g[item_index] = gi.get_y();
7621                                run.gi_b[item_index] = gi.get_z();
7622                                run.ao[item_index] = ao;
7623                            }
7624                            item_index += 1;
7625                            sub_x += 2;
7626                        }
7627                    }
7628                }
7629                if sub_x >= step2_i32 {
7630                    sub_x -= step2_i32;
7631                    gx_cur += 1;
7632                }
7633            } else {
7634                let (gx0, gx1): (usize, usize) = if sub_x <= 0 && gx_cur == 0 {
7635                    (0, gw_max.min(1))
7636                } else {
7637                    (gw_max, gw_max)
7638                };
7639                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7640                if *cached_probe_key != probe_key {
7641                    *cached_probe_key = probe_key;
7642                    CachedProbeCell::load_into(
7643                        cached_cell,
7644                        probe_r0,
7645                        probe_r1,
7646                        (gx0, gx1),
7647                        tri.shade_n,
7648                        (tri.do_refl, gi_active),
7649                    );
7650                }
7651                let bws: [f32; 4] = [wy0, 0.0, wy1, 0.0];
7652                let depth_i: f32 = run.depths[item_index];
7653                let (vm, sh, s_min, s_max, rf, gi, ao): (u32, f32, f32, f32, Vec3, Vec3, f32) =
7654                    CachedProbeCell::sample_1x(cached_cell, bws, depth_i, (tri.do_refl, gi_active));
7655                let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7656                    18.0
7657                } else {
7658                    42.0
7659                };
7660                if vm == 0 || (check_shadow_edge && depth_i < edge_max_d && (s_max - s_min) > 0.12)
7661                {
7662                    break 'run;
7663                }
7664                run.shadow[item_index] = sh;
7665                if tri.do_refl {
7666                    run.refl_r[item_index] = rf.get_x();
7667                    run.refl_g[item_index] = rf.get_y();
7668                    run.refl_b[item_index] = rf.get_z();
7669                }
7670                if gi_active {
7671                    run.gi_r[item_index] = gi.get_x();
7672                    run.gi_g[item_index] = gi.get_y();
7673                    run.gi_b[item_index] = gi.get_z();
7674                    run.ao[item_index] = ao;
7675                }
7676                item_index += 1;
7677                sub_x += 2;
7678                if sub_x >= step2_i32 {
7679                    sub_x -= step2_i32;
7680                    gx_cur += 1;
7681                }
7682            }
7683        }
7684        let out_count: usize = item_index & !3;
7685        if out_count == item_index {
7686            *gx_ref = gx_cur;
7687            *sub_ref = sub_x;
7688        } else {
7689            let mut final_sub: i32 = *sub_ref + ((out_count as i32) * 2);
7690            let mut final_gx: usize = *gx_ref;
7691            while final_sub >= step2_i32 {
7692                final_sub -= step2_i32;
7693                final_gx += 1;
7694            }
7695            *gx_ref = final_gx;
7696            *sub_ref = final_sub;
7697        }
7698        out_count
7699    }
7700
7701    /// 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).
7702    ///
7703    /// # Arguments
7704    ///
7705    /// - `&DeferredFrameContext` - Per-frame camera, sun, and fog configuration.
7706    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
7707    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
7708    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and 32-pixel L1 scratch.
7709    /// - `(&[u32], &[f32], RunRowOut<'_>)` - Scanline G-Buffer, depth, and writable output buffers.
7710    /// - `(&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32)` - Scanline cursor `(px, raw_ray, ray_dx, gx_cur, sub_x)`.
7711    ///
7712    /// # Returns
7713    ///
7714    /// - `bool` - `true` when any 4-pixel span in the run emitted non-zero HDR bloom radiance.
7715    #[inline(always)]
7716    fn shade_tri_run_4x(
7717        frame_context: &DeferredFrameContext,
7718        tri_info: (&GShadeTri, u32, bool, bool),
7719        probe_ctx: &ProbeBandContext<'_>,
7720        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
7721        rows: (&[u32], &[f32], RunRowOut<'_>),
7722        state: (&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32),
7723    ) -> bool {
7724        let (tri, tid, _, _): (&GShadeTri, u32, bool, bool) = tri_info;
7725        let (cached_probe_key, cached_cell, run): (
7726            &mut (usize, u32),
7727            &mut CachedProbeCell,
7728            &mut RunScratch32,
7729        ) = cache;
7730        let (g_row, d_row, mut out_row): (&[u32], &[f32], RunRowOut<'_>) = rows;
7731        let (px_ref, raw_ray_ref, ray_dx, gx_ref, sub_ref): (
7732            &mut usize,
7733            &mut Vec3,
7734            Vec3,
7735            &mut usize,
7736            &mut i32,
7737        ) = state;
7738        let width_val: usize = frame_context.width;
7739        let sn: Vec3 = tri.shade_n;
7740        let detail_kind: u8 =
7741            if tri.surface_detail == SurfaceDetailMode::OceanWater && sn.get_y() > 0.90 {
7742                3
7743            } else if tri.surface_detail == SurfaceDetailMode::ArchitecturalFacade
7744                && sn.get_y().abs() < 0.25
7745                && tri.mat_emissive.length_sq() < 0.02
7746            {
7747                2
7748            } else if tri.surface_detail == SurfaceDetailMode::RoadSurface && sn.get_y() > 0.92 {
7749                1
7750            } else if matches!(
7751                tri.surface_detail,
7752                SurfaceDetailMode::MasonryBrick
7753                    | SurfaceDetailMode::StoneCobble
7754                    | SurfaceDetailMode::OrganicFoliage
7755                    | SurfaceDetailMode::VolumetricCloud
7756                    | SurfaceDetailMode::RiverWater
7757            ) {
7758                4
7759            } else {
7760                0
7761            };
7762        let mut any_bloom: bool = false;
7763        loop {
7764            let px0: usize = *px_ref;
7765            let count: usize = Self::upsample_run_probes_32(
7766                tri_info,
7767                probe_ctx,
7768                (cached_probe_key, cached_cell, run),
7769                (g_row, d_row, px0, width_val),
7770                (gx_ref, sub_ref),
7771            );
7772            if count == 0 {
7773                break;
7774            }
7775            let hit: bool = match detail_kind {
7776                4 => Self::shade_run_eco_material_32(
7777                    frame_context,
7778                    tri,
7779                    (px0, count, *raw_ray_ref, ray_dx),
7780                    run,
7781                    &mut out_row,
7782                ),
7783                3 => Self::shade_run_ocean_32(
7784                    frame_context,
7785                    tri,
7786                    (px0, count, *raw_ray_ref, ray_dx),
7787                    run,
7788                    &mut out_row,
7789                ),
7790                2 => Self::shade_run_facade_32(
7791                    frame_context,
7792                    tri,
7793                    (px0, count, *raw_ray_ref, ray_dx),
7794                    run,
7795                    &mut out_row,
7796                ),
7797                1 => Self::shade_run_road_32(
7798                    frame_context,
7799                    tri,
7800                    (px0, count, *raw_ray_ref, ray_dx),
7801                    run,
7802                    &mut out_row,
7803                ),
7804                _ => Self::shade_run_plain_32(
7805                    frame_context,
7806                    tri,
7807                    (px0, count, *raw_ray_ref, ray_dx),
7808                    run,
7809                    &mut out_row,
7810                ),
7811            };
7812            if hit {
7813                any_bloom = true;
7814            }
7815            *px_ref = px0 + count;
7816            *raw_ray_ref = raw_ray_ref.add(ray_dx.scale(count as f32));
7817            if count < 32 {
7818                break;
7819            }
7820        }
7821        let _: u32 = tid;
7822        any_bloom
7823    }
7824
7825    /// 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.
7826    ///
7827    /// # Arguments
7828    ///
7829    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and RT settings.
7830    /// - `&ShadeBandInputs<'_>` - Read-only depth, G-Buffer IDs, shading records, raw SoA probes, static BVH, and dynamic instances.
7831    /// - `(usize, &mut [u8], &mut [u8], &mut [[f32; 4]])` - `(py_start, color band, luma band, bloom band)`.
7832    ///
7833    /// # Returns
7834    ///
7835    /// - `(usize, bool)` - `(edge_rays_traced, band_emitted_nonzero_bloom)`.
7836    fn shade_deferred_band(
7837        frame_context: &DeferredFrameContext,
7838        inputs: &ShadeBandInputs<'_>,
7839        outputs: (usize, &mut [u8], &mut [u8], &mut [[f32; 4]]),
7840    ) -> (usize, bool) {
7841        let depth_buf: &[f32] = inputs.depth_buf;
7842        let g_tri_idx: &[u32] = inputs.g_tri_idx;
7843        let shaded_tris: &[GShadeTri] = inputs.shaded_tris;
7844        let raw_probes: &RtProbeGridSoa = inputs.raw_probes;
7845        let (py_start, color_band, luma_band, bloom_band): (
7846            usize,
7847            &mut [u8],
7848            &mut [u8],
7849            &mut [[f32; 4]],
7850        ) = outputs;
7851        let width_val: usize = frame_context.width;
7852        let gw: usize = frame_context.grid_width;
7853        let gh: usize = frame_context.grid_height;
7854        let gw_max: usize = gw.saturating_sub(1);
7855        let gh_max: usize = gh.saturating_sub(1);
7856        let border_width: usize = frame_context.bloom_width;
7857        let rt_step: usize = frame_context.raytrace_step.max(1);
7858        let step_f: f32 = rt_step as f32;
7859        let inv_step: f32 = 1.0 / step_f;
7860        let step2_i32: i32 = (rt_step * 2) as i32;
7861        let init_sub_x: i32 = 1 - (rt_step as i32);
7862        let inv_step2: f32 = 0.5 * inv_step;
7863        let mut fx_lut: [f32; 16] = [0.0; 16];
7864        let lut_len: usize = (rt_step * 2).min(16);
7865        for (idx, slot) in fx_lut.iter_mut().take(lut_len).enumerate() {
7866            *slot = (idx as f32) * inv_step2;
7867        }
7868        let sun_dir: Vec3 = frame_context.sun.get_direction();
7869        let inv_sun: Vec3 = frame_context.inv_sun_dir;
7870        let sun_col: Vec3 = frame_context.sun.get_color();
7871        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
7872        let rt_active: bool = frame_context.raytrace_mode != RayTracingMode::Off
7873            && frame_context.raytrace_step > 0
7874            && !raw_probes.is_empty();
7875        let gi_active: bool = (frame_context.raytrace_mode == RayTracingMode::FullPathTracedGi
7876            || frame_context.has_clustered_lights)
7877            && rt_active;
7878        let band_rows: usize = luma_band.len() / width_val.max(1);
7879        let ray_dx: Vec3 = frame_context
7880            .camera_right_scaled
7881            .scale(2.0 * frame_context.inv_width);
7882        let ndc_x0: f32 = frame_context.inv_width - 1.0;
7883        let mut edge_rays: usize = 0;
7884        let mut bloom_emitted: bool = false;
7885        let mut static_shadow_cache: u32 = u32::MAX;
7886        let mut dyn_shadow_cache: u32 = u32::MAX;
7887        let use_stack_denoise: bool = rt_active && gw <= PROBE_ROW_STACK_CAP;
7888        let mut a_is_r0: bool = true;
7889        let mut run_scratch: RunScratch32 = RunScratch32 {
7890            depths: [1.0; 32],
7891            shadow: [1.0; 32],
7892            refl_r: [sky_horizon.get_x(); 32],
7893            refl_g: [sky_horizon.get_y(); 32],
7894            refl_b: [sky_horizon.get_z(); 32],
7895            gi_r: [0.0; 32],
7896            gi_g: [0.0; 32],
7897            gi_b: [0.0; 32],
7898            ao: [1.0; 32],
7899        };
7900        PROBE_ROW_SCRATCH.with(|cell: &RefCell<Box<RtProbeRowScratch>>| {
7901            let mut guard: RefMut<'_, Box<RtProbeRowScratch>> = cell.borrow_mut();
7902            let scratch: &mut RtProbeRowScratch = guard.as_mut();
7903            if scratch.frame_gen != frame_context.probe_frame_generation {
7904                scratch.frame_gen = frame_context.probe_frame_generation;
7905                scratch.cached_gy_a = usize::MAX;
7906                scratch.cached_gy_b = usize::MAX;
7907            }
7908            for local_y in 0..band_rows {
7909                let py: usize = py_start + local_y;
7910                let row_off: usize = py * width_val;
7911                let out_row_luma: usize = local_y * width_val;
7912                let out_row_rgba: usize = out_row_luma * 4;
7913                let write_bloom_row: bool =
7914                    frame_context.bloom_on && (py & 3) == 0 && border_width > 0;
7915                let mut row_bloom_hit: bool = false;
7916                let bloom_row_off: usize = if write_bloom_row {
7917                    (local_y / 4) * border_width
7918                } else {
7919                    0
7920                };
7921                let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * frame_context.inv_height);
7922                let row_base_dir: Vec3 = frame_context
7923                    .camera_forward
7924                    .add(frame_context.camera_up_scaled.scale(ndc_y));
7925                let gy_f: f32 = (((py as f32) + 0.5) * inv_step - 0.5).clamp(0.0, gh_max as f32);
7926                let gy0: usize = (gy_f as usize).min(gh_max);
7927                let gy1: usize = (gy0 + 1).min(gh_max);
7928                let fy: f32 = gy_f - (gy0 as f32);
7929                let wy0: f32 = 1.0 - fy;
7930                let wy1: f32 = fy;
7931                if use_stack_denoise {
7932                    if gy0 == scratch.cached_gy_a {
7933                        a_is_r0 = true;
7934                    } else if gy0 == scratch.cached_gy_b {
7935                        a_is_r0 = false;
7936                    } else {
7937                        a_is_r0 = true;
7938                        Self::populate_probe_row_stack(
7939                            raw_probes,
7940                            gw,
7941                            gh,
7942                            gy0,
7943                            (inputs.denoise_probes, inputs.denoise_gi_channels),
7944                            &mut scratch.buf_a,
7945                        );
7946                        scratch.cached_gy_a = gy0;
7947                    }
7948                    if gy1 != gy0 {
7949                        if a_is_r0 && gy1 != scratch.cached_gy_b {
7950                            Self::populate_probe_row_stack(
7951                                raw_probes,
7952                                gw,
7953                                gh,
7954                                gy1,
7955                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7956                                &mut scratch.buf_b,
7957                            );
7958                            scratch.cached_gy_b = gy1;
7959                        } else if !a_is_r0 && gy1 != scratch.cached_gy_a {
7960                            Self::populate_probe_row_stack(
7961                                raw_probes,
7962                                gw,
7963                                gh,
7964                                gy1,
7965                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7966                                &mut scratch.buf_a,
7967                            );
7968                            scratch.cached_gy_a = gy1;
7969                        }
7970                    }
7971                }
7972                let (probe_r0, probe_r1): (RtProbeRowView<'_>, RtProbeRowView<'_>) =
7973                    if use_stack_denoise {
7974                        let (v0, v_other): (RtProbeRowView<'_>, RtProbeRowView<'_>) = if a_is_r0 {
7975                            (scratch.buf_a.as_view(gw), scratch.buf_b.as_view(gw))
7976                        } else {
7977                            (scratch.buf_b.as_view(gw), scratch.buf_a.as_view(gw))
7978                        };
7979                        if gy1 == gy0 { (v0, v0) } else { (v0, v_other) }
7980                    } else if rt_active {
7981                        let grid: &RtProbeGridSoa = if !inputs.wide_denoised_probes.is_empty() {
7982                            inputs.wide_denoised_probes
7983                        } else {
7984                            raw_probes
7985                        };
7986                        (grid.row_view(gy0, gw), grid.row_view(gy1, gw))
7987                    } else {
7988                        (scratch.buf_a.as_view(0), scratch.buf_a.as_view(0))
7989                    };
7990                let mut cached_probe_key: (usize, u32) = (usize::MAX, u32::MAX);
7991                let mut cached_cell: CachedProbeCell = CachedProbeCell::empty();
7992                let mut raw_ray: Vec3 =
7993                    row_base_dir.add(frame_context.camera_right_scaled.scale(ndc_x0));
7994                let mut gx_cur: usize = 0;
7995                let mut sub_x: i32 = init_sub_x;
7996                let g_row: &[u32] = &g_tri_idx[row_off..(row_off + width_val)];
7997                let d_row: &[f32] = &depth_buf[row_off..(row_off + width_val)];
7998                let c_row: &mut [u8] =
7999                    &mut color_band[out_row_rgba..(out_row_rgba + width_val * 4)];
8000                let l_row: &mut [u8] = &mut luma_band[out_row_luma..(out_row_luma + width_val)];
8001                let mut px: usize = 0;
8002                while px < width_val {
8003                    let tid: u32 = g_row[px];
8004                    if tid == u32::MAX {
8005                        let sky_hdr: Vec3 =
8006                            Self::sample_sky_lut(inputs.sky_lut, raw_ray, &frame_context.sun);
8007                        let exposed: Vec3 = sky_hdr.scale(frame_context.exposure_scale);
8008                        let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
8009                        let luma: u8 = (((rgba[0] as u32) * 77
8010                            + (rgba[1] as u32) * 150
8011                            + (rgba[2] as u32) * 29)
8012                            >> 8) as u8;
8013                        if write_bloom_row && (px & 3) == 0 {
8014                            let bidx: usize = bloom_row_off + (px >> 2);
8015                            if bidx < bloom_band.len() {
8016                                let er: f32 = (exposed.get_x() - 1.15).max(0.0);
8017                                let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
8018                                let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
8019                                bloom_band[bidx] = [er, eg, eb, 0.0];
8020                                if er + eg + eb > 0.0 {
8021                                    bloom_emitted = true;
8022                                    row_bloom_hit = true;
8023                                }
8024                            }
8025                        }
8026                        let cidx_sky: usize = px * 4;
8027                        c_row[cidx_sky..(cidx_sky + 4)].copy_from_slice(&rgba);
8028                        l_row[px] = luma;
8029                        raw_ray = raw_ray.add(ray_dx);
8030                        sub_x += 2;
8031                        if sub_x >= step2_i32 {
8032                            sub_x -= step2_i32;
8033                            gx_cur += 1;
8034                        }
8035                        px += 1;
8036                        continue;
8037                    }
8038                    if px + 4 <= width_val
8039                        && g_row[px + 1] == tid
8040                        && g_row[px + 2] == tid
8041                        && g_row[px + 3] == tid
8042                        && shaded_tris[tid as usize].smooth_idx == u32::MAX
8043                    {
8044                        let tri: &GShadeTri = &shaded_tris[tid as usize];
8045                        let prev_px: usize = px;
8046                        let probe_band: ProbeBandContext<'_> = ProbeBandContext {
8047                            top_row: &probe_r0,
8048                            bottom_row: &probe_r1,
8049                            wy0,
8050                            wy1,
8051                            gw_max,
8052                            step2_i32,
8053                            fx_lut: &fx_lut,
8054                        };
8055                        let hit_b: bool = Self::shade_tri_run_4x(
8056                            frame_context,
8057                            (tri, tid, rt_active, gi_active),
8058                            &probe_band,
8059                            (&mut cached_probe_key, &mut cached_cell, &mut run_scratch),
8060                            (
8061                                g_row,
8062                                d_row,
8063                                RunRowOut {
8064                                    color: c_row,
8065                                    luma: l_row,
8066                                    write_bloom: write_bloom_row,
8067                                    bloom_off: bloom_row_off,
8068                                    bloom_band,
8069                                    sky_lut: inputs.sky_lut,
8070                                    aces_lut: inputs.aces_lut,
8071                                },
8072                            ),
8073                            (&mut px, &mut raw_ray, ray_dx, &mut gx_cur, &mut sub_x),
8074                        );
8075                        if hit_b {
8076                            bloom_emitted = true;
8077                            row_bloom_hit = true;
8078                        }
8079                        if px != prev_px {
8080                            continue;
8081                        }
8082                    }
8083                    let cidx: usize = px * 4;
8084                    let tri: &GShadeTri = &shaded_tris[tid as usize];
8085                    let depth: f32 = 1.0 / d_row[px].max(1e-6);
8086                    let world_p_px: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
8087                    if tri.smooth_idx != u32::MAX
8088                        && let Some(smooth_tri) = inputs.smooth_tris.get(tri.smooth_idx as usize)
8089                    {
8090                        let smooth_rgba: [u8; 4] = Self::shade_pixel_principled_smooth(
8091                            frame_context,
8092                            inputs,
8093                            tri,
8094                            smooth_tri,
8095                            (px, py),
8096                            (world_p_px, raw_ray, depth),
8097                        );
8098                        c_row[cidx..(cidx + 4)].copy_from_slice(&smooth_rgba);
8099                        l_row[px] = (((smooth_rgba[0] as u32) * 77
8100                            + (smooth_rgba[1] as u32) * 150
8101                            + (smooth_rgba[2] as u32) * 29)
8102                            >> 8) as u8;
8103                        raw_ray = raw_ray.add(ray_dx);
8104                        sub_x += 2;
8105                        if sub_x >= step2_i32 {
8106                            sub_x -= step2_i32;
8107                            gx_cur += 1;
8108                        }
8109                        px += 1;
8110                        continue;
8111                    }
8112                    let mut shadow: f32 = 1.0;
8113                    let mut refl: Vec3 = sky_horizon;
8114                    let mut gi_col: Vec3 = Vec3::zero();
8115                    let mut ao: f32 = 1.0;
8116                    if rt_active {
8117                        let (gx0, gx1, fx): (usize, usize, f32) = if sub_x <= 0 && gx_cur == 0 {
8118                            (0, gw_max.min(1), 0.0)
8119                        } else if gx_cur >= gw_max {
8120                            (gw_max, gw_max, 0.0)
8121                        } else {
8122                            (gx_cur, gx_cur + 1, fx_lut[(sub_x as usize).min(15)])
8123                        };
8124                        let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
8125                        if cached_probe_key != probe_key {
8126                            cached_probe_key = probe_key;
8127                            CachedProbeCell::load_into(
8128                                &mut cached_cell,
8129                                &probe_r0,
8130                                &probe_r1,
8131                                (gx0, gx1),
8132                                tri.shade_n,
8133                                (tri.do_refl, gi_active),
8134                            );
8135                        }
8136                        let wx0: f32 = 1.0 - fx;
8137                        let wx1: f32 = fx;
8138                        let bws: [f32; 4] = [wx0 * wy0, wx1 * wy0, wx0 * wy1, wx1 * wy1];
8139                        let (valid_matches, sh_b, s_min, s_max, rf_b, gi_b, ao_b): (
8140                            u32,
8141                            f32,
8142                            f32,
8143                            f32,
8144                            Vec3,
8145                            Vec3,
8146                            f32,
8147                        ) = CachedProbeCell::sample_1x(
8148                            &cached_cell,
8149                            bws,
8150                            depth,
8151                            (tri.do_refl, gi_active),
8152                        );
8153                        let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
8154                            18.0
8155                        } else {
8156                            42.0
8157                        };
8158                        let need_exact_shadow: bool = tri.n_dot_l > 0.02
8159                            && depth < edge_max_d
8160                            && (valid_matches == 0 || (!gi_active && (s_max - s_min) > 0.12));
8161                        if need_exact_shadow {
8162                            let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
8163                            edge_rays += 1;
8164                            shadow = if World3D::trace_any_shadow_with_instances(
8165                                inputs.static_bvh,
8166                                inputs.dyn_instances,
8167                                inputs.local_bvhs,
8168                                (origin, sun_dir, inv_sun),
8169                                (0.05, 140.0),
8170                                (&mut static_shadow_cache, &mut dyn_shadow_cache),
8171                            ) {
8172                                0.22
8173                            } else {
8174                                1.0
8175                            };
8176                        } else if valid_matches > 0 {
8177                            shadow = sh_b;
8178                        }
8179                        if tri.do_refl {
8180                            if valid_matches > 0 {
8181                                refl = rf_b;
8182                            } else if depth < 32.0 {
8183                                let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
8184                                let refl_dir: Vec3 =
8185                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
8186                                let inv_refl: Vec3 = Ray3D::safe_inv_vec(refl_dir);
8187                                edge_rays += 1;
8188                                refl = match World3D::trace_closest_with_instances(
8189                                    inputs.static_bvh,
8190                                    inputs.dyn_instances,
8191                                    inputs.local_bvhs,
8192                                    (origin, refl_dir, inv_refl),
8193                                    (0.08, 96.0),
8194                                ) {
8195                                    Some((_, hit_n, hit_mat)) => Self::shade_surface_hit(
8196                                        hit_n,
8197                                        hit_mat,
8198                                        &frame_context.sun,
8199                                        gi_active,
8200                                    ),
8201                                    None => Self::sample_sky_lut(
8202                                        inputs.sky_lut,
8203                                        refl_dir,
8204                                        &frame_context.sun,
8205                                    ),
8206                                };
8207                            } else {
8208                                let refl_dir: Vec3 =
8209                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
8210                                refl = Self::sample_sky_lut(
8211                                    inputs.sky_lut,
8212                                    refl_dir,
8213                                    &frame_context.sun,
8214                                );
8215                            }
8216                        }
8217                        if gi_active && valid_matches > 0 {
8218                            gi_col = gi_b;
8219                            ao = ao_b;
8220                        }
8221                    }
8222                    let view_in: Vec3 = raw_ray.normalize();
8223                    let view_to_cam: Vec3 = view_in.scale(-1.0);
8224                    let ndv_raw: f32 = tri.shade_n.dot(view_to_cam);
8225                    let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
8226                    let f_om: f32 = 1.0 - ndv;
8227                    let f_om2: f32 = f_om * f_om;
8228                    let fresnel_t: f32 = f_om2 * f_om2 * f_om;
8229                    let v_dot_l: f32 = view_to_cam.dot(sun_dir);
8230                    let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
8231                        let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
8232                        let h_len_sq: f32 = 2.0_f32.mul_add(v_dot_l, 2.0).max(1e-6);
8233                        let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
8234                        let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
8235                        let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * shadow;
8236                        let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
8237                        let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
8238                        let spec_scalar: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
8239                        let fresnel_rgb: Vec3 =
8240                            tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
8241                        fresnel_rgb.mul(sun_col.scale(spec_scalar))
8242                    } else {
8243                        Vec3::zero()
8244                    };
8245                    let mut surf_base: Vec3 = tri.mat_base;
8246                    let mut surf_emissive: Vec3 = tri.mat_emissive;
8247                    let mut surf_refl: f32 = tri.mat_refl;
8248                    match tri.surface_detail {
8249                        SurfaceDetailMode::ArchitecturalFacade
8250                            if tri.shade_n.get_y().abs() < 0.25
8251                                && surf_emissive.length_sq() < 0.02 =>
8252                        {
8253                            let (wall_tan_x, wall_tan_z): (f32, f32) =
8254                                Self::facade_wall_tangent(tri.shade_n);
8255                            let u_coord: f32 = world_p_px
8256                                .get_x()
8257                                .mul_add(wall_tan_x, world_p_px.get_z() * wall_tan_z);
8258                            let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
8259                                (u_coord, world_p_px.get_y(), depth, frame_context.inv_height),
8260                                (surf_base, surf_emissive, surf_refl),
8261                            );
8262                            surf_base = nb;
8263                            surf_emissive = ne;
8264                            surf_refl = nr;
8265                        }
8266                        SurfaceDetailMode::RoadSurface
8267                            if tri.shade_n.get_y() > 0.92 && world_p_px.get_y().abs() < 0.15 =>
8268                        {
8269                            let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
8270                                (
8271                                    world_p_px.get_x(),
8272                                    world_p_px.get_z(),
8273                                    depth,
8274                                    frame_context.inv_height,
8275                                ),
8276                                (
8277                                    view_to_cam,
8278                                    fresnel_t,
8279                                    tri.metallic,
8280                                    frame_context.world_time_secs,
8281                                ),
8282                                surf_base,
8283                            );
8284                            surf_base = nb;
8285                            surf_refl = nr;
8286                        }
8287                        SurfaceDetailMode::MasonryBrick
8288                        | SurfaceDetailMode::StoneCobble
8289                        | SurfaceDetailMode::OrganicFoliage
8290                        | SurfaceDetailMode::VolumetricCloud
8291                        | SurfaceDetailMode::RiverWater => {
8292                            let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_eco_material_detail(
8293                                tri.surface_detail,
8294                                (world_p_px, tri.shade_n, view_to_cam),
8295                                (frame_context, depth),
8296                                (surf_base, surf_emissive, surf_refl),
8297                            );
8298                            surf_base = nb;
8299                            surf_emissive = ne;
8300                            surf_refl = nr;
8301                        }
8302                        _ => {}
8303                    }
8304                    let is_east_coastal_bay: bool = tri.surface_detail
8305                        == SurfaceDetailMode::RoadSurface
8306                        && tri.shade_n.get_y() > 0.92
8307                        && world_p_px.get_y().abs() < 0.15
8308                        && world_p_px.get_x() > 144.0
8309                        && {
8310                            let bay_spine_z: f32 = world_p_px.get_z().clamp(-140.0, 140.0);
8311                            (world_p_px.get_x() - 64.0).hypot(world_p_px.get_z() - bay_spine_z)
8312                                > 78.2
8313                        };
8314                    let radiance: Vec3 = if (tri.surface_detail == SurfaceDetailMode::OceanWater
8315                        && tri.shade_n.get_y() > 0.90)
8316                        || is_east_coastal_bay
8317                    {
8318                        Self::eval_ocean_water_radiance(
8319                            frame_context,
8320                            inputs.sky_lut,
8321                            (world_p_px, view_to_cam, depth),
8322                            (shadow, refl),
8323                        )
8324                    } else {
8325                        let kd_scale: f32 =
8326                            (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
8327                        let direct: Vec3 = sun_col.scale(tri.n_dot_l * shadow * kd_scale);
8328                        let indirect: Vec3 = tri.ambient_sky.scale(0.44 * ao).add(gi_col);
8329                        let mut lit: Vec3 = surf_base
8330                            .mul(direct.add(indirect))
8331                            .add(spec_col)
8332                            .add(surf_emissive);
8333                        if tri.do_refl {
8334                            let refl_fresnel: f32 =
8335                                (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
8336                            let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
8337                            lit = lit.lerp(refl, refl_blend);
8338                        }
8339                        if frame_context.fog_on {
8340                            let py_world: f32 = world_p_px.get_y();
8341                            let height_atten: f32 = if py_world > 0.0 {
8342                                (1.0 / (1.0 + py_world * 0.045)).max(0.32)
8343                            } else {
8344                                1.0
8345                            };
8346                            let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
8347                            let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
8348                            let sun_align: f32 = (-v_dot_l).max(0.0);
8349                            let sa2: f32 = sun_align * sun_align;
8350                            let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * shadow);
8351                            let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
8352                            lit = lit.lerp(fog_col, fog_t);
8353                        }
8354                        lit
8355                    };
8356                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
8357                    if write_bloom_row && (px & 3) == 0 {
8358                        let bidx: usize = bloom_row_off + (px >> 2);
8359                        if bidx < bloom_band.len() {
8360                            let er: f32 = (exposed.get_x() - 1.05).max(0.0);
8361                            let eg: f32 = (exposed.get_y() - 1.05).max(0.0);
8362                            let eb: f32 = (exposed.get_z() - 1.05).max(0.0);
8363                            bloom_band[bidx] = [er, eg, eb, 0.0];
8364                            let rg_pos: bool = er > 0.0 || eg > 0.0;
8365                            if rg_pos || eb > 0.0 {
8366                                bloom_emitted = true;
8367                                row_bloom_hit = true;
8368                            }
8369                        }
8370                    }
8371                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
8372                    c_row[cidx..(cidx + 4)].copy_from_slice(&rgba);
8373                    l_row[px] =
8374                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
8375                            >> 8) as u8;
8376                    raw_ray = raw_ray.add(ray_dx);
8377                    sub_x += 2;
8378                    if sub_x >= step2_i32 {
8379                        sub_x -= step2_i32;
8380                        gx_cur += 1;
8381                    }
8382                    px += 1;
8383                }
8384                if row_bloom_hit {
8385                    let by: usize = py >> 2;
8386                    let word: usize = by >> 6;
8387                    if word < inputs.bloom_row_bits.len() {
8388                        let _: u64 = inputs.bloom_row_bits[word]
8389                            .fetch_or(1_u64 << (by & 63), Ordering::Relaxed);
8390                    }
8391                }
8392            }
8393        });
8394        (edge_rays, bloom_emitted)
8395    }
8396
8397    /// Samples the quarter-resolution HDR bloom buffer using row-hoisted coordinates for active bloom tiles.
8398    ///
8399    /// # Arguments
8400    ///
8401    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom slice.
8402    /// - `(usize, usize, usize)` - Row offsets and max X `(bloom_r0, bloom_r1, bw_max)`.
8403    /// - `(usize, f32, f32)` - Tile column and fractional weights `(bx0, tx, ty)`.
8404    ///
8405    /// # Returns
8406    ///
8407    /// - `[f32; 3]` - Bilinearly filtered bloom RGB radiance.
8408    #[inline(always)]
8409    #[must_use]
8410    fn sample_bloom_bilinear_row(
8411        bloom: &[[f32; 4]],
8412        row_info: (usize, usize, usize),
8413        tap: (usize, f32, f32),
8414    ) -> [f32; 3] {
8415        let (r0, r1, bw_max): (usize, usize, usize) = row_info;
8416        let (bx0, tx, ty): (usize, f32, f32) = tap;
8417        let bx1: usize = (bx0 + 1).min(bw_max);
8418        let c00: [f32; 4] = bloom[r0 + bx0];
8419        let c10: [f32; 4] = bloom[r0 + bx1];
8420        let c01: [f32; 4] = bloom[r1 + bx0];
8421        let c11: [f32; 4] = bloom[r1 + bx1];
8422        let omt_x: f32 = 1.0 - tx;
8423        let omt_y: f32 = 1.0 - ty;
8424        let w00: f32 = omt_x * omt_y;
8425        let w10: f32 = tx * omt_y;
8426        let w01: f32 = omt_x * ty;
8427        let w11: f32 = tx * ty;
8428        [
8429            c00[0].mul_add(w00, c10[0].mul_add(w10, c01[0].mul_add(w01, c11[0] * w11))),
8430            c00[1].mul_add(w00, c10[1].mul_add(w10, c01[1].mul_add(w01, c11[1] * w11))),
8431            c00[2].mul_add(w00, c10[2].mul_add(w10, c01[2].mul_add(w01, c11[2] * w11))),
8432        ]
8433    }
8434
8435    /// Populates `bloom_tile_active` (`1` where any bilinear corner contributes `>= 1` RGB LSB) and returns whether any tile is active.
8436    ///
8437    /// # Arguments
8438    ///
8439    /// - `usize` - Quarter-resolution bloom grid width.
8440    /// - `usize` - Quarter-resolution bloom grid height.
8441    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom buffer.
8442    /// - `&mut [u8]` - Output tile-activity mask slice (`len >= bw * bh`).
8443    ///
8444    /// # Returns
8445    ///
8446    /// - `bool` - `true` when at least one bloom tile requires sampling in `post_process_band`.
8447    #[must_use]
8448    fn build_bloom_tile_mask(
8449        border_width: usize,
8450        bh: usize,
8451        bloom: &[[f32; 4]],
8452        tile_active: &mut [u8],
8453    ) -> bool {
8454        let len: usize = border_width * bh;
8455        let short_bloom: bool = len == 0 || bloom.len() < len;
8456        if short_bloom || tile_active.len() < len {
8457            return false;
8458        }
8459        let bw_max: usize = border_width - 1;
8460        let bh_max: usize = bh - 1;
8461        let mut any_active: bool = false;
8462        for by in 0..bh {
8463            let r0: usize = by * border_width;
8464            let r1: usize = (by + 1).min(bh_max) * border_width;
8465            for bx in 0..border_width {
8466                let bx1: usize = (bx + 1).min(bw_max);
8467                let c00: [f32; 4] = bloom[r0 + bx];
8468                let c10: [f32; 4] = bloom[r0 + bx1];
8469                let c01: [f32; 4] = bloom[r1 + bx];
8470                let c11: [f32; 4] = bloom[r1 + bx1];
8471                let max_r: f32 = c00[0].max(c10[0]).max(c01[0]).max(c11[0]);
8472                let max_g: f32 = c00[1].max(c10[1]).max(c01[1]).max(c11[1]);
8473                let max_b: f32 = c00[2].max(c10[2]).max(c01[2]).max(c11[2]);
8474                let active: bool = max_r.max(max_g).max(max_b) >= 0.015;
8475                tile_active[r0 + bx] = u8::from(active);
8476                if active {
8477                    any_active = true;
8478                }
8479            }
8480        }
8481        any_active
8482    }
8483
8484    /// Loads one 4-byte RGBA pixel at `idx` from `src` into an ARM64 NEON `uint8x8_t` duplicated vector.
8485    ///
8486    /// # Arguments
8487    ///
8488    /// - `&[u8]` - Source RGBA8 pixel buffer.
8489    /// - `usize` - Byte offset (`idx + 4 <= src.len()`).
8490    ///
8491    /// # Returns
8492    ///
8493    /// - `core::arch::aarch64::uint8x8_t` - Replicated RGBA byte vector.
8494    #[cfg(target_arch = "aarch64")]
8495    #[inline(always)]
8496    unsafe fn neon_load_px_u8(src: &[u8], idx: usize) -> core::arch::aarch64::uint8x8_t {
8497        // SAFETY: Caller guarantees `idx + 4 <= src.len()` and ARM64 NEON execution context.
8498        unsafe {
8499            let word: u32 = src.as_ptr().add(idx).cast::<u32>().read_unaligned();
8500            core::arch::aarch64::vreinterpret_u8_u32(core::arch::aarch64::vdup_n_u32(word))
8501        }
8502    }
8503
8504    /// 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.
8505    ///
8506    /// # Arguments
8507    ///
8508    /// - `(usize, usize, usize, usize)` - Dimensions `(w, h, bloom_w, bloom_h)`.
8509    /// - `&PostProcessInputs<'_>` - Read-only color, luma, G-Buffer IDs, bloom, bloom mask, and TAA history.
8510    /// - `(bool, bool, bool)` - Flags `(use_fxaa, use_taa, use_bloom)`.
8511    /// - `(usize, *mut u8, usize)` - `(y_start, writable band RGBA base pointer, band row count)`.
8512    unsafe fn post_process_band(
8513        dims: (usize, usize, usize, usize),
8514        inputs: &PostProcessInputs<'_>,
8515        flags: (bool, bool, bool),
8516        band: (usize, *mut u8, usize),
8517    ) {
8518        let (width_val, height_val, border_width, bh): (usize, usize, usize, usize) = dims;
8519        let src: &[u8] = inputs.color_src;
8520        let luma: &[u8] = inputs.luma;
8521        let g_tri_idx: &[u32] = inputs.g_tri_idx;
8522        let bloom: &[[f32; 4]] = inputs.bloom;
8523        let bloom_active: &[u8] = inputs.bloom_tile_active;
8524        let history: &[u8] = inputs.taa_history;
8525        let (use_fxaa, use_taa, use_bloom): (bool, bool, bool) = flags;
8526        let (y_start, dst_ptr, band_rows): (usize, *mut u8, usize) = band;
8527        let row_bytes: usize = width_val * 4;
8528        let bloom_len: usize = border_width * bh;
8529        let has_bloom: bool = use_bloom
8530            && bloom_len > 0
8531            && bloom.len() >= bloom_len
8532            && bloom_active.len() >= bloom_len;
8533        let bw_max: usize = border_width.saturating_sub(1);
8534        let bh_max: usize = bh.saturating_sub(1);
8535        let has_taa: bool = use_taa && history.len() == src.len();
8536        let w_i32: i32 = width_val as i32;
8537        let h_i32: i32 = height_val as i32;
8538        for local_y in 0..band_rows {
8539            let coord_y: usize = y_start + local_y;
8540            let src_off: usize = coord_y * row_bytes;
8541            let dst_off: usize = local_y * row_bytes;
8542            if !use_fxaa && !has_bloom && !has_taa {
8543                // SAFETY: Caller guarantees `dst_ptr` covers `band_rows * row_bytes` disjoint writable bytes,
8544                // and `src_off + row_bytes <= src.len()` since `y < h`.
8545                unsafe {
8546                    dst_ptr
8547                        .add(dst_off)
8548                        .copy_from_nonoverlapping(src.as_ptr().add(src_off), row_bytes);
8549                }
8550                continue;
8551            }
8552            let by0: usize = (coord_y >> 2).min(bh_max);
8553            let by1: usize = (by0 + 1).min(bh_max);
8554            let ty: f32 = ((coord_y & 3) as f32) * 0.25;
8555            let bloom_r0: usize = by0 * border_width;
8556            let bloom_r1: usize = by1 * border_width;
8557            let edge_row: bool = coord_y == 0 || coord_y + 1 >= height_val;
8558            let simple_row: bool = !use_fxaa || edge_row;
8559            if simple_row || width_val < 3 {
8560                for pos_x in 0..width_val {
8561                    let scale_factor: usize = src_off + pos_x * 4;
8562                    let dc: usize = dst_off + pos_x * 4;
8563                    let mut red_val: i32 = src[scale_factor] as i32;
8564                    let mut green_val: i32 = src[scale_factor + 1] as i32;
8565                    let mut blue_val: i32 = src[scale_factor + 2] as i32;
8566                    if has_bloom {
8567                        let bx0: usize = (pos_x >> 2).min(bw_max);
8568                        if bloom_active[bloom_r0 + bx0] != 0 {
8569                            let tx: f32 = ((pos_x & 3) as f32) * 0.25;
8570                            let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
8571                                bloom,
8572                                (bloom_r0, bloom_r1, bw_max),
8573                                (bx0, tx, ty),
8574                            );
8575                            red_val = (red_val + (bl[0] * 64.0) as i32).min(255);
8576                            green_val = (green_val + (bl[1] * 64.0) as i32).min(255);
8577                            blue_val = (blue_val + (bl[2] * 64.0) as i32).min(255);
8578                        }
8579                    }
8580                    // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
8581                    unsafe {
8582                        dst_ptr.add(dc).cast::<[u8; 4]>().write([
8583                            red_val as u8,
8584                            green_val as u8,
8585                            blue_val as u8,
8586                            255,
8587                        ]);
8588                    }
8589                }
8590                continue;
8591            }
8592            let last_px: usize = (width_val - 1) * 4;
8593            // SAFETY: `w >= 3`, so both first and last 4-byte pixels lie within `dst_off..dst_off + row_bytes`.
8594            unsafe {
8595                dst_ptr
8596                    .add(dst_off)
8597                    .copy_from_nonoverlapping(src.as_ptr().add(src_off), 4);
8598                dst_ptr
8599                    .add(dst_off + last_px)
8600                    .copy_from_nonoverlapping(src.as_ptr().add(src_off + last_px), 4);
8601            }
8602            let row: usize = coord_y * width_val;
8603            let row_up: usize = (coord_y - 1) * width_val;
8604            let row_dn: usize = (coord_y + 1) * width_val;
8605            let y_i32: i32 = coord_y as i32;
8606            let luma_c: &[u8] = &luma[row..(row + width_val)];
8607            let luma_u: &[u8] = &luma[row_up..(row_up + width_val)];
8608            let luma_d: &[u8] = &luma[row_dn..(row_dn + width_val)];
8609            let bloom_row_mask: &[u8] = if has_bloom {
8610                &bloom_active[bloom_r0..(bloom_r0 + border_width)]
8611            } else {
8612                &[]
8613            };
8614            let row_has_bloom: bool =
8615                has_bloom && bloom_row_mask.iter().any(|&flag: &u8| flag != 0);
8616            let mut coord_x: usize = 1;
8617            let x_end: usize = width_val - 1;
8618            while coord_x < x_end {
8619                #[cfg(target_arch = "aarch64")]
8620                if coord_x + 16 <= x_end {
8621                    let lc_u8: u8 = luma_c[coord_x];
8622                    if luma_c[coord_x + 4] == lc_u8
8623                        && luma_u[coord_x] == lc_u8
8624                        && luma_d[coord_x] == lc_u8
8625                    {
8626                        let no_bloom_16: bool = !row_has_bloom || {
8627                            let t0: usize = (coord_x >> 2).min(bw_max);
8628                            let t1: usize = (t0 + 1).min(bw_max);
8629                            let t2: usize = (t0 + 2).min(bw_max);
8630                            let t3: usize = (t0 + 3).min(bw_max);
8631                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8632                            (bloom_row_mask[t0]
8633                                | bloom_row_mask[t1]
8634                                | bloom_row_mask[t2]
8635                                | bloom_row_mask[t3]
8636                                | bloom_row_mask[t4])
8637                                == 0
8638                        };
8639                        if no_bloom_16 {
8640                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8641                            let flat_16: bool = unsafe {
8642                                let splat: core::arch::aarch64::uint8x16_t =
8643                                    core::arch::aarch64::vdupq_n_u8(lc_u8);
8644                                let c16: core::arch::aarch64::uint8x16_t =
8645                                    core::arch::aarch64::vld1q_u8(luma_c.as_ptr().add(coord_x));
8646                                let u16_v: core::arch::aarch64::uint8x16_t =
8647                                    core::arch::aarch64::vld1q_u8(luma_u.as_ptr().add(coord_x));
8648                                let d16: core::arch::aarch64::uint8x16_t =
8649                                    core::arch::aarch64::vld1q_u8(luma_d.as_ptr().add(coord_x));
8650                                let eq_all: core::arch::aarch64::uint8x16_t =
8651                                    core::arch::aarch64::vandq_u8(
8652                                        core::arch::aarch64::vandq_u8(
8653                                            core::arch::aarch64::vceqq_u8(c16, splat),
8654                                            core::arch::aarch64::vceqq_u8(u16_v, splat),
8655                                        ),
8656                                        core::arch::aarch64::vceqq_u8(d16, splat),
8657                                    );
8658                                core::arch::aarch64::vminvq_u8(eq_all) == 0xFF
8659                                    && luma_c[coord_x - 1] == lc_u8
8660                                    && luma_c[coord_x + 16] == lc_u8
8661                                    && luma_u[coord_x - 1] == lc_u8
8662                                    && luma_u[coord_x + 16] == lc_u8
8663                                    && luma_d[coord_x - 1] == lc_u8
8664                                    && luma_d[coord_x + 16] == lc_u8
8665                            };
8666                            let rgba_uniform: bool = flat_16
8667                                && (!has_taa || {
8668                                    let base_px_off: usize = (row + coord_x) * 4;
8669                                    let px0_bytes: &[u8] = &src[base_px_off..(base_px_off + 4)];
8670                                    let row_span_bytes: usize = 18 * 4;
8671                                    let up_slice: &[u8] = &src[((row_up + coord_x - 1) * 4)
8672                                        ..((row_up + coord_x - 1) * 4 + row_span_bytes)];
8673                                    let mid_slice: &[u8] = &src[((row + coord_x - 1) * 4)
8674                                        ..((row + coord_x - 1) * 4 + row_span_bytes)];
8675                                    let dn_slice: &[u8] = &src[((row_dn + coord_x - 1) * 4)
8676                                        ..((row_dn + coord_x - 1) * 4 + row_span_bytes)];
8677                                    mid_slice == up_slice
8678                                        && mid_slice == dn_slice
8679                                        && mid_slice[..68] == mid_slice[4..72]
8680                                        && &mid_slice[..4] == px0_bytes
8681                                });
8682                            if rgba_uniform {
8683                                let sc16: usize = (row + coord_x) * 4;
8684                                let dc16: usize = dst_off + coord_x * 4;
8685                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8686                                unsafe {
8687                                    dst_ptr
8688                                        .add(dc16)
8689                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8690                                }
8691                                coord_x += 16;
8692                                continue;
8693                            }
8694                        }
8695                    }
8696                }
8697                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8698                if !has_taa && coord_x + 16 <= x_end {
8699                    let no_bloom_16: bool = !row_has_bloom || {
8700                        let t0: usize = (coord_x >> 2).min(bw_max);
8701                        let t1: usize = (t0 + 1).min(bw_max);
8702                        let t2: usize = (t0 + 2).min(bw_max);
8703                        let t3: usize = (t0 + 3).min(bw_max);
8704                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8705                        (bloom_row_mask[t0]
8706                            | bloom_row_mask[t1]
8707                            | bloom_row_mask[t2]
8708                            | bloom_row_mask[t3]
8709                            | bloom_row_mask[t4])
8710                            == 0
8711                    };
8712                    if no_bloom_16 {
8713                        // 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`.
8714                        let skip_n: usize = unsafe {
8715                            let c_w: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8716                                luma_c.as_ptr().add(coord_x - 1).cast(),
8717                            );
8718                            let c_m: core::arch::wasm32::v128 =
8719                                core::arch::wasm32::v128_load(luma_c.as_ptr().add(coord_x).cast());
8720                            let c_e: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8721                                luma_c.as_ptr().add(coord_x + 1).cast(),
8722                            );
8723                            let u_m: core::arch::wasm32::v128 =
8724                                core::arch::wasm32::v128_load(luma_u.as_ptr().add(coord_x).cast());
8725                            let d_m: core::arch::wasm32::v128 =
8726                                core::arch::wasm32::v128_load(luma_d.as_ptr().add(coord_x).cast());
8727                            let lmax: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_max(
8728                                core::arch::wasm32::u8x16_max(
8729                                    core::arch::wasm32::u8x16_max(c_m, u_m),
8730                                    core::arch::wasm32::u8x16_max(d_m, c_e),
8731                                ),
8732                                c_w,
8733                            );
8734                            let lmin: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_min(
8735                                core::arch::wasm32::u8x16_min(
8736                                    core::arch::wasm32::u8x16_min(c_m, u_m),
8737                                    core::arch::wasm32::u8x16_min(d_m, c_e),
8738                                ),
8739                                c_w,
8740                            );
8741                            let contrast: core::arch::wasm32::v128 =
8742                                core::arch::wasm32::i8x16_sub(lmax, lmin);
8743                            let ge3_mask: u32 =
8744                                core::arch::wasm32::u8x16_bitmask(core::arch::wasm32::u8x16_ge(
8745                                    contrast,
8746                                    core::arch::wasm32::u8x16_splat(3),
8747                                )) as u32;
8748                            if ge3_mask == 0 {
8749                                16
8750                            } else if (ge3_mask & 0x00FF) == 0 {
8751                                8
8752                            } else if (ge3_mask & 0x000F) == 0 {
8753                                4
8754                            } else {
8755                                0
8756                            }
8757                        };
8758                        if skip_n != 0 {
8759                            let sc_n: usize = (row + coord_x) * 4;
8760                            let dc_n: usize = dst_off + coord_x * 4;
8761                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8762                            unsafe {
8763                                dst_ptr
8764                                    .add(dc_n)
8765                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8766                            }
8767                            coord_x += skip_n;
8768                            continue;
8769                        }
8770                    }
8771                }
8772                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8773                if has_taa && coord_x + 16 <= x_end {
8774                    let lc_u8: u8 = luma_c[coord_x];
8775                    if luma_c[coord_x + 4] == lc_u8
8776                        && luma_u[coord_x] == lc_u8
8777                        && luma_d[coord_x] == lc_u8
8778                    {
8779                        let no_bloom_16: bool = !row_has_bloom || {
8780                            let t0: usize = (coord_x >> 2).min(bw_max);
8781                            let t1: usize = (t0 + 1).min(bw_max);
8782                            let t2: usize = (t0 + 2).min(bw_max);
8783                            let t3: usize = (t0 + 3).min(bw_max);
8784                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8785                            (bloom_row_mask[t0]
8786                                | bloom_row_mask[t1]
8787                                | bloom_row_mask[t2]
8788                                | bloom_row_mask[t3]
8789                                | bloom_row_mask[t4])
8790                                == 0
8791                        };
8792                        if no_bloom_16 {
8793                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8794                            let flat_16: bool = unsafe {
8795                                let splat: core::arch::wasm32::v128 =
8796                                    core::arch::wasm32::u8x16_splat(lc_u8);
8797                                let c16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8798                                    luma_c.as_ptr().add(coord_x).cast(),
8799                                );
8800                                let u16_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8801                                    luma_u.as_ptr().add(coord_x).cast(),
8802                                );
8803                                let d16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8804                                    luma_d.as_ptr().add(coord_x).cast(),
8805                                );
8806                                let eq_all: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
8807                                    core::arch::wasm32::v128_and(
8808                                        core::arch::wasm32::u8x16_eq(c16, splat),
8809                                        core::arch::wasm32::u8x16_eq(u16_v, splat),
8810                                    ),
8811                                    core::arch::wasm32::u8x16_eq(d16, splat),
8812                                );
8813                                core::arch::wasm32::u8x16_all_true(eq_all)
8814                                    && luma_c[coord_x - 1] == lc_u8
8815                                    && luma_c[coord_x + 16] == lc_u8
8816                                    && luma_u[coord_x - 1] == lc_u8
8817                                    && luma_u[coord_x + 16] == lc_u8
8818                                    && luma_d[coord_x - 1] == lc_u8
8819                                    && luma_d[coord_x + 16] == lc_u8
8820                            };
8821                            if flat_16 {
8822                                let sc16: usize = (row + coord_x) * 4;
8823                                let dc16: usize = dst_off + coord_x * 4;
8824                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8825                                unsafe {
8826                                    dst_ptr
8827                                        .add(dc16)
8828                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8829                                }
8830                                coord_x += 16;
8831                                continue;
8832                            }
8833                        }
8834                    }
8835                }
8836                #[cfg(target_arch = "x86_64")]
8837                if !has_taa && coord_x + 16 <= x_end {
8838                    let no_bloom_16: bool = !row_has_bloom || {
8839                        let t0: usize = (coord_x >> 2).min(bw_max);
8840                        let t1: usize = (t0 + 1).min(bw_max);
8841                        let t2: usize = (t0 + 2).min(bw_max);
8842                        let t3: usize = (t0 + 3).min(bw_max);
8843                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8844                        (bloom_row_mask[t0]
8845                            | bloom_row_mask[t1]
8846                            | bloom_row_mask[t2]
8847                            | bloom_row_mask[t3]
8848                            | bloom_row_mask[t4])
8849                            == 0
8850                    };
8851                    if no_bloom_16 {
8852                        // 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`.
8853                        let skip_n: usize = unsafe {
8854                            let c_w: core::arch::x86_64::__m128i =
8855                                core::arch::x86_64::_mm_loadu_si128(
8856                                    luma_c.as_ptr().add(coord_x - 1).cast(),
8857                                );
8858                            let c_m: core::arch::x86_64::__m128i =
8859                                core::arch::x86_64::_mm_loadu_si128(
8860                                    luma_c.as_ptr().add(coord_x).cast(),
8861                                );
8862                            let c_e: core::arch::x86_64::__m128i =
8863                                core::arch::x86_64::_mm_loadu_si128(
8864                                    luma_c.as_ptr().add(coord_x + 1).cast(),
8865                                );
8866                            let u_m: core::arch::x86_64::__m128i =
8867                                core::arch::x86_64::_mm_loadu_si128(
8868                                    luma_u.as_ptr().add(coord_x).cast(),
8869                                );
8870                            let d_m: core::arch::x86_64::__m128i =
8871                                core::arch::x86_64::_mm_loadu_si128(
8872                                    luma_d.as_ptr().add(coord_x).cast(),
8873                                );
8874                            let lmax: core::arch::x86_64::__m128i =
8875                                core::arch::x86_64::_mm_max_epu8(
8876                                    core::arch::x86_64::_mm_max_epu8(
8877                                        core::arch::x86_64::_mm_max_epu8(c_m, u_m),
8878                                        core::arch::x86_64::_mm_max_epu8(d_m, c_e),
8879                                    ),
8880                                    c_w,
8881                                );
8882                            let lmin: core::arch::x86_64::__m128i =
8883                                core::arch::x86_64::_mm_min_epu8(
8884                                    core::arch::x86_64::_mm_min_epu8(
8885                                        core::arch::x86_64::_mm_min_epu8(c_m, u_m),
8886                                        core::arch::x86_64::_mm_min_epu8(d_m, c_e),
8887                                    ),
8888                                    c_w,
8889                                );
8890                            let contrast: core::arch::x86_64::__m128i =
8891                                core::arch::x86_64::_mm_subs_epu8(lmax, lmin);
8892                            let lt3: core::arch::x86_64::__m128i =
8893                                core::arch::x86_64::_mm_cmpeq_epi8(
8894                                    core::arch::x86_64::_mm_subs_epu8(
8895                                        contrast,
8896                                        core::arch::x86_64::_mm_set1_epi8(2),
8897                                    ),
8898                                    core::arch::x86_64::_mm_setzero_si128(),
8899                                );
8900                            let ge3_mask: u32 =
8901                                (!core::arch::x86_64::_mm_movemask_epi8(lt3) as u32) & 0xFFFF;
8902                            if ge3_mask == 0 {
8903                                16
8904                            } else if (ge3_mask & 0x00FF) == 0 {
8905                                8
8906                            } else if (ge3_mask & 0x000F) == 0 {
8907                                4
8908                            } else {
8909                                0
8910                            }
8911                        };
8912                        if skip_n != 0 {
8913                            let sc_n: usize = (row + coord_x) * 4;
8914                            let dc_n: usize = dst_off + coord_x * 4;
8915                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8916                            unsafe {
8917                                dst_ptr
8918                                    .add(dc_n)
8919                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8920                            }
8921                            coord_x += skip_n;
8922                            continue;
8923                        }
8924                    }
8925                }
8926                #[cfg(target_arch = "x86_64")]
8927                if has_taa && coord_x + 16 <= x_end {
8928                    let lc_u8: u8 = luma_c[coord_x];
8929                    if luma_c[coord_x + 4] == lc_u8
8930                        && luma_u[coord_x] == lc_u8
8931                        && luma_d[coord_x] == lc_u8
8932                    {
8933                        let no_bloom_16: bool = !row_has_bloom || {
8934                            let t0: usize = (coord_x >> 2).min(bw_max);
8935                            let t1: usize = (t0 + 1).min(bw_max);
8936                            let t2: usize = (t0 + 2).min(bw_max);
8937                            let t3: usize = (t0 + 3).min(bw_max);
8938                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8939                            (bloom_row_mask[t0]
8940                                | bloom_row_mask[t1]
8941                                | bloom_row_mask[t2]
8942                                | bloom_row_mask[t3]
8943                                | bloom_row_mask[t4])
8944                                == 0
8945                        };
8946                        if no_bloom_16 {
8947                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8948                            let flat_16: bool = unsafe {
8949                                let splat: core::arch::x86_64::__m128i =
8950                                    core::arch::x86_64::_mm_set1_epi8(lc_u8 as i8);
8951                                let c16: core::arch::x86_64::__m128i =
8952                                    core::arch::x86_64::_mm_loadu_si128(
8953                                        luma_c.as_ptr().add(coord_x).cast(),
8954                                    );
8955                                let u16_v: core::arch::x86_64::__m128i =
8956                                    core::arch::x86_64::_mm_loadu_si128(
8957                                        luma_u.as_ptr().add(coord_x).cast(),
8958                                    );
8959                                let d16: core::arch::x86_64::__m128i =
8960                                    core::arch::x86_64::_mm_loadu_si128(
8961                                        luma_d.as_ptr().add(coord_x).cast(),
8962                                    );
8963                                let eq_all: core::arch::x86_64::__m128i =
8964                                    core::arch::x86_64::_mm_and_si128(
8965                                        core::arch::x86_64::_mm_and_si128(
8966                                            core::arch::x86_64::_mm_cmpeq_epi8(c16, splat),
8967                                            core::arch::x86_64::_mm_cmpeq_epi8(u16_v, splat),
8968                                        ),
8969                                        core::arch::x86_64::_mm_cmpeq_epi8(d16, splat),
8970                                    );
8971                                core::arch::x86_64::_mm_movemask_epi8(eq_all) == 0xFFFF
8972                                    && luma_c[coord_x - 1] == lc_u8
8973                                    && luma_c[coord_x + 16] == lc_u8
8974                                    && luma_u[coord_x - 1] == lc_u8
8975                                    && luma_u[coord_x + 16] == lc_u8
8976                                    && luma_d[coord_x - 1] == lc_u8
8977                                    && luma_d[coord_x + 16] == lc_u8
8978                            };
8979                            if flat_16 {
8980                                let sc16: usize = (row + coord_x) * 4;
8981                                let dc16: usize = dst_off + coord_x * 4;
8982                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8983                                unsafe {
8984                                    dst_ptr
8985                                        .add(dc16)
8986                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8987                                }
8988                                coord_x += 16;
8989                                continue;
8990                            }
8991                        }
8992                    }
8993                }
8994                #[cfg(not(target_arch = "aarch64"))]
8995                #[cfg(not(target_arch = "x86_64"))]
8996                #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8997                {
8998                    let no_bloom_8: bool = coord_x + 8 <= x_end
8999                        && (!row_has_bloom
9000                            || (bloom_row_mask[(coord_x >> 2).min(bw_max)] == 0
9001                                && bloom_row_mask[((coord_x + 4) >> 2).min(bw_max)] == 0
9002                                && bloom_row_mask[((coord_x + 7) >> 2).min(bw_max)] == 0));
9003                    if no_bloom_8 {
9004                        let lc_u8: u8 = luma_c[coord_x];
9005                        let splat: u64 = (lc_u8 as u64) * 0x0101_0101_0101_0101_u64;
9006                        // SAFETY: `x >= 1` and `x + 8 <= w - 1`, so all 8-byte unaligned loads and boundary bytes are in bounds.
9007                        let flat_8: bool = unsafe {
9008                            let c8: u64 =
9009                                luma_c.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
9010                            let u8_w: u64 =
9011                                luma_u.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
9012                            let d8: u64 =
9013                                luma_d.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
9014                            c8 == splat
9015                                && u8_w == splat
9016                                && d8 == splat
9017                                && luma_c[coord_x - 1] == lc_u8
9018                                && luma_c[coord_x + 8] == lc_u8
9019                                && luma_u[coord_x - 1] == lc_u8
9020                                && luma_u[coord_x + 8] == lc_u8
9021                                && luma_d[coord_x - 1] == lc_u8
9022                                && luma_d[coord_x + 8] == lc_u8
9023                        };
9024                        if flat_8 {
9025                            let sc8: usize = (row + coord_x) * 4;
9026                            let dc8: usize = dst_off + coord_x * 4;
9027                            // SAFETY: 32-byte range `[dc8..dc8+32]` lies strictly within this band row.
9028                            unsafe {
9029                                dst_ptr
9030                                    .add(dc8)
9031                                    .copy_from_nonoverlapping(src.as_ptr().add(sc8), 32);
9032                            }
9033                            coord_x += 8;
9034                            continue;
9035                        }
9036                    }
9037                }
9038                #[cfg(target_arch = "aarch64")]
9039                if coord_x + 6 <= x_end {
9040                    let no_bloom_4: bool = !row_has_bloom
9041                        || (bloom_row_mask[(coord_x >> 2).min(bw_max)]
9042                            | bloom_row_mask[((coord_x + 3) >> 2).min(bw_max)])
9043                            == 0;
9044                    if no_bloom_4 {
9045                        // 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.
9046                        let handled_4: bool = unsafe {
9047                            let lc_w: core::arch::aarch64::uint8x8_t =
9048                                core::arch::aarch64::vld1_u8(luma_c.as_ptr().add(coord_x - 1));
9049                            let lu_w: core::arch::aarch64::uint8x8_t =
9050                                core::arch::aarch64::vld1_u8(luma_u.as_ptr().add(coord_x - 1));
9051                            let ld_w: core::arch::aarch64::uint8x8_t =
9052                                core::arch::aarch64::vld1_u8(luma_d.as_ptr().add(coord_x - 1));
9053                            let c_mid: core::arch::aarch64::uint8x8_t =
9054                                core::arch::aarch64::vext_u8::<1>(lc_w, lc_w);
9055                            let c_east: core::arch::aarch64::uint8x8_t =
9056                                core::arch::aarch64::vext_u8::<2>(lc_w, lc_w);
9057                            let u_mid: core::arch::aarch64::uint8x8_t =
9058                                core::arch::aarch64::vext_u8::<1>(lu_w, lu_w);
9059                            let d_mid: core::arch::aarch64::uint8x8_t =
9060                                core::arch::aarch64::vext_u8::<1>(ld_w, ld_w);
9061                            let lmax: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmax_u8(
9062                                core::arch::aarch64::vmax_u8(
9063                                    core::arch::aarch64::vmax_u8(c_mid, u_mid),
9064                                    core::arch::aarch64::vmax_u8(d_mid, c_east),
9065                                ),
9066                                lc_w,
9067                            );
9068                            let lmin: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmin_u8(
9069                                core::arch::aarch64::vmin_u8(
9070                                    core::arch::aarch64::vmin_u8(c_mid, u_mid),
9071                                    core::arch::aarch64::vmin_u8(d_mid, c_east),
9072                                ),
9073                                lc_w,
9074                            );
9075                            let contrast_v: core::arch::aarch64::uint8x8_t =
9076                                core::arch::aarch64::vsub_u8(lmax, lmin);
9077                            let ge3_mask: u32 = core::arch::aarch64::vget_lane_u32::<0>(
9078                                core::arch::aarch64::vreinterpret_u32_u8(
9079                                    core::arch::aarch64::vcge_u8(
9080                                        contrast_v,
9081                                        core::arch::aarch64::vdup_n_u8(3),
9082                                    ),
9083                                ),
9084                            );
9085                            if ge3_mask == 0 {
9086                                let sc4: usize = (row + coord_x) * 4;
9087                                let dc4: usize = dst_off + coord_x * 4;
9088                                if !has_taa {
9089                                    let px4: core::arch::aarch64::uint8x16_t =
9090                                        core::arch::aarch64::vld1q_u8(src.as_ptr().add(sc4));
9091                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), px4);
9092                                } else {
9093                                    let su_a: core::arch::aarch64::uint8x16_t =
9094                                        core::arch::aarch64::vld1q_u8(
9095                                            src.as_ptr().add((row_up + coord_x - 1) * 4),
9096                                        );
9097                                    let su_b: core::arch::aarch64::uint8x16_t =
9098                                        core::arch::aarch64::vld1q_u8(
9099                                            src.as_ptr().add((row_up + coord_x + 1) * 4),
9100                                        );
9101                                    let su_m: core::arch::aarch64::uint8x16_t =
9102                                        core::arch::aarch64::vextq_u8::<4>(su_a, su_b);
9103                                    let sc_a: core::arch::aarch64::uint8x16_t =
9104                                        core::arch::aarch64::vld1q_u8(
9105                                            src.as_ptr().add((row + coord_x - 1) * 4),
9106                                        );
9107                                    let sc_b: core::arch::aarch64::uint8x16_t =
9108                                        core::arch::aarch64::vld1q_u8(
9109                                            src.as_ptr().add((row + coord_x + 1) * 4),
9110                                        );
9111                                    let sc_m: core::arch::aarch64::uint8x16_t =
9112                                        core::arch::aarch64::vextq_u8::<4>(sc_a, sc_b);
9113                                    let sd_a: core::arch::aarch64::uint8x16_t =
9114                                        core::arch::aarch64::vld1q_u8(
9115                                            src.as_ptr().add((row_dn + coord_x - 1) * 4),
9116                                        );
9117                                    let sd_b: core::arch::aarch64::uint8x16_t =
9118                                        core::arch::aarch64::vld1q_u8(
9119                                            src.as_ptr().add((row_dn + coord_x + 1) * 4),
9120                                        );
9121                                    let sd_m: core::arch::aarch64::uint8x16_t =
9122                                        core::arch::aarch64::vextq_u8::<4>(sd_a, sd_b);
9123                                    let min_u: core::arch::aarch64::uint8x16_t =
9124                                        core::arch::aarch64::vminq_u8(
9125                                            core::arch::aarch64::vminq_u8(su_a, su_m),
9126                                            su_b,
9127                                        );
9128                                    let max_u: core::arch::aarch64::uint8x16_t =
9129                                        core::arch::aarch64::vmaxq_u8(
9130                                            core::arch::aarch64::vmaxq_u8(su_a, su_m),
9131                                            su_b,
9132                                        );
9133                                    let min_c: core::arch::aarch64::uint8x16_t =
9134                                        core::arch::aarch64::vminq_u8(
9135                                            core::arch::aarch64::vminq_u8(sc_a, sc_m),
9136                                            sc_b,
9137                                        );
9138                                    let max_c: core::arch::aarch64::uint8x16_t =
9139                                        core::arch::aarch64::vmaxq_u8(
9140                                            core::arch::aarch64::vmaxq_u8(sc_a, sc_m),
9141                                            sc_b,
9142                                        );
9143                                    let min_d: core::arch::aarch64::uint8x16_t =
9144                                        core::arch::aarch64::vminq_u8(
9145                                            core::arch::aarch64::vminq_u8(sd_a, sd_m),
9146                                            sd_b,
9147                                        );
9148                                    let max_d: core::arch::aarch64::uint8x16_t =
9149                                        core::arch::aarch64::vmaxq_u8(
9150                                            core::arch::aarch64::vmaxq_u8(sd_a, sd_m),
9151                                            sd_b,
9152                                        );
9153                                    let box_min: core::arch::aarch64::uint8x16_t =
9154                                        core::arch::aarch64::vminq_u8(
9155                                            core::arch::aarch64::vminq_u8(min_u, min_c),
9156                                            min_d,
9157                                        );
9158                                    let box_max: core::arch::aarch64::uint8x16_t =
9159                                        core::arch::aarch64::vmaxq_u8(
9160                                            core::arch::aarch64::vmaxq_u8(max_u, max_c),
9161                                            max_d,
9162                                        );
9163                                    let hist_v: core::arch::aarch64::uint8x16_t =
9164                                        core::arch::aarch64::vld1q_u8(history.as_ptr().add(sc4));
9165                                    let hist_c: core::arch::aarch64::uint8x16_t =
9166                                        core::arch::aarch64::vminq_u8(
9167                                            core::arch::aarch64::vmaxq_u8(hist_v, box_min),
9168                                            box_max,
9169                                        );
9170                                    let w_cur: core::arch::aarch64::uint8x8_t =
9171                                        core::arch::aarch64::vdup_n_u8(192);
9172                                    let w_his: core::arch::aarch64::uint8x8_t =
9173                                        core::arch::aarch64::vdup_n_u8(64);
9174                                    let lo_sum: core::arch::aarch64::uint16x8_t =
9175                                        core::arch::aarch64::vmlal_u8(
9176                                            core::arch::aarch64::vmull_u8(
9177                                                core::arch::aarch64::vget_low_u8(sc_m),
9178                                                w_cur,
9179                                            ),
9180                                            core::arch::aarch64::vget_low_u8(hist_c),
9181                                            w_his,
9182                                        );
9183                                    let hi_sum: core::arch::aarch64::uint16x8_t =
9184                                        core::arch::aarch64::vmlal_u8(
9185                                            core::arch::aarch64::vmull_u8(
9186                                                core::arch::aarch64::vget_high_u8(sc_m),
9187                                                w_cur,
9188                                            ),
9189                                            core::arch::aarch64::vget_high_u8(hist_c),
9190                                            w_his,
9191                                        );
9192                                    let blended: core::arch::aarch64::uint8x16_t =
9193                                        core::arch::aarch64::vcombine_u8(
9194                                            core::arch::aarch64::vrshrn_n_u16::<8>(lo_sum),
9195                                            core::arch::aarch64::vrshrn_n_u16::<8>(hi_sum),
9196                                        );
9197                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), blended);
9198                                }
9199                                true
9200                            } else {
9201                                false
9202                            }
9203                        };
9204                        if handled_4 {
9205                            coord_x += 4;
9206                            continue;
9207                        }
9208                    }
9209                }
9210                let lc: i32 = luma_c[coord_x] as i32;
9211                let ln: i32 = luma_u[coord_x] as i32;
9212                let ls: i32 = luma_d[coord_x] as i32;
9213                let le: i32 = luma_c[coord_x + 1] as i32;
9214                let lw: i32 = luma_c[coord_x - 1] as i32;
9215                let lmax: i32 = lc.max(ln).max(ls).max(le).max(lw);
9216                let lmin: i32 = lc.min(ln).min(ls).min(le).min(lw);
9217                let contrast: i32 = lmax - lmin;
9218                let dpi_scale: usize = (row + coord_x) * 4;
9219                let dc: usize = dst_off + coord_x * 4;
9220                if contrast < 3 {
9221                    let pix_bloom: bool =
9222                        row_has_bloom && bloom_row_mask[(coord_x >> 2).min(bw_max)] != 0;
9223                    if !pix_bloom {
9224                        if !has_taa {
9225                            // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
9226                            unsafe {
9227                                dst_ptr
9228                                    .add(dc)
9229                                    .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
9230                            }
9231                            coord_x += 1;
9232                            continue;
9233                        }
9234                        if contrast == 0 {
9235                            let lc_u8: u8 = lc as u8;
9236                            if luma_u[coord_x - 1] == lc_u8
9237                                && luma_u[coord_x + 1] == lc_u8
9238                                && luma_d[coord_x - 1] == lc_u8
9239                                && luma_d[coord_x + 1] == lc_u8
9240                            {
9241                                // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
9242                                unsafe {
9243                                    dst_ptr
9244                                        .add(dc)
9245                                        .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
9246                                }
9247                                coord_x += 1;
9248                                continue;
9249                            }
9250                        }
9251                    }
9252                }
9253                let (geom_edge, run_fxaa): (bool, bool) = if contrast >= 3 {
9254                    let tid_c: u32 = g_tri_idx[row + coord_x];
9255                    let edge_v_id: bool = tid_c != g_tri_idx[row_up + coord_x]
9256                        || tid_c != g_tri_idx[row_dn + coord_x];
9257                    let edge_h_id: bool = tid_c != g_tri_idx[row + coord_x - 1]
9258                        || tid_c != g_tri_idx[row + coord_x + 1];
9259                    let ge: bool = edge_v_id || edge_h_id;
9260                    (ge, contrast >= 7 || ge)
9261                } else {
9262                    (false, false)
9263                };
9264                let mut rgb: [i32; 3] = [
9265                    src[dpi_scale] as i32,
9266                    src[dpi_scale + 1] as i32,
9267                    src[dpi_scale + 2] as i32,
9268                ];
9269                if run_fxaa {
9270                    let lnw: i32 = luma[row_up + coord_x - 1] as i32;
9271                    let lne: i32 = luma[row_up + coord_x + 1] as i32;
9272                    let lsw: i32 = luma[row_dn + coord_x - 1] as i32;
9273                    let lse: i32 = luma[row_dn + coord_x + 1] as i32;
9274                    let edge_h: i32 = (lnw + lne - 2 * ln).abs()
9275                        + 2 * (lw + le - 2 * lc).abs()
9276                        + (lsw + lse - 2 * ls).abs();
9277                    let edge_v: i32 = (lnw + lsw - 2 * lw).abs()
9278                        + 2 * (ln + ls - 2 * lc).abs()
9279                        + (lne + lse - 2 * le).abs();
9280                    let is_horiz: bool = edge_h >= edge_v;
9281                    let (l_neg, l_pos): (i32, i32) = if is_horiz { (ln, ls) } else { (lw, le) };
9282                    let grad_neg: i32 = (l_neg - lc).abs();
9283                    let grad_pos: i32 = (l_pos - lc).abs();
9284                    let step_sign: i32 = if grad_neg >= grad_pos { -1 } else { 1 };
9285                    let grad_steep: i32 = grad_neg.max(grad_pos);
9286                    let l_other: i32 = if step_sign < 0 { l_neg } else { l_pos };
9287                    let edge_avg_2: i32 = lc + l_other;
9288                    let grad_thresh_2: i32 = (grad_steep >> 1).max(3);
9289                    let (perp_dx, perp_dy, tan_dx, tan_dy): (i32, i32, i32, i32) = if is_horiz {
9290                        (0, step_sign, 1, 0)
9291                    } else {
9292                        (step_sign, 0, 0, 1)
9293                    };
9294                    let x_i32: i32 = coord_x as i32;
9295                    let mut dist_neg: i32 = MLAA_MAX_WALK_STEPS as i32;
9296                    let mut end_neg_delta: i32 = 0;
9297                    for source_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
9298                        let sx: i32 = x_i32 - tan_dx * source_val;
9299                        let sy: i32 = y_i32 - tan_dy * source_val;
9300                        let ox: i32 = sx + perp_dx;
9301                        let oy: i32 = sy + perp_dy;
9302                        let oob_sx: bool = sx < 0 || sx >= w_i32;
9303                        let oob_sy: bool = sy < 0 || sy >= h_i32;
9304                        let oob_ox: bool = ox < 0 || ox >= w_i32;
9305                        let oob_oy: bool = oy < 0 || oy >= h_i32;
9306                        let oob_a: bool = oob_sx || oob_sy;
9307                        let oob_b: bool = oob_ox || oob_oy;
9308                        if oob_a || oob_b {
9309                            dist_neg = source_val;
9310                            break;
9311                        }
9312                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
9313                            as i32)
9314                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
9315                        let delta: i32 = pair_sum - edge_avg_2;
9316                        if delta.abs() >= grad_thresh_2 {
9317                            dist_neg = source_val;
9318                            end_neg_delta = delta;
9319                            break;
9320                        }
9321                    }
9322                    let mut dist_pos: i32 = MLAA_MAX_WALK_STEPS as i32;
9323                    let mut end_pos_delta: i32 = 0;
9324                    for scale_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
9325                        let sx: i32 = x_i32 + tan_dx * scale_val;
9326                        let sy: i32 = y_i32 + tan_dy * scale_val;
9327                        let ox: i32 = sx + perp_dx;
9328                        let oy: i32 = sy + perp_dy;
9329                        let oob_sx: bool = sx < 0 || sx >= w_i32;
9330                        let oob_sy: bool = sy < 0 || sy >= h_i32;
9331                        let oob_ox: bool = ox < 0 || ox >= w_i32;
9332                        let oob_oy: bool = oy < 0 || oy >= h_i32;
9333                        let oob_a: bool = oob_sx || oob_sy;
9334                        let oob_b: bool = oob_ox || oob_oy;
9335                        if oob_a || oob_b {
9336                            dist_pos = scale_val;
9337                            break;
9338                        }
9339                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
9340                            as i32)
9341                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
9342                        let delta: i32 = pair_sum - edge_avg_2;
9343                        if delta.abs() >= grad_thresh_2 {
9344                            dist_pos = scale_val;
9345                            end_pos_delta = delta;
9346                            break;
9347                        }
9348                    }
9349                    let center_lt_avg: bool = (lc * 2) < edge_avg_2;
9350                    let (closer_dist, closer_delta): (i32, i32) = if dist_neg <= dist_pos {
9351                        (dist_neg, end_neg_delta)
9352                    } else {
9353                        (dist_pos, end_pos_delta)
9354                    };
9355                    let good_span: bool = (closer_delta < 0) != center_lt_avg;
9356                    let span_total: f32 = ((dist_neg + dist_pos).max(1)) as f32;
9357                    let morph_blend: f32 = if good_span {
9358                        (0.5 - ((closer_dist as f32) - 0.5).max(0.0) / span_total).clamp(0.0, 0.5)
9359                    } else {
9360                        0.0
9361                    };
9362                    let avg_8: i32 = ((ln + ls + le + lw) * 2 + lnw + lne + lsw + lse + 6) / 12;
9363                    let subpix_raw: f32 =
9364                        (((avg_8 - lc).abs() as f32) / (contrast.max(1) as f32)).clamp(0.0, 1.0);
9365                    let subpix_s: f32 = subpix_raw * subpix_raw * (3.0 - 2.0 * subpix_raw);
9366                    let subpix_blend: f32 =
9367                        subpix_s * subpix_s * if geom_edge { 0.52 } else { 0.32 };
9368                    let final_blend: f32 = morph_blend.max(subpix_blend).clamp(0.0, 0.58);
9369                    let blend_q8: i32 = (final_blend * 256.0).round() as i32;
9370                    if blend_q8 > 0 {
9371                        let nx: usize = (x_i32 + perp_dx).clamp(0, w_i32 - 1) as usize;
9372                        let ny: usize = (y_i32 + perp_dy).clamp(0, h_i32 - 1) as usize;
9373                        let n_sc: usize = (ny * width_val + nx) * 4;
9374                        let keep_q8: i32 = 256 - blend_q8;
9375                        for ch in 0..3 {
9376                            rgb[ch] =
9377                                ((rgb[ch] * keep_q8 + (src[n_sc + ch] as i32) * blend_q8 + 128)
9378                                    >> 8)
9379                                    .clamp(0, 255);
9380                        }
9381                    }
9382                }
9383                if has_taa {
9384                    let flat_3x3: bool = if contrast == 0 {
9385                        let lc_u8: u8 = lc as u8;
9386                        let diag_top: bool = luma[row_up + coord_x - 1] == lc_u8
9387                            && luma[row_up + coord_x + 1] == lc_u8;
9388                        let diag_bot: bool = luma[row_dn + coord_x - 1] == lc_u8
9389                            && luma[row_dn + coord_x + 1] == lc_u8;
9390                        diag_top && diag_bot
9391                    } else {
9392                        false
9393                    };
9394                    if !flat_3x3 {
9395                        let hr: i32 = history[dpi_scale] as i32;
9396                        let hg: i32 = history[dpi_scale + 1] as i32;
9397                        let hb: i32 = history[dpi_scale + 2] as i32;
9398                        let diff_rg: bool = hr != rgb[0] || hg != rgb[1];
9399                        if diff_rg || hb != rgb[2] {
9400                            #[cfg(target_arch = "aarch64")]
9401                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
9402                                i32,
9403                                i32,
9404                                i32,
9405                                i32,
9406                                i32,
9407                                i32,
9408                            ) = {
9409                                // SAFETY: `x >= 1`, `x + 1 < w`, `y >= 1`, `y + 1 < h`, so every 4-byte pixel offset lies inside `src`.
9410                                unsafe {
9411                                    let c_word: u32 = u32::from_le_bytes([
9412                                        rgb[0] as u8,
9413                                        rgb[1] as u8,
9414                                        rgb[2] as u8,
9415                                        255,
9416                                    ]);
9417                                    let c_v: core::arch::aarch64::uint8x8_t =
9418                                        core::arch::aarch64::vreinterpret_u8_u32(
9419                                            core::arch::aarch64::vdup_n_u32(c_word),
9420                                        );
9421                                    let p0: core::arch::aarch64::uint8x8_t =
9422                                        Self::neon_load_px_u8(src, (row_up + coord_x - 1) * 4);
9423                                    let p1: core::arch::aarch64::uint8x8_t =
9424                                        Self::neon_load_px_u8(src, (row_up + coord_x) * 4);
9425                                    let p2: core::arch::aarch64::uint8x8_t =
9426                                        Self::neon_load_px_u8(src, (row_up + coord_x + 1) * 4);
9427                                    let p3: core::arch::aarch64::uint8x8_t =
9428                                        Self::neon_load_px_u8(src, (row + coord_x - 1) * 4);
9429                                    let p4: core::arch::aarch64::uint8x8_t =
9430                                        Self::neon_load_px_u8(src, (row + coord_x + 1) * 4);
9431                                    let p5: core::arch::aarch64::uint8x8_t =
9432                                        Self::neon_load_px_u8(src, (row_dn + coord_x - 1) * 4);
9433                                    let p6: core::arch::aarch64::uint8x8_t =
9434                                        Self::neon_load_px_u8(src, (row_dn + coord_x) * 4);
9435                                    let p7: core::arch::aarch64::uint8x8_t =
9436                                        Self::neon_load_px_u8(src, (row_dn + coord_x + 1) * 4);
9437                                    let lo_a: core::arch::aarch64::uint8x8_t =
9438                                        core::arch::aarch64::vmin_u8(
9439                                            core::arch::aarch64::vmin_u8(p0, p1),
9440                                            core::arch::aarch64::vmin_u8(p2, p3),
9441                                        );
9442                                    let lo_b: core::arch::aarch64::uint8x8_t =
9443                                        core::arch::aarch64::vmin_u8(
9444                                            core::arch::aarch64::vmin_u8(p4, p5),
9445                                            core::arch::aarch64::vmin_u8(p6, p7),
9446                                        );
9447                                    let v_min: core::arch::aarch64::uint8x8_t =
9448                                        core::arch::aarch64::vmin_u8(
9449                                            core::arch::aarch64::vmin_u8(lo_a, lo_b),
9450                                            c_v,
9451                                        );
9452                                    let hi_a: core::arch::aarch64::uint8x8_t =
9453                                        core::arch::aarch64::vmax_u8(
9454                                            core::arch::aarch64::vmax_u8(p0, p1),
9455                                            core::arch::aarch64::vmax_u8(p2, p3),
9456                                        );
9457                                    let hi_b: core::arch::aarch64::uint8x8_t =
9458                                        core::arch::aarch64::vmax_u8(
9459                                            core::arch::aarch64::vmax_u8(p4, p5),
9460                                            core::arch::aarch64::vmax_u8(p6, p7),
9461                                        );
9462                                    let v_max: core::arch::aarch64::uint8x8_t =
9463                                        core::arch::aarch64::vmax_u8(
9464                                            core::arch::aarch64::vmax_u8(hi_a, hi_b),
9465                                            c_v,
9466                                        );
9467                                    let min_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
9468                                        core::arch::aarch64::vreinterpret_u32_u8(v_min),
9469                                    );
9470                                    let max_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
9471                                        core::arch::aarch64::vreinterpret_u32_u8(v_max),
9472                                    );
9473                                    let min_b: [u8; 4] = min_u32.to_le_bytes();
9474                                    let max_b: [u8; 4] = max_u32.to_le_bytes();
9475                                    (
9476                                        min_b[0] as i32,
9477                                        max_b[0] as i32,
9478                                        min_b[1] as i32,
9479                                        max_b[1] as i32,
9480                                        min_b[2] as i32,
9481                                        max_b[2] as i32,
9482                                    )
9483                                }
9484                            };
9485                            #[cfg(not(target_arch = "aarch64"))]
9486                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
9487                                i32,
9488                                i32,
9489                                i32,
9490                                i32,
9491                                i32,
9492                                i32,
9493                            ) = {
9494                                let offsets: [usize; 8] = [
9495                                    (row_up + coord_x - 1) * 4,
9496                                    (row_up + coord_x) * 4,
9497                                    (row_up + coord_x + 1) * 4,
9498                                    (row + coord_x - 1) * 4,
9499                                    (row + coord_x + 1) * 4,
9500                                    (row_dn + coord_x - 1) * 4,
9501                                    (row_dn + coord_x) * 4,
9502                                    (row_dn + coord_x + 1) * 4,
9503                                ];
9504                                let mut r_lo: i32 = rgb[0];
9505                                let mut r_hi: i32 = rgb[0];
9506                                let mut g_lo: i32 = rgb[1];
9507                                let mut g_hi: i32 = rgb[1];
9508                                let mut b_lo: i32 = rgb[2];
9509                                let mut b_hi: i32 = rgb[2];
9510                                for off in offsets.into_iter() {
9511                                    let vr: i32 = src[off] as i32;
9512                                    let vg: i32 = src[off + 1] as i32;
9513                                    let vb: i32 = src[off + 2] as i32;
9514                                    r_lo = r_lo.min(vr);
9515                                    r_hi = r_hi.max(vr);
9516                                    g_lo = g_lo.min(vg);
9517                                    g_hi = g_hi.max(vg);
9518                                    b_lo = b_lo.min(vb);
9519                                    b_hi = b_hi.max(vb);
9520                                }
9521                                (r_lo, r_hi, g_lo, g_hi, b_lo, b_hi)
9522                            };
9523                            let hr_c: i32 = hr.clamp(r_min, r_max);
9524                            let hg_c: i32 = hg.clamp(g_min, g_max);
9525                            let hb_c: i32 = hb.clamp(b_min, b_max);
9526                            rgb[0] = ((rgb[0] * 192 + hr_c * 64 + 128) >> 8).clamp(0, 255);
9527                            rgb[1] = ((rgb[1] * 192 + hg_c * 64 + 128) >> 8).clamp(0, 255);
9528                            rgb[2] = ((rgb[2] * 192 + hb_c * 64 + 128) >> 8).clamp(0, 255);
9529                        }
9530                    }
9531                }
9532                if !geom_edge && (4..=56).contains(&contrast) {
9533                    let off_u: usize = (row_up + coord_x) * 4;
9534                    let off_d: usize = (row_dn + coord_x) * 4;
9535                    let off_l: usize = (row + coord_x - 1) * 4;
9536                    let off_r: usize = (row + coord_x + 1) * 4;
9537                    for ch in 0..3usize {
9538                        let cu: i32 = src[off_u + ch] as i32;
9539                        let cd: i32 = src[off_d + ch] as i32;
9540                        let cl: i32 = src[off_l + ch] as i32;
9541                        let cr: i32 = src[off_r + ch] as i32;
9542                        let nbr_min: i32 = cu.min(cd).min(cl).min(cr).min(rgb[ch]);
9543                        let nbr_max: i32 = cu.max(cd).max(cl).max(cr).max(rgb[ch]);
9544                        let lap: i32 = rgb[ch] * 4 - (cu + cd + cl + cr);
9545                        rgb[ch] = (rgb[ch] + ((lap * 56) >> 10)).clamp(nbr_min, nbr_max);
9546                    }
9547                }
9548                if row_has_bloom {
9549                    let bx0: usize = (coord_x >> 2).min(bw_max);
9550                    if bloom_row_mask[bx0] != 0 {
9551                        let tx: f32 = ((coord_x & 3) as f32) * 0.25;
9552                        let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
9553                            bloom,
9554                            (bloom_r0, bloom_r1, bw_max),
9555                            (bx0, tx, ty),
9556                        );
9557                        rgb[0] = (rgb[0] + (bl[0] * 78.0) as i32).min(255);
9558                        rgb[1] = (rgb[1] + (bl[1] * 78.0) as i32).min(255);
9559                        rgb[2] = (rgb[2] + (bl[2] * 78.0) as i32).min(255);
9560                    }
9561                }
9562                // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
9563                unsafe {
9564                    dst_ptr.add(dc).cast::<[u8; 4]>().write([
9565                        rgb[0] as u8,
9566                        rgb[1] as u8,
9567                        rgb[2] as u8,
9568                        255,
9569                    ]);
9570                }
9571                coord_x += 1;
9572            }
9573            if use_fxaa || has_bloom {
9574                let v_norm: f32 = (((coord_y as f32) + 0.5) / (height_val.max(1) as f32)) - 0.5;
9575                let v_sq: f32 = v_norm * v_norm;
9576                let inv_wf: f32 = 1.0 / (width_val.max(1) as f32);
9577                for vig_x in 0..width_val {
9578                    let u_norm: f32 = (((vig_x as f32) + 0.5) * inv_wf) - 0.5;
9579                    let r2: f32 = u_norm * u_norm + v_sq;
9580                    if r2 > 0.16 {
9581                        let vig_q8: u32 =
9582                            ((1.0 - (r2 - 0.16) * 0.44).clamp(0.82, 1.0) * 256.0) as u32;
9583                        let px_off: usize = dst_off + vig_x * 4;
9584                        // SAFETY: `px_off + 4 <= band_rows * row_bytes`.
9585                        unsafe {
9586                            let p_ptr: *mut u8 = dst_ptr.add(px_off);
9587                            *p_ptr = (((*p_ptr as u32) * vig_q8) >> 8) as u8;
9588                            *p_ptr.add(1) = (((*p_ptr.add(1) as u32) * vig_q8) >> 8) as u8;
9589                            *p_ptr.add(2) = (((*p_ptr.add(2) as u32) * vig_q8) >> 8) as u8;
9590                        }
9591                    }
9592                }
9593            }
9594        }
9595    }
9596
9597    /// Projects, culls, clips, and builds screen-space setup records for one frustum-visible object with smooth 3-vertex normal averaging.
9598    ///
9599    /// # Arguments
9600    ///
9601    /// - `&GeomPassContext<'_>` - Immutable per-frame frustum, Hi-Z, camera, and sky parameters.
9602    /// - `usize` - Index inside `visible_scratch` for Hi-Z pre-pass flag lookup.
9603    /// - `f32` - Squared distance from camera to object bounds center.
9604    /// - `usize` - Object index inside `ctx.objects`.
9605    /// - `&mut GeomPassOut<'_>` - Mutable per-chunk or sequential geometry output buffers and counters.
9606    fn process_visible_object_geom(
9607        ctx: &GeomPassContext<'_>,
9608        vis_slot: usize,
9609        dist_sq: f32,
9610        obj_idx: usize,
9611        out: &mut GeomPassOut<'_>,
9612    ) {
9613        let obj: &SceneObject3D = &ctx.objects[obj_idx];
9614        let skip_hiz_obj: bool = obj.get_is_dynamic()
9615            || obj.get_material().get_emissive().length_sq() > 0.05
9616            || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater;
9617        if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 && !skip_hiz_obj {
9618            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
9619            let area_px: f32 = HiZPyramid::projected_screen_area_px(
9620                obj_bounds,
9621                &ctx.view_proj,
9622                ctx.w_f,
9623                ctx.h_f,
9624                ctx.near_plane,
9625            );
9626            if area_px < NANITE_MIN_SCREEN_AREA_PX
9627                || ctx
9628                    .hiz_pyramid
9629                    .is_bounds_occluded(obj_bounds, &ctx.view_proj, ctx.near_plane)
9630            {
9631                out.hiz_culled_objects += 1;
9632                return;
9633            }
9634        }
9635        let Some(chain) = ctx.mesh_lib.get(obj.get_mesh_id()) else {
9636            return;
9637        };
9638        out.visible_objects += 1;
9639        if let Some(unique_set) = out.unique_meshes.as_deref_mut() {
9640            let _: bool = unique_set.insert(obj.get_mesh_id());
9641        } else if let Some(mesh_ids) = out.mesh_ids.as_deref_mut() {
9642            mesh_ids.push(obj.get_mesh_id());
9643        }
9644        let dist: f32 = dist_sq.sqrt();
9645        let obj_radius: f32 = obj.get_world_bounds().radius();
9646        let deformed_mesh: Option<&Mesh3D> =
9647            ctx.deformed_meshes.get(obj_idx).and_then(Option::as_ref);
9648        let (mesh, lod_idx): (&Mesh3D, usize) = if let Some(deformed) = deformed_mesh {
9649            (deformed, 0)
9650        } else {
9651            chain.select_screen_error(dist, obj_radius, ctx.focal_px, ctx.lod_bias)
9652        };
9653        if lod_idx > 0 {
9654            out.lod_simplified_objects += 1;
9655        }
9656        let transform_val: Transform3D = obj.get_transform();
9657        let model_mat4: Mat4 = transform_val.to_mat4();
9658        let mvp_mat4: Mat4 = ctx.view_proj.mul(model_mat4);
9659        let normal_mat3: [Vec3; 3] = transform_val.normal_mat3();
9660        let tr_scale: Vec3 = transform_val.get_scale();
9661        let det_scale: f32 = tr_scale.get_x() * tr_scale.get_y() * tr_scale.get_z();
9662        let principled_id: Option<u32> = obj.try_get_principled_material_id();
9663        let double_sided: bool = principled_id
9664            .and_then(|mat_idx: u32| ctx.principled_materials.get(mat_idx as usize))
9665            .is_some_and(PrincipledMaterial3D::get_double_sided);
9666        let cull_backface: bool = mesh.get_is_closed() && det_scale > 0.0 && !double_sided;
9667        let obj_mat: PbrMaterial = obj.get_material();
9668        let has_sub_mats: bool = !mesh.get_tri_materials().is_empty();
9669        let base_mat_base: Vec3 = obj_mat.get_base_color();
9670        let base_mat_emissive: Vec3 = obj_mat.get_emissive();
9671        let base_mat_refl: f32 = obj_mat.get_reflectivity();
9672        let base_metallic: f32 = obj_mat.get_metallic();
9673        let base_rough: f32 = obj_mat.get_roughness();
9674        let base_alpha: f32 = (base_rough * base_rough).max(0.018);
9675        let base_alpha2: f32 = base_alpha * base_alpha;
9676        let base_f0: Vec3 = Vec3::splat(0.04).lerp(base_mat_base, base_metallic);
9677        let base_diffuse_scale: f32 = 1.0 - base_metallic;
9678        let base_do_refl: bool = ctx.use_rt_refl && base_mat_refl > 0.25;
9679        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
9680        let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
9681        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
9682        out.cluster_ranges.clear();
9683        if deformed_mesh.is_none()
9684            && lod_idx == 0
9685            && ctx.frustum_on
9686            && let Some(nanite_dag) = ctx
9687                .nanite_dags
9688                .get(obj.get_mesh_id())
9689                .and_then(Option::as_ref)
9690        {
9691            let hiz_opt: Option<&HiZPyramid> =
9692                if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 {
9693                    Some(ctx.hiz_pyramid)
9694                } else {
9695                    None
9696                };
9697            let cut_ctx: NaniteCutContext<'_> = NaniteCutContext {
9698                camera_position: ctx.cam_pos,
9699                model_matrix: model_mat4,
9700                view_projection: ctx.view_proj,
9701                normal_basis: normal_mat3,
9702                frustum: ctx.frustum,
9703                hiz_pyramid: hiz_opt,
9704                cull_backface,
9705                focal_px: ctx.focal_px,
9706                error_threshold_px: (1.5 * ctx.lod_bias.max(0.25)).clamp(0.5, 8.0),
9707                near_plane: ctx.near_plane,
9708                viewport_width: ctx.w_f,
9709                viewport_height: ctx.h_f,
9710                total_triangles: indices.len(),
9711            };
9712            let cut_stats: NaniteCutStats = nanite_dag.select_cut(&cut_ctx, out.cluster_ranges);
9713            out.meshlets_drawn += cut_stats.get_clusters_drawn();
9714            out.meshlets_culled += cut_stats.get_clusters_frustum_culled()
9715                + cut_stats.get_clusters_cone_culled()
9716                + cut_stats.get_clusters_micro_culled()
9717                + cut_stats.get_clusters_hiz_culled();
9718        } else if deformed_mesh.is_none() && meshlets.len() > 1 && ctx.frustum_on {
9719            for mlet in meshlets.iter() {
9720                let wb: AxisAlignedBox3D = model_mat4.transform_bounds(mlet.get_bounds());
9721                if !ctx.frustum.intersects_bounds(&wb) {
9722                    out.meshlets_culled += 1;
9723                    continue;
9724                }
9725                if ctx.hiz_active
9726                    && ctx.hiz_occluder_flags[vis_slot] == 0
9727                    && ctx
9728                        .hiz_pyramid
9729                        .is_bounds_occluded(wb, &ctx.view_proj, ctx.near_plane)
9730                {
9731                    out.meshlets_culled += 1;
9732                    continue;
9733                }
9734                let cutoff: f32 = mlet.get_cone_cutoff();
9735                if cull_backface && cutoff > 0.05 {
9736                    let world_axis: Vec3 =
9737                        Mat4::transform_normal_with_basis(mlet.get_cone_axis(), normal_mat3);
9738                    let v_cam: Vec3 = wb.center().sub(ctx.cam_pos);
9739                    let v_len: f32 = v_cam.length();
9740                    let sin_alpha: f32 = (1.0 - cutoff * cutoff).max(0.0).sqrt();
9741                    if v_cam.dot(world_axis) > v_len * sin_alpha + wb.radius() {
9742                        out.meshlets_culled += 1;
9743                        continue;
9744                    }
9745                }
9746                out.meshlets_drawn += 1;
9747                let s0: usize = mlet.get_first_tri() as usize;
9748                let s1: usize = (s0 + (mlet.get_tri_count() as usize)).min(indices.len());
9749                out.cluster_ranges.push((s0, s1));
9750            }
9751        } else {
9752            out.meshlets_drawn += meshlets.len().max(1);
9753            out.cluster_ranges.push((0, indices.len()));
9754        }
9755        if out.cluster_ranges.is_empty() {
9756            return;
9757        }
9758        out.projected_verts.clear();
9759        out.projected_verts.reserve(verts.len());
9760        for item_val in verts.iter() {
9761            let lp: Vec3 = item_val.get_position();
9762            let cp: [f32; 4] = mvp_mat4.mul_point4(lp);
9763            let wp: Vec3 = model_mat4.mul_point3(lp);
9764            out.projected_verts.push((cp, wp));
9765        }
9766        let vert_count: usize = out.projected_verts.len();
9767        for &(tri_start, tri_end) in out.cluster_ranges.iter() {
9768            for (local_offset, tri) in indices[tri_start..tri_end].iter().enumerate() {
9769                let global_tri_idx: usize = tri_start + local_offset;
9770                let (i0, i1, i2): (usize, usize, usize) =
9771                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
9772                let oob_01: bool = i0 >= vert_count || i1 >= vert_count;
9773                if oob_01 || i2 >= vert_count {
9774                    continue;
9775                }
9776                let (c0, wp0): ([f32; 4], Vec3) = out.projected_verts[i0];
9777                let (c1, wp1): ([f32; 4], Vec3) = out.projected_verts[i1];
9778                let (c2, wp2): ([f32; 4], Vec3) = out.projected_verts[i2];
9779                if c0[3] < ctx.near_plane && c1[3] < ctx.near_plane && c2[3] < ctx.near_plane {
9780                    continue;
9781                }
9782                let out_l: bool = c0[0] < -c0[3] && c1[0] < -c1[3] && c2[0] < -c2[3];
9783                let out_r: bool = c0[0] > c0[3] && c1[0] > c1[3] && c2[0] > c2[3];
9784                let out_b: bool = c0[1] < -c0[3] && c1[1] < -c1[3] && c2[1] < -c2[3];
9785                let out_t: bool = c0[1] > c0[3] && c1[1] > c1[3] && c2[1] > c2[3];
9786                let out_x: bool = out_l || out_r;
9787                let out_y: bool = out_b || out_t;
9788                if out_x || out_y {
9789                    continue;
9790                }
9791                let (clipped_tris, clipped_count): ([ClippedBaryVert; 6], usize) = if c0[3]
9792                    >= ctx.near_plane
9793                    && c1[3] >= ctx.near_plane
9794                    && c2[3] >= ctx.near_plane
9795                {
9796                    let zero_clip: ClippedBaryVert = ClippedBaryVert {
9797                        clip_pos: [0.0; 4],
9798                        world_pos: Vec3::zero(),
9799                        bary: [0.0; 3],
9800                    };
9801                    (
9802                        [
9803                            ClippedBaryVert {
9804                                clip_pos: c0,
9805                                world_pos: wp0,
9806                                bary: [1.0, 0.0, 0.0],
9807                            },
9808                            ClippedBaryVert {
9809                                clip_pos: c1,
9810                                world_pos: wp1,
9811                                bary: [0.0, 1.0, 0.0],
9812                            },
9813                            ClippedBaryVert {
9814                                clip_pos: c2,
9815                                world_pos: wp2,
9816                                bary: [0.0, 0.0, 1.0],
9817                            },
9818                            zero_clip,
9819                            zero_clip,
9820                            zero_clip,
9821                        ],
9822                        1,
9823                    )
9824                } else {
9825                    Self::clip_triangle_near_bary((c0, wp0), (c1, wp1), (c2, wp2), ctx.near_plane)
9826                };
9827                if clipped_count == 0 {
9828                    continue;
9829                }
9830                let vert0: Vertex3D = verts[i0];
9831                let vert1: Vertex3D = verts[i1];
9832                let vert2: Vertex3D = verts[i2];
9833                let local_n0: Vec3 = vert0.get_normal();
9834                let local_n1: Vec3 = vert1.get_normal();
9835                let local_n2: Vec3 = vert2.get_normal();
9836                let has_varied_normals: bool = local_n0.sub(local_n1).length_sq() > 1.0e-4
9837                    || local_n0.sub(local_n2).length_sq() > 1.0e-4;
9838                let has_extra_attrs: bool =
9839                    ((vert0.get_flags() | vert1.get_flags() | vert2.get_flags()) & 9) != 0;
9840                let mut cached_wn: Option<Vec3> = None;
9841                for ci in 0..clipped_count {
9842                    let base_ci: usize = ci * 3;
9843                    let cv0: ClippedBaryVert = clipped_tris[base_ci];
9844                    let cv1: ClippedBaryVert = clipped_tris[base_ci + 1];
9845                    let cv2: ClippedBaryVert = clipped_tris[base_ci + 2];
9846                    let (tc0, tw0, tb0): ([f32; 4], Vec3, [f32; 3]) =
9847                        (cv0.clip_pos, cv0.world_pos, cv0.bary);
9848                    let (tc1, tw1, tb1): ([f32; 4], Vec3, [f32; 3]) =
9849                        (cv1.clip_pos, cv1.world_pos, cv1.bary);
9850                    let (tc2, tw2, tb2): ([f32; 4], Vec3, [f32; 3]) =
9851                        (cv2.clip_pos, cv2.world_pos, cv2.bary);
9852                    let inv_w0: f32 = 1.0 / tc0[3];
9853                    let inv_w1: f32 = 1.0 / tc1[3];
9854                    let inv_w2: f32 = 1.0 / tc2[3];
9855                    let sx0: f32 = (tc0[0] * inv_w0 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9856                    let sy0: f32 = (0.5 - tc0[1] * inv_w0 * 0.5) * ctx.h_f + ctx.jitter_y;
9857                    let sx1: f32 = (tc1[0] * inv_w1 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9858                    let sy1: f32 = (0.5 - tc1[1] * inv_w1 * 0.5) * ctx.h_f + ctx.jitter_y;
9859                    let sx2: f32 = (tc2[0] * inv_w2 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9860                    let sy2: f32 = (0.5 - tc2[1] * inv_w2 * 0.5) * ctx.h_f + ctx.jitter_y;
9861                    let area: f32 = (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0);
9862                    if cull_backface {
9863                        if area >= -0.25 {
9864                            continue;
9865                        }
9866                    } else if area.abs() < 0.25 {
9867                        continue;
9868                    }
9869                    let min_x: i32 = (sx0.min(sx1).min(sx2).floor() as i32).max(0);
9870                    let max_x: i32 = (sx0.max(sx1).max(sx2).ceil() as i32).min(ctx.w_max_i);
9871                    let min_y: i32 = (sy0.min(sy1).min(sy2).floor() as i32).max(0);
9872                    let max_y: i32 = (sy0.max(sy1).max(sy2).ceil() as i32).min(ctx.h_max_i);
9873                    if min_x > max_x || min_y > max_y {
9874                        continue;
9875                    }
9876                    let wn: Vec3 = match cached_wn {
9877                        Some(item_count) => item_count,
9878                        None => {
9879                            let n_avg_local: Vec3 = local_n0.add(local_n1).add(local_n2);
9880                            let n_local: Vec3 = if n_avg_local.length_sq() > 1.0e-6 {
9881                                n_avg_local.normalize()
9882                            } else {
9883                                local_n0
9884                            };
9885                            let computed: Vec3 =
9886                                Mat4::transform_normal_with_basis(n_local, normal_mat3);
9887                            cached_wn = Some(computed);
9888                            computed
9889                        }
9890                    };
9891                    let tri_id: u32 = out.shaded_tris.len() as u32;
9892                    let shade_n: Vec3 = if cull_backface {
9893                        wn
9894                    } else {
9895                        let tri_center: Vec3 = tw0.add(tw1).add(tw2).scale(1.0 / 3.0);
9896                        let tri_view: Vec3 = ctx.cam_pos.sub(tri_center);
9897                        if wn.dot(tri_view) < 0.0 {
9898                            wn.scale(-1.0)
9899                        } else {
9900                            wn
9901                        }
9902                    };
9903                    let n_dot_l: f32 = shade_n.dot(ctx.sun_dir).max(0.0);
9904                    let ambient_sky: Vec3 = ctx.sky_horizon.lerp(
9905                        ctx.sky_zenith,
9906                        (shade_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
9907                    );
9908                    let (
9909                        tri_base,
9910                        tri_emissive,
9911                        tri_f0,
9912                        tri_alpha2,
9913                        tri_diffuse_scale,
9914                        tri_refl,
9915                        tri_metallic,
9916                        tri_do_refl,
9917                        tri_surface_detail,
9918                    ): (
9919                        Vec3,
9920                        Vec3,
9921                        Vec3,
9922                        f32,
9923                        f32,
9924                        f32,
9925                        f32,
9926                        bool,
9927                        SurfaceDetailMode,
9928                    ) = if !has_sub_mats {
9929                        (
9930                            base_mat_base,
9931                            base_mat_emissive,
9932                            base_f0,
9933                            base_alpha2,
9934                            base_diffuse_scale,
9935                            base_mat_refl,
9936                            base_metallic,
9937                            base_do_refl,
9938                            obj_mat.get_surface_detail(),
9939                        )
9940                    } else {
9941                        let (resolved, _): (PbrMaterial, u16) =
9942                            mesh.resolve_triangle_material(global_tri_idx, obj_mat);
9943                        let sub_base: Vec3 = resolved.get_base_color();
9944                        let sub_metal: f32 = resolved.get_metallic();
9945                        let sub_rough: f32 = resolved.get_roughness();
9946                        let sub_alpha: f32 = (sub_rough * sub_rough).max(0.018);
9947                        let sub_refl: f32 = resolved.get_reflectivity();
9948                        (
9949                            sub_base,
9950                            resolved.get_emissive(),
9951                            Vec3::splat(0.04).lerp(sub_base, sub_metal),
9952                            sub_alpha * sub_alpha,
9953                            1.0 - sub_metal,
9954                            sub_refl,
9955                            sub_metal,
9956                            ctx.use_rt_refl && sub_refl > 0.25,
9957                            resolved.get_surface_detail(),
9958                        )
9959                    };
9960                    let inv_area: f32 = 1.0 / area;
9961                    let smooth_attrs: bool = has_varied_normals || has_extra_attrs;
9962                    let smooth_legacy: bool = smooth_attrs || ctx.use_agx_tonemap;
9963                    let use_smooth: bool = principled_id.is_some()
9964                        || (tri_surface_detail == SurfaceDetailMode::None && smooth_legacy);
9965                    let smooth_idx: u32 = if use_smooth {
9966                        let world_n0: Vec3 =
9967                            Mat4::transform_normal_with_basis(local_n0, normal_mat3);
9968                        let world_n1: Vec3 =
9969                            Mat4::transform_normal_with_basis(local_n1, normal_mat3);
9970                        let world_n2: Vec3 =
9971                            Mat4::transform_normal_with_basis(local_n2, normal_mat3);
9972                        let tan_raw0: [f32; 4] = vert0.get_tangent();
9973                        let tan_raw1: [f32; 4] = vert1.get_tangent();
9974                        let tan_raw2: [f32; 4] = vert2.get_tangent();
9975                        let world_t0_v: Vec3 = Mat4::transform_normal_with_basis(
9976                            Vec3::new(tan_raw0[0], tan_raw0[1], tan_raw0[2]),
9977                            normal_mat3,
9978                        );
9979                        let world_t1_v: Vec3 = Mat4::transform_normal_with_basis(
9980                            Vec3::new(tan_raw1[0], tan_raw1[1], tan_raw1[2]),
9981                            normal_mat3,
9982                        );
9983                        let world_t2_v: Vec3 = Mat4::transform_normal_with_basis(
9984                            Vec3::new(tan_raw2[0], tan_raw2[1], tan_raw2[2]),
9985                            normal_mat3,
9986                        );
9987                        let uv0_orig: [[f32; 2]; 3] =
9988                            [vert0.get_uv0(), vert1.get_uv0(), vert2.get_uv0()];
9989                        let uv1_orig: [[f32; 2]; 3] =
9990                            [vert0.get_uv1(), vert1.get_uv1(), vert2.get_uv1()];
9991                        let unpack_col: fn([u8; 4]) -> [f32; 4] = |rgba_u8: [u8; 4]| -> [f32; 4] {
9992                            [
9993                                srgb_u8_to_linear(rgba_u8[0]),
9994                                srgb_u8_to_linear(rgba_u8[1]),
9995                                srgb_u8_to_linear(rgba_u8[2]),
9996                                f32::from(rgba_u8[3]) / 255.0,
9997                            ]
9998                        };
9999                        let col_orig: [[f32; 4]; 3] = [
10000                            unpack_col(vert0.get_color0()),
10001                            unpack_col(vert1.get_color0()),
10002                            unpack_col(vert2.get_color0()),
10003                        ];
10004                        let bary_list: [[f32; 3]; 3] = [tb0, tb1, tb2];
10005                        let mut interp_normals: [Vec3; 3] = [Vec3::zero(); 3];
10006                        let mut interp_tangents: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 1.0]; 3];
10007                        let mut interp_uv0: [[f32; 2]; 3] = [[0.0; 2]; 3];
10008                        let mut interp_uv1: [[f32; 2]; 3] = [[0.0; 2]; 3];
10009                        let mut interp_col: [[f32; 4]; 3] = [[1.0; 4]; 3];
10010                        for corner_idx in 0..3usize {
10011                            let b_w: [f32; 3] = bary_list[corner_idx];
10012                            let n_mix: Vec3 = world_n0
10013                                .scale(b_w[0])
10014                                .add(world_n1.scale(b_w[1]))
10015                                .add(world_n2.scale(b_w[2]));
10016                            interp_normals[corner_idx] = if n_mix.length_sq() > 1.0e-8 {
10017                                n_mix.normalize()
10018                            } else {
10019                                shade_n
10020                            };
10021                            let t_mix: Vec3 = world_t0_v
10022                                .scale(b_w[0])
10023                                .add(world_t1_v.scale(b_w[1]))
10024                                .add(world_t2_v.scale(b_w[2]));
10025                            let t_unit: Vec3 = if t_mix.length_sq() > 1.0e-8 {
10026                                t_mix.normalize()
10027                            } else {
10028                                Vec3::new(1.0, 0.0, 0.0)
10029                            };
10030                            let t_hand: f32 =
10031                                tan_raw0[3] * b_w[0] + tan_raw1[3] * b_w[1] + tan_raw2[3] * b_w[2];
10032                            interp_tangents[corner_idx] = [
10033                                t_unit.get_x(),
10034                                t_unit.get_y(),
10035                                t_unit.get_z(),
10036                                if t_hand < 0.0 { -1.0 } else { 1.0 },
10037                            ];
10038                            interp_uv0[corner_idx] = [
10039                                uv0_orig[0][0] * b_w[0]
10040                                    + uv0_orig[1][0] * b_w[1]
10041                                    + uv0_orig[2][0] * b_w[2],
10042                                uv0_orig[0][1] * b_w[0]
10043                                    + uv0_orig[1][1] * b_w[1]
10044                                    + uv0_orig[2][1] * b_w[2],
10045                            ];
10046                            interp_uv1[corner_idx] = [
10047                                uv1_orig[0][0] * b_w[0]
10048                                    + uv1_orig[1][0] * b_w[1]
10049                                    + uv1_orig[2][0] * b_w[2],
10050                                uv1_orig[0][1] * b_w[0]
10051                                    + uv1_orig[1][1] * b_w[1]
10052                                    + uv1_orig[2][1] * b_w[2],
10053                            ];
10054                            for ch_idx in 0..4usize {
10055                                interp_col[corner_idx][ch_idx] = col_orig[0][ch_idx] * b_w[0]
10056                                    + col_orig[1][ch_idx] * b_w[1]
10057                                    + col_orig[2][ch_idx] * b_w[2];
10058                            }
10059                        }
10060                        let new_smooth_id: u32 = out.smooth_tris.len() as u32;
10061                        out.smooth_tris.push(GSmoothTri {
10062                            screen_x: [sx0, sx1, sx2],
10063                            screen_y: [sy0, sy1, sy2],
10064                            inv_w: [inv_w0, inv_w1, inv_w2],
10065                            inv_area,
10066                            normals: interp_normals,
10067                            tangents: interp_tangents,
10068                            uv0: interp_uv0,
10069                            uv1: interp_uv1,
10070                            color0: interp_col,
10071                            principled_material_id: principled_id.unwrap_or(u32::MAX),
10072                            double_sided: !cull_backface,
10073                        });
10074                        new_smooth_id
10075                    } else {
10076                        u32::MAX
10077                    };
10078                    out.shaded_tris.push(GShadeTri {
10079                        shade_n,
10080                        mat_base: tri_base,
10081                        mat_emissive: tri_emissive,
10082                        ambient_sky,
10083                        f0: tri_f0,
10084                        n_dot_l,
10085                        alpha2: tri_alpha2,
10086                        diffuse_scale: tri_diffuse_scale,
10087                        mat_refl: tri_refl,
10088                        metallic: tri_metallic,
10089                        do_refl: tri_do_refl,
10090                        surface_detail: tri_surface_detail,
10091                        smooth_idx,
10092                    });
10093                    let dw0_dx: f32 = (sy1 - sy2) * inv_area;
10094                    let dw1_dx: f32 = (sy2 - sy0) * inv_area;
10095                    let dw2_dx: f32 = -(dw0_dx + dw1_dx);
10096                    let dw0_dy: f32 = (sx2 - sx1) * inv_area;
10097                    let dw1_dy: f32 = (sx0 - sx2) * inv_area;
10098                    let dw2_dy: f32 = -(dw0_dy + dw1_dy);
10099                    let d_inv_w_dx: f32 = dw0_dx * inv_w0 + dw1_dx * inv_w1 + dw2_dx * inv_w2;
10100                    let d_inv_w_dy: f32 = dw0_dy * inv_w0 + dw1_dy * inv_w1 + dw2_dy * inv_w2;
10101                    let neg_inv_slopes: [f32; 3] = [
10102                        if dw0_dx.abs() > 1e-9 {
10103                            -1.0 / dw0_dx
10104                        } else {
10105                            0.0
10106                        },
10107                        if dw1_dx.abs() > 1e-9 {
10108                            -1.0 / dw1_dx
10109                        } else {
10110                            0.0
10111                        },
10112                        if dw2_dx.abs() > 1e-9 {
10113                            -1.0 / dw2_dx
10114                        } else {
10115                            0.0
10116                        },
10117                    ];
10118                    let slopes: [f32; 3] = [dw0_dx, dw1_dx, dw2_dx];
10119                    let span_max: i32 = max_x - min_x;
10120                    let fx_start: f32 = (min_x as f32) + 0.5;
10121                    let fy_start: f32 = (min_y as f32) + 0.5;
10122                    let w0_row: f32 = ((sx1 - fx_start) * (sy2 - fy_start)
10123                        - (sy1 - fy_start) * (sx2 - fx_start))
10124                        * inv_area;
10125                    let w1_row: f32 = ((sx2 - fx_start) * (sy0 - fy_start)
10126                        - (sy2 - fy_start) * (sx0 - fx_start))
10127                        * inv_area;
10128                    let w2_row: f32 = 1.0 - w0_row - w1_row;
10129                    let inv_w_row: f32 = w0_row * inv_w0 + w1_row * inv_w1 + w2_row * inv_w2;
10130                    out.raster_tris.push(RasterTri2D {
10131                        min_y,
10132                        max_y,
10133                        min_x,
10134                        span_max,
10135                        tri_id,
10136                        slopes,
10137                        neg_inv_slopes,
10138                        dw_dy: [dw0_dy, dw1_dy, dw2_dy],
10139                        w_start: [w0_row, w1_row, w2_row],
10140                        inv_w_start: inv_w_row,
10141                        d_inv_w_dx,
10142                        d_inv_w_dy,
10143                    });
10144                }
10145            }
10146        }
10147    }
10148
10149    /// Renders `world` at runtime-configured `quality` directly into `out_pixels` without zero-filling, returning internal `(width, height)`.
10150    ///
10151    /// # Arguments
10152    ///
10153    /// - `&Self` - Mutable 3D renderer.
10154    /// - `&mut World3D` - Open-world 3D scene graph.
10155    /// - `u32` - Target viewport width in logical pixels.
10156    /// - `u32` - Target viewport height in logical pixels.
10157    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
10158    /// - `&mut Vec<u8>` - Destination RGBA8 byte buffer resized without zero-fill and populated completely.
10159    ///
10160    /// # Returns
10161    ///
10162    /// - `(u32, u32)` - Internal rasterized framebuffer `(width, height)`.
10163    fn render_world_into_vec(
10164        &mut self,
10165        world: &mut World3D,
10166        viewport_w: u32,
10167        viewport_h: u32,
10168        quality: &RenderQualityConfig,
10169        out_pixels: &mut Vec<u8>,
10170    ) -> (u32, u32) {
10171        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
10172        let min_width: u32 = viewport_w.clamp(1, 240);
10173        let min_height: u32 = viewport_h.clamp(1, 144);
10174        let span_width: u32 = (((viewport_w as f32) * scale).round() as u32).max(min_width);
10175        let span_height: u32 = (((viewport_h as f32) * scale).round() as u32).max(min_height);
10176        let w_usize: usize = span_width as usize;
10177        let h_usize: usize = span_height as usize;
10178        let pixel_count: usize = w_usize * h_usize;
10179        let border_width: usize = w_usize.div_ceil(4);
10180        let bh: usize = h_usize.div_ceil(4);
10181        if self.get_width() != span_width || self.get_height() != span_height {
10182            self.set_width(span_width);
10183            self.set_height(span_height);
10184            let Self {
10185                color_buffer,
10186                aa_buffer,
10187                depth_buffer,
10188                g_tri_idx,
10189                luma_buffer,
10190                bloom_a,
10191                bloom_b,
10192                bloom_tile_active,
10193                hiz_pyramid,
10194                tsr_internal_scratch,
10195                has_taa_history,
10196                has_probe_history,
10197                ..
10198            } = self;
10199            let rgba_bytes: usize = pixel_count * 4;
10200            let bloom_cells: usize = border_width * bh;
10201            color_buffer.resize(rgba_bytes, 0);
10202            aa_buffer.resize(rgba_bytes, 0);
10203            depth_buffer.resize(pixel_count, 0.0);
10204            g_tri_idx.resize(pixel_count, u32::MAX);
10205            luma_buffer.resize(pixel_count, 0);
10206            bloom_a.resize(bloom_cells, [0.0; 4]);
10207            bloom_b.resize(bloom_cells, [0.0; 4]);
10208            bloom_tile_active.resize(bloom_cells, 0);
10209            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
10210            tsr_internal_scratch.clear();
10211            if tsr_internal_scratch.capacity() < rgba_bytes {
10212                tsr_internal_scratch.reserve_exact(rgba_bytes);
10213            }
10214            *has_taa_history = false;
10215            *has_probe_history = false;
10216        }
10217        let rt_mode: RayTracingMode = quality.get_ray_tracing();
10218        if rt_mode != RayTracingMode::Off
10219            && (world.get_bvh_dirty()
10220                || world.get_dynamic_bvh_dirty()
10221                || (world.get_bvh().is_empty() && !world.get_objects().is_empty()))
10222        {
10223            world.ensure_bvh();
10224        }
10225        let sun: DirectionalLight3D = world.get_sun();
10226        self.ensure_sky_lut(&sun);
10227        let cam: Camera3D = world.get_camera();
10228        let aspect: f32 = (span_width as f32) / (span_height as f32).max(1.0);
10229        let matrix_value: Mat4 = world.active_view_projection(aspect);
10230        let frustum: Frustum3D = Frustum3D::from_view_proj(&matrix_value);
10231        let cam_fwd: Vec3 = cam.forward();
10232        let cam_right: Vec3 = cam.right();
10233        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
10234        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
10235        let half_h: f32 = (eff_fov_rad * 0.5).tan();
10236        let half_w: f32 = half_h * aspect;
10237        let focal_px: f32 = (span_height as f32) * 0.5 / half_h.max(0.05);
10238        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
10239        let frustum_on: bool = quality.get_frustum_culling();
10240        let chunk_on: bool = quality.get_chunk_streaming();
10241        let lod_bias: f32 = quality.get_lod_bias();
10242        let aa_mode: AntiAliasingMode = quality.get_anti_aliasing();
10243        let mut visible_objects: usize = 0;
10244        let mut culled_objects: usize = 0;
10245        let mut lod_simplified_objects: usize = 0;
10246        let mut meshlets_drawn: usize = 0;
10247        let mut meshlets_culled: usize = 0;
10248        let mut hiz_culled_objects: usize = 0;
10249        let use_vsm: bool = quality.get_virtual_shadow_maps()
10250            && (rt_mode == RayTracingMode::Off || !world.get_principled_materials().is_empty());
10251        if use_vsm {
10252            let Self {
10253                virtual_shadow_map, ..
10254            } = self;
10255            virtual_shadow_map.update_from_world(world);
10256        }
10257        let has_world_local_lights: bool = quality.get_clustered_lighting()
10258            && (!world.get_point_lights().is_empty() || !world.get_spot_lights().is_empty());
10259        let active_local_lights: usize = if has_world_local_lights {
10260            let Self { light_clusters, .. } = self;
10261            light_clusters.build_clusters(
10262                &cam,
10263                aspect,
10264                world.get_point_lights().as_slice(),
10265                world.get_spot_lights().as_slice(),
10266            );
10267            light_clusters.get_active_light_count()
10268        } else {
10269            0
10270        };
10271        let rt_stride_bias: usize = self.get_rt_stride_bias().min(2);
10272        let static_bvh: &Bvh3D = world.get_bvh();
10273        let dyn_instances: &[DynamicRayInstance] = world.dynamic_instances.as_slice();
10274        let local_bvhs: &[Option<Bvh3D>] = world.mesh_local_bvhs.as_slice();
10275        let total_bvh_nodes: usize = world.total_bvh_nodes();
10276        let world_rev: u64 = world.get_world_revision();
10277        let quality_fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
10278        {
10279            let Self {
10280                render_graph,
10281                cached_rdg_schedule,
10282                cached_rdg_key,
10283                last_executed_rdg_passes,
10284                ..
10285            } = self;
10286            if *cached_rdg_key != quality_fp || cached_rdg_schedule.get_ordered_passes().is_empty()
10287            {
10288                *render_graph =
10289                    RenderGraph3D::build_ue5_frame_graph(span_width, span_height, quality);
10290                *cached_rdg_schedule = render_graph.compile();
10291                *cached_rdg_key = quality_fp;
10292            }
10293            let executed_count: usize = render_graph.execute(
10294                cached_rdg_schedule,
10295                |_pass_kind: RenderPassKind3D, _pass_name: &str| -> u64 { 0 },
10296            );
10297            *last_executed_rdg_passes = executed_count;
10298        }
10299        let objects: &[SceneObject3D] = world.get_objects().as_slice();
10300        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
10301        let deformed_meshes_slice: &[Option<Mesh3D>] = world.deformed_meshes.as_slice();
10302        let principled_mats_slice: &[PrincipledMaterial3D] =
10303            world.get_principled_materials().as_slice();
10304        let textures_slice: &[Texture2D3D] = world.get_textures().as_slice();
10305        let area_lights_slice: &[AreaLight3D] = world.get_area_lights().as_slice();
10306        let environment_ibl_ref: Option<&EnvironmentIbl3D> = world.environment_ibl();
10307        let use_agx_tonemap: bool = world.get_use_agx_tonemap();
10308        let cam_pos: Vec3 = cam.get_position();
10309        let sun_dir: Vec3 = sun.get_direction();
10310        let sky_horizon: Vec3 = sun.get_sky_horizon();
10311        let sky_zenith: Vec3 = sun.get_sky_zenith();
10312        let use_rt_refl: bool = matches!(
10313            rt_mode,
10314            RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
10315        );
10316        let base_rt_step: usize = if rt_mode == RayTracingMode::Off {
10317            0
10318        } else if cfg!(target_arch = "wasm32") {
10319            if w_usize >= 440 {
10320                7
10321            } else if w_usize >= 300 {
10322                6
10323            } else {
10324                4
10325            }
10326        } else if w_usize >= 1120 {
10327            7
10328        } else if w_usize >= 780 {
10329            6
10330        } else if w_usize >= 460 {
10331            5
10332        } else if w_usize >= 300 {
10333            4
10334        } else {
10335            2
10336        };
10337        let rt_step: usize = if base_rt_step > 0 {
10338            (base_rt_step + rt_stride_bias).min(8)
10339        } else {
10340            0
10341        };
10342        let gw: usize = if rt_step > 0 {
10343            w_usize.div_ceil(rt_step)
10344        } else {
10345            0
10346        };
10347        let gh: usize = if rt_step > 0 {
10348            h_usize.div_ceil(rt_step)
10349        } else {
10350            0
10351        };
10352        let tile_px: usize = ENGINE3D_TILE_MAX_PX
10353            .checked_div(rt_step)
10354            .map_or(ENGINE3D_TILE_MAX_PX, |entry_index: usize| {
10355                entry_index.max(1) * rt_step
10356            });
10357        let tiles_x: usize = w_usize.div_ceil(tile_px);
10358        let tiles_y: usize = h_usize.div_ceil(tile_px);
10359        let total_tiles: usize = tiles_x * tiles_y;
10360        let Self {
10361            color_buffer,
10362            aa_buffer,
10363            depth_buffer,
10364            g_tri_idx,
10365            luma_buffer,
10366            shaded_tris,
10367            smooth_tris,
10368            nanite_dags_cache,
10369            rt_probes,
10370            prev_rt_probes,
10371            has_probe_history,
10372            prev_probe_gw,
10373            prev_probe_gh,
10374            prev_probe_rt_mode,
10375            prev_sun_dir,
10376            rt_probes_wide_denoised,
10377            bloom_a,
10378            bloom_b,
10379            bloom_tile_active,
10380            visible_scratch,
10381            cluster_ranges_scratch,
10382            projected_verts_scratch,
10383            unique_meshes_scratch,
10384            raster_tris_scratch,
10385            tile_counts_scratch,
10386            tile_offsets_scratch,
10387            tile_cursors_scratch,
10388            tile_tri_indices_scratch,
10389            has_taa_history,
10390            prev_vp_m0,
10391            prev_view_proj,
10392            has_prev_vp,
10393            prev_render_dims,
10394            prev_rt_step,
10395            hiz_pyramid,
10396            hiz_occluder_flags_scratch,
10397            lumen_cache,
10398            light_clusters,
10399            virtual_shadow_map,
10400            tsr_upscaler,
10401            tsr_internal_scratch,
10402            geom_chunks_scratch,
10403            adapted_exposure,
10404            frame_index,
10405            sky_lut,
10406            aces_lut,
10407            saved_objs_scratch,
10408            reserved_object_cap,
10409            reserved_mesh_cap,
10410            ..
10411        } = self;
10412        if nanite_dags_cache.len() < mesh_lib.len() {
10413            let start_dag_idx: usize = nanite_dags_cache.len();
10414            for chain_item in mesh_lib[start_dag_idx..].iter() {
10415                let dag_entry: Option<NaniteClusterDag> = chain_item
10416                    .get_levels()
10417                    .first()
10418                    .filter(|lod0: &&Mesh3D| lod0.get_meshlets().len() > 1)
10419                    .map(NaniteClusterDag::from_mesh);
10420                nanite_dags_cache.push(dag_entry);
10421            }
10422        }
10423        let cur_frame_idx: usize = *frame_index as usize;
10424        let (jitter_x, jitter_y): (f32, f32) = if aa_mode == AntiAliasingMode::Tsr {
10425            HALTON_JITTER_8[cur_frame_idx & 7]
10426        } else {
10427            (0.0, 0.0)
10428        };
10429        *frame_index = frame_index.wrapping_add(1);
10430        if *reserved_object_cap < objects.len()
10431            || *reserved_mesh_cap < mesh_lib.len()
10432            || shaded_tris.capacity() == 0
10433        {
10434            let mut lod0_tris_sum: usize = 0;
10435            for scene_obj in objects.iter() {
10436                if let Some(chain) = mesh_lib.get(scene_obj.get_mesh_id())
10437                    && let Some(level0) = chain.get_levels().first()
10438                {
10439                    lod0_tris_sum = lod0_tris_sum.saturating_add(level0.get_indices().len());
10440                }
10441            }
10442            let mut max_mesh_verts: usize = 1_024;
10443            let mut max_mesh_clusters: usize = 128;
10444            for chain in mesh_lib.iter() {
10445                if let Some(level0) = chain.get_levels().first() {
10446                    max_mesh_verts = max_mesh_verts.max(level0.get_vertices().len());
10447                    max_mesh_clusters = max_mesh_clusters.max(level0.get_meshlets().len());
10448                }
10449            }
10450            let obj_cap: usize = objects.len().max(128);
10451            let mesh_cap: usize = mesh_lib.len().max(64);
10452            let max_scene_tris: usize = lod0_tris_sum.saturating_mul(2).max(8_192);
10453            let chunk_tri_cap: usize = (max_scene_tris / 2).max(2_048);
10454            if visible_scratch.capacity() < obj_cap {
10455                visible_scratch.reserve(obj_cap.saturating_sub(visible_scratch.len()));
10456            }
10457            if hiz_occluder_flags_scratch.capacity() < obj_cap {
10458                hiz_occluder_flags_scratch
10459                    .reserve(obj_cap.saturating_sub(hiz_occluder_flags_scratch.len()));
10460            }
10461            if saved_objs_scratch.capacity() < obj_cap {
10462                saved_objs_scratch.reserve(obj_cap.saturating_sub(saved_objs_scratch.len()));
10463            }
10464            if unique_meshes_scratch.capacity() < mesh_cap {
10465                unique_meshes_scratch.reserve(mesh_cap.saturating_sub(unique_meshes_scratch.len()));
10466            }
10467            if shaded_tris.capacity() < max_scene_tris {
10468                shaded_tris.reserve(max_scene_tris.saturating_sub(shaded_tris.len()));
10469            }
10470            if smooth_tris.capacity() < max_scene_tris {
10471                smooth_tris.reserve(max_scene_tris.saturating_sub(smooth_tris.len()));
10472            }
10473            if raster_tris_scratch.capacity() < max_scene_tris {
10474                raster_tris_scratch
10475                    .reserve(max_scene_tris.saturating_sub(raster_tris_scratch.len()));
10476            }
10477            if projected_verts_scratch.capacity() < max_mesh_verts {
10478                projected_verts_scratch
10479                    .reserve(max_mesh_verts.saturating_sub(projected_verts_scratch.len()));
10480            }
10481            if cluster_ranges_scratch.capacity() < max_mesh_clusters {
10482                cluster_ranges_scratch
10483                    .reserve(max_mesh_clusters.saturating_sub(cluster_ranges_scratch.len()));
10484            }
10485            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
10486                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, GeomChunkScratch::default);
10487            }
10488            for chunk_buf in geom_chunks_scratch.iter_mut() {
10489                if chunk_buf.shaded_tris.capacity() < chunk_tri_cap {
10490                    chunk_buf
10491                        .shaded_tris
10492                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.shaded_tris.len()));
10493                }
10494                if chunk_buf.smooth_tris.capacity() < chunk_tri_cap {
10495                    chunk_buf
10496                        .smooth_tris
10497                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.smooth_tris.len()));
10498                }
10499                if chunk_buf.raster_tris.capacity() < chunk_tri_cap {
10500                    chunk_buf
10501                        .raster_tris
10502                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.raster_tris.len()));
10503                }
10504                if chunk_buf.projected_verts.capacity() < max_mesh_verts {
10505                    chunk_buf
10506                        .projected_verts
10507                        .reserve(max_mesh_verts.saturating_sub(chunk_buf.projected_verts.len()));
10508                }
10509                if chunk_buf.cluster_ranges.capacity() < max_mesh_clusters {
10510                    chunk_buf
10511                        .cluster_ranges
10512                        .reserve(max_mesh_clusters.saturating_sub(chunk_buf.cluster_ranges.len()));
10513                }
10514                if chunk_buf.mesh_ids.capacity() < obj_cap {
10515                    chunk_buf
10516                        .mesh_ids
10517                        .reserve(obj_cap.saturating_sub(chunk_buf.mesh_ids.len()));
10518                }
10519            }
10520            *reserved_object_cap = obj_cap;
10521            *reserved_mesh_cap = mesh_cap;
10522        }
10523        visible_scratch.clear();
10524        unique_meshes_scratch.clear();
10525        if tile_counts_scratch.capacity() < total_tiles {
10526            tile_counts_scratch.reserve(total_tiles.saturating_sub(tile_counts_scratch.len()));
10527        }
10528        if tile_offsets_scratch.capacity() < total_tiles + 1 {
10529            tile_offsets_scratch
10530                .reserve((total_tiles + 1).saturating_sub(tile_offsets_scratch.len()));
10531        }
10532        if tile_cursors_scratch.capacity() < total_tiles {
10533            tile_cursors_scratch.reserve(total_tiles.saturating_sub(tile_cursors_scratch.len()));
10534        }
10535        let min_tile_indices: usize = total_tiles
10536            .saturating_mul(256)
10537            .max(shaded_tris.capacity().saturating_mul(8));
10538        if tile_tri_indices_scratch.capacity() < min_tile_indices {
10539            tile_tri_indices_scratch
10540                .reserve(min_tile_indices.saturating_sub(tile_tri_indices_scratch.len()));
10541        }
10542        for (obj_idx, obj) in objects.iter().enumerate() {
10543            if !world.is_object_visible(obj_idx) {
10544                culled_objects += 1;
10545                continue;
10546            }
10547            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
10548            let dist_sq: f32 = bounds.center().sub(cam_pos).length_sq();
10549            if chunk_on {
10550                let bmin: Vec3 = bounds.get_min();
10551                let bmax: Vec3 = bounds.get_max();
10552                let cx: f32 = cam_pos.get_x().clamp(bmin.get_x(), bmax.get_x());
10553                let cy: f32 = cam_pos.get_y().clamp(bmin.get_y(), bmax.get_y());
10554                let cz: f32 = cam_pos.get_z().clamp(bmin.get_z(), bmax.get_z());
10555                let closest_dist_sq: f32 = Vec3::new(cx, cy, cz).sub(cam_pos).length_sq();
10556                if closest_dist_sq > draw_dist_sq {
10557                    culled_objects += 1;
10558                    continue;
10559                }
10560            }
10561            if frustum_on && !frustum.intersects_bounds(&bounds) {
10562                culled_objects += 1;
10563                continue;
10564            }
10565            visible_scratch.push((dist_sq, obj_idx));
10566        }
10567        visible_scratch.sort_unstable_by(|alpha_val: &(f32, usize), blue_val: &(f32, usize)| {
10568            alpha_val
10569                .0
10570                .total_cmp(&blue_val.0)
10571                .then_with(|| alpha_val.1.cmp(&blue_val.1))
10572        });
10573        shaded_tris.clear();
10574        smooth_tris.clear();
10575        raster_tris_scratch.clear();
10576        let near_plane: f32 = cam.get_near().max(0.15);
10577        let w_f: f32 = span_width as f32;
10578        let h_f: f32 = span_height as f32;
10579        let w_max_i: i32 = (span_width as i32) - 1;
10580        let h_max_i: i32 = (span_height as i32) - 1;
10581        let hiz_active: bool =
10582            quality.get_occlusion_culling() && objects.len() >= 220 && visible_scratch.len() >= 64;
10583        if hiz_active {
10584            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
10585            hiz_pyramid.clear_for_prepass();
10586            hiz_occluder_flags_scratch.clear();
10587            hiz_occluder_flags_scratch.resize(visible_scratch.len(), 0);
10588            let mut stamped_occluders: usize = 0;
10589            let mut stamped_tris: usize = 0;
10590            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10591                if stamped_occluders >= HIZ_MAX_PREPASS_OCCLUDERS
10592                    || stamped_tris >= HIZ_MAX_OCCLUDER_TRIS
10593                {
10594                    break;
10595                }
10596                if dist_sq < 16.0 {
10597                    continue;
10598                }
10599                let obj: &SceneObject3D = &objects[obj_idx];
10600                if !obj.get_ray_trace_caster() || obj.get_world_bounds().radius() < 4.0 {
10601                    continue;
10602                }
10603                let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
10604                    continue;
10605                };
10606                let Some(mesh) = chain.get_levels().first() else {
10607                    continue;
10608                };
10609                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
10610                let invalid_occ: bool = !mesh.get_is_closed() || indices.is_empty();
10611                if invalid_occ || indices.len() > 24 {
10612                    continue;
10613                }
10614                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
10615                let mvp_occ: Mat4 = matrix_value.mul(obj.get_transform().to_mat4());
10616                projected_verts_scratch.clear();
10617                projected_verts_scratch.reserve(verts.len());
10618                for item_val in verts.iter() {
10619                    let cp: [f32; 4] = mvp_occ.mul_point4(item_val.get_position());
10620                    projected_verts_scratch.push((cp, Vec3::zero()));
10621                }
10622                let vlen: usize = projected_verts_scratch.len();
10623                for tri in indices.iter() {
10624                    let (i0, i1, i2): (usize, usize, usize) =
10625                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
10626                    let out_01: bool = i0 >= vlen || i1 >= vlen;
10627                    if out_01 || i2 >= vlen {
10628                        continue;
10629                    }
10630                    let c0: [f32; 4] = projected_verts_scratch[i0].0;
10631                    let c1: [f32; 4] = projected_verts_scratch[i1].0;
10632                    let c2: [f32; 4] = projected_verts_scratch[i2].0;
10633                    let clipped_01: bool = c0[3] < near_plane || c1[3] < near_plane;
10634                    if clipped_01 || c2[3] < near_plane {
10635                        continue;
10636                    }
10637                    let iw0: f32 = 1.0 / c0[3];
10638                    let iw1: f32 = 1.0 / c1[3];
10639                    let iw2: f32 = 1.0 / c2[3];
10640                    let sx0: f32 = (c0[0] * iw0 * 0.5 + 0.5) * w_f;
10641                    let sy0: f32 = (0.5 - c0[1] * iw0 * 0.5) * h_f;
10642                    let sx1: f32 = (c1[0] * iw1 * 0.5 + 0.5) * w_f;
10643                    let sy1: f32 = (0.5 - c1[1] * iw1 * 0.5) * h_f;
10644                    let sx2: f32 = (c2[0] * iw2 * 0.5 + 0.5) * w_f;
10645                    let sy2: f32 = (0.5 - c2[1] * iw2 * 0.5) * h_f;
10646                    hiz_pyramid.stamp_occluder_triangle_conservative(
10647                        [sx0, sx1, sx2],
10648                        [sy0, sy1, sy2],
10649                        [iw0, iw1, iw2],
10650                    );
10651                    stamped_tris += 1;
10652                }
10653                hiz_occluder_flags_scratch[vis_slot] = 1;
10654                stamped_occluders += 1;
10655            }
10656            hiz_pyramid.rebuild_mips();
10657        }
10658        let geom_ctx: GeomPassContext<'_> = GeomPassContext {
10659            objects,
10660            mesh_lib,
10661            deformed_meshes: deformed_meshes_slice,
10662            principled_materials: principled_mats_slice,
10663            nanite_dags: nanite_dags_cache.as_slice(),
10664            hiz_pyramid: &*hiz_pyramid,
10665            hiz_occluder_flags: hiz_occluder_flags_scratch.as_slice(),
10666            frustum,
10667            view_proj: matrix_value,
10668            cam_pos,
10669            sun_dir,
10670            sky_horizon,
10671            sky_zenith,
10672            focal_px,
10673            lod_bias,
10674            near_plane,
10675            w_f,
10676            h_f,
10677            w_max_i,
10678            h_max_i,
10679            jitter_x,
10680            jitter_y,
10681            frustum_on,
10682            hiz_active,
10683            use_rt_refl,
10684            use_agx_tonemap,
10685        };
10686        let vis_len: usize = visible_scratch.len();
10687        if vis_len >= GEOM_PARALLEL_MIN_OBJECTS {
10688            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
10689                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, || GeomChunkScratch {
10690                    shaded_tris: Vec::with_capacity(512),
10691                    smooth_tris: Vec::with_capacity(512),
10692                    raster_tris: Vec::with_capacity(512),
10693                    mesh_ids: Vec::with_capacity(64),
10694                    projected_verts: Vec::with_capacity(512),
10695                    cluster_ranges: Vec::with_capacity(64),
10696                    visible_objects: 0,
10697                    hiz_culled_objects: 0,
10698                    lod_simplified_objects: 0,
10699                    meshlets_drawn: 0,
10700                    meshlets_culled: 0,
10701                });
10702            }
10703            let vis_slice: &[(f32, usize)] = visible_scratch.as_slice();
10704            let chunks_base: usize = geom_chunks_scratch.as_mut_ptr() as usize;
10705            parallel_for_ranges(GEOM_PARALLEL_CHUNKS, 1, |c0: usize, c1: usize| {
10706                for ci in c0..c1 {
10707                    // SAFETY: `parallel_for_ranges` partitions `0..GEOM_PARALLEL_CHUNKS` into strictly disjoint indices.
10708                    let chunk: &mut GeomChunkScratch =
10709                        unsafe { &mut *(chunks_base as *mut GeomChunkScratch).add(ci) };
10710                    chunk.shaded_tris.clear();
10711                    chunk.smooth_tris.clear();
10712                    chunk.raster_tris.clear();
10713                    chunk.mesh_ids.clear();
10714                    chunk.visible_objects = 0;
10715                    chunk.hiz_culled_objects = 0;
10716                    chunk.lod_simplified_objects = 0;
10717                    chunk.meshlets_drawn = 0;
10718                    chunk.meshlets_culled = 0;
10719                    let mut out_view: GeomPassOut<'_> = GeomPassOut {
10720                        shaded_tris: &mut chunk.shaded_tris,
10721                        smooth_tris: &mut chunk.smooth_tris,
10722                        raster_tris: &mut chunk.raster_tris,
10723                        projected_verts: &mut chunk.projected_verts,
10724                        cluster_ranges: &mut chunk.cluster_ranges,
10725                        mesh_ids: Some(&mut chunk.mesh_ids),
10726                        unique_meshes: None,
10727                        visible_objects: 0,
10728                        hiz_culled_objects: 0,
10729                        lod_simplified_objects: 0,
10730                        meshlets_drawn: 0,
10731                        meshlets_culled: 0,
10732                    };
10733                    let vis_start: usize = (ci * vis_len) / GEOM_PARALLEL_CHUNKS;
10734                    let vis_end: usize = ((ci + 1) * vis_len) / GEOM_PARALLEL_CHUNKS;
10735                    for (offset, &(dist_sq, obj_idx)) in
10736                        vis_slice[vis_start..vis_end].iter().enumerate()
10737                    {
10738                        let vis_slot: usize = vis_start + offset;
10739                        Self::process_visible_object_geom(
10740                            &geom_ctx,
10741                            vis_slot,
10742                            dist_sq,
10743                            obj_idx,
10744                            &mut out_view,
10745                        );
10746                    }
10747                    chunk.visible_objects = out_view.visible_objects;
10748                    chunk.hiz_culled_objects = out_view.hiz_culled_objects;
10749                    chunk.lod_simplified_objects = out_view.lod_simplified_objects;
10750                    chunk.meshlets_drawn = out_view.meshlets_drawn;
10751                    chunk.meshlets_culled = out_view.meshlets_culled;
10752                }
10753            });
10754            let mut total_chunk_tris: usize = 0;
10755            let mut total_chunk_smooth: usize = 0;
10756            for chunk in geom_chunks_scratch.iter() {
10757                total_chunk_tris += chunk.shaded_tris.len();
10758                total_chunk_smooth += chunk.smooth_tris.len();
10759            }
10760            if shaded_tris.capacity() < total_chunk_tris {
10761                shaded_tris.reserve(total_chunk_tris - shaded_tris.capacity());
10762            }
10763            if smooth_tris.capacity() < total_chunk_smooth {
10764                smooth_tris.reserve(total_chunk_smooth - smooth_tris.capacity());
10765            }
10766            if raster_tris_scratch.capacity() < total_chunk_tris {
10767                raster_tris_scratch.reserve(total_chunk_tris - raster_tris_scratch.capacity());
10768            }
10769            for chunk in geom_chunks_scratch.iter() {
10770                let base_tri_id: u32 = shaded_tris.len() as u32;
10771                let base_smooth_id: u32 = smooth_tris.len() as u32;
10772                smooth_tris.extend_from_slice(chunk.smooth_tris.as_slice());
10773                for &shaded_rec in chunk.shaded_tris.iter() {
10774                    let mut shifted_tri: GShadeTri = shaded_rec;
10775                    if shifted_tri.smooth_idx != u32::MAX {
10776                        shifted_tri.smooth_idx += base_smooth_id;
10777                    }
10778                    shaded_tris.push(shifted_tri);
10779                }
10780                for &rt in chunk.raster_tris.iter() {
10781                    let mut shifted: RasterTri2D = rt;
10782                    shifted.tri_id += base_tri_id;
10783                    raster_tris_scratch.push(shifted);
10784                }
10785                visible_objects += chunk.visible_objects;
10786                hiz_culled_objects += chunk.hiz_culled_objects;
10787                culled_objects += chunk.hiz_culled_objects;
10788                lod_simplified_objects += chunk.lod_simplified_objects;
10789                meshlets_drawn += chunk.meshlets_drawn;
10790                meshlets_culled += chunk.meshlets_culled;
10791                for &mesh_id in chunk.mesh_ids.iter() {
10792                    let _: bool = unique_meshes_scratch.insert(mesh_id);
10793                }
10794            }
10795        } else {
10796            let mut seq_out: GeomPassOut<'_> = GeomPassOut {
10797                shaded_tris,
10798                smooth_tris,
10799                raster_tris: raster_tris_scratch,
10800                projected_verts: projected_verts_scratch,
10801                cluster_ranges: cluster_ranges_scratch,
10802                mesh_ids: None,
10803                unique_meshes: Some(unique_meshes_scratch),
10804                visible_objects: 0,
10805                hiz_culled_objects: 0,
10806                lod_simplified_objects: 0,
10807                meshlets_drawn: 0,
10808                meshlets_culled: 0,
10809            };
10810            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10811                Self::process_visible_object_geom(
10812                    &geom_ctx,
10813                    vis_slot,
10814                    dist_sq,
10815                    obj_idx,
10816                    &mut seq_out,
10817                );
10818            }
10819            visible_objects += seq_out.visible_objects;
10820            hiz_culled_objects += seq_out.hiz_culled_objects;
10821            culled_objects += seq_out.hiz_culled_objects;
10822            lod_simplified_objects += seq_out.lod_simplified_objects;
10823            meshlets_drawn += seq_out.meshlets_drawn;
10824            meshlets_culled += seq_out.meshlets_culled;
10825        }
10826        let triangles_drawn: usize = shaded_tris.len();
10827        tile_counts_scratch.clear();
10828        tile_counts_scratch.resize(total_tiles, 0);
10829        let tile_px_i: i32 = tile_px as i32;
10830        let tiles_x_max: usize = tiles_x.saturating_sub(1);
10831        let tiles_y_max: usize = tiles_y.saturating_sub(1);
10832        for tri in raster_tris_scratch.iter() {
10833            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10834            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10835            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10836            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10837            for ty in ty0..=ty1 {
10838                let row_t: usize = ty * tiles_x;
10839                for tx in tx0..=tx1 {
10840                    tile_counts_scratch[row_t + tx] += 1;
10841                }
10842            }
10843        }
10844        tile_offsets_scratch.clear();
10845        tile_offsets_scratch.reserve(total_tiles + 1);
10846        let mut prefix_sum: u32 = 0;
10847        tile_offsets_scratch.push(0);
10848        for &cnt in tile_counts_scratch.iter() {
10849            prefix_sum += cnt;
10850            tile_offsets_scratch.push(prefix_sum);
10851        }
10852        tile_cursors_scratch.clear();
10853        tile_cursors_scratch.extend_from_slice(&tile_offsets_scratch[..total_tiles]);
10854        tile_tri_indices_scratch.resize(prefix_sum as usize, 0);
10855        for (slot, tri) in raster_tris_scratch.iter().enumerate() {
10856            let slot_u32: u32 = slot as u32;
10857            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10858            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10859            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10860            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10861            for ty in ty0..=ty1 {
10862                let row_t: usize = ty * tiles_x;
10863                for tx in tx0..=tx1 {
10864                    let t_idx: usize = row_t + tx;
10865                    let dst_pos: usize = tile_cursors_scratch[t_idx] as usize;
10866                    tile_cursors_scratch[t_idx] = (dst_pos as u32) + 1;
10867                    tile_tri_indices_scratch[dst_pos] = slot_u32;
10868                }
10869            }
10870        }
10871        let bloom_on: bool = matches!(
10872            quality.get_preset(),
10873            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
10874        );
10875        if bloom_on {
10876            let bloom_cells: usize = border_width * bh;
10877            if bloom_a.len() != bloom_cells {
10878                bloom_a.resize(bloom_cells, [0.0; 4]);
10879                bloom_b.resize(bloom_cells, [0.0; 4]);
10880                bloom_tile_active.resize(bloom_cells, 0);
10881            }
10882        }
10883        let sun_inv_dir: Vec3 = Ray3D::safe_inv_vec(sun_dir);
10884        let soft_shadow_rays: [(Vec3, Vec3); 16] = if rt_mode == RayTracingMode::FullPathTracedGi {
10885            let sun_t1: Vec3 = sun_dir.cross(Vec3::new(0.0, 1.0, 0.0)).normalize();
10886            let sun_t2: Vec3 = sun_dir.cross(sun_t1).normalize();
10887            let mut table: [(Vec3, Vec3); 16] = [(sun_dir, sun_inv_dir); 16];
10888            for (slot, &(ox, oy)) in table.iter_mut().zip(SOFT_SHADOW_RING_16.iter()) {
10889                let jittered: Vec3 = sun_dir
10890                    .add(sun_t1.scale(ox))
10891                    .add(sun_t2.scale(oy))
10892                    .normalize();
10893                *slot = (jittered, Ray3D::safe_inv_vec(jittered));
10894            }
10895            table
10896        } else {
10897            [(sun_dir, sun_inv_dir); 16]
10898        };
10899        let frame_context: DeferredFrameContext = DeferredFrameContext {
10900            width: w_usize,
10901            height: h_usize,
10902            grid_width: gw,
10903            grid_height: gh,
10904            bloom_width: border_width,
10905            raytrace_step: rt_step,
10906            inv_width: 1.0 / (span_width as f32).max(1.0),
10907            inv_height: 1.0 / (span_height as f32).max(1.0),
10908            camera_position: cam_pos,
10909            camera_forward: cam_fwd,
10910            camera_right_scaled: cam_right.scale(half_w),
10911            camera_up_scaled: cam_up.scale(half_h),
10912            sun,
10913            inv_sun_dir: sun_inv_dir,
10914            soft_shadow_rays,
10915            frame_index: cur_frame_idx,
10916            raytrace_mode: rt_mode,
10917            reflection_bounces: quality.get_reflection_bounces(),
10918            fog_on: quality.get_volumetric_fog(),
10919            inv_fog_distance: 0.92 / quality.get_draw_distance().max(40.0),
10920            exposure_scale: *adapted_exposure,
10921            bloom_on,
10922            has_clustered_lights: active_local_lights > 0,
10923            probe_frame_generation: PROBE_SCRATCH_FRAME_GEN.fetch_add(1, Ordering::Relaxed),
10924            world_time_secs: world.get_world_time_secs(),
10925        };
10926        let vp_m0: f32 = matrix_value.get_elements()[0]
10927            + matrix_value.get_elements()[12] * 0.01
10928            + matrix_value.get_elements()[14] * 0.01;
10929        let cam_stable: bool = (*prev_vp_m0 - vp_m0).abs() < 0.35;
10930        let sun_stable: bool = prev_sun_dir.dot(sun_dir) > 0.9999;
10931        let probe_hist_valid: bool = *has_probe_history
10932            && *has_prev_vp
10933            && rt_step > 0
10934            && *prev_probe_rt_mode == rt_mode
10935            && sun_stable;
10936        if rt_step > 0 {
10937            rt_probes.resize(gw * gh);
10938            prev_rt_probes.resize(gw * gh);
10939        }
10940        let use_lumen_cache: bool = quality.get_lumen_radiance_cache()
10941            && rt_step > 0
10942            && rt_mode == RayTracingMode::FullPathTracedGi;
10943        if use_lumen_cache && !sun_stable {
10944            lumen_cache.invalidate();
10945        }
10946        let rays_atom: AtomicUsize = AtomicUsize::new(0);
10947        let reproj_hits_atom: AtomicUsize = AtomicUsize::new(0);
10948        {
10949            let prev_probes_ref: Option<&RtProbeGridSoa> = if probe_hist_valid {
10950                Some(&*prev_rt_probes)
10951            } else {
10952                None
10953            };
10954            let lumen_ref: Option<&LumenRadianceCache> =
10955                if use_lumen_cache && lumen_cache.get_active_cells() > 0 {
10956                    Some(&*lumen_cache)
10957                } else {
10958                    None
10959                };
10960            let clusters_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
10961                Some(&*light_clusters)
10962            } else {
10963                None
10964            };
10965            let vsm_ref: Option<&VirtualShadowMap> = if use_vsm {
10966                Some(&*virtual_shadow_map)
10967            } else {
10968                None
10969            };
10970            let same_camera_pose: bool = probe_hist_valid
10971                && *prev_render_dims == (w_usize, h_usize)
10972                && *prev_rt_step == rt_step
10973                && *prev_probe_gw == gw
10974                && *prev_probe_gh == gh
10975                && prev_view_proj.get_elements() == matrix_value.get_elements();
10976            let tile_inputs: TileRasterProbeInputs<'_> = TileRasterProbeInputs {
10977                raster_tris: raster_tris_scratch.as_slice(),
10978                tile_offsets: tile_offsets_scratch.as_slice(),
10979                tile_tri_indices: tile_tri_indices_scratch.as_slice(),
10980                shaded_tris: shaded_tris.as_slice(),
10981                static_bvh,
10982                dyn_instances,
10983                local_bvhs,
10984                prev_probes: prev_probes_ref,
10985                prev_view_proj: *prev_view_proj,
10986                prev_render_dims: *prev_render_dims,
10987                prev_rt_step: *prev_rt_step,
10988                prev_gw: *prev_probe_gw,
10989                prev_gh: *prev_probe_gh,
10990                lumen_cache: lumen_ref,
10991                light_clusters: clusters_ref,
10992                vsm: vsm_ref,
10993                use_vsm_far_shadows: use_vsm,
10994                probe_checker_parity: cur_frame_idx & 1,
10995                same_camera_pose,
10996                tile_px,
10997                tiles_x,
10998                sky_lut: sky_lut.as_slice(),
10999            };
11000            let depth_base: usize = depth_buffer.as_mut_ptr() as usize;
11001            let gtri_base: usize = g_tri_idx.as_mut_ptr() as usize;
11002            let probe_ptrs: RtProbeGridMutPtrs = rt_probes.mut_ptrs();
11003            let tile_grain: usize = 1;
11004            parallel_for_ranges(total_tiles, tile_grain, |t0: usize, t1: usize| {
11005                // SAFETY: `parallel_for_ranges` partitions `0..total_tiles` into strictly disjoint screen tiles and probe blocks.
11006                let (red_val, hit_val): (usize, usize) = unsafe {
11007                    Self::raster_and_trace_tiles(
11008                        &frame_context,
11009                        &tile_inputs,
11010                        t0,
11011                        t1,
11012                        (depth_base, gtri_base, probe_ptrs),
11013                    )
11014                };
11015                if red_val > 0 {
11016                    let _: usize = rays_atom.fetch_add(red_val, Ordering::Relaxed);
11017                }
11018                if hit_val > 0 {
11019                    let _: usize = reproj_hits_atom.fetch_add(hit_val, Ordering::Relaxed);
11020                }
11021            });
11022        }
11023        if use_lumen_cache {
11024            lumen_cache.begin_frame(sun_dir);
11025            let total_probes: usize = gw * gh;
11026            let probe_stride: usize = (total_probes / 384).max(1).next_power_of_two();
11027            let mut p_cursor: usize = cur_frame_idx & (probe_stride - 1);
11028            while p_cursor < total_probes {
11029                if rt_probes.valid[p_cursor] != 0 {
11030                    lumen_cache.accumulate_sample(
11031                        Vec3::new(
11032                            rt_probes.world_x[p_cursor],
11033                            rt_probes.world_y[p_cursor],
11034                            rt_probes.world_z[p_cursor],
11035                        ),
11036                        Vec3::new(
11037                            rt_probes.nx[p_cursor],
11038                            rt_probes.ny[p_cursor],
11039                            rt_probes.nz[p_cursor],
11040                        ),
11041                        cam_pos,
11042                        Vec3::new(
11043                            rt_probes.gi_r[p_cursor],
11044                            rt_probes.gi_g[p_cursor],
11045                            rt_probes.gi_b[p_cursor],
11046                        ),
11047                        rt_probes.ao[p_cursor],
11048                        rt_probes.shadow[p_cursor],
11049                    );
11050                }
11051                p_cursor += probe_stride;
11052            }
11053        }
11054        let lumen_cache_cells: usize = lumen_cache.get_active_cells();
11055        let probe_reproj_hits: usize = reproj_hits_atom.load(Ordering::Relaxed);
11056        let denoise_probes: bool = rt_step > 0
11057            && matches!(
11058                rt_mode,
11059                RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
11060            );
11061        if denoise_probes && gw > PROBE_ROW_STACK_CAP {
11062            Self::denoise_wide_grid(rt_probes, gw, gh, rt_probes_wide_denoised);
11063        }
11064        let bloom_any_atom: AtomicUsize = AtomicUsize::new(0);
11065        let bloom_row_bits: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9];
11066        {
11067            let clusters_shade_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
11068                Some(&*light_clusters)
11069            } else {
11070                None
11071            };
11072            let vsm_shade_ref: Option<&VirtualShadowMap> = if use_vsm {
11073                Some(&*virtual_shadow_map)
11074            } else {
11075                None
11076            };
11077            let shade_inputs: ShadeBandInputs<'_> = ShadeBandInputs {
11078                depth_buf: depth_buffer.as_slice(),
11079                g_tri_idx: g_tri_idx.as_slice(),
11080                shaded_tris: shaded_tris.as_slice(),
11081                smooth_tris: smooth_tris.as_slice(),
11082                principled_materials: principled_mats_slice,
11083                textures: textures_slice,
11084                area_lights: area_lights_slice,
11085                light_clusters: clusters_shade_ref,
11086                vsm: vsm_shade_ref,
11087                environment_ibl: environment_ibl_ref,
11088                use_agx_tonemap,
11089                raw_probes: rt_probes,
11090                wide_denoised_probes: rt_probes_wide_denoised,
11091                denoise_probes,
11092                denoise_gi_channels: rt_mode == RayTracingMode::FullPathTracedGi,
11093                static_bvh,
11094                dyn_instances,
11095                local_bvhs,
11096                bloom_row_bits: &bloom_row_bits,
11097                sky_lut: sky_lut.as_slice(),
11098                aces_lut: aces_lut.as_slice(),
11099            };
11100            let color_base: usize = color_buffer.as_mut_ptr() as usize;
11101            let luma_base: usize = luma_buffer.as_mut_ptr() as usize;
11102            let bloom_base: usize = bloom_a.as_mut_ptr() as usize;
11103            let bloom_total_len: usize = bloom_a.len();
11104            let shade_grain: usize = 4;
11105            parallel_for_ranges(h_usize, shade_grain, |y0: usize, y1: usize| {
11106                let rows: usize = y1 - y0;
11107                // SAFETY: `shade_grain` is a multiple of 4 and `parallel_for_ranges` yields disjoint row bands.
11108                let c_band: &mut [u8] = unsafe {
11109                    from_raw_parts_mut(
11110                        (color_base as *mut u8).add(y0 * w_usize * 4),
11111                        rows * w_usize * 4,
11112                    )
11113                };
11114                // SAFETY: Disjoint luma row band for `[y0, y1)`.
11115                let l_band: &mut [u8] = unsafe {
11116                    from_raw_parts_mut((luma_base as *mut u8).add(y0 * w_usize), rows * w_usize)
11117                };
11118                let b_start: usize = (y0 / 4) * border_width;
11119                let b_end: usize = ((y1.div_ceil(4)) * border_width).min(bloom_total_len);
11120                let b_band: &mut [[f32; 4]] = if b_start < b_end {
11121                    // SAFETY: Since `y0` and non-final `y1` are multiples of 4, `[b_start, b_end)` ranges are disjoint.
11122                    unsafe {
11123                        from_raw_parts_mut(
11124                            (bloom_base as *mut [f32; 4]).add(b_start),
11125                            b_end - b_start,
11126                        )
11127                    }
11128                } else {
11129                    &mut []
11130                };
11131                let (radius_val, has_bloom_band): (usize, bool) = Self::shade_deferred_band(
11132                    &frame_context,
11133                    &shade_inputs,
11134                    (y0, c_band, l_band, b_band),
11135                );
11136                if radius_val > 0 {
11137                    let _: usize = rays_atom.fetch_add(radius_val, Ordering::Relaxed);
11138                }
11139                if has_bloom_band {
11140                    bloom_any_atom.store(1, Ordering::Relaxed);
11141                }
11142            });
11143        }
11144        let rays_traced: usize = rays_atom.load(Ordering::Relaxed);
11145        let luma_len: usize = luma_buffer.len();
11146        if luma_len >= 64 {
11147            let sample_stride: usize = (luma_len / 1024).max(1);
11148            let mut luma_sum: u32 = 0;
11149            let mut sample_cnt: u32 = 0;
11150            let mut sample_idx: usize = sample_stride >> 1;
11151            while sample_idx < luma_len {
11152                luma_sum += luma_buffer[sample_idx] as u32;
11153                sample_cnt += 1;
11154                sample_idx += sample_stride;
11155            }
11156            if sample_cnt > 0 {
11157                let avg_luma: f32 = ((luma_sum as f32) / ((sample_cnt as f32) * 255.0)).max(0.06);
11158                let desired_exp: f32 = ((*adapted_exposure)
11159                    * (AUTO_EXPOSURE_TARGET_LUMA / avg_luma))
11160                    .clamp(AUTO_EXPOSURE_MIN, AUTO_EXPOSURE_MAX);
11161                let exp_delta: f32 = desired_exp - *adapted_exposure;
11162                if exp_delta.abs() > 0.015 {
11163                    *adapted_exposure += exp_delta * AUTO_EXPOSURE_ADAPT_RATE;
11164                }
11165            }
11166        }
11167        let particles_drawn: usize = if world.get_niagara().get_active_count() > 0 {
11168            world.get_niagara().composite_depth_tested(
11169                &matrix_value,
11170                focal_px,
11171                (w_usize, h_usize),
11172                depth_buffer.as_slice(),
11173                color_buffer.as_mut_slice(),
11174            )
11175        } else {
11176            0
11177        };
11178        let bloom_effective: bool = if bloom_on && bloom_any_atom.load(Ordering::Relaxed) != 0 {
11179            let mut row_bits_snap: [u64; 9] = [0; 9];
11180            for (dst, src_atom) in row_bits_snap.iter_mut().zip(bloom_row_bits.iter()) {
11181                *dst = src_atom.load(Ordering::Relaxed);
11182            }
11183            Self::blur_bloom_and_mask(
11184                border_width,
11185                bh,
11186                bloom_a.as_mut_slice(),
11187                bloom_b.as_mut_slice(),
11188                bloom_tile_active.as_mut_slice(),
11189                &row_bits_snap,
11190            )
11191        } else {
11192            false
11193        };
11194        let byte_len: usize = pixel_count * 4;
11195        if aa_mode == AntiAliasingMode::Tsr {
11196            let tsr_params: TsrFrameParams = TsrFrameParams {
11197                src_width: w_usize,
11198                src_height: h_usize,
11199                dst_width: w_usize,
11200                dst_height: h_usize,
11201                camera_position: cam_pos,
11202                camera_forward: cam_fwd,
11203                camera_right_scaled: cam_right.scale(half_w),
11204                camera_up_scaled: cam_up.scale(half_h),
11205                view_projection: matrix_value,
11206                jitter_offset: (jitter_x, jitter_y),
11207                sharpness: TSR_DEFAULT_SHARPNESS,
11208            };
11209            if bloom_effective {
11210                tsr_internal_scratch.clear();
11211                if tsr_internal_scratch.capacity() < byte_len {
11212                    tsr_internal_scratch.reserve_exact(byte_len);
11213                }
11214                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
11215                    color_src: color_buffer.as_slice(),
11216                    luma: luma_buffer.as_slice(),
11217                    g_tri_idx: g_tri_idx.as_slice(),
11218                    bloom: bloom_a.as_slice(),
11219                    bloom_tile_active: bloom_tile_active.as_slice(),
11220                    taa_history: aa_buffer.as_slice(),
11221                };
11222                let tmp_base: usize = tsr_internal_scratch.as_mut_ptr() as usize;
11223                let post_grain: usize = 8;
11224                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
11225                    // SAFETY: `tsr_internal_scratch` has capacity `>= byte_len` and row ranges are disjoint.
11226                    unsafe {
11227                        let band_ptr: *mut u8 = (tmp_base as *mut u8).add(y0 * w_usize * 4);
11228                        Self::post_process_band(
11229                            (w_usize, h_usize, border_width, bh),
11230                            &post_inputs,
11231                            (false, false, true),
11232                            (y0, band_ptr, y1 - y0),
11233                        );
11234                    }
11235                });
11236                // SAFETY: `parallel_for_ranges` initialized every byte in `0..byte_len`.
11237                unsafe {
11238                    tsr_internal_scratch.set_len(byte_len);
11239                }
11240                tsr_upscaler.upscale_rgba(
11241                    tsr_internal_scratch.as_slice(),
11242                    depth_buffer.as_slice(),
11243                    &tsr_params,
11244                    out_pixels,
11245                );
11246            } else {
11247                tsr_upscaler.upscale_rgba(
11248                    color_buffer.as_slice(),
11249                    depth_buffer.as_slice(),
11250                    &tsr_params,
11251                    out_pixels,
11252                );
11253            }
11254        } else {
11255            let use_fxaa: bool = aa_mode != AntiAliasingMode::Off;
11256            let use_taa: bool = aa_mode == AntiAliasingMode::Taa && *has_taa_history && cam_stable;
11257            out_pixels.clear();
11258            if out_pixels.capacity() < byte_len {
11259                out_pixels.reserve_exact(byte_len);
11260            }
11261            {
11262                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
11263                    color_src: color_buffer.as_slice(),
11264                    luma: luma_buffer.as_slice(),
11265                    g_tri_idx: g_tri_idx.as_slice(),
11266                    bloom: bloom_a.as_slice(),
11267                    bloom_tile_active: bloom_tile_active.as_slice(),
11268                    taa_history: aa_buffer.as_slice(),
11269                };
11270                let out_base: usize = out_pixels.as_mut_ptr() as usize;
11271                let post_grain: usize = 8;
11272                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
11273                    // SAFETY: `out_pixels` has capacity `>= byte_len`, `parallel_for_ranges` partitions `0..h_usize`
11274                    // into disjoint row ranges, and `post_process_band` writes all `(y1 - y0) * w_usize * 4` bytes.
11275                    unsafe {
11276                        let band_ptr: *mut u8 = (out_base as *mut u8).add(y0 * w_usize * 4);
11277                        Self::post_process_band(
11278                            (w_usize, h_usize, border_width, bh),
11279                            &post_inputs,
11280                            (use_fxaa, use_taa, bloom_effective),
11281                            (y0, band_ptr, y1 - y0),
11282                        );
11283                    }
11284                });
11285            }
11286            // SAFETY: `parallel_for_ranges` has joined and initialized every byte in `0..byte_len`.
11287            unsafe {
11288                out_pixels.set_len(byte_len);
11289            }
11290        }
11291        if rt_step > 0 {
11292            swap(rt_probes, prev_rt_probes);
11293            *has_probe_history = true;
11294            *prev_probe_gw = gw;
11295            *prev_probe_gh = gh;
11296            *prev_probe_rt_mode = rt_mode;
11297            *prev_sun_dir = sun_dir;
11298        } else {
11299            *has_probe_history = false;
11300        }
11301        *prev_vp_m0 = vp_m0;
11302        *prev_view_proj = matrix_value;
11303        *has_prev_vp = true;
11304        *prev_render_dims = (w_usize, h_usize);
11305        *prev_rt_step = rt_step;
11306        if aa_mode == AntiAliasingMode::Taa {
11307            if aa_buffer.len() != byte_len {
11308                aa_buffer.resize(byte_len, 0);
11309            }
11310            swap(aa_buffer, color_buffer);
11311            *has_taa_history = true;
11312        } else {
11313            *has_taa_history = false;
11314        }
11315        let instanced_batches: usize = if quality.get_gpu_instancing() {
11316            unique_meshes_scratch.len()
11317        } else {
11318            visible_objects
11319        };
11320        let stats: RenderStats3D = RenderStats3D {
11321            render_width: span_width,
11322            render_height: span_height,
11323            visible_objects,
11324            culled_objects,
11325            instanced_batches,
11326            triangles_drawn,
11327            rays_traced,
11328            bvh_nodes: total_bvh_nodes,
11329            lod_simplified_objects,
11330            meshlets_drawn,
11331            meshlets_culled,
11332            hiz_culled_objects,
11333            lumen_cache_cells,
11334            active_local_lights,
11335            particles_drawn,
11336            probe_reproj_hits,
11337        };
11338        let same_world_and_cfg: bool = self.get_last_world_revision() == world_rev && {
11339            let Self {
11340                last_quality_fingerprint,
11341                ..
11342            } = self;
11343            *last_quality_fingerprint == quality_fp
11344        };
11345        let next_taa_count: u32 =
11346            if matches!(aa_mode, AntiAliasingMode::Taa | AntiAliasingMode::Tsr) {
11347                if same_world_and_cfg {
11348                    self.get_taa_accumulated_frames().saturating_add(1).min(8)
11349                } else {
11350                    1
11351                }
11352            } else {
11353                0
11354            };
11355        self.set_taa_accumulated_frames(next_taa_count);
11356        self.set_last_world_revision(world_rev);
11357        let Self {
11358            last_quality_fingerprint,
11359            ..
11360        } = self;
11361        *last_quality_fingerprint = quality_fp;
11362        self.set_last_stats(stats);
11363        (span_width, span_height)
11364    }
11365
11366    /// Computes a stable configuration fingerprint covering viewport dimensions and visual quality knobs.
11367    ///
11368    /// # Arguments
11369    ///
11370    /// - `u32` - Target viewport width.
11371    /// - `u32` - Target viewport height.
11372    /// - `&RenderQualityConfig` - Active quality settings.
11373    ///
11374    /// # Returns
11375    ///
11376    /// - `u64` - Combined configuration fingerprint.
11377    #[must_use]
11378    fn quality_fingerprint(viewport_w: u32, viewport_h: u32, quality: &RenderQualityConfig) -> u64 {
11379        let mut height_val: u64 = 0xCBF2_9CE4_8422_2325;
11380        let parts: [u64; 8] = [
11381            viewport_w as u64,
11382            viewport_h as u64,
11383            quality.get_resolution_scale().to_bits() as u64,
11384            quality.get_draw_distance().to_bits() as u64,
11385            quality.get_lod_bias().to_bits() as u64,
11386            quality.get_reflection_bounces() as u64,
11387            (quality.get_ray_tracing() as u64)
11388                | ((quality.get_anti_aliasing() as u64) << 8)
11389                | ((quality.get_preset() as u64) << 16)
11390                | ((quality.get_upscaler() as u64) << 24),
11391            u64::from(quality.get_volumetric_fog())
11392                | (u64::from(quality.get_frustum_culling()) << 1)
11393                | (u64::from(quality.get_chunk_streaming()) << 2)
11394                | (u64::from(quality.get_occlusion_culling()) << 3)
11395                | (u64::from(quality.get_virtual_shadow_maps()) << 4)
11396                | (u64::from(quality.get_clustered_lighting()) << 5)
11397                | (u64::from(quality.get_lumen_radiance_cache()) << 6),
11398        ];
11399        for point_val in parts.into_iter() {
11400            height_val ^= point_val;
11401            height_val = height_val.wrapping_mul(0x0100_0000_01B3);
11402        }
11403        height_val
11404    }
11405
11406    /// Attaches a shared-device GPU 3D render target texture handle for zero-readback single-pass UI+3D compositing.
11407    ///
11408    /// # Arguments
11409    ///
11410    /// - `&Self` - Mutable 3D renderer.
11411    /// - `GpuTextureHandle` - Shared-device GPU texture backing the 3D render target.
11412    /// - `Rect` - Viewport rectangle in logical UI pixels.
11413    pub fn attach_gpu_target(&mut self, handle: GpuTextureHandle, rect: Rect) {
11414        let Self { gpu_target, .. } = self;
11415        gpu_target.attach_handle(handle, rect);
11416    }
11417
11418    /// Prepares a `GpuCompositeDescriptor` referencing the attached shared-device GPU 3D render target for single-pass UI+3D compositing.
11419    ///
11420    /// # Arguments
11421    ///
11422    /// - `&Self` - Mutable 3D renderer.
11423    /// - `u64` - Monotonic compositor frame index.
11424    ///
11425    /// # Returns
11426    ///
11427    /// - `Option<GpuCompositeDescriptor>` - Single-pass composite descriptor when a GPU target is attached.
11428    #[must_use]
11429    pub fn prepare_gpu_composite_descriptor(
11430        &mut self,
11431        frame_index: u64,
11432    ) -> Option<GpuCompositeDescriptor> {
11433        let Self { gpu_target, .. } = self;
11434        gpu_target.record_composite_present(frame_index)
11435    }
11436
11437    /// Explicitly resets temporal anti-aliasing history on camera cuts or world teleports without touching unrelated HUD state.
11438    ///
11439    /// # Arguments
11440    ///
11441    /// - `&Self` - Mutable 3D renderer.
11442    pub fn invalidate_taa_history(&mut self) {
11443        let Self {
11444            has_taa_history,
11445            has_probe_history,
11446            has_prev_vp,
11447            tsr_upscaler,
11448            lumen_cache,
11449            adapted_exposure,
11450            ..
11451        } = self;
11452        *has_taa_history = false;
11453        *has_probe_history = false;
11454        *has_prev_vp = false;
11455        *adapted_exposure = 1.0;
11456        tsr_upscaler.invalidate_history();
11457        lumen_cache.invalidate();
11458        self.set_taa_accumulated_frames(0);
11459    }
11460
11461    /// 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.
11462    ///
11463    /// # Arguments
11464    ///
11465    /// - `&Self` - 3D renderer reference.
11466    /// - `&World3D` - Active 3D world.
11467    /// - `u32` - Viewport width in pixels.
11468    /// - `u32` - Viewport height in pixels.
11469    /// - `&RenderQualityConfig` - Active quality settings.
11470    ///
11471    /// # Returns
11472    ///
11473    /// - `bool` - `true` when the cached 3D frame is valid and TAA accumulation does not require another sample.
11474    #[must_use]
11475    pub fn can_reuse_cached_world(
11476        &self,
11477        world: &World3D,
11478        viewport_w: u32,
11479        viewport_h: u32,
11480        quality: &RenderQualityConfig,
11481    ) -> bool {
11482        let Self {
11483            rgba_scratch,
11484            last_quality_fingerprint,
11485            ..
11486        } = self;
11487        if rgba_scratch.is_empty() {
11488            return false;
11489        }
11490        let fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
11491        if self.get_last_world_revision() != world.get_world_revision()
11492            || *last_quality_fingerprint != fp
11493        {
11494            return false;
11495        }
11496        if matches!(
11497            quality.get_anti_aliasing(),
11498            AntiAliasingMode::Taa | AntiAliasingMode::Tsr
11499        ) {
11500            self.get_taa_accumulated_frames() >= 8
11501        } else {
11502            true
11503        }
11504    }
11505
11506    /// 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.
11507    ///
11508    /// # Arguments
11509    ///
11510    /// - `&Self` - Mutable 3D renderer.
11511    /// - `&mut World3D` - Open-world 3D scene graph.
11512    /// - `u32` - Target viewport width in logical pixels.
11513    /// - `u32` - Target viewport height in logical pixels.
11514    /// - `&RenderQualityConfig` - Runtime quality settings.
11515    ///
11516    /// # Returns
11517    ///
11518    /// - `(&[u8], bool)` - Borrowed RGBA8 pixel slice and `true` if satisfied from cache without re-rasterization.
11519    #[must_use]
11520    pub fn render_world_or_reuse_cached(
11521        &mut self,
11522        world: &mut World3D,
11523        viewport_w: u32,
11524        viewport_h: u32,
11525        quality: &RenderQualityConfig,
11526    ) -> (&[u8], bool) {
11527        if self.can_reuse_cached_world(world, viewport_w, viewport_h, quality) {
11528            let next_reuses: u64 = self.get_cached_world_reuses().saturating_add(1);
11529            self.set_cached_world_reuses(next_reuses);
11530            let Self { rgba_scratch, .. } = self;
11531            return (rgba_scratch.as_slice(), true);
11532        }
11533        let pixels: &[u8] = self.render_world_rgba(world, viewport_w, viewport_h, quality);
11534        (pixels, false)
11535    }
11536
11537    /// Renders `world` directly into a bounded zero-allocation `RenderBufferPool` slot tagged with `fence_id`.
11538    ///
11539    /// # Arguments
11540    ///
11541    /// - `&Self` - Mutable 3D renderer.
11542    /// - `&mut World3D` - Open-world 3D scene graph.
11543    /// - `u32` - Target viewport width in logical pixels.
11544    /// - `u32` - Target viewport height in logical pixels.
11545    /// - `&RenderQualityConfig` - Runtime quality settings.
11546    /// - `&RenderBufferPool` - Bounded CPU output buffer pool.
11547    /// - `u64` - Submission fence value guarding reclamation.
11548    ///
11549    /// # Returns
11550    ///
11551    /// - `Option<PooledFrameLease>` - Populated pooled RGBA8 lease, or `None` if all bounded pool slots are in flight.
11552    #[must_use]
11553    pub fn render_world_into_pool(
11554        &mut self,
11555        world: &mut World3D,
11556        viewport_w: u32,
11557        viewport_h: u32,
11558        quality: &RenderQualityConfig,
11559        pool: &RenderBufferPool,
11560        fence_id: u64,
11561    ) -> Option<PooledFrameLease> {
11562        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
11563        let min_width: u32 = viewport_w.clamp(1, 240);
11564        let min_height: u32 = viewport_h.clamp(1, 144);
11565        let width_val: u32 = ((viewport_w as f32 * scale).round() as u32).max(min_width);
11566        let height_val: u32 = ((viewport_h as f32 * scale).round() as u32).max(min_height);
11567        let mut lease: PooledFrameLease = pool.acquire(width_val, height_val, fence_id)?;
11568        let (rw, rh): (u32, u32) = self.render_world_into_vec(
11569            world,
11570            viewport_w,
11571            viewport_h,
11572            quality,
11573            lease.get_mut_pixels(),
11574        );
11575        lease.set_dimensions(rw, rh);
11576        Some(lease)
11577    }
11578
11579    /// Renders `world` using a discontinuity-safe interpolated `World3DSnapshot` sampled at `alpha` with object-space inverse-interpolated dynamic RT (zero `dynamic_bvh` rebuilds per VSync).
11580    ///
11581    /// # Arguments
11582    ///
11583    /// - `&Self` - Mutable 3D renderer.
11584    /// - `&mut World3D` - 3D world holding shared mesh library, lighting, and BVH acceleration structures.
11585    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Immutable `(prev_state, curr_state)` snapshot buffer.
11586    /// - `f32` - Normalized interpolation alpha in `[0.0, 1.0]`.
11587    /// - `(u32, u32)` - Target viewport `(width, height)` in logical pixels.
11588    /// - `&RenderQualityConfig` - Runtime quality settings.
11589    /// - `(&RenderBufferPool, u64)` - Bounded CPU output buffer pool and submission fence value.
11590    ///
11591    /// # Returns
11592    ///
11593    /// - `Option<PooledFrameLease>` - Rendered interpolated frame lease, or `None` under pool backpressure.
11594    #[must_use]
11595    pub fn render_world_interpolated_into_pool(
11596        &mut self,
11597        world: &mut World3D,
11598        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
11599        alpha: f32,
11600        viewport: (u32, u32),
11601        quality: &RenderQualityConfig,
11602        target_pool: (&RenderBufferPool, u64),
11603    ) -> Option<PooledFrameLease> {
11604        let (viewport_w, viewport_h): (u32, u32) = viewport;
11605        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11606        if quality.get_ray_tracing() != RayTracingMode::Off
11607            && (world.get_bvh_dirty() || world.get_dynamic_bvh_dirty())
11608        {
11609            world.ensure_bvh();
11610        }
11611        let entry_index: f32 = alpha.clamp(0.0, 1.0);
11612        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
11613        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
11614        let cam_cut: bool = curr_snap.get_camera_cut();
11615        if cam_cut {
11616            self.invalidate_taa_history();
11617        }
11618        let interp_cam: Camera3D = if cam_cut {
11619            curr_snap.get_camera()
11620        } else {
11621            prev_snap
11622                .get_camera()
11623                .lerp(curr_snap.get_camera(), entry_index)
11624        };
11625        let saved_cam: Camera3D = world.get_camera();
11626        let mut saved_objs: Vec<(usize, Transform3D, AxisAlignedBox3D)> = {
11627            let Self {
11628                saved_objs_scratch, ..
11629            } = self;
11630            take(saved_objs_scratch)
11631        };
11632        saved_objs.clear();
11633        world.set_camera(interp_cam);
11634        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
11635        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
11636        if saved_objs.capacity() < next_objs.len() {
11637            saved_objs.reserve(next_objs.len());
11638        }
11639        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
11640            let obj_idx: usize = curr.get_object_index();
11641            let mut blended_tr: Transform3D = curr.get_transform();
11642            if curr.get_visible()
11643                && let Some(prev) = prev_objs.get(slot_idx).copied()
11644            {
11645                let continuous: bool = prev.get_visible()
11646                    && prev.get_object_index() == obj_idx
11647                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
11648                if continuous {
11649                    blended_tr = prev
11650                        .get_transform()
11651                        .lerp_shortest_angle(curr.get_transform(), entry_index);
11652                }
11653            }
11654            let Some((orig_tr, orig_wb, mesh_id, is_dyn)) =
11655                world
11656                    .get_objects()
11657                    .get(obj_idx)
11658                    .map(|output_val: &SceneObject3D| {
11659                        (
11660                            output_val.get_transform(),
11661                            output_val.get_world_bounds(),
11662                            output_val.get_mesh_id(),
11663                            output_val.get_is_dynamic(),
11664                        )
11665                    })
11666            else {
11667                continue;
11668            };
11669            if orig_tr == blended_tr {
11670                continue;
11671            }
11672            saved_objs.push((obj_idx, orig_tr, orig_wb));
11673            let local_bounds: AxisAlignedBox3D = world
11674                .get_mesh_library()
11675                .get(mesh_id)
11676                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
11677                .map(Mesh3D::get_bounds)
11678                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
11679            let world_b: AxisAlignedBox3D = blended_tr.transform_bounds(local_bounds);
11680            if let Some(obj_mut) = world.get_mut_objects().get_mut(obj_idx) {
11681                obj_mut.set_transform(blended_tr);
11682                obj_mut.set_world_bounds(world_b);
11683            }
11684            if is_dyn {
11685                world.override_dynamic_instance_pose(obj_idx, blended_tr, world_b);
11686            }
11687        }
11688        let result: Option<PooledFrameLease> =
11689            self.render_world_into_pool(world, viewport_w, viewport_h, quality, pool, fence_id);
11690        world.set_camera(saved_cam);
11691        for &(idx, transform_val, wb) in saved_objs.iter() {
11692            let is_dyn: bool = world
11693                .get_objects()
11694                .get(idx)
11695                .is_some_and(SceneObject3D::get_is_dynamic);
11696            if let Some(obj_mut) = world.get_mut_objects().get_mut(idx) {
11697                obj_mut.set_transform(transform_val);
11698                obj_mut.set_world_bounds(wb);
11699            }
11700            if is_dyn {
11701                world.override_dynamic_instance_pose(idx, transform_val, wb);
11702            }
11703        }
11704        saved_objs.clear();
11705        let Self {
11706            saved_objs_scratch, ..
11707        } = self;
11708        *saved_objs_scratch = saved_objs;
11709        result
11710    }
11711
11712    /// Renders `world` at runtime-configured `quality` into an `ImageBuffer` without zero-filling output memory.
11713    ///
11714    /// # Arguments
11715    ///
11716    /// - `&Self` - Mutable 3D renderer.
11717    /// - `&mut World3D` - Open-world 3D scene graph.
11718    /// - `u32` - Target viewport width in logical pixels.
11719    /// - `u32` - Target viewport height in logical pixels.
11720    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11721    ///
11722    /// # Returns
11723    ///
11724    /// - `ImageBuffer` - Ready RGBA8 rendered 3D frame for immediate presentation.
11725    pub fn render_world(
11726        &mut self,
11727        world: &mut World3D,
11728        viewport_w: u32,
11729        viewport_h: u32,
11730        quality: &RenderQualityConfig,
11731    ) -> ImageBuffer {
11732        let mut out_pixels: Vec<u8> = Vec::new();
11733        let (width_val, height_val): (u32, u32) =
11734            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11735        ImageBuffer::new(width_val, height_val, out_pixels)
11736    }
11737
11738    /// Renders `world` into the persistent internal `rgba_scratch` buffer, eliminating per-frame output heap allocations.
11739    ///
11740    /// # Arguments
11741    ///
11742    /// - `&Self` - Mutable 3D renderer.
11743    /// - `&mut World3D` - Open-world 3D scene graph.
11744    /// - `u32` - Target viewport width in logical pixels.
11745    /// - `u32` - Target viewport height in logical pixels.
11746    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11747    ///
11748    /// # Returns
11749    ///
11750    /// - `&[u8]` - Borrowed RGBA8 pixel slice of the rendered 3D frame.
11751    #[must_use]
11752    pub fn render_world_rgba(
11753        &mut self,
11754        world: &mut World3D,
11755        viewport_w: u32,
11756        viewport_h: u32,
11757        quality: &RenderQualityConfig,
11758    ) -> &[u8] {
11759        let mut scratch: Vec<u8> = {
11760            let Self { rgba_scratch, .. } = self;
11761            take(rgba_scratch)
11762        };
11763        let _: (u32, u32) =
11764            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut scratch);
11765        let Self { rgba_scratch, .. } = self;
11766        *rgba_scratch = scratch;
11767        rgba_scratch.as_slice()
11768    }
11769
11770    /// Renders `world` at sub-native resolution and reconstructs a sharp native `(viewport_w, viewport_h)` frame via UE5 Temporal Super Resolution (TSR).
11771    ///
11772    /// # Arguments
11773    ///
11774    /// - `&mut World3D` - Open-world 3D scene graph.
11775    /// - `u32` - Target native output width in pixels.
11776    /// - `u32` - Target native output height in pixels.
11777    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal `resolution_scale`.
11778    /// - `&mut Vec<u8>` - Reusable full-resolution destination RGBA8 buffer.
11779    ///
11780    /// # Returns
11781    ///
11782    /// - `(u32, u32)` - Actual reconstructed output dimensions `(dst_w, dst_h)`.
11783    pub fn render_world_tsr_into_vec(
11784        &mut self,
11785        world: &mut World3D,
11786        viewport_w: u32,
11787        viewport_h: u32,
11788        quality: &RenderQualityConfig,
11789        out_pixels: &mut Vec<u8>,
11790    ) -> (u32, u32) {
11791        let dst_w: u32 = viewport_w.max(1);
11792        let dst_h: u32 = viewport_h.max(1);
11793        let mut internal_quality: RenderQualityConfig = *quality;
11794        internal_quality.set_anti_aliasing(AntiAliasingMode::Off);
11795        let mut internal_buf: Vec<u8> = {
11796            let Self {
11797                tsr_internal_scratch,
11798                ..
11799            } = self;
11800            take(tsr_internal_scratch)
11801        };
11802        let (src_w, src_h): (u32, u32) =
11803            self.render_world_into_vec(world, dst_w, dst_h, &internal_quality, &mut internal_buf);
11804        let cam: Camera3D = world.get_camera();
11805        let aspect: f32 = (src_w as f32) / (src_h as f32).max(1.0);
11806        let view_proj: Mat4 = cam.view_projection(aspect);
11807        let cam_fwd: Vec3 = cam.forward();
11808        let cam_right: Vec3 = cam.right();
11809        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
11810        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
11811        let half_h: f32 = (eff_fov_rad * 0.5).tan();
11812        let half_w: f32 = half_h * aspect;
11813        let tsr_params: TsrFrameParams = TsrFrameParams {
11814            src_width: src_w as usize,
11815            src_height: src_h as usize,
11816            dst_width: dst_w as usize,
11817            dst_height: dst_h as usize,
11818            camera_position: cam.get_position(),
11819            camera_forward: cam_fwd,
11820            camera_right_scaled: cam_right.scale(half_w),
11821            camera_up_scaled: cam_up.scale(half_h),
11822            view_projection: view_proj,
11823            jitter_offset: (0.0, 0.0),
11824            sharpness: TSR_DEFAULT_SHARPNESS,
11825        };
11826        {
11827            let Self {
11828                depth_buffer,
11829                tsr_upscaler,
11830                ..
11831            } = self;
11832            tsr_upscaler.upscale_rgba(
11833                internal_buf.as_slice(),
11834                depth_buffer.as_slice(),
11835                &tsr_params,
11836                out_pixels,
11837            );
11838        }
11839        let Self {
11840            tsr_internal_scratch,
11841            ..
11842        } = self;
11843        *tsr_internal_scratch = internal_buf;
11844        (dst_w, dst_h)
11845    }
11846
11847    /// Renders `world` using UE5 Temporal Super Resolution (TSR) upscaling and returns a full-resolution `ImageBuffer`.
11848    ///
11849    /// # Arguments
11850    ///
11851    /// - `&mut World3D` - Open-world 3D scene graph.
11852    /// - `u32` - Target native output width in pixels.
11853    /// - `u32` - Target native output height in pixels.
11854    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal scale and RT/Lumen toggles.
11855    ///
11856    /// # Returns
11857    ///
11858    /// - `ImageBuffer` - Reconstructed native-resolution RGBA8 frame.
11859    pub fn render_world_tsr(
11860        &mut self,
11861        world: &mut World3D,
11862        viewport_w: u32,
11863        viewport_h: u32,
11864        quality: &RenderQualityConfig,
11865    ) -> ImageBuffer {
11866        let mut out_pixels: Vec<u8> = Vec::new();
11867        let (dst_w, dst_h): (u32, u32) =
11868            self.render_world_tsr_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11869        ImageBuffer::new(dst_w, dst_h, out_pixels)
11870    }
11871
11872    /// Renders `world` at sub-native resolution and writes the TSR-reconstructed native frame directly into a bounded zero-allocation `RenderBufferPool` slot.
11873    ///
11874    /// # Arguments
11875    ///
11876    /// - `&mut World3D` - Open-world 3D scene graph.
11877    /// - `(u32, u32)` - Target native output `(viewport_w, viewport_h)` in pixels.
11878    /// - `&RenderQualityConfig` - Runtime quality configuration controlling internal TSR scale.
11879    /// - `(&RenderBufferPool, u64)` - Bounded output frame pool and fence value.
11880    ///
11881    /// # Returns
11882    ///
11883    /// - `Option<PooledFrameLease>` - Populated native-resolution TSR frame lease, or `None` under pool backpressure.
11884    #[must_use]
11885    pub fn render_world_tsr_into_pool(
11886        &mut self,
11887        world: &mut World3D,
11888        viewport: (u32, u32),
11889        quality: &RenderQualityConfig,
11890        target_pool: (&RenderBufferPool, u64),
11891    ) -> Option<PooledFrameLease> {
11892        let (viewport_w, viewport_h): (u32, u32) = viewport;
11893        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11894        let dst_w: u32 = viewport_w.max(1);
11895        let dst_h: u32 = viewport_h.max(1);
11896        let mut lease: PooledFrameLease = pool.acquire(dst_w, dst_h, fence_id)?;
11897        let (rw, rh): (u32, u32) =
11898            self.render_world_tsr_into_vec(world, dst_w, dst_h, quality, lease.get_mut_pixels());
11899        lease.set_dimensions(rw, rh);
11900        Some(lease)
11901    }
11902
11903    /// 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.
11904    ///
11905    /// # Arguments
11906    ///
11907    /// - `f32` - Measured render duration of the most recent frame in milliseconds.
11908    /// - `&mut RenderQualityConfig` - Mutable runtime quality settings updated when `dynamic_resolution` is enabled.
11909    ///
11910    /// # Returns
11911    ///
11912    /// - `FramePacingTelemetry3D` - Updated smoothed frame-time and stability telemetry.
11913    pub fn apply_frame_pacing_feedback(
11914        &mut self,
11915        frame_ms: f32,
11916        quality: &mut RenderQualityConfig,
11917    ) -> FramePacingTelemetry3D {
11918        let target_hz: f32 = quality.get_target_fps().max(30.0);
11919        let governor: &mut AdaptiveFrameGovernor = self.get_mut_frame_governor();
11920        if (governor.get_target_hz() - target_hz).abs() > 0.5 {
11921            governor.set_target_hz(target_hz);
11922        }
11923        let telemetry: FramePacingTelemetry3D = governor.record_frame(frame_ms, quality);
11924        if quality.get_dynamic_resolution() {
11925            self.set_rt_stride_bias(telemetry.get_effective_rt_stride_bias());
11926        } else {
11927            self.set_rt_stride_bias(0);
11928        }
11929        telemetry
11930    }
11931
11932    /// 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.
11933    ///
11934    /// # Arguments
11935    ///
11936    /// - `u32` - Target viewport width in pixels.
11937    /// - `u32` - Target viewport height in pixels.
11938    /// - `&RenderQualityConfig` - Active quality configuration controlling RT, Lumen, VSM, and TSR passes.
11939    ///
11940    /// # Returns
11941    ///
11942    /// - `RenderGraphSchedule3D` - Compiled pass schedule with transient memory aliasing telemetry.
11943    #[must_use]
11944    pub fn compile_frame_graph(
11945        &mut self,
11946        viewport_w: u32,
11947        viewport_h: u32,
11948        quality: &RenderQualityConfig,
11949    ) -> RenderGraphSchedule3D {
11950        let built: RenderGraph3D =
11951            RenderGraph3D::build_ue5_frame_graph(viewport_w, viewport_h, quality);
11952        let schedule: RenderGraphSchedule3D = built.compile();
11953        self.set_render_graph(built);
11954        schedule
11955    }
11956
11957    /// Clips a triangle against the camera near plane `w >= near_w` (Sutherland-Hodgman) while tracking original barycentric weights for exact attribute interpolation.
11958    ///
11959    /// # Arguments
11960    ///
11961    /// - `([f32; 4], Vec3)` - First clip-space and world-space vertex.
11962    /// - `([f32; 4], Vec3)` - Second clip-space and world-space vertex.
11963    /// - `([f32; 4], Vec3)` - Third clip-space and world-space vertex.
11964    /// - `f32` - Positive near-plane clip `w` threshold.
11965    ///
11966    /// # Returns
11967    ///
11968    /// - `([ClippedBaryVert; 6], usize)` - Packed output triangles with barycentric weights and valid triangle count (`0..=2`).
11969    #[must_use]
11970    fn clip_triangle_near_bary(
11971        vert0: ([f32; 4], Vec3),
11972        vert1: ([f32; 4], Vec3),
11973        vert2: ([f32; 4], Vec3),
11974        near_w: f32,
11975    ) -> ([ClippedBaryVert; 6], usize) {
11976        let zero_vert: ClippedBaryVert = ClippedBaryVert {
11977            clip_pos: [0.0; 4],
11978            world_pos: Vec3::zero(),
11979            bary: [0.0; 3],
11980        };
11981        let mut out_tris: [ClippedBaryVert; 6] = [zero_vert; 6];
11982        let input: [ClippedBaryVert; 3] = [
11983            ClippedBaryVert {
11984                clip_pos: vert0.0,
11985                world_pos: vert0.1,
11986                bary: [1.0, 0.0, 0.0],
11987            },
11988            ClippedBaryVert {
11989                clip_pos: vert1.0,
11990                world_pos: vert1.1,
11991                bary: [0.0, 1.0, 0.0],
11992            },
11993            ClippedBaryVert {
11994                clip_pos: vert2.0,
11995                world_pos: vert2.1,
11996                bary: [0.0, 0.0, 1.0],
11997            },
11998        ];
11999        let mut poly: [ClippedBaryVert; 4] = [zero_vert; 4];
12000        let mut count: usize = 0;
12001        for edge_idx in 0..3usize {
12002            let cur: ClippedBaryVert = input[edge_idx];
12003            let nxt: ClippedBaryVert = input[(edge_idx + 1) % 3];
12004            let cur_in: bool = cur.clip_pos[3] >= near_w;
12005            let nxt_in: bool = nxt.clip_pos[3] >= near_w;
12006            if cur_in && count < 4 {
12007                poly[count] = cur;
12008                count += 1;
12009            }
12010            if cur_in != nxt_in && count < 4 {
12011                let denom: f32 = nxt.clip_pos[3] - cur.clip_pos[3];
12012                let blend_factor: f32 = if denom.abs() > 1.0e-6 {
12013                    ((near_w - cur.clip_pos[3]) / denom).clamp(0.0, 1.0)
12014                } else {
12015                    0.5
12016                };
12017                let interp_clip: [f32; 4] = [
12018                    cur.clip_pos[0] + (nxt.clip_pos[0] - cur.clip_pos[0]) * blend_factor,
12019                    cur.clip_pos[1] + (nxt.clip_pos[1] - cur.clip_pos[1]) * blend_factor,
12020                    cur.clip_pos[2] + (nxt.clip_pos[2] - cur.clip_pos[2]) * blend_factor,
12021                    near_w,
12022                ];
12023                let interp_world: Vec3 = cur.world_pos.lerp(nxt.world_pos, blend_factor);
12024                let interp_bary: [f32; 3] = [
12025                    cur.bary[0] + (nxt.bary[0] - cur.bary[0]) * blend_factor,
12026                    cur.bary[1] + (nxt.bary[1] - cur.bary[1]) * blend_factor,
12027                    cur.bary[2] + (nxt.bary[2] - cur.bary[2]) * blend_factor,
12028                ];
12029                poly[count] = ClippedBaryVert {
12030                    clip_pos: interp_clip,
12031                    world_pos: interp_world,
12032                    bary: interp_bary,
12033                };
12034                count += 1;
12035            }
12036        }
12037        if count < 3 {
12038            return (out_tris, 0);
12039        }
12040        out_tris[0] = poly[0];
12041        out_tris[1] = poly[1];
12042        out_tris[2] = poly[2];
12043        if count == 4 {
12044            out_tris[3] = poly[0];
12045            out_tris[4] = poly[2];
12046            out_tris[5] = poly[3];
12047            (out_tris, 2)
12048        } else {
12049            (out_tris, 1)
12050        }
12051    }
12052
12053    /// Samples an optional `TextureSlot3D` with `KHR_texture_transform` and isotropic trilinear mip selection.
12054    ///
12055    /// # Arguments
12056    ///
12057    /// - `Option<TextureSlot3D>` - Optional texture binding slot.
12058    /// - `([f32; 2], [f32; 2])` - Interpolated `(uv0, uv1)` coordinates.
12059    /// - `(f32, f32, f32)` - `(uv0_area, uv1_area, screen_area_px)` for mip LOD estimation.
12060    /// - `&[Texture2D3D]` - Scene texture pool.
12061    ///
12062    /// # Returns
12063    ///
12064    /// - `Option<[f32; 4]>` - Linear RGBA sample when the slot references a valid texture.
12065    #[must_use]
12066    fn sample_principled_slot(
12067        slot_opt: Option<TextureSlot3D>,
12068        uv_pair: ([f32; 2], [f32; 2]),
12069        area_terms: (f32, f32, f32),
12070        textures: &[Texture2D3D],
12071    ) -> Option<[f32; 4]> {
12072        let slot: TextureSlot3D = slot_opt?;
12073        let texture: &Texture2D3D = textures.get(slot.get_texture_index() as usize)?;
12074        let (uv0_coord, uv1_coord): ([f32; 2], [f32; 2]) = uv_pair;
12075        let (uv0_area, uv1_area, screen_area): (f32, f32, f32) = area_terms;
12076        let (raw_uv, uv_area): ([f32; 2], f32) = if slot.get_tex_coord() == 1 {
12077            (uv1_coord, uv1_area)
12078        } else {
12079            (uv0_coord, uv0_area)
12080        };
12081        let transformed_uv: Vec2 = slot
12082            .get_transform()
12083            .apply_uv(Vec2::new(raw_uv[0], raw_uv[1]));
12084        let tex_scale: Vec2 = slot.get_transform().get_scale();
12085        let scale_area: f32 = (tex_scale.get_x() * tex_scale.get_y()).abs().max(1.0e-4);
12086        let tex_pixels: f32 =
12087            (texture.get_width().max(1) as f32) * (texture.get_height().max(1) as f32);
12088        let texels_per_px: f32 = (uv_area * scale_area * tex_pixels) / screen_area.max(1.0);
12089        let mip_lod: f32 = if texels_per_px > 1.0 {
12090            0.5 * texels_per_px.log2()
12091        } else {
12092            0.0
12093        };
12094        Some(texture.sample_trilinear(transformed_uv.get_x(), transformed_uv.get_y(), mip_lod))
12095    }
12096
12097    /// Evaluates the Estevez-Kulla Charlie sheen microfacet NDF and Ashikhmin visibility term.
12098    ///
12099    /// # Arguments
12100    ///
12101    /// - `f32` - Perceptual sheen roughness in `[0.07, 1.0]`.
12102    /// - `f32` - Clamped `N·H` cosine.
12103    /// - `f32` - Clamped `N·V` cosine.
12104    /// - `f32` - Clamped `N·L` cosine.
12105    ///
12106    /// # Returns
12107    ///
12108    /// - `f32` - Scalar Charlie sheen BRDF factor.
12109    #[cfg_attr(not(target_arch = "wasm32"), inline)]
12110    #[must_use]
12111    fn eval_charlie_sheen(sheen_rough: f32, n_dot_h: f32, n_dot_v: f32, n_dot_l: f32) -> f32 {
12112        let clamped_r: f32 = sheen_rough.clamp(0.07, 1.0);
12113        let alpha_g: f32 = clamped_r * clamped_r;
12114        let inv_r: f32 = 1.0 / alpha_g.max(1.0e-4);
12115        let sin2_h: f32 = (1.0 - n_dot_h * n_dot_h).max(1.0e-4);
12116        let ndf_charlie: f32 = (2.0 + inv_r) * sin2_h.powf(inv_r * 0.5) / (2.0 * PI);
12117        let vis_ashikhmin: f32 = 1.0 / (4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v)).max(1.0e-3);
12118        (ndf_charlie * vis_ashikhmin).min(8.0)
12119    }
12120
12121    /// Computes Snell refraction direction for unit incident vector `incident` and outward unit `normal` at IOR ratio `eta`.
12122    ///
12123    /// # Arguments
12124    ///
12125    /// - `Vec3` - Unit incident vector pointing toward surface (`-view_dir`).
12126    /// - `Vec3` - Unit outward surface normal.
12127    /// - `f32` - Refractive index ratio `eta_i / eta_t`.
12128    ///
12129    /// # Returns
12130    ///
12131    /// - `Vec3` - Unit refracted direction (falls back to reflection on total internal reflection).
12132    #[cfg_attr(not(target_arch = "wasm32"), inline)]
12133    #[must_use]
12134    fn refract_unit_ray(incident: Vec3, normal: Vec3, eta: f32) -> Vec3 {
12135        let cos_i: f32 = (-incident.dot(normal)).clamp(-1.0, 1.0);
12136        let sin2_t: f32 = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
12137        if sin2_t >= 1.0 {
12138            return incident.reflect(normal).normalize();
12139        }
12140        let cos_t: f32 = (1.0 - sin2_t).sqrt();
12141        incident
12142            .scale(eta)
12143            .add(normal.scale(eta * cos_i - cos_t))
12144            .normalize()
12145    }
12146
12147    /// Encodes a display-referred linear RGB `[0..1]` color into exact sRGB `[u8; 4]` RGBA bytes.
12148    ///
12149    /// # Arguments
12150    ///
12151    /// - `Vec3` - Linear RGB color in `[0.0, 1.0]`.
12152    ///
12153    /// # Returns
12154    ///
12155    /// - `[u8; 4]` - Opaque sRGB RGBA8 pixel.
12156    #[cfg_attr(not(target_arch = "wasm32"), inline)]
12157    #[must_use]
12158    fn encode_srgb_rgba8(linear_rgb: Vec3) -> [u8; 4] {
12159        let to_srgb: fn(f32) -> u8 = |chan: f32| -> u8 {
12160            let clamped: f32 = chan.clamp(0.0, 1.0);
12161            let encoded: f32 = if clamped <= 0.003_130_8 {
12162                clamped * 12.92
12163            } else {
12164                1.055 * clamped.powf(1.0 / 2.4) - 0.055
12165            };
12166            (encoded * 255.0 + 0.5).clamp(0.0, 255.0) as u8
12167        };
12168        [
12169            to_srgb(linear_rgb.get_x()),
12170            to_srgb(linear_rgb.get_y()),
12171            to_srgb(linear_rgb.get_z()),
12172            255,
12173        ]
12174    }
12175
12176    /// 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).
12177    ///
12178    /// # Arguments
12179    ///
12180    /// - `&DeferredFrameContext` - Per-frame camera, sun, exposure, and ray-tracing settings.
12181    /// - `&ShadeBandInputs<'_>` - Read-only scene textures, Principled materials, lights, CSM, IBL, and BVH references.
12182    /// - `&GShadeTri` - Precomputed legacy fallback material record.
12183    /// - `&GSmoothTri` - Perspective-correct per-vertex normal, tangent, UV, and color record.
12184    /// - `(usize, usize)` - Pixel coordinates `(pixel_x, pixel_y)`.
12185    /// - `(Vec3, Vec3, f32)` - `(world_pos, raw_ray, linear_depth)` pixel geometry sample.
12186    ///
12187    /// # Returns
12188    ///
12189    /// - `[u8; 4]` - Tone-mapped sRGB RGBA8 output pixel.
12190    #[must_use]
12191    fn shade_pixel_principled_smooth(
12192        frame_context: &DeferredFrameContext,
12193        inputs: &ShadeBandInputs<'_>,
12194        tri: &GShadeTri,
12195        smooth_tri: &GSmoothTri,
12196        pixel_coords: (usize, usize),
12197        geom_sample: (Vec3, Vec3, f32),
12198    ) -> [u8; 4] {
12199        let (pixel_x, pixel_y): (usize, usize) = pixel_coords;
12200        let (world_pos, raw_ray, linear_depth): (Vec3, Vec3, f32) = geom_sample;
12201        let sample_x: f32 = (pixel_x as f32) + 0.5;
12202        let sample_y: f32 = (pixel_y as f32) + 0.5;
12203        let sx: [f32; 3] = smooth_tri.screen_x;
12204        let sy: [f32; 3] = smooth_tri.screen_y;
12205        let inv_area: f32 = smooth_tri.inv_area;
12206        let screen_w0: f32 = ((sx[1] - sample_x) * (sy[2] - sample_y)
12207            - (sy[1] - sample_y) * (sx[2] - sample_x))
12208            * inv_area;
12209        let screen_w1: f32 = ((sx[2] - sample_x) * (sy[0] - sample_y)
12210            - (sy[2] - sample_y) * (sx[0] - sample_x))
12211            * inv_area;
12212        let screen_w2: f32 = 1.0 - screen_w0 - screen_w1;
12213        let persp_0: f32 = screen_w0.max(0.0) * smooth_tri.inv_w[0];
12214        let persp_1: f32 = screen_w1.max(0.0) * smooth_tri.inv_w[1];
12215        let persp_2: f32 = screen_w2.max(0.0) * smooth_tri.inv_w[2];
12216        let inv_persp_sum: f32 = 1.0 / (persp_0 + persp_1 + persp_2).max(1.0e-9);
12217        let bary_0: f32 = persp_0 * inv_persp_sum;
12218        let bary_1: f32 = persp_1 * inv_persp_sum;
12219        let bary_2: f32 = persp_2 * inv_persp_sum;
12220        let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
12221        let raw_normal: Vec3 = smooth_tri.normals[0]
12222            .scale(bary_0)
12223            .add(smooth_tri.normals[1].scale(bary_1))
12224            .add(smooth_tri.normals[2].scale(bary_2));
12225        let mut geom_normal: Vec3 = if raw_normal.length_sq() > 1.0e-8 {
12226            raw_normal.normalize()
12227        } else {
12228            tri.shade_n
12229        };
12230        if smooth_tri.double_sided && geom_normal.dot(view_dir) < 0.0 {
12231            geom_normal = geom_normal.scale(-1.0);
12232        }
12233        let raw_tangent: Vec3 = Vec3::new(
12234            smooth_tri.tangents[0][0] * bary_0
12235                + smooth_tri.tangents[1][0] * bary_1
12236                + smooth_tri.tangents[2][0] * bary_2,
12237            smooth_tri.tangents[0][1] * bary_0
12238                + smooth_tri.tangents[1][1] * bary_1
12239                + smooth_tri.tangents[2][1] * bary_2,
12240            smooth_tri.tangents[0][2] * bary_0
12241                + smooth_tri.tangents[1][2] * bary_1
12242                + smooth_tri.tangents[2][2] * bary_2,
12243        );
12244        let ortho_tangent: Vec3 = raw_tangent.sub(geom_normal.scale(raw_tangent.dot(geom_normal)));
12245        let tangent_dir: Vec3 = if ortho_tangent.length_sq() > 1.0e-6 {
12246            ortho_tangent.normalize()
12247        } else {
12248            let helper_axis: Vec3 = if geom_normal.get_y().abs() < 0.9 {
12249                Vec3::new(0.0, 1.0, 0.0)
12250            } else {
12251                Vec3::new(1.0, 0.0, 0.0)
12252            };
12253            helper_axis.cross(geom_normal).normalize()
12254        };
12255        let tan_sign: f32 = if smooth_tri.tangents[0][3] < 0.0 {
12256            -1.0
12257        } else {
12258            1.0
12259        };
12260        let bitangent_dir: Vec3 = geom_normal.cross(tangent_dir).scale(tan_sign);
12261        let uv0_interp: [f32; 2] = [
12262            smooth_tri.uv0[0][0] * bary_0
12263                + smooth_tri.uv0[1][0] * bary_1
12264                + smooth_tri.uv0[2][0] * bary_2,
12265            smooth_tri.uv0[0][1] * bary_0
12266                + smooth_tri.uv0[1][1] * bary_1
12267                + smooth_tri.uv0[2][1] * bary_2,
12268        ];
12269        let uv1_interp: [f32; 2] = [
12270            smooth_tri.uv1[0][0] * bary_0
12271                + smooth_tri.uv1[1][0] * bary_1
12272                + smooth_tri.uv1[2][0] * bary_2,
12273            smooth_tri.uv1[0][1] * bary_0
12274                + smooth_tri.uv1[1][1] * bary_1
12275                + smooth_tri.uv1[2][1] * bary_2,
12276        ];
12277        let vcol_r: f32 = smooth_tri.color0[0][0] * bary_0
12278            + smooth_tri.color0[1][0] * bary_1
12279            + smooth_tri.color0[2][0] * bary_2;
12280        let vcol_g: f32 = smooth_tri.color0[0][1] * bary_0
12281            + smooth_tri.color0[1][1] * bary_1
12282            + smooth_tri.color0[2][1] * bary_2;
12283        let vcol_b: f32 = smooth_tri.color0[0][2] * bary_0
12284            + smooth_tri.color0[1][2] * bary_1
12285            + smooth_tri.color0[2][2] * bary_2;
12286        let vcol_a: f32 = smooth_tri.color0[0][3] * bary_0
12287            + smooth_tri.color0[1][3] * bary_1
12288            + smooth_tri.color0[2][3] * bary_2;
12289        let screen_area_px: f32 = 0.5 / inv_area.abs().max(1.0e-8);
12290        let uv0_area: f32 = ((smooth_tri.uv0[1][0] - smooth_tri.uv0[0][0])
12291            * (smooth_tri.uv0[2][1] - smooth_tri.uv0[0][1])
12292            - (smooth_tri.uv0[1][1] - smooth_tri.uv0[0][1])
12293                * (smooth_tri.uv0[2][0] - smooth_tri.uv0[0][0]))
12294            .abs()
12295            * 0.5;
12296        let uv1_area: f32 = ((smooth_tri.uv1[1][0] - smooth_tri.uv1[0][0])
12297            * (smooth_tri.uv1[2][1] - smooth_tri.uv1[0][1])
12298            - (smooth_tri.uv1[1][1] - smooth_tri.uv1[0][1])
12299                * (smooth_tri.uv1[2][0] - smooth_tri.uv1[0][0]))
12300            .abs()
12301            * 0.5;
12302        let area_terms: (f32, f32, f32) = (uv0_area, uv1_area, screen_area_px);
12303        let uv_pair: ([f32; 2], [f32; 2]) = (uv0_interp, uv1_interp);
12304        let mat_opt: Option<&PrincipledMaterial3D> =
12305            if smooth_tri.principled_material_id != u32::MAX {
12306                inputs
12307                    .principled_materials
12308                    .get(smooth_tri.principled_material_id as usize)
12309            } else {
12310                None
12311            };
12312        let mut albedo: Vec3 = Vec3::new(
12313            tri.mat_base.get_x() * vcol_r,
12314            tri.mat_base.get_y() * vcol_g,
12315            tri.mat_base.get_z() * vcol_b,
12316        );
12317        let mut alpha_val: f32 = vcol_a;
12318        let mut metallic: f32 = tri.metallic.clamp(0.0, 1.0);
12319        let mut roughness: f32 = tri.alpha2.sqrt().sqrt().clamp(0.04, 1.0);
12320        let mut shade_normal: Vec3 = geom_normal;
12321        let mut coat_normal: Vec3 = geom_normal;
12322        let mut ao_factor: f32 = 1.0;
12323        let mut emissive_rgb: Vec3 = tri.mat_emissive;
12324        let mut ior_val: f32 = 1.5;
12325        let mut spec_factor: f32 = 1.0;
12326        let mut spec_color: Vec3 = Vec3::splat(1.0);
12327        let mut coat_weight: f32 = 0.0;
12328        let mut coat_rough: f32 = 0.04;
12329        let mut sheen_color: Vec3 = Vec3::zero();
12330        let mut sheen_rough: f32 = 0.5;
12331        let mut transmission: f32 = 0.0;
12332        let mut thickness: f32 = 0.0;
12333        let mut atten_dist: f32 = f32::INFINITY;
12334        let mut atten_color: Vec3 = Vec3::splat(1.0);
12335        let mut is_unlit: bool = false;
12336        let mut alpha_masked: bool = false;
12337        if let Some(pmat) = mat_opt {
12338            let base_fac: [f32; 4] = pmat.get_base_color_factor();
12339            let base_tex: [f32; 4] = Self::sample_principled_slot(
12340                pmat.try_get_base_color_texture(),
12341                uv_pair,
12342                area_terms,
12343                inputs.textures,
12344            )
12345            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12346            albedo = Vec3::new(
12347                base_fac[0] * base_tex[0] * vcol_r,
12348                base_fac[1] * base_tex[1] * vcol_g,
12349                base_fac[2] * base_tex[2] * vcol_b,
12350            );
12351            alpha_val = base_fac[3] * base_tex[3] * vcol_a;
12352            if pmat.get_alpha_mode() == AlphaMode3D::Mask && alpha_val < pmat.get_alpha_cutoff() {
12353                alpha_masked = true;
12354            }
12355            is_unlit = pmat.get_unlit();
12356            let mr_tex: [f32; 4] = Self::sample_principled_slot(
12357                pmat.try_get_metallic_roughness_texture(),
12358                uv_pair,
12359                area_terms,
12360                inputs.textures,
12361            )
12362            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12363            metallic = (pmat.get_metallic_factor() * mr_tex[2]).clamp(0.0, 1.0);
12364            roughness = (pmat.get_roughness_factor() * mr_tex[1]).clamp(0.04, 1.0);
12365            if let Some(norm_tex) = Self::sample_principled_slot(
12366                pmat.try_get_normal_texture(),
12367                uv_pair,
12368                area_terms,
12369                inputs.textures,
12370            ) {
12371                let nscale: f32 = pmat.get_normal_scale();
12372                let ts_x: f32 = (norm_tex[0] * 2.0 - 1.0) * nscale;
12373                let ts_y: f32 = (norm_tex[1] * 2.0 - 1.0) * nscale;
12374                let ts_z: f32 = (norm_tex[2] * 2.0 - 1.0).max(0.05);
12375                let perturbed: Vec3 = tangent_dir
12376                    .scale(ts_x)
12377                    .add(bitangent_dir.scale(ts_y))
12378                    .add(geom_normal.scale(ts_z));
12379                if perturbed.length_sq() > 1.0e-8 {
12380                    shade_normal = perturbed.normalize();
12381                }
12382            }
12383            if let Some(occ_tex) = Self::sample_principled_slot(
12384                pmat.try_get_occlusion_texture(),
12385                uv_pair,
12386                area_terms,
12387                inputs.textures,
12388            ) {
12389                ao_factor =
12390                    (1.0 + pmat.get_occlusion_strength() * (occ_tex[0] - 1.0)).clamp(0.0, 1.0);
12391            }
12392            let em_fac: [f32; 3] = pmat.get_emissive_factor();
12393            let em_tex: [f32; 4] = Self::sample_principled_slot(
12394                pmat.try_get_emissive_texture(),
12395                uv_pair,
12396                area_terms,
12397                inputs.textures,
12398            )
12399            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12400            let em_str: f32 = pmat.get_emissive_strength().max(0.0);
12401            emissive_rgb = Vec3::new(
12402                em_fac[0] * em_tex[0] * em_str,
12403                em_fac[1] * em_tex[1] * em_str,
12404                em_fac[2] * em_tex[2] * em_str,
12405            );
12406            ior_val = pmat.get_ior().max(1.0);
12407            let sp_tex: [f32; 4] = Self::sample_principled_slot(
12408                pmat.try_get_specular_texture(),
12409                uv_pair,
12410                area_terms,
12411                inputs.textures,
12412            )
12413            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12414            spec_factor = (pmat.get_specular_factor() * sp_tex[3]).clamp(0.0, 1.0);
12415            let sp_col_fac: [f32; 3] = pmat.get_specular_color_factor();
12416            let sp_col_tex: [f32; 4] = Self::sample_principled_slot(
12417                pmat.try_get_specular_color_texture(),
12418                uv_pair,
12419                area_terms,
12420                inputs.textures,
12421            )
12422            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12423            spec_color = Vec3::new(
12424                sp_col_fac[0] * sp_col_tex[0],
12425                sp_col_fac[1] * sp_col_tex[1],
12426                sp_col_fac[2] * sp_col_tex[2],
12427            );
12428            let cc_tex: [f32; 4] = Self::sample_principled_slot(
12429                pmat.try_get_clearcoat_texture(),
12430                uv_pair,
12431                area_terms,
12432                inputs.textures,
12433            )
12434            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12435            coat_weight = (pmat.get_clearcoat_factor() * cc_tex[0]).clamp(0.0, 1.0);
12436            let cc_r_tex: [f32; 4] = Self::sample_principled_slot(
12437                pmat.try_get_clearcoat_roughness_texture(),
12438                uv_pair,
12439                area_terms,
12440                inputs.textures,
12441            )
12442            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12443            coat_rough = (pmat.get_clearcoat_roughness_factor() * cc_r_tex[1]).clamp(0.04, 1.0);
12444            if let Some(cc_norm_tex) = Self::sample_principled_slot(
12445                pmat.try_get_clearcoat_normal_texture(),
12446                uv_pair,
12447                area_terms,
12448                inputs.textures,
12449            ) {
12450                let cc_x: f32 = cc_norm_tex[0] * 2.0 - 1.0;
12451                let cc_y: f32 = cc_norm_tex[1] * 2.0 - 1.0;
12452                let cc_z: f32 = (cc_norm_tex[2] * 2.0 - 1.0).max(0.05);
12453                let cc_pert: Vec3 = tangent_dir
12454                    .scale(cc_x)
12455                    .add(bitangent_dir.scale(cc_y))
12456                    .add(geom_normal.scale(cc_z));
12457                if cc_pert.length_sq() > 1.0e-8 {
12458                    coat_normal = cc_pert.normalize();
12459                }
12460            }
12461            let sh_col_fac: [f32; 3] = pmat.get_sheen_color_factor();
12462            let sh_col_tex: [f32; 4] = Self::sample_principled_slot(
12463                pmat.try_get_sheen_color_texture(),
12464                uv_pair,
12465                area_terms,
12466                inputs.textures,
12467            )
12468            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12469            sheen_color = Vec3::new(
12470                sh_col_fac[0] * sh_col_tex[0],
12471                sh_col_fac[1] * sh_col_tex[1],
12472                sh_col_fac[2] * sh_col_tex[2],
12473            );
12474            let sh_r_tex: [f32; 4] = Self::sample_principled_slot(
12475                pmat.try_get_sheen_roughness_texture(),
12476                uv_pair,
12477                area_terms,
12478                inputs.textures,
12479            )
12480            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12481            sheen_rough = (pmat.get_sheen_roughness_factor() * sh_r_tex[3]).clamp(0.07, 1.0);
12482            let tr_tex: [f32; 4] = Self::sample_principled_slot(
12483                pmat.try_get_transmission_texture(),
12484                uv_pair,
12485                area_terms,
12486                inputs.textures,
12487            )
12488            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
12489            transmission =
12490                (pmat.get_transmission_factor() * tr_tex[0]).clamp(0.0, 1.0) * (1.0 - metallic);
12491            thickness = pmat.get_thickness_factor().max(0.0);
12492            atten_dist = pmat.get_attenuation_distance();
12493            atten_color = Vec3::from_array(pmat.get_attenuation_color());
12494        }
12495        if alpha_masked {
12496            let sky_hdr: Vec3 =
12497                Self::sample_sky_lut(inputs.sky_lut, raw_ray.normalize(), &frame_context.sun)
12498                    .scale(frame_context.exposure_scale);
12499            let sky_ldr: Vec3 = if inputs.use_agx_tonemap {
12500                agx_tonemap(sky_hdr)
12501            } else {
12502                aces_filmic_tonemap(sky_hdr)
12503            };
12504            return Self::encode_srgb_rgba8(sky_ldr);
12505        }
12506        if is_unlit {
12507            let unlit_hdr: Vec3 = albedo.scale(frame_context.exposure_scale);
12508            let unlit_ldr: Vec3 = if inputs.use_agx_tonemap {
12509                agx_tonemap(unlit_hdr)
12510            } else {
12511                aces_filmic_tonemap(unlit_hdr)
12512            };
12513            return Self::encode_srgb_rgba8(unlit_ldr);
12514        }
12515        let dielectric_f0_s: f32 = dielectric_f0_from_ior(ior_val);
12516        let dielectric_f0: Vec3 = Vec3::new(
12517            (dielectric_f0_s * spec_color.get_x()).min(1.0) * spec_factor,
12518            (dielectric_f0_s * spec_color.get_y()).min(1.0) * spec_factor,
12519            (dielectric_f0_s * spec_color.get_z()).min(1.0) * spec_factor,
12520        );
12521        let f0: Vec3 = dielectric_f0.lerp(albedo, metallic);
12522        let diffuse_albedo: Vec3 = albedo.scale((1.0 - metallic) * (1.0 - transmission));
12523        let alpha_rough: f32 = roughness * roughness;
12524        let alpha2: f32 = (alpha_rough * alpha_rough).max(1.0e-4);
12525        let n_dot_v: f32 = shade_normal.dot(view_dir).max(0.001);
12526        let sun_dir: Vec3 = frame_context.sun.get_direction();
12527        let sun_color: Vec3 = frame_context.sun.get_color();
12528        let sun_vis: f32 = if let Some(vsm) = inputs.vsm {
12529            vsm.sample_visibility(world_pos, shade_normal, sun_dir)
12530        } else if frame_context.raytrace_mode != RayTracingMode::Off {
12531            let shadow_origin: Vec3 = world_pos.add(shade_normal.scale(0.05));
12532            let mut static_hint: u32 = u32::MAX;
12533            let mut dyn_hint: u32 = u32::MAX;
12534            if World3D::trace_any_shadow_with_instances(
12535                inputs.static_bvh,
12536                inputs.dyn_instances,
12537                inputs.local_bvhs,
12538                (shadow_origin, sun_dir, frame_context.inv_sun_dir),
12539                (0.04, 140.0),
12540                (&mut static_hint, &mut dyn_hint),
12541            ) {
12542                0.15
12543            } else {
12544                1.0
12545            }
12546        } else {
12547            1.0
12548        };
12549        let brdf_lut_sample: [f32; 2] = inputs
12550            .environment_ibl
12551            .map_or([0.82, 0.08], |ibl: &EnvironmentIbl3D| {
12552                ibl.sample_brdf_lut(n_dot_v, roughness)
12553            });
12554        let multi_scatter: Vec3 =
12555            kulla_conty_multiscatter_factor(f0, brdf_lut_sample[0] + brdf_lut_sample[1]);
12556        let n_dot_l: f32 = shade_normal.dot(sun_dir).max(0.0);
12557        let mut direct_rgb: Vec3 = Vec3::zero();
12558        if n_dot_l > 0.0 && sun_vis > 0.0 {
12559            let half_vec: Vec3 = sun_dir.add(view_dir).normalize();
12560            let n_dot_h: f32 = shade_normal.dot(half_vec).max(0.0);
12561            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
12562            let ggx_den: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
12563            let ggx_d: f32 = alpha2 / (PI * ggx_den * ggx_den).max(1.0e-5);
12564            let vis_v: f32 = n_dot_l * (n_dot_v * (n_dot_v - n_dot_v * alpha2) + alpha2).sqrt();
12565            let vis_l: f32 = n_dot_v * (n_dot_l * (n_dot_l - n_dot_l * alpha2) + alpha2).sqrt();
12566            let smith_vis: f32 = 0.5 / (vis_v + vis_l).max(1.0e-4);
12567            let om_vh: f32 = 1.0 - v_dot_h;
12568            let pow5_vh: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
12569            let fresnel_base: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5_vh));
12570            let base_spec: Vec3 = fresnel_base.mul(multi_scatter).scale(ggx_d * smith_vis);
12571            let base_diff: Vec3 = diffuse_albedo
12572                .mul(Vec3::splat(1.0).sub(fresnel_base))
12573                .scale(1.0 / PI);
12574            let mut layer_brdf: Vec3 = base_diff.add(base_spec);
12575            let max_sheen: f32 = sheen_color
12576                .get_x()
12577                .max(sheen_color.get_y())
12578                .max(sheen_color.get_z());
12579            if max_sheen > 1.0e-4 {
12580                let sheen_brdf: f32 =
12581                    Self::eval_charlie_sheen(sheen_rough, n_dot_h, n_dot_v, n_dot_l);
12582                let sheen_atten: f32 = (1.0 - max_sheen * 0.25).clamp(0.25, 1.0);
12583                layer_brdf = layer_brdf
12584                    .scale(sheen_atten)
12585                    .add(sheen_color.scale(sheen_brdf));
12586            }
12587            if coat_weight > 1.0e-4 {
12588                let cc_nl: f32 = coat_normal.dot(sun_dir).max(0.0);
12589                let cc_nh: f32 = coat_normal.dot(half_vec).max(0.0);
12590                let cc_a: f32 = coat_rough * coat_rough;
12591                let cc_a2: f32 = (cc_a * cc_a).max(1.0e-4);
12592                let cc_den: f32 = cc_nh * cc_nh * (cc_a2 - 1.0) + 1.0;
12593                let cc_d: f32 = cc_a2 / (PI * cc_den * cc_den).max(1.0e-5);
12594                let cc_vis: f32 = 0.25 / (v_dot_h * v_dot_h).max(0.04);
12595                let f_coat: f32 = 0.04 + 0.96 * pow5_vh;
12596                let coat_spec: f32 = (cc_d * cc_vis * f_coat * coat_weight).min(12.0);
12597                let coat_atten: f32 = (1.0 - coat_weight * f_coat).clamp(0.0, 1.0);
12598                layer_brdf = layer_brdf.scale(coat_atten).add(Vec3::splat(
12599                    coat_spec * (cc_nl / n_dot_l.max(1.0e-4)).min(1.5),
12600                ));
12601            }
12602            direct_rgb = layer_brdf.mul(sun_color).scale(n_dot_l * sun_vis);
12603        }
12604        let mut local_rgb: Vec3 = Vec3::zero();
12605        if let Some(clusters) = inputs.light_clusters {
12606            let screen_u: f32 = sample_x * frame_context.inv_width;
12607            let screen_v: f32 = sample_y * frame_context.inv_height;
12608            local_rgb = clusters.evaluate_pixel(
12609                world_pos,
12610                shade_normal,
12611                view_dir,
12612                (albedo, f0, alpha2, (1.0 - metallic) * (1.0 - transmission)),
12613                (screen_u, screen_v, linear_depth),
12614            );
12615        }
12616        for area_light in inputs.area_lights.iter() {
12617            local_rgb = local_rgb.add(area_light.evaluate_pbr(
12618                world_pos,
12619                shade_normal,
12620                view_dir,
12621                (
12622                    albedo,
12623                    f0,
12624                    roughness,
12625                    (1.0 - metallic) * (1.0 - transmission),
12626                ),
12627            ));
12628        }
12629        let refl_dir: Vec3 = view_dir.scale(-1.0).reflect(shade_normal).normalize();
12630        let om_nv: f32 = (1.0 - n_dot_v).clamp(0.0, 1.0);
12631        let pow5_nv: f32 = om_nv * om_nv * om_nv * om_nv * om_nv;
12632        let max_smooth_f0: Vec3 = Vec3::new(
12633            (1.0 - roughness).max(f0.get_x()),
12634            (1.0 - roughness).max(f0.get_y()),
12635            (1.0 - roughness).max(f0.get_z()),
12636        );
12637        let fresnel_ibl: Vec3 = f0.add(max_smooth_f0.sub(f0).scale(pow5_nv));
12638        let mut ibl_rgb: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12639            let irradiance: Vec3 = ibl.evaluate_sh_diffuse(shade_normal);
12640            let prefiltered: Vec3 = ibl.sample_specular_octahedral(refl_dir, roughness);
12641            let ibl_diff: Vec3 = irradiance
12642                .mul(diffuse_albedo)
12643                .mul(Vec3::splat(1.0).sub(fresnel_ibl));
12644            let ibl_spec: Vec3 = prefiltered
12645                .mul(
12646                    f0.scale(brdf_lut_sample[0])
12647                        .add(Vec3::splat(brdf_lut_sample[1])),
12648                )
12649                .mul(multi_scatter);
12650            let mut combined_ibl: Vec3 = ibl_diff.add(ibl_spec);
12651            if coat_weight > 1.0e-4 {
12652                let cc_nv: f32 = coat_normal.dot(view_dir).max(0.001);
12653                let cc_om: f32 = (1.0 - cc_nv).clamp(0.0, 1.0);
12654                let f_coat_v: f32 = 0.04 + 0.96 * cc_om * cc_om * cc_om * cc_om * cc_om;
12655                let cc_refl: Vec3 = view_dir.scale(-1.0).reflect(coat_normal).normalize();
12656                let cc_pref: Vec3 = ibl.sample_specular_octahedral(cc_refl, coat_rough);
12657                combined_ibl = combined_ibl
12658                    .scale(1.0 - coat_weight * f_coat_v)
12659                    .add(cc_pref.scale(coat_weight * f_coat_v));
12660            }
12661            combined_ibl.scale(ao_factor)
12662        } else {
12663            let sky_hemi: Vec3 = frame_context.sun.get_sky_horizon().lerp(
12664                frame_context.sun.get_sky_zenith(),
12665                (shade_normal.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
12666            );
12667            let sky_spec: Vec3 = Self::sample_sky_lut(inputs.sky_lut, refl_dir, &frame_context.sun);
12668            let hemi_diff: Vec3 = sky_hemi
12669                .mul(diffuse_albedo)
12670                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12671                .scale(0.45);
12672            let hemi_spec: Vec3 = sky_spec
12673                .mul(fresnel_ibl)
12674                .mul(multi_scatter)
12675                .scale((1.0 - roughness * 0.65).clamp(0.15, 1.0));
12676            hemi_diff.add(hemi_spec).scale(ao_factor)
12677        };
12678        if sheen_color.length_sq() > 1.0e-6 {
12679            let sheen_grazing: f32 = pow5_nv * (0.35 + 0.65 * sheen_rough);
12680            ibl_rgb = ibl_rgb.add(sheen_color.scale(sheen_grazing * 0.45 * ao_factor));
12681        }
12682        let transmitted_rgb: Vec3 = if transmission > 1.0e-4 {
12683            let refr_dir: Vec3 =
12684                Self::refract_unit_ray(view_dir.scale(-1.0), shade_normal, 1.0 / ior_val);
12685            let bg_radiance: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12686                ibl.sample_specular_octahedral(refr_dir, roughness)
12687            } else {
12688                Self::sample_sky_lut(inputs.sky_lut, refr_dir, &frame_context.sun)
12689            };
12690            let beer_atten: Vec3 =
12691                if thickness > 1.0e-4 && atten_dist.is_finite() && atten_dist > 1.0e-4 {
12692                    let sigma_r: f32 = -(atten_color.get_x().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12693                    let sigma_g: f32 = -(atten_color.get_y().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12694                    let sigma_b: f32 = -(atten_color.get_z().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12695                    Vec3::new(
12696                        (-sigma_r * thickness).exp(),
12697                        (-sigma_g * thickness).exp(),
12698                        (-sigma_b * thickness).exp(),
12699                    )
12700                } else {
12701                    Vec3::splat(1.0)
12702                };
12703            bg_radiance
12704                .mul(albedo)
12705                .mul(beer_atten)
12706                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12707                .scale(transmission)
12708        } else {
12709            Vec3::zero()
12710        };
12711        let _alpha_blend_guard: f32 = alpha_val;
12712        let hdr_rgb: Vec3 = direct_rgb
12713            .add(local_rgb)
12714            .add(ibl_rgb)
12715            .add(transmitted_rgb)
12716            .add(emissive_rgb)
12717            .scale(frame_context.exposure_scale);
12718        let ldr_linear: Vec3 = if inputs.use_agx_tonemap {
12719            agx_tonemap(hdr_rgb)
12720        } else {
12721            aces_filmic_tonemap(hdr_rgb)
12722        };
12723        Self::encode_srgb_rgba8(ldr_linear)
12724    }
12725}