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

/// Evaluates the 32-bit Wang integer avalanche hash for decorrelated deterministic RNG seeding.
///
/// # Arguments
///
/// - `u32` - Input integer seed.
///
/// # Returns
///
/// - `u32` - Scrambled 32-bit hash value.
#[must_use]
pub fn wang_hash(seed: u32) -> u32 {
    let mut x: u32 = (seed ^ 61) ^ (seed >> 16);
    x = x.wrapping_mul(9);
    x ^= x >> 4;
    x = x.wrapping_mul(0x27d4_eb2d);
    x ^ (x >> 15)
}

/// Computes Rec.709 linear RGB luminance `0.2126*R + 0.7152*G + 0.0722*B`.
///
/// # Arguments
///
/// - `Vec3` - Linear RGB color or radiance.
///
/// # Returns
///
/// - `f32` - Scalar luminance.
#[must_use]
pub fn rgb_luminance(color: Vec3) -> f32 {
    0.2126 * color.get_x() + 0.7152 * color.get_y() + 0.0722 * color.get_z()
}

/// Sanitizes HDR radiance by zeroing NaN/Inf/negative components and applying hue-preserving firefly luminance clamping.
///
/// # Arguments
///
/// - `Vec3` - Raw HDR RGB radiance.
/// - `f32` - Maximum allowed luminance (`<= 0.0` disables upper clamp).
///
/// # Returns
///
/// - `Vec3` - Finite, non-negative, firefly-clamped HDR RGB radiance.
#[must_use]
pub fn sanitize_radiance(color: Vec3, max_luminance: f32) -> Vec3 {
    let r: f32 = if color.get_x().is_finite() {
        color.get_x().max(0.0)
    } else {
        0.0
    };
    let g: f32 = if color.get_y().is_finite() {
        color.get_y().max(0.0)
    } else {
        0.0
    };
    let b: f32 = if color.get_z().is_finite() {
        color.get_z().max(0.0)
    } else {
        0.0
    };
    let clean: Vec3 = Vec3::new(r, g, b);
    if max_luminance > 0.0 {
        let luma: f32 = rgb_luminance(clean);
        if luma > max_luminance && luma.is_finite() {
            return clean.scale(max_luminance / luma);
        }
    }
    clean
}

/// Evaluates Schlick's Fresnel reflectance approximation `F0 + (1 - F0) * (1 - cos_theta)^5`.
///
/// # Arguments
///
/// - `f32` - Clamped cosine of incidence angle in `[0.0, 1.0]`.
/// - `Vec3` - Normal-incidence reflectance `F0`.
///
/// # Returns
///
/// - `Vec3` - Component-wise Fresnel reflectance in `[0.0, 1.0]`.
#[must_use]
pub fn fresnel_schlick(cos_theta: f32, f0: Vec3) -> Vec3 {
    let m: f32 = (1.0 - cos_theta.clamp(0.0, 1.0)).clamp(0.0, 1.0);
    let m2: f32 = m * m;
    let m5: f32 = m2 * m2 * m;
    Vec3::new(
        (f0.get_x() + (1.0 - f0.get_x()) * m5).clamp(0.0, 1.0),
        (f0.get_y() + (1.0 - f0.get_y()) * m5).clamp(0.0, 1.0),
        (f0.get_z() + (1.0 - f0.get_z()) * m5).clamp(0.0, 1.0),
    )
}

/// Evaluates exact unpolarized dielectric Fresnel reflectance including Total Internal Reflection (`1.0`).
///
/// # Arguments
///
/// - `f32` - Cosine of incident angle `cos(theta_i) >= 0`.
/// - `f32` - Incident medium index of refraction `eta_i`.
/// - `f32` - Transmitted medium index of refraction `eta_t`.
///
/// # Returns
///
/// - `f32` - Dielectric reflectance fraction in `[0.0, 1.0]`.
#[must_use]
pub fn fresnel_dielectric(cos_theta_i: f32, eta_i: f32, eta_t: f32) -> f32 {
    let cos_i: f32 = cos_theta_i.clamp(0.0, 1.0);
    let eta: f32 = eta_i / eta_t.max(1e-4);
    let sin_t_sq: f32 = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
    if sin_t_sq >= 1.0 {
        return 1.0;
    }
    let cos_t: f32 = (1.0 - sin_t_sq).max(0.0).sqrt();
    let r_par_num: f32 = eta_t * cos_i - eta_i * cos_t;
    let r_par_den: f32 = (eta_t * cos_i + eta_i * cos_t).max(RT_MIN_PDF);
    let r_perp_num: f32 = eta_i * cos_i - eta_t * cos_t;
    let r_perp_den: f32 = (eta_i * cos_i + eta_t * cos_t).max(RT_MIN_PDF);
    let r_par: f32 = r_par_num / r_par_den;
    let r_perp: f32 = r_perp_num / r_perp_den;
    (0.5 * (r_par * r_par + r_perp * r_perp)).clamp(0.0, 1.0)
}

/// Computes Snell's law refracted direction for unit `incident` striking `normal` with ratio `eta = eta_i / eta_t`, returning `None` on Total Internal Reflection.
///
/// # Arguments
///
/// - `Vec3` - Unit incident ray direction pointing toward the interface.
/// - `Vec3` - Unit surface normal pointing against `incident`.
/// - `f32` - Ratio of incident to transmitted refractive indices `eta_i / eta_t`.
///
/// # Returns
///
/// - `Option<Vec3>` - Unit refracted direction, or `None` under Total Internal Reflection.
#[must_use]
pub fn refract_snell(incident: Vec3, normal: Vec3, eta: f32) -> Option<Vec3> {
    let cos_i: f32 = (-incident.dot(normal)).clamp(0.0, 1.0);
    let sin_t_sq: f32 = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
    if sin_t_sq >= 1.0 {
        return None;
    }
    let cos_t: f32 = (1.0 - sin_t_sq).max(0.0).sqrt();
    let refracted: Vec3 = incident.scale(eta).add(normal.scale(eta * cos_i - cos_t));
    if refracted.length_sq() > RT_MIN_PDF {
        Some(refracted.normalize())
    } else {
        None
    }
}

/// Evaluates the isotropic GGX / Trowbridge-Reitz Normal Distribution Function `D(h)`.
///
/// # Arguments
///
/// - `f32` - Clamped `N·H` in `[0.0, 1.0]`.
/// - `f32` - Roughness parameter `alpha = roughness^2`.
///
/// # Returns
///
/// - `f32` - Microfacet NDF density value.
#[must_use]
pub fn ggx_d(n_dot_h: f32, alpha: f32) -> f32 {
    let a: f32 = alpha.max(RT_MIN_ALPHA);
    let a2: f32 = a * a;
    let nh: f32 = n_dot_h.clamp(0.0, 1.0);
    let denom: f32 = nh * nh * (a2 - 1.0) + 1.0;
    a2 / (PI * denom * denom).max(RT_MIN_PDF)
}

/// Evaluates the Smith GGX auxiliary masking function `Lambda(cos_theta)`.
///
/// # Arguments
///
/// - `f32` - Cosine of view or light elevation angle.
/// - `f32` - Roughness parameter `alpha`.
///
/// # Returns
///
/// - `f32` - Non-negative Smith `Lambda` term.
#[must_use]
pub fn ggx_lambda(cos_theta: f32, alpha: f32) -> f32 {
    let c: f32 = cos_theta.abs().clamp(1e-4, 1.0);
    let a: f32 = alpha.max(RT_MIN_ALPHA);
    let tan2: f32 = (1.0 - c * c).max(0.0) / (c * c);
    0.5 * ((1.0 + a * a * tan2).sqrt() - 1.0)
}

/// Evaluates the Smith GGX single-direction masking term `G1(v)`.
///
/// # Arguments
///
/// - `f32` - Clamped `N·V`.
/// - `f32` - Roughness parameter `alpha`.
///
/// # Returns
///
/// - `f32` - Masking attenuation in `(0.0, 1.0]`.
#[must_use]
pub fn ggx_g1(n_dot_v: f32, alpha: f32) -> f32 {
    if n_dot_v <= 0.0 {
        return 0.0;
    }
    1.0 / (1.0 + ggx_lambda(n_dot_v, alpha))
}

/// Evaluates the height-correlated Smith GGX shadowing-masking term `G2(v, l)`.
///
/// # Arguments
///
/// - `f32` - Clamped `N·V`.
/// - `f32` - Clamped `N·L`.
/// - `f32` - Roughness parameter `alpha`.
///
/// # Returns
///
/// - `f32` - Height-correlated shadowing-masking factor in `[0.0, 1.0]`.
#[must_use]
pub fn ggx_g2(n_dot_v: f32, n_dot_l: f32, alpha: f32) -> f32 {
    if n_dot_v <= 0.0 || n_dot_l <= 0.0 {
        return 0.0;
    }
    1.0 / (1.0 + ggx_lambda(n_dot_v, alpha) + ggx_lambda(n_dot_l, alpha))
}

/// Evaluates the solid-angle PDF of a reflected direction drawn via GGX VNDF importance sampling.
///
/// # Arguments
///
/// - `f32` - Positive `N·V`.
/// - `f32` - Positive `N·H`.
/// - `f32` - Roughness parameter `alpha`.
///
/// # Returns
///
/// - `f32` - Reflected direction solid-angle PDF `p(wi)`.
#[must_use]
pub fn ggx_vndf_pdf(n_dot_v: f32, n_dot_h: f32, alpha: f32) -> f32 {
    if n_dot_v <= RT_MIN_PDF || n_dot_h <= RT_MIN_PDF {
        return 0.0;
    }
    let g1: f32 = ggx_g1(n_dot_v, alpha);
    let d: f32 = ggx_d(n_dot_h, alpha);
    (g1 * d) / (4.0 * n_dot_v).max(RT_MIN_PDF)
}

/// Importance-samples a GGX visible-normal microfacet half-vector `H` in world space using Heitz's 2018 VNDF algorithm.
///
/// # Arguments
///
/// - `Vec3` - Outgoing view direction `wo` in world space (pointing away from surface).
/// - `Vec3` - Unit shading normal `N` oriented in the same hemisphere as `wo`.
/// - `f32` - Roughness parameter `alpha = roughness^2`.
/// - `[f32; 2]` - Uniform random sample in `[0.0, 1.0)^2`.
///
/// # Returns
///
/// - `Vec3` - Importance-sampled unit world-space microfacet normal `H`.
#[must_use]
pub fn sample_ggx_vndf(view_world: Vec3, normal: Vec3, alpha: f32, xi: [f32; 2]) -> Vec3 {
    let a: f32 = alpha.max(RT_MIN_ALPHA);
    let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(normal);
    let ve_x: f32 = view_world.dot(tangent);
    let ve_y: f32 = view_world.dot(bitangent);
    let ve_z: f32 = view_world.dot(normal).max(1e-4);
    let vh: Vec3 = Vec3::new(a * ve_x, a * ve_y, ve_z).normalize();
    let lensq: f32 = vh.get_x() * vh.get_x() + vh.get_y() * vh.get_y();
    let t1: Vec3 = if lensq > 1e-8 {
        let inv_len: f32 = 1.0 / lensq.sqrt();
        Vec3::new(-vh.get_y() * inv_len, vh.get_x() * inv_len, 0.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let t2: Vec3 = vh.cross(t1);
    let r: f32 = xi[0].clamp(0.0, 0.999_999).sqrt();
    let phi: f32 = TAU * xi[1];
    let p1: f32 = r * phi.cos();
    let raw_p2: f32 = r * phi.sin();
    let s: f32 = 0.5 * (1.0 + vh.get_z());
    let p2: f32 = (1.0 - s) * (1.0 - p1 * p1).max(0.0).sqrt() + s * raw_p2;
    let nh_z: f32 = (1.0 - p1 * p1 - p2 * p2).max(0.0).sqrt();
    let nh: Vec3 = t1.scale(p1).add(t2.scale(p2)).add(vh.scale(nh_z));
    let ne_local: Vec3 = Vec3::new(a * nh.get_x(), a * nh.get_y(), nh.get_z().max(0.0)).normalize();
    tangent
        .scale(ne_local.get_x())
        .add(bitangent.scale(ne_local.get_y()))
        .add(normal.scale(ne_local.get_z()))
        .normalize()
}

/// Samples a cosine-weighted hemisphere direction around `normal` returning `(direction, pdf = cos_theta / PI)`.
///
/// # Arguments
///
/// - `Vec3` - Unit surface normal defining the hemisphere pole.
/// - `[f32; 2]` - Uniform sample in `[0.0, 1.0)^2`.
///
/// # Returns
///
/// - `(Vec3, f32)` - Sampled unit world-space direction and its solid-angle PDF.
#[must_use]
pub fn sample_cosine_hemisphere(normal: Vec3, xi: [f32; 2]) -> (Vec3, f32) {
    let disk: [f32; 2] = concentric_sample_disk(xi);
    let z: f32 = (1.0 - disk[0] * disk[0] - disk[1] * disk[1])
        .max(0.0)
        .sqrt();
    let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(normal);
    let dir: Vec3 = tangent
        .scale(disk[0])
        .add(bitangent.scale(disk[1]))
        .add(normal.scale(z))
        .normalize();
    let pdf: f32 = (z / PI).max(RT_MIN_PDF);
    (dir, pdf)
}

/// Evaluates the MIS balance heuristic weight `pdf_a / (pdf_a + pdf_b)`.
///
/// # Arguments
///
/// - `f32` - Sampling PDF of the primary strategy.
/// - `f32` - Sampling PDF of the competing strategy.
///
/// # Returns
///
/// - `f32` - Balance heuristic MIS weight in `[0.0, 1.0]`.
#[must_use]
pub fn mis_weight_balance(pdf_a: f32, pdf_b: f32) -> f32 {
    let a: f32 = pdf_a.max(0.0);
    let b: f32 = pdf_b.max(0.0);
    let sum: f32 = a + b;
    if sum <= RT_MIN_PDF {
        0.0
    } else {
        (a / sum).clamp(0.0, 1.0)
    }
}

/// Evaluates the MIS power heuristic weight (`beta = 2`) `pdf_a^2 / (pdf_a^2 + pdf_b^2)`.
///
/// # Arguments
///
/// - `f32` - Sampling PDF of the primary strategy.
/// - `f32` - Sampling PDF of the competing strategy.
///
/// # Returns
///
/// - `f32` - Power heuristic MIS weight in `[0.0, 1.0]`.
#[must_use]
pub fn mis_weight_power(pdf_a: f32, pdf_b: f32) -> f32 {
    let a: f32 = pdf_a.max(0.0);
    let b: f32 = pdf_b.max(0.0);
    let a2: f32 = a * a;
    let b2: f32 = b * b;
    let sum: f32 = a2 + b2;
    if sum <= RT_MIN_PDF * RT_MIN_PDF {
        0.0
    } else {
        (a2 / sum).clamp(0.0, 1.0)
    }
}

/// Computes an offset ray origin shifted along `normal` in the direction of `ray_dir` to prevent self-intersection.
///
/// # Arguments
///
/// - `Vec3` - Surface intersection point.
/// - `Vec3` - Unit geometric surface normal.
/// - `Vec3` - Outgoing ray direction.
///
/// # Returns
///
/// - `Vec3` - Biased ray origin.
#[must_use]
pub(crate) fn offset_ray_origin(point: Vec3, geometric_normal: Vec3, ray_dir: Vec3) -> Vec3 {
    let sign: f32 = if ray_dir.dot(geometric_normal) >= 0.0 {
        1.0
    } else {
        -1.0
    };
    point.add(geometric_normal.scale(sign * RT_SURFACE_BIAS))
}

/// Evaluates Fujii's energy-conserving Oren-Nayar diffuse BRDF value `f_d(wo, wi)`.
///
/// # Arguments
///
/// - `Vec3` - Linear diffuse albedo.
/// - `f32` - Roughness sigma in `[0.0, 1.0]`.
/// - `Vec3` - Unit shading normal.
/// - `Vec3` - Outgoing view direction `wo`.
/// - `Vec3` - Incident light direction `wi`.
///
/// # Returns
///
/// - `Vec3` - Energy-conserving diffuse BRDF RGB value.
#[must_use]
pub(crate) fn eval_oren_nayar_brdf(
    albedo: Vec3,
    sigma: f32,
    normal: Vec3,
    wo: Vec3,
    wi: Vec3,
) -> Vec3 {
    let n_dot_v: f32 = normal.dot(wo).max(0.0);
    let n_dot_l: f32 = normal.dot(wi).max(0.0);
    if n_dot_v <= RT_MIN_PDF || n_dot_l <= RT_MIN_PDF {
        return Vec3::zero();
    }
    let s: f32 = sigma.clamp(0.0, 1.0);
    if s <= 1e-4 {
        return albedo.scale(1.0 / PI);
    }
    let a_coeff: f32 = 1.0 / (PI + (FRAC_PI_2 - (2.0 / 3.0)) * s);
    let b_coeff: f32 = s * a_coeff;
    let s_dot: f32 = wo.dot(wi) - n_dot_l * n_dot_v;
    let t_den: f32 = if s_dot > 0.0 {
        n_dot_l.max(n_dot_v).max(1e-4)
    } else {
        1.0
    };
    let factor: f32 = (a_coeff + b_coeff * (s_dot / t_den)).max(0.0);
    albedo.scale(factor)
}

/// Evaluates the non-delta BSDF value `f(wo, wi)` and its matching solid-angle sampling PDF `p(wi)` for direct lighting and MIS.
///
/// # Arguments
///
/// - `&RtMaterial` - Surface physical material.
/// - `Vec3` - Unit shading normal in the hemisphere of `wo`.
/// - `Vec3` - Outgoing view vector `wo`.
/// - `Vec3` - Incident light direction `wi`.
///
/// # Returns
///
/// - `(Vec3, f32)` - Evaluated BSDF RGB value and combined sampling PDF.
#[must_use]
pub(crate) fn eval_material_bsdf_and_pdf(
    material: &RtMaterial,
    normal: Vec3,
    wo: Vec3,
    wi: Vec3,
) -> (Vec3, f32) {
    let n_dot_v: f32 = normal.dot(wo);
    let n_dot_l: f32 = normal.dot(wi);
    if n_dot_v <= RT_MIN_PDF || n_dot_l <= RT_MIN_PDF {
        return (Vec3::zero(), 0.0);
    }
    let half_sum: Vec3 = wo.add(wi);
    if half_sum.length_sq() <= RT_MIN_PDF {
        return (Vec3::zero(), 0.0);
    }
    let h: Vec3 = half_sum.normalize();
    let n_dot_h: f32 = normal.dot(h).max(0.0);
    let v_dot_h: f32 = wo.dot(h).max(0.0);
    match material.get_kind() {
        RtMaterialKind::Emissive => (Vec3::zero(), 0.0),
        RtMaterialKind::Diffuse => {
            let brdf: Vec3 = eval_oren_nayar_brdf(
                material.get_albedo(),
                material.get_oren_nayar_sigma(),
                normal,
                wo,
                wi,
            );
            (brdf, n_dot_l / PI)
        }
        RtMaterialKind::Metal => {
            if material.is_delta_specular() {
                return (Vec3::zero(), 0.0);
            }
            let r: f32 = material.get_roughness().clamp(0.01, 1.0);
            let alpha: f32 = (r * r).max(RT_MIN_ALPHA);
            let f: Vec3 = fresnel_schlick(v_dot_h, material.get_albedo());
            let d: f32 = ggx_d(n_dot_h, alpha);
            let g2: f32 = ggx_g2(n_dot_v, n_dot_l, alpha);
            let spec: Vec3 = f.scale((d * g2) / (4.0 * n_dot_v * n_dot_l).max(RT_MIN_PDF));
            let pdf: f32 = ggx_vndf_pdf(n_dot_v, n_dot_h, alpha);
            (spec, pdf)
        }
        RtMaterialKind::Dielectric => (Vec3::zero(), 0.0),
        RtMaterialKind::Principled => {
            let albedo: Vec3 = material.get_albedo();
            let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
            let r: f32 = material.get_roughness().clamp(0.01, 1.0);
            let alpha: f32 = (r * r).max(RT_MIN_ALPHA);
            let ior: f32 = material.get_ior().clamp(1.001, 3.0);
            let f0_scalar: f32 = ((ior - 1.0) / (ior + 1.0)).powi(2);
            let f0: Vec3 = Vec3::splat(f0_scalar).lerp(albedo, metallic);
            let fresnel: Vec3 = fresnel_schlick(v_dot_h, f0);
            let d: f32 = ggx_d(n_dot_h, alpha);
            let g2: f32 = ggx_g2(n_dot_v, n_dot_l, alpha);
            let base_spec: Vec3 =
                fresnel.scale((d * g2) / (4.0 * n_dot_v * n_dot_l).max(RT_MIN_PDF));
            let trans: f32 = material.get_transmission().clamp(0.0, 1.0);
            let kd_weight: f32 = (1.0 - metallic) * (1.0 - trans);
            let kd: Vec3 = Vec3::new(
                ((1.0 - fresnel.get_x()) * kd_weight).max(0.0),
                ((1.0 - fresnel.get_y()) * kd_weight).max(0.0),
                ((1.0 - fresnel.get_z()) * kd_weight).max(0.0),
            );
            let diff_base: Vec3 =
                eval_oren_nayar_brdf(albedo, material.get_oren_nayar_sigma(), normal, wo, wi);
            let mut total_brdf: Vec3 = Vec3::new(
                kd.get_x() * diff_base.get_x() + base_spec.get_x(),
                kd.get_y() * diff_base.get_y() + base_spec.get_y(),
                kd.get_z() * diff_base.get_z() + base_spec.get_z(),
            );
            let coat: f32 = material.get_clearcoat().clamp(0.0, 1.0);
            let coat_r: f32 = material.get_clearcoat_roughness().clamp(0.01, 1.0);
            let coat_alpha: f32 = (coat_r * coat_r).max(RT_MIN_ALPHA);
            let mut coat_pdf: f32 = 0.0;
            if coat > 1e-4 {
                let coat_f: f32 = fresnel_schlick(v_dot_h, Vec3::splat(0.04)).get_x();
                let coat_d: f32 = ggx_d(n_dot_h, coat_alpha);
                let coat_g2: f32 = ggx_g2(n_dot_v, n_dot_l, coat_alpha);
                let coat_spec: f32 =
                    (coat * coat_f * coat_d * coat_g2) / (4.0 * n_dot_v * n_dot_l).max(RT_MIN_PDF);
                let atten: f32 = 1.0 - coat * coat_f;
                total_brdf = total_brdf.scale(atten).add(Vec3::splat(coat_spec));
                coat_pdf = ggx_vndf_pdf(n_dot_v, n_dot_h, coat_alpha);
            }
            let (p_coat, p_spec, p_diff): (f32, f32, f32) =
                principled_lobe_probabilities(material, n_dot_v);
            let spec_pdf: f32 = ggx_vndf_pdf(n_dot_v, n_dot_h, alpha);
            let diff_pdf: f32 = n_dot_l / PI;
            let combined_pdf: f32 = p_coat * coat_pdf + p_spec * spec_pdf + p_diff * diff_pdf;
            (total_brdf, combined_pdf)
        }
    }
}

/// Computes normalized lobe selection probabilities `(p_coat, p_spec, p_diff)` for a `Principled` material.
///
/// # Arguments
///
/// - `&RtMaterial` - Surface material.
/// - `f32` - Positive `N·V`.
///
/// # Returns
///
/// - `(f32, f32, f32)` - Probabilities summing to `<= 1.0` (remainder goes to transmission if present).
#[must_use]
pub(crate) fn principled_lobe_probabilities(
    material: &RtMaterial,
    n_dot_v: f32,
) -> (f32, f32, f32) {
    let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
    let trans: f32 = material.get_transmission().clamp(0.0, 1.0);
    let coat: f32 = material.get_clearcoat().clamp(0.0, 1.0);
    let w_coat: f32 = coat * 0.25;
    let f0_s: f32 = ((material.get_ior() - 1.0) / (material.get_ior() + 1.0)).powi(2);
    let f_approx: f32 = fresnel_schlick(n_dot_v, Vec3::splat(f0_s)).get_x();
    let w_spec: f32 = (metallic + (1.0 - metallic) * f_approx).clamp(0.05, 1.0);
    let w_diff: f32 = ((1.0 - metallic) * (1.0 - trans) * (1.0 - f_approx)).max(0.0);
    let w_trans: f32 = ((1.0 - metallic) * trans * (1.0 - f_approx)).max(0.0);
    let sum: f32 = (w_coat + w_spec + w_diff + w_trans).max(RT_MIN_PDF);
    (w_coat / sum, w_spec / sum, w_diff / sum)
}

/// Importance-samples an outgoing scattering direction and throughput weight from an `RtMaterial`.
///
/// # Arguments
///
/// - `&RtMaterial` - Surface material.
/// - `Vec3` - Unit shading normal oriented against the incoming ray.
/// - `bool` - Whether the ray struck the exterior front face.
/// - `Vec3` - Outgoing view direction `wo` (`-ray.direction`).
/// - `&mut RtRng` - Deterministic per-pixel RNG.
///
/// # Returns
///
/// - `Option<RtBsdfSample>` - Sampled direction, throughput weight, and PDF, or `None` if absorbed/emissive.
#[must_use]
pub(crate) fn sample_material_bsdf(
    material: &RtMaterial,
    normal: Vec3,
    front_face: bool,
    wo: Vec3,
    rng: &mut RtRng,
) -> Option<RtBsdfSample> {
    let n_dot_v: f32 = normal.dot(wo);
    if n_dot_v <= RT_MIN_PDF {
        return None;
    }
    match material.get_kind() {
        RtMaterialKind::Emissive => None,
        RtMaterialKind::Diffuse => {
            let xi: [f32; 2] = rng.next_f32_pair();
            let (wi, pdf): (Vec3, f32) = sample_cosine_hemisphere(normal, xi);
            let n_dot_l: f32 = normal.dot(wi).max(0.0);
            if n_dot_l <= RT_MIN_PDF {
                return None;
            }
            let brdf: Vec3 = eval_oren_nayar_brdf(
                material.get_albedo(),
                material.get_oren_nayar_sigma(),
                normal,
                wo,
                wi,
            );
            let weight: Vec3 = brdf.scale(n_dot_l / pdf.max(RT_MIN_PDF));
            Some(RtBsdfSample::new(wi, weight, pdf, false, false))
        }
        RtMaterialKind::Metal => {
            if material.is_delta_specular() {
                let wi: Vec3 = wo.scale(-1.0).reflect(normal).normalize();
                if normal.dot(wi) <= 0.0 {
                    return None;
                }
                let f: Vec3 = fresnel_schlick(n_dot_v, material.get_albedo());
                return Some(RtBsdfSample::new(wi, f, 0.0, true, false));
            }
            let r: f32 = material.get_roughness().clamp(0.01, 1.0);
            let alpha: f32 = (r * r).max(RT_MIN_ALPHA);
            let xi: [f32; 2] = rng.next_f32_pair();
            let h: Vec3 = sample_ggx_vndf(wo, normal, alpha, xi);
            let wi: Vec3 = wo.scale(-1.0).reflect(h).normalize();
            let n_dot_l: f32 = normal.dot(wi);
            if n_dot_l <= RT_MIN_PDF {
                return None;
            }
            let v_dot_h: f32 = wo.dot(h).max(0.0);
            let n_dot_h: f32 = normal.dot(h).max(0.0);
            let f: Vec3 = fresnel_schlick(v_dot_h, material.get_albedo());
            let g1: f32 = ggx_g1(n_dot_v, alpha).max(RT_MIN_PDF);
            let g2: f32 = ggx_g2(n_dot_v, n_dot_l, alpha);
            let weight: Vec3 = f.scale((g2 / g1).clamp(0.0, 1.0));
            let pdf: f32 = ggx_vndf_pdf(n_dot_v, n_dot_h, alpha);
            Some(RtBsdfSample::new(wi, weight, pdf, false, false))
        }
        RtMaterialKind::Dielectric => {
            let ior: f32 = material.get_ior().clamp(1.001, 3.0);
            let (eta_i, eta_t): (f32, f32) = if front_face { (1.0, ior) } else { (ior, 1.0) };
            let micro_n: Vec3 = if material.get_roughness() > 0.005 {
                let r: f32 = material.get_roughness().clamp(0.005, 1.0);
                let alpha: f32 = (r * r).max(RT_MIN_ALPHA);
                let xi: [f32; 2] = rng.next_f32_pair();
                sample_ggx_vndf(wo, normal, alpha, xi)
            } else {
                normal
            };
            let cos_i: f32 = wo.dot(micro_n).clamp(0.0, 1.0);
            let refl_prob: f32 = fresnel_dielectric(cos_i, eta_i, eta_t);
            let incident: Vec3 = wo.scale(-1.0);
            let u_select: f32 = rng.next_f32();
            if u_select < refl_prob {
                let wi: Vec3 = incident.reflect(micro_n).normalize();
                Some(RtBsdfSample::new(
                    wi,
                    material.get_albedo(),
                    0.0,
                    true,
                    false,
                ))
            } else if let Some(refracted) = refract_snell(incident, micro_n, eta_i / eta_t) {
                Some(RtBsdfSample::new(
                    refracted,
                    material.get_albedo(),
                    0.0,
                    true,
                    true,
                ))
            } else {
                let wi: Vec3 = incident.reflect(micro_n).normalize();
                Some(RtBsdfSample::new(
                    wi,
                    material.get_albedo(),
                    0.0,
                    true,
                    false,
                ))
            }
        }
        RtMaterialKind::Principled => {
            let (p_coat, p_spec, p_diff): (f32, f32, f32) =
                principled_lobe_probabilities(material, n_dot_v);
            let u_lobe: f32 = rng.next_f32();
            let xi: [f32; 2] = rng.next_f32_pair();
            if u_lobe < p_coat {
                let coat_r: f32 = material.get_clearcoat_roughness().clamp(0.01, 1.0);
                let coat_alpha: f32 = (coat_r * coat_r).max(RT_MIN_ALPHA);
                let h: Vec3 = sample_ggx_vndf(wo, normal, coat_alpha, xi);
                let wi: Vec3 = wo.scale(-1.0).reflect(h).normalize();
                let n_dot_l: f32 = normal.dot(wi);
                if n_dot_l <= RT_MIN_PDF {
                    return None;
                }
                let (brdf, pdf): (Vec3, f32) = eval_material_bsdf_and_pdf(material, normal, wo, wi);
                if pdf <= RT_MIN_PDF {
                    return None;
                }
                Some(RtBsdfSample::new(
                    wi,
                    brdf.scale(n_dot_l / pdf),
                    pdf,
                    false,
                    false,
                ))
            } else if u_lobe < p_coat + p_spec {
                let r: f32 = material.get_roughness().clamp(0.01, 1.0);
                let alpha: f32 = (r * r).max(RT_MIN_ALPHA);
                let h: Vec3 = sample_ggx_vndf(wo, normal, alpha, xi);
                let wi: Vec3 = wo.scale(-1.0).reflect(h).normalize();
                let n_dot_l: f32 = normal.dot(wi);
                if n_dot_l <= RT_MIN_PDF {
                    return None;
                }
                let (brdf, pdf): (Vec3, f32) = eval_material_bsdf_and_pdf(material, normal, wo, wi);
                if pdf <= RT_MIN_PDF {
                    return None;
                }
                Some(RtBsdfSample::new(
                    wi,
                    brdf.scale(n_dot_l / pdf),
                    pdf,
                    false,
                    false,
                ))
            } else if u_lobe < p_coat + p_spec + p_diff {
                let (wi, _): (Vec3, f32) = sample_cosine_hemisphere(normal, xi);
                let n_dot_l: f32 = normal.dot(wi);
                if n_dot_l <= RT_MIN_PDF {
                    return None;
                }
                let (brdf, pdf): (Vec3, f32) = eval_material_bsdf_and_pdf(material, normal, wo, wi);
                if pdf <= RT_MIN_PDF {
                    return None;
                }
                Some(RtBsdfSample::new(
                    wi,
                    brdf.scale(n_dot_l / pdf),
                    pdf,
                    false,
                    false,
                ))
            } else {
                let ior: f32 = material.get_ior().clamp(1.001, 3.0);
                let (eta_i, eta_t): (f32, f32) = if front_face { (1.0, ior) } else { (ior, 1.0) };
                let incident: Vec3 = wo.scale(-1.0);
                if let Some(refracted) = refract_snell(incident, normal, eta_i / eta_t) {
                    Some(RtBsdfSample::new(
                        refracted,
                        material.get_albedo(),
                        0.0,
                        true,
                        true,
                    ))
                } else {
                    let wi: Vec3 = incident.reflect(normal).normalize();
                    Some(RtBsdfSample::new(
                        wi,
                        material.get_albedo(),
                        0.0,
                        true,
                        false,
                    ))
                }
            }
        }
    }
}