euv-core 0.55.0

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

/// Encodes a 32-bit IEEE-754 floating-point scalar into a 16-bit IEEE-754 binary16 bit pattern.
///
/// # Arguments
///
/// - `f32` - Input finite or non-finite 32-bit float value.
///
/// # Returns
///
/// - `u16` - Packed IEEE-754 half-precision bit pattern.
#[must_use]
pub fn encode_f32_to_f16(val: f32) -> u16 {
    let bits: u32 = val.to_bits();
    let sign: u16 = ((bits >> 16) & 0x8000) as u16;
    let exp: i32 = ((bits >> 23) & 0xFF) as i32;
    let mant: u32 = bits & 0x007F_FFFF;
    if exp == 255 {
        let nan_mant: u16 = if mant != 0 { 0x0200 } else { 0 };
        let inf_bits: u16 = sign | 0x7C00;
        return inf_bits | nan_mant;
    }
    let unbiased: i32 = exp - 127;
    if unbiased > 15 {
        return sign | 0x7C00;
    }
    if unbiased < -24 {
        return sign;
    }
    if unbiased < -14 {
        let shift: u32 = (-14 - unbiased) as u32;
        let full_mant: u32 = mant | 0x0080_0000;
        let rounded: u32 = (full_mant >> (shift + 13)) + ((full_mant >> (shift + 12)) & 1);
        return sign | (rounded as u16);
    }
    let h_exp: u16 = ((unbiased + 15) as u16) << 10;
    let round_bit: u32 = (mant >> 12) & 1;
    let h_mant: u16 = ((mant >> 13) + round_bit) as u16;
    sign | (h_exp.wrapping_add(h_mant))
}

/// Decodes a 16-bit IEEE-754 binary16 bit pattern back into a 32-bit floating-point scalar.
///
/// # Arguments
///
/// - `u16` - Packed IEEE-754 half-precision bit pattern.
///
/// # Returns
///
/// - `f32` - Decoded 32-bit float value.
#[must_use]
pub fn decode_f16_to_f32(bits: u16) -> f32 {
    let sign: u32 = ((bits & 0x8000) as u32) << 16;
    let exp: u32 = ((bits >> 10) & 0x1F) as u32;
    let mant: u32 = (bits & 0x03FF) as u32;
    if exp == 0 {
        if mant == 0 {
            return f32::from_bits(sign);
        }
        let mut m: u32 = mant;
        let mut e: i32 = -14;
        while (m & 0x0400) == 0 {
            m <<= 1;
            e -= 1;
        }
        m &= 0x03FF;
        let f_exp: u32 = ((e + 127) as u32) << 23;
        let sub_head: u32 = sign | f_exp;
        return f32::from_bits(sub_head | (m << 13));
    }
    if exp == 31 {
        let f_mant: u32 = if mant != 0 { mant << 13 } else { 0 };
        let inf_head: u32 = sign | 0x7F80_0000;
        return f32::from_bits(inf_head | f_mant);
    }
    let f_exp: u32 = (exp + 112) << 23;
    let norm_head: u32 = sign | f_exp;
    f32::from_bits(norm_head | (mant << 13))
}

/// Encodes a unit 3D direction vector using octahedral hemisphere folding into signed 16-bit normalized coordinates (`< 0.01°` angular error).
///
/// # Arguments
///
/// - `Vec3` - Input 3D normal or tangent vector.
///
/// # Returns
///
/// - `[i16; 2]` - Octahedral-encoded `SNORM16` pair in `[-32767, 32767]`.
#[must_use]
pub fn encode_oct_normal_i16(vec: Vec3) -> [i16; 2] {
    let n: Vec3 = vec.normalize();
    let nx: f32 = n.get_x();
    let ny: f32 = n.get_y();
    let nz: f32 = n.get_z();
    let l1: f32 = (nx.abs() + ny.abs() + nz.abs()).max(1e-6);
    let mut ox: f32 = nx / l1;
    let mut oy: f32 = ny / l1;
    if nz < 0.0 {
        let sx: f32 = if ox >= 0.0 { 1.0 } else { -1.0 };
        let sy: f32 = if oy >= 0.0 { 1.0 } else { -1.0 };
        let folded_x: f32 = (1.0 - oy.abs()) * sx;
        let folded_y: f32 = (1.0 - ox.abs()) * sy;
        ox = folded_x;
        oy = folded_y;
    }
    let qx: i16 = (ox.clamp(-1.0, 1.0) * 32_767.0).round() as i16;
    let qy: i16 = (oy.clamp(-1.0, 1.0) * 32_767.0).round() as i16;
    [qx, qy]
}

/// Decodes a signed 16-bit octahedral normal pair back into a unit 3D vector.
///
/// # Arguments
///
/// - `[i16; 2]` - Octahedral-encoded `SNORM16` coordinates.
///
/// # Returns
///
/// - `Vec3` - Decoded unit 3D vector.
#[must_use]
pub fn decode_oct_normal_i16(oct: [i16; 2]) -> Vec3 {
    let ox: f32 = (f32::from(oct[0]) / 32_767.0).clamp(-1.0, 1.0);
    let oy: f32 = (f32::from(oct[1]) / 32_767.0).clamp(-1.0, 1.0);
    let nz: f32 = 1.0 - ox.abs() - oy.abs();
    let (nx, ny): (f32, f32) = if nz < 0.0 {
        let sx: f32 = if ox >= 0.0 { 1.0 } else { -1.0 };
        let sy: f32 = if oy >= 0.0 { 1.0 } else { -1.0 };
        ((1.0 - oy.abs()) * sx, (1.0 - ox.abs()) * sy)
    } else {
        (ox, oy)
    };
    Vec3::new(nx, ny, nz).normalize()
}

/// Quantizes a 64-byte `Vertex3D` into an exact 24-byte `QuantizedVertex3D` normalized against `(bounds_min, bounds_extent)`.
///
/// # Arguments
///
/// - `&Vertex3D` - Source uncompressed 64-byte vertex.
/// - `Vec3` - Local mesh bounding-box minimum corner.
/// - `Vec3` - Local mesh bounding-box extent (`max - min`).
/// - `u8` - Meshlet cluster color tag embedded in upper `pad_flags` bits for debug visualization.
///
/// # Returns
///
/// - `QuantizedVertex3D` - Compact 24-byte quantized GPU vertex.
#[must_use]
pub fn quantize_vertex_3d(
    vertex: &Vertex3D,
    bounds_min: Vec3,
    bounds_extent: Vec3,
    meshlet_tag: u8,
) -> QuantizedVertex3D {
    let pos: Vec3 = vertex.get_position();
    let ex: f32 = bounds_extent.get_x().max(1e-6);
    let ey: f32 = bounds_extent.get_y().max(1e-6);
    let ez: f32 = bounds_extent.get_z().max(1e-6);
    let px: u16 =
        (((pos.get_x() - bounds_min.get_x()) / ex).clamp(0.0, 1.0) * 65_535.0).round() as u16;
    let py: u16 =
        (((pos.get_y() - bounds_min.get_y()) / ey).clamp(0.0, 1.0) * 65_535.0).round() as u16;
    let pz: u16 =
        (((pos.get_z() - bounds_min.get_z()) / ez).clamp(0.0, 1.0) * 65_535.0).round() as u16;
    let tan: [f32; 4] = vertex.get_tangent();
    let tan_sign_bit: u16 = if tan[3] < 0.0 { 16 } else { 0 };
    let attr_bits: u16 = (vertex.get_flags() & 0x0F) as u16;
    let low_flags: u16 = attr_bits | tan_sign_bit;
    let pad_flags: u16 = low_flags | ((meshlet_tag as u16) << 8);
    let normal_oct: [i16; 2] = encode_oct_normal_i16(vertex.get_normal());
    let tangent_vec: Vec3 = Vec3::new(tan[0], tan[1], tan[2]);
    let tangent_oct_sign: [i16; 2] = if tangent_vec.length_sq() > 1e-8 {
        encode_oct_normal_i16(tangent_vec)
    } else {
        encode_oct_normal_i16(Vec3::new(1.0, 0.0, 0.0))
    };
    let uv0: [f32; 2] = vertex.get_uv0();
    let uv0_f16: [u16; 2] = [encode_f32_to_f16(uv0[0]), encode_f32_to_f16(uv0[1])];
    QuantizedVertex3D::new(
        [px, py, pz],
        pad_flags,
        normal_oct,
        tangent_oct_sign,
        uv0_f16,
        vertex.get_color0(),
    )
}

/// Dequantizes a 24-byte `QuantizedVertex3D` back into a 64-byte `Vertex3D` using `(bounds_min, bounds_extent)`.
///
/// # Arguments
///
/// - `&QuantizedVertex3D` - Source 24-byte quantized GPU vertex.
/// - `Vec3` - Local mesh bounding-box minimum corner.
/// - `Vec3` - Local mesh bounding-box extent (`max - min`).
///
/// # Returns
///
/// - `Vertex3D` - Reconstructed vertex with position, normal, tangent, primary UV, and color.
#[must_use]
pub fn dequantize_vertex_3d(
    quantized: &QuantizedVertex3D,
    bounds_min: Vec3,
    bounds_extent: Vec3,
) -> Vertex3D {
    let pq: [u16; 3] = quantized.get_pos_q16();
    let pos: Vec3 = Vec3::new(
        bounds_min.get_x() + (f32::from(pq[0]) / 65_535.0) * bounds_extent.get_x(),
        bounds_min.get_y() + (f32::from(pq[1]) / 65_535.0) * bounds_extent.get_y(),
        bounds_min.get_z() + (f32::from(pq[2]) / 65_535.0) * bounds_extent.get_z(),
    );
    let normal: Vec3 = decode_oct_normal_i16(quantized.get_normal_oct());
    let tan_dir: Vec3 = decode_oct_normal_i16(quantized.get_tangent_oct_sign());
    let flags_raw: u16 = quantized.get_pad_flags();
    let handedness: f32 = if (flags_raw & 16) != 0 { -1.0 } else { 1.0 };
    let uv_raw: [u16; 2] = quantized.get_uv0_f16();
    let uv0: [f32; 2] = [decode_f16_to_f32(uv_raw[0]), decode_f16_to_f32(uv_raw[1])];
    Vertex3D {
        position: pos,
        normal,
        tangent: [
            tan_dir.get_x(),
            tan_dir.get_y(),
            tan_dir.get_z(),
            handedness,
        ],
        uv0,
        uv1: [0.0, 0.0],
        color0: quantized.get_color0_rgba8(),
        flags: u32::from(flags_raw & 0x0F),
    }
}

/// Quantizes a 48-byte `MeshSkinInfluence3D` into a normalized 16-byte `QuantizedSkinVertex3D` whose `UNORM8` weights sum to `255`.
///
/// # Arguments
///
/// - `&MeshSkinInfluence3D` - Source skeletal joint and weight influence record.
///
/// # Returns
///
/// - `QuantizedSkinVertex3D` - Compact 16-byte GPU skinning sidecar.
#[must_use]
pub fn quantize_skin_vertex_3d(influence: &MeshSkinInfluence3D) -> QuantizedSkinVertex3D {
    let raw_w: [f32; 4] = influence.get_weights_0();
    let mut clamped: [f32; 4] = [
        raw_w[0].max(0.0),
        raw_w[1].max(0.0),
        raw_w[2].max(0.0),
        raw_w[3].max(0.0),
    ];
    let sum: f32 = clamped[0] + clamped[1] + clamped[2] + clamped[3];
    if sum > 1e-6 {
        let inv: f32 = 1.0 / sum;
        for weight in clamped.iter_mut() {
            *weight *= inv;
        }
    } else {
        clamped = [1.0, 0.0, 0.0, 0.0];
    }
    let mut q: [u8; 4] = [0; 4];
    let mut max_idx: usize = 0;
    let mut total: u16 = 0;
    for idx in 0..4 {
        let val: u8 = (clamped[idx] * 255.0).round().clamp(0.0, 255.0) as u8;
        q[idx] = val;
        total += u16::from(val);
        if clamped[idx] > clamped[max_idx] {
            max_idx = idx;
        }
    }
    if total != 255 {
        let adjusted: i32 = i32::from(q[max_idx]) + (255 - i32::from(total));
        q[max_idx] = adjusted.clamp(0, 255) as u8;
    }
    QuantizedSkinVertex3D::new(influence.get_joints_0(), q, 0)
}

/// Tests four axis-aligned bounding boxes simultaneously against six frustum planes using NEON (`aarch64`), SSE2 (`x86_64`), WASM `simd128`, or scalar fallback.
///
/// # Arguments
///
/// - `&[[f32; 4]; 6]` - Six frustum plane equations `(a, b, c, d)` where `ax + by + cz + d >= 0` is inside.
/// - `&SimdAabbBatch4` - Four-lane Structure-of-Arrays bounding box coordinates.
///
/// # Returns
///
/// - `u8` - 4-bit visibility bitmask (`bit i == 1` when AABB `i` intersects or lies inside the frustum).
#[must_use]
pub fn cull_aabb_batch4_simd(planes: &[[f32; 4]; 6], batch: &SimdAabbBatch4) -> u8 {
    let min_x: [f32; 4] = batch.get_min_x();
    let min_y: [f32; 4] = batch.get_min_y();
    let min_z: [f32; 4] = batch.get_min_z();
    let max_x: [f32; 4] = batch.get_max_x();
    let max_y: [f32; 4] = batch.get_max_y();
    let max_z: [f32; 4] = batch.get_max_z();
    #[cfg(target_arch = "aarch64")]
    {
        // SAFETY: NEON is baseline on all `aarch64` targets and all arrays are 4-element `[f32; 4]`.
        unsafe {
            let zero: float32x4_t = vdupq_n_f32(0.0);
            let mut inside: uint32x4_t = vcgeq_f32(zero, zero);
            for plane in planes.iter() {
                let px_arr: &[f32; 4] = if plane[0] >= 0.0 { &max_x } else { &min_x };
                let py_arr: &[f32; 4] = if plane[1] >= 0.0 { &max_y } else { &min_y };
                let pz_arr: &[f32; 4] = if plane[2] >= 0.0 { &max_z } else { &min_z };
                let mut acc: float32x4_t = vdupq_n_f32(plane[3]);
                acc = vmlaq_f32(acc, vdupq_n_f32(plane[0]), vld1q_f32(px_arr.as_ptr()));
                acc = vmlaq_f32(acc, vdupq_n_f32(plane[1]), vld1q_f32(py_arr.as_ptr()));
                acc = vmlaq_f32(acc, vdupq_n_f32(plane[2]), vld1q_f32(pz_arr.as_ptr()));
                inside = vandq_u32(inside, vcgeq_f32(acc, zero));
            }
            let weights: [u32; 4] = [1, 2, 4, 8];
            let masked: uint32x4_t = vandq_u32(inside, vld1q_u32(weights.as_ptr()));
            vaddvq_u32(masked) as u8
        }
    }
    #[cfg(target_arch = "x86_64")]
    {
        // SAFETY: SSE2 is baseline on all `x86_64` targets and `_mm_loadu_ps` handles arbitrary alignment.
        unsafe {
            let zero: __m128 = _mm_set1_ps(0.0);
            let mut mask: u8 = 0x0F;
            for plane in planes.iter() {
                let px_arr: &[f32; 4] = if plane[0] >= 0.0 { &max_x } else { &min_x };
                let py_arr: &[f32; 4] = if plane[1] >= 0.0 { &max_y } else { &min_y };
                let pz_arr: &[f32; 4] = if plane[2] >= 0.0 { &max_z } else { &min_z };
                let ax: __m128 = _mm_mul_ps(_mm_set1_ps(plane[0]), _mm_loadu_ps(px_arr.as_ptr()));
                let ay: __m128 = _mm_mul_ps(_mm_set1_ps(plane[1]), _mm_loadu_ps(py_arr.as_ptr()));
                let az: __m128 = _mm_mul_ps(_mm_set1_ps(plane[2]), _mm_loadu_ps(pz_arr.as_ptr()));
                let sum: __m128 =
                    _mm_add_ps(_mm_add_ps(ax, ay), _mm_add_ps(az, _mm_set1_ps(plane[3])));
                let cmp: __m128 = _mm_cmpge_ps(sum, zero);
                mask &= _mm_movemask_ps(cmp) as u8;
                if mask == 0 {
                    return 0;
                }
            }
            mask
        }
    }
    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
    {
        // SAFETY: `simd128` target feature is enabled by cfg gate and arrays are valid 16-byte spans.
        unsafe {
            let zero: v128 = f32x4_splat(0.0);
            let mut mask: u8 = 0x0F;
            for plane in planes.iter() {
                let px_arr: &[f32; 4] = if plane[0] >= 0.0 { &max_x } else { &min_x };
                let py_arr: &[f32; 4] = if plane[1] >= 0.0 { &max_y } else { &min_y };
                let pz_arr: &[f32; 4] = if plane[2] >= 0.0 { &max_z } else { &min_z };
                let ax: v128 = f32x4_mul(
                    f32x4_splat(plane[0]),
                    v128_load(px_arr.as_ptr().cast::<v128>()),
                );
                let ay: v128 = f32x4_mul(
                    f32x4_splat(plane[1]),
                    v128_load(py_arr.as_ptr().cast::<v128>()),
                );
                let az: v128 = f32x4_mul(
                    f32x4_splat(plane[2]),
                    v128_load(pz_arr.as_ptr().cast::<v128>()),
                );
                let sum: v128 = f32x4_add(f32x4_add(ax, ay), f32x4_add(az, f32x4_splat(plane[3])));
                let cmp: v128 = f32x4_ge(sum, zero);
                mask &= i32x4_bitmask(cmp) as u8;
                if mask == 0 {
                    return 0;
                }
            }
            mask
        }
    }
    #[cfg(not(target_arch = "aarch64"))]
    #[cfg(not(target_arch = "x86_64"))]
    #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
    {
        let mut mask: u8 = 0x0F;
        for plane in planes.iter() {
            let px_arr: &[f32; 4] = if plane[0] >= 0.0 { &max_x } else { &min_x };
            let py_arr: &[f32; 4] = if plane[1] >= 0.0 { &max_y } else { &min_y };
            let pz_arr: &[f32; 4] = if plane[2] >= 0.0 { &max_z } else { &min_z };
            for lane in 0..4 {
                let d: f32 = plane[0] * px_arr[lane]
                    + plane[1] * py_arr[lane]
                    + plane[2] * pz_arr[lane]
                    + plane[3];
                if d < 0.0 {
                    mask &= !(1u8 << lane);
                }
            }
        }
        mask
    }
}

/// Tests four closed-mesh meshlet normal cones simultaneously against `camera_local` using NEON, SSE2, WASM `simd128`, or scalar fallback.
///
/// # Arguments
///
/// - `[f32; 3]` - Camera eye position transformed into mesh local space.
/// - `&SimdMeshletConeBatch4` - Four-lane Structure-of-Arrays meshlet centers, cone axes, squared half-angle sines, and extent margins.
///
/// # Returns
///
/// - `u8` - 4-bit visibility bitmask (`bit i == 1` when meshlet `i` is potentially front-facing and must be kept; `0` when strictly backfacing).
#[must_use]
pub fn cull_meshlet_cones_batch4_simd(camera_local: [f32; 3], cones: &SimdMeshletConeBatch4) -> u8 {
    let cx: [f32; 4] = cones.get_center_x();
    let cy: [f32; 4] = cones.get_center_y();
    let cz: [f32; 4] = cones.get_center_z();
    let ax: [f32; 4] = cones.get_axis_x();
    let ay: [f32; 4] = cones.get_axis_y();
    let az: [f32; 4] = cones.get_axis_z();
    let sin_sq: [f32; 4] = cones.get_sin_alpha_sq();
    let margin: [f32; 4] = cones.get_extent_margin();
    #[cfg(target_arch = "aarch64")]
    {
        // SAFETY: NEON is baseline on all `aarch64` targets and all lane buffers have 4 `f32` elements.
        unsafe {
            let zero: float32x4_t = vdupq_n_f32(0.0);
            let neg_one: float32x4_t = vdupq_n_f32(-1.0);
            let eps: float32x4_t = vdupq_n_f32(1e-5);
            let vx: float32x4_t = vaddq_f32(vld1q_f32(cx.as_ptr()), vdupq_n_f32(-camera_local[0]));
            let vy: float32x4_t = vaddq_f32(vld1q_f32(cy.as_ptr()), vdupq_n_f32(-camera_local[1]));
            let vz: float32x4_t = vaddq_f32(vld1q_f32(cz.as_ptr()), vdupq_n_f32(-camera_local[2]));
            let mut dot_val: float32x4_t = vmlaq_f32(zero, vx, vld1q_f32(ax.as_ptr()));
            dot_val = vmlaq_f32(dot_val, vy, vld1q_f32(ay.as_ptr()));
            dot_val = vmlaq_f32(dot_val, vz, vld1q_f32(az.as_ptr()));
            let mut dist_sq: float32x4_t = vmlaq_f32(zero, vx, vx);
            dist_sq = vmlaq_f32(dist_sq, vy, vy);
            dist_sq = vmlaq_f32(dist_sq, vz, vz);
            let excess: float32x4_t = vmlaq_f32(dot_val, neg_one, vld1q_f32(margin.as_ptr()));
            let excess_sq: float32x4_t = vmlaq_f32(zero, excess, excess);
            let rhs: float32x4_t = vmlaq_f32(zero, dist_sq, vld1q_f32(sin_sq.as_ptr()));
            let pos_mask: uint32x4_t = vcgeq_f32(excess, eps);
            let cone_mask: uint32x4_t = vcgeq_f32(excess_sq, rhs);
            let culled: uint32x4_t = vandq_u32(pos_mask, cone_mask);
            let weights: [u32; 4] = [1, 2, 4, 8];
            let culled_bits: u8 = vaddvq_u32(vandq_u32(culled, vld1q_u32(weights.as_ptr()))) as u8;
            (!culled_bits) & 0x0F
        }
    }
    #[cfg(target_arch = "x86_64")]
    {
        // SAFETY: SSE2 is baseline on all `x86_64` targets and `_mm_loadu_ps` accepts arbitrary alignment.
        unsafe {
            let eps: __m128 = _mm_set1_ps(1e-5);
            let neg_one: __m128 = _mm_set1_ps(-1.0);
            let vx: __m128 = _mm_add_ps(_mm_loadu_ps(cx.as_ptr()), _mm_set1_ps(-camera_local[0]));
            let vy: __m128 = _mm_add_ps(_mm_loadu_ps(cy.as_ptr()), _mm_set1_ps(-camera_local[1]));
            let vz: __m128 = _mm_add_ps(_mm_loadu_ps(cz.as_ptr()), _mm_set1_ps(-camera_local[2]));
            let dot_val: __m128 = _mm_add_ps(
                _mm_add_ps(
                    _mm_mul_ps(vx, _mm_loadu_ps(ax.as_ptr())),
                    _mm_mul_ps(vy, _mm_loadu_ps(ay.as_ptr())),
                ),
                _mm_mul_ps(vz, _mm_loadu_ps(az.as_ptr())),
            );
            let dist_sq: __m128 = _mm_add_ps(
                _mm_add_ps(_mm_mul_ps(vx, vx), _mm_mul_ps(vy, vy)),
                _mm_mul_ps(vz, vz),
            );
            let excess: __m128 =
                _mm_add_ps(dot_val, _mm_mul_ps(neg_one, _mm_loadu_ps(margin.as_ptr())));
            let excess_sq: __m128 = _mm_mul_ps(excess, excess);
            let rhs: __m128 = _mm_mul_ps(dist_sq, _mm_loadu_ps(sin_sq.as_ptr()));
            let m_pos: u8 = _mm_movemask_ps(_mm_cmpge_ps(excess, eps)) as u8;
            let m_cone: u8 = _mm_movemask_ps(_mm_cmpge_ps(excess_sq, rhs)) as u8;
            let culled_bits: u8 = m_pos & m_cone;
            (!culled_bits) & 0x0F
        }
    }
    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
    {
        // SAFETY: `simd128` target feature is verified by cfg gate and arrays are valid 16-byte spans.
        unsafe {
            let eps: v128 = f32x4_splat(1e-5);
            let neg_one: v128 = f32x4_splat(-1.0);
            let vx: v128 = f32x4_add(
                v128_load(cx.as_ptr().cast::<v128>()),
                f32x4_splat(-camera_local[0]),
            );
            let vy: v128 = f32x4_add(
                v128_load(cy.as_ptr().cast::<v128>()),
                f32x4_splat(-camera_local[1]),
            );
            let vz: v128 = f32x4_add(
                v128_load(cz.as_ptr().cast::<v128>()),
                f32x4_splat(-camera_local[2]),
            );
            let dot_val: v128 = f32x4_add(
                f32x4_add(
                    f32x4_mul(vx, v128_load(ax.as_ptr().cast::<v128>())),
                    f32x4_mul(vy, v128_load(ay.as_ptr().cast::<v128>())),
                ),
                f32x4_mul(vz, v128_load(az.as_ptr().cast::<v128>())),
            );
            let dist_sq: v128 = f32x4_add(
                f32x4_add(f32x4_mul(vx, vx), f32x4_mul(vy, vy)),
                f32x4_mul(vz, vz),
            );
            let excess: v128 = f32x4_add(
                dot_val,
                f32x4_mul(neg_one, v128_load(margin.as_ptr().cast::<v128>())),
            );
            let excess_sq: v128 = f32x4_mul(excess, excess);
            let rhs: v128 = f32x4_mul(dist_sq, v128_load(sin_sq.as_ptr().cast::<v128>()));
            let m_pos: u8 = i32x4_bitmask(f32x4_ge(excess, eps)) as u8;
            let m_cone: u8 = i32x4_bitmask(f32x4_ge(excess_sq, rhs)) as u8;
            let culled_bits: u8 = m_pos & m_cone;
            (!culled_bits) & 0x0F
        }
    }
    #[cfg(not(target_arch = "aarch64"))]
    #[cfg(not(target_arch = "x86_64"))]
    #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
    {
        let mut visible: u8 = 0;
        for lane in 0..4 {
            let vx: f32 = cx[lane] - camera_local[0];
            let vy: f32 = cy[lane] - camera_local[1];
            let vz: f32 = cz[lane] - camera_local[2];
            let dot_val: f32 = vx * ax[lane] + vy * ay[lane] + vz * az[lane];
            let dist_sq: f32 = vx * vx + vy * vy + vz * vz;
            let excess: f32 = dot_val - margin[lane];
            let culled: bool = excess >= 1e-5 && (excess * excess) >= (dist_sq * sin_sq[lane]);
            if !culled {
                visible |= 1u8 << lane;
            }
        }
        visible
    }
}

/// Runs 4-wide SIMD frustum and normal-cone backface culling over a slice of local-space `Meshlet3D` clusters transformed into world space.
///
/// # Arguments
///
/// - `&[Meshlet3D]` - Meshlet clusters belonging to one mesh LOD level.
/// - `&Mat4` - Object-to-world model matrix.
/// - `&Frustum3D` - Active six-plane world-space view frustum.
/// - `Vec3` - Camera world-space eye position.
/// - `bool` - Whether the owning mesh is closed and eligible for normal-cone backface rejection.
///
/// # Returns
///
/// - `(u32, u32)` - Pair `(meshlets_tested, meshlets_culled)`.
#[must_use]
pub fn cull_meshlets_simd(
    meshlets: &[Meshlet3D],
    model: &Mat4,
    frustum: &Frustum3D,
    camera_world: Vec3,
    is_closed: bool,
) -> (u32, u32) {
    let total: usize = meshlets.len();
    if total == 0 {
        return (0, 0);
    }
    let planes: [[f32; 4]; 6] = frustum.get_planes();
    let elems: [f32; 16] = model.get_elements();
    let cam_arr: [f32; 3] = [
        camera_world.get_x(),
        camera_world.get_y(),
        camera_world.get_z(),
    ];
    let mut culled: u32 = 0;
    let mut idx: usize = 0;
    while idx < total {
        let count: usize = (total - idx).min(4);
        let mut min_x: [f32; 4] = [0.0; 4];
        let mut min_y: [f32; 4] = [0.0; 4];
        let mut min_z: [f32; 4] = [0.0; 4];
        let mut max_x: [f32; 4] = [0.0; 4];
        let mut max_y: [f32; 4] = [0.0; 4];
        let mut max_z: [f32; 4] = [0.0; 4];
        let mut cx: [f32; 4] = [0.0; 4];
        let mut cy: [f32; 4] = [0.0; 4];
        let mut cz: [f32; 4] = [0.0; 4];
        let mut ax: [f32; 4] = [0.0; 4];
        let mut ay: [f32; 4] = [0.0; 4];
        let mut az: [f32; 4] = [0.0; 4];
        let mut sin_sq: [f32; 4] = [4.0; 4];
        let mut margin: [f32; 4] = [0.0; 4];
        for lane in 0..count {
            let m: &Meshlet3D = &meshlets[idx + lane];
            let lb: AxisAlignedBox3D = m.get_bounds();
            let lc: Vec3 = lb.center();
            let lh: Vec3 = lb.get_max().sub(lb.get_min()).scale(0.5);
            let wc_x: f32 =
                elems[0] * lc.get_x() + elems[4] * lc.get_y() + elems[8] * lc.get_z() + elems[12];
            let wc_y: f32 =
                elems[1] * lc.get_x() + elems[5] * lc.get_y() + elems[9] * lc.get_z() + elems[13];
            let wc_z: f32 =
                elems[2] * lc.get_x() + elems[6] * lc.get_y() + elems[10] * lc.get_z() + elems[14];
            let wh_x: f32 = elems[0].abs() * lh.get_x()
                + elems[4].abs() * lh.get_y()
                + elems[8].abs() * lh.get_z();
            let wh_y: f32 = elems[1].abs() * lh.get_x()
                + elems[5].abs() * lh.get_y()
                + elems[9].abs() * lh.get_z();
            let wh_z: f32 = elems[2].abs() * lh.get_x()
                + elems[6].abs() * lh.get_y()
                + elems[10].abs() * lh.get_z();
            min_x[lane] = wc_x - wh_x;
            min_y[lane] = wc_y - wh_y;
            min_z[lane] = wc_z - wh_z;
            max_x[lane] = wc_x + wh_x;
            max_y[lane] = wc_y + wh_y;
            max_z[lane] = wc_z + wh_z;
            cx[lane] = wc_x;
            cy[lane] = wc_y;
            cz[lane] = wc_z;
            if is_closed {
                let ca: Vec3 = m.get_cone_axis();
                let wa: Vec3 = Vec3::new(
                    elems[0] * ca.get_x() + elems[4] * ca.get_y() + elems[8] * ca.get_z(),
                    elems[1] * ca.get_x() + elems[5] * ca.get_y() + elems[9] * ca.get_z(),
                    elems[2] * ca.get_x() + elems[6] * ca.get_y() + elems[10] * ca.get_z(),
                )
                .normalize();
                ax[lane] = wa.get_x();
                ay[lane] = wa.get_y();
                az[lane] = wa.get_z();
                let cutoff: f32 = m.get_cone_cutoff();
                if cutoff > 0.05 {
                    let s2: f32 = (1.0 - cutoff * cutoff).max(0.0);
                    sin_sq[lane] = s2;
                    let r_axis: f32 =
                        wh_x * wa.get_x().abs() + wh_y * wa.get_y().abs() + wh_z * wa.get_z().abs();
                    let radius: f32 = (wh_x * wh_x + wh_y * wh_y + wh_z * wh_z).sqrt();
                    margin[lane] = r_axis + radius * s2.sqrt();
                }
            }
        }
        let aabb_batch: SimdAabbBatch4 =
            SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
        let frustum_mask: u8 = cull_aabb_batch4_simd(&planes, &aabb_batch);
        let cone_mask: u8 = if is_closed && frustum_mask != 0 {
            let cone_batch: SimdMeshletConeBatch4 = SimdMeshletConeBatch4 {
                center_x: cx,
                center_y: cy,
                center_z: cz,
                axis_x: ax,
                axis_y: ay,
                axis_z: az,
                sin_alpha_sq: sin_sq,
                extent_margin: margin,
            };
            cull_meshlet_cones_batch4_simd(cam_arr, &cone_batch)
        } else {
            0x0F
        };
        let combined: u8 = frustum_mask & cone_mask;
        for lane in 0..count {
            if ((combined >> lane) & 1) == 0 {
                culled += 1;
            }
        }
        idx += 4;
    }
    (total as u32, culled)
}

/// Packs a 64-bit deterministic render-state sort key `(alpha_pass | pso_variant | material_id | mesh_id | lod_level | quantized_depth)`.
///
/// # Arguments
///
/// - `u8` - Alpha pass bucket (`0` = opaque/mask front-to-back, `1` = alpha-blend back-to-front).
/// - `u8` - Pipeline variant (`0=OpaquePbr, 1=SkinnedPbr, 2=AlphaBlendPbr`).
/// - `u32` - Material slot index (`0..=65535`).
/// - `u32` - Mesh library identifier (`0..=65535`).
/// - `u8` - Selected geometric LOD level (`0..=3`).
/// - `u16` - Quantized camera-space depth in `0..=65535`.
///
/// # Returns
///
/// - `u64` - Packed 64-bit render sort key keeping identical `(alpha, pso, material, mesh, lod)` instances contiguous for automatic hardware instancing.
#[must_use]
pub fn pack_pbr_sort_key(
    alpha_pass: u8,
    pso_variant: u8,
    material_id: u32,
    mesh_id: u32,
    lod_level: u8,
    quantized_depth: u16,
) -> u64 {
    let alpha_bits: u64 = u64::from(alpha_pass & 0x03) << 62;
    let pso_bits: u64 = u64::from(pso_variant & 0x07) << 59;
    let mat_bits: u64 = u64::from(material_id & 0xFFFF) << 43;
    let mesh_bits: u64 = u64::from(mesh_id & 0xFFFF) << 27;
    let lod_bits: u64 = u64::from(lod_level & 0x07) << 24;
    let depth_ordered: u16 = if alpha_pass != 0 {
        u16::MAX - quantized_depth
    } else {
        quantized_depth
    };
    let depth_bits: u64 = u64::from(depth_ordered) << 8;
    let hi_bits: u64 = (alpha_bits | pso_bits).wrapping_add(mat_bits);
    let mid_bits: u64 = mesh_bits | lod_bits;
    hi_bits.wrapping_add(mid_bits).wrapping_add(depth_bits)
}

/// Sorts `scratch.entries` by their 64-bit state key and coalesces adjacent identical `(alpha | pso | material | mesh | lod)` instances into hardware instanced `GpuPbrDrawBatch`es with zero steady-state heap allocations.
///
/// # Arguments
///
/// - `&mut GpuPbrBatcherScratch3D` - Reusable scratch buffer containing sortable PBR entries.
/// - `&mut Vec<GpuPbrInstance3D>` - Destination instance buffer overwritten in-place.
/// - `&mut Vec<GpuPbrDrawBatch>` - Destination instanced draw-batch buffer overwritten in-place.
///
/// # Returns
///
/// - `u32` - Number of coalesced GPU instanced draw batches emitted.
pub fn coalesce_pbr_batches_into(
    scratch: &mut GpuPbrBatcherScratch3D,
    instances_out: &mut Vec<GpuPbrInstance3D>,
    batches_out: &mut Vec<GpuPbrDrawBatch>,
) -> u32 {
    let entries: &mut Vec<PbrSortEntry3D> = scratch.get_mut_entries();
    entries.sort_unstable_by_key(|entry: &PbrSortEntry3D| entry.get_sort_key());
    instances_out.clear();
    batches_out.clear();
    if instances_out.capacity() < entries.len() {
        instances_out.reserve(entries.len() - instances_out.len());
    }
    let mut cursor: usize = 0;
    let total: usize = entries.len();
    while cursor < total {
        let head: PbrSortEntry3D = entries[cursor];
        let batch_state_key: u64 = head.get_sort_key() & !0x00FF_FFFFu64;
        let instance_start: u32 = instances_out.len() as u32;
        let mut instance_count: u32 = 0;
        while cursor < total {
            let cur: PbrSortEntry3D = entries[cursor];
            let cur_state_key: u64 = cur.get_sort_key() & !0x00FF_FFFFu64;
            if cur_state_key != batch_state_key
                || cur.get_index_start() != head.get_index_start()
                || cur.get_index_count() != head.get_index_count()
                || cur.get_base_vertex() != head.get_base_vertex()
            {
                break;
            }
            instances_out.push(cur.get_instance());
            instance_count = instance_count.saturating_add(1);
            cursor += 1;
        }
        batches_out.push(GpuPbrDrawBatch {
            index_start: head.get_index_start(),
            index_count: head.get_index_count(),
            base_vertex: head.get_base_vertex(),
            instance_start,
            instance_count,
            material_index: head.get_material_index(),
            pso_variant: head.get_pso_variant(),
            lod_level: head.get_lod_level(),
            reserved: [0, 0],
            sort_key: head.get_sort_key(),
        });
    }
    batches_out.len() as u32
}

/// Builds a 320-byte `PbrSceneUniformBlock` from `pass` and active batch metadata for Metal and D3D11 constant buffer uploads.
///
/// # Arguments
///
/// - `&GpuPbrScenePass` - Active hardware PBR scene pass descriptor.
/// - `u32` - Packed `[lod_level | (mip_residency_tier << 8) | (tex_present_mask << 16)]` word.
/// - `u32` - Active material table slot index.
/// - `[u32; 4]` - Per-draw offsets `[base_vertex, instance_start, morph_delta_stride, index_start]`.
///
/// # Returns
///
/// - `PbrSceneUniformBlock` - Packed 320-byte constant buffer payload.
#[must_use]
pub fn build_pbr_scene_uniform_block(
    pass: &GpuPbrScenePass,
    lod_mip_texmask: u32,
    material_index: u32,
    draw_offsets: [u32; 4],
) -> PbrSceneUniformBlock {
    let light_count: u32 = pass.get_local_lights().len().min(PBR_MAX_LOCAL_LIGHTS) as u32;
    PbrSceneUniformBlock {
        view_proj: pass.get_view_proj(),
        camera_pos_exposure: pass.get_camera_pos_exposure(),
        sun_dir_fog: pass.get_sun_dir_fog(),
        sun_color_ambient: pass.get_sun_color_ambient(),
        sky_horizon_tod: pass.get_sky_horizon_tod(),
        sky_zenith_agx: pass.get_sky_zenith_agx(),
        ibl_sh: pass.get_ibl_sh(),
        batch_params: [
            u32::from(pass.get_debug_view_mode()),
            lod_mip_texmask,
            light_count,
            material_index,
        ],
        draw_offsets,
    }
}

/// Returns the unified `(vertex_or_combined, fragment_or_combined)` `DirectGpuScenePass::PbrScene` shader source pair for `lang`.
///
/// # Arguments
///
/// - `GpuShaderLanguage3D` - Target GPU shading language dialect.
///
/// # Returns
///
/// - `(&'static str, &'static str)` - Validated `(vertex_or_unified, fragment_or_unified)` shader sources for `PbrScene`.
#[must_use]
pub const fn pbr_scene_shader_source_pair(
    lang: GpuShaderLanguage3D,
) -> (&'static str, &'static str) {
    match lang {
        GpuShaderLanguage3D::Msl => (MSL_PBR_SCENE_SHADER, MSL_PBR_SCENE_SHADER),
        GpuShaderLanguage3D::GlslEs3 => (
            GLSL_ES3_PBR_SCENE_VERT_SHADER,
            GLSL_ES3_PBR_SCENE_FRAG_SHADER,
        ),
        GpuShaderLanguage3D::Hlsl => (HLSL_PBR_SCENE_SHADER, HLSL_PBR_SCENE_SHADER),
        GpuShaderLanguage3D::Wgsl => (WGSL_PBR_SCENE_SHADER, WGSL_PBR_SCENE_SHADER),
    }
}