three-rs 0.3.0

A port of three.js core and its WebGPURenderer to Rust on wgpu, graded against three.js's own end-to-end pixel comparison.
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
//! Port of `three.js/src/nodes/functions/PhysicalLightingModel.js` and the
//! BSDF functions it reaches: `BRDF_GGX` (`F_Schlick` × `V_GGX_SmithCorrelated`
//! × `D_GGX`), `BRDF_Lambert`, `computeMultiscattering`, `DFGLUT` and the
//! thin-film block (`evalIridescence`, `evalSensitivity`).
//!
//! Every statement is read off the rung-8 dumps of `webgpu_lights_physical`
//! (`handoff/scouts/rung8/MeshStandardMaterial_1{7,8,9}`,`_20`); the node graph
//! here is arranged to emit that arithmetic in that order. `docs/nodes.md` §8
//! lists where the emitted text differs (temp names, a few hoisted zero
//! initialisers) without changing a value.

use std::rc::Rc;

use super::dfg_lut::dfg_lut;
use super::phong::{self, LightDesc};
use super::transmission;
use crate::nodes::node::{FnDef, Type};
use crate::nodes::tsl::*;
use crate::nodes::NodeRef;

/// `1 / π`.
pub(crate) const RECIPROCAL_PI: f64 = std::f64::consts::FRAC_1_PI;

// ---------------------------------------------------------------------------
// material functions
// ---------------------------------------------------------------------------

/// `getGeometryRoughness()` — `max3( max( abs( dFdx( normalViewGeometry ) ),
/// abs( dFdy( normalViewGeometry ) ) ) )`, with `dFdy`'s sign flip inside
/// `dpdy()`.
/// `has_normal` is `builder.geometry.hasAttribute( 'normal' )`: with no normal
/// attribute the function returns `float( 0 )` outright, and the derivative
/// pair is never emitted. `webgpu_deferred`'s resolve quad is the first
/// geometry on the ladder that has none, and its dump reads
/// `min( ( max( nodeVar4.w, 0.045 ) + 0.0 ), 1.0 )`.
pub fn geometry_roughness(has_normal: bool) -> NodeRef {
    if !has_normal {
        return float(0.0);
    }
    let d = max(
        abs(dpdx(normal_view_geometry())),
        abs(dpdy(normal_view_geometry())),
    );
    max(max(d.x(), d.y()), d.z())
}

/// `getRoughness( { roughness } )` — `min( max( roughness, 0.045 ) +
/// geometryRoughness, 1.0 )`. "Minimum roughness, so even a perfect mirror
/// samples a prefiltered level of the environment map" — Filament's desktop
/// `MIN_PERCEPTUAL_ROUGHNESS`, which three.js restored in b745e6c (#34645)
/// after r186's 0.0525.
pub fn get_roughness(roughness: NodeRef, has_normal: bool) -> NodeRef {
    max(roughness, float(0.045))
        .add(geometry_roughness(has_normal))
        .min(float(1.0))
}

// ---------------------------------------------------------------------------
// BSDF
// ---------------------------------------------------------------------------

/// `V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } )`, emitted as a real WGSL
/// `fn` because three.js gives it a layout.
fn v_ggx_smith_correlated() -> Rc<FnDef> {
    thread_local! { static CELL: crate::nodes::node::Lazy<Rc<FnDef>> = const { crate::nodes::node::Lazy::new() }; }
    CELL.with(|c| {
        c.get(|| {
            shader_fn(
                Some("V_GGX_SmithCorrelated"),
                vec![
                    ("alpha", Type::F32),
                    ("dotNL", Type::F32),
                    ("dotNV", Type::F32),
                ],
                Type::F32,
                |args| {
                    let (alpha, dot_nl, dot_nv) =
                        (args[0].clone(), args[1].clone(), args[2].clone());
                    let a2 = alpha.clone().mul(alpha);
                    let gv = dot_nl.clone().mul(
                        a2.clone()
                            .add(
                                float(1.0)
                                    .sub(a2.clone())
                                    .mul(dot_nv.clone().mul(dot_nv.clone())),
                            )
                            .sqrt(),
                    );
                    let gl = dot_nv.mul(
                        a2.clone()
                            .add(float(1.0).sub(a2).mul(dot_nl.clone().mul(dot_nl)))
                            .sqrt(),
                    );
                    // `EPSILON` is 1e-6.
                    float(0.5).div(max(gv.add(gl), float(0.000001)))
                },
            )
        })
    })
}

/// `D_GGX( { alpha, dotNH } )`.
fn d_ggx() -> Rc<FnDef> {
    thread_local! { static CELL: crate::nodes::node::Lazy<Rc<FnDef>> = const { crate::nodes::node::Lazy::new() }; }
    CELL.with(|c| {
        c.get(|| {
            shader_fn(
                Some("D_GGX"),
                vec![("alpha", Type::F32), ("dotNH", Type::F32)],
                Type::F32,
                |args| {
                    let (alpha, dot_nh) = (args[0].clone(), args[1].clone());
                    let a2 = alpha.clone().mul(alpha);
                    let denom =
                        float(1.0).sub(dot_nh.clone().mul(dot_nh).mul(float(1.0).sub(a2.clone())));
                    a2.div(denom.clone().mul(denom)).mul(RECIPROCAL_PI)
                },
            )
        })
    })
}

/// `BRDF_GGX( { lightDirection, f0, f90, roughness } )` — the isotropic,
/// non-iridescent path, with the default `normalView` and the material's own
/// `roughness`.
pub fn brdf_ggx(light_direction: NodeRef, f0: NodeRef, f90: NodeRef) -> NodeRef {
    brdf_ggx_on(light_direction, f0, f90, roughness(), normal_view(), None)
}

/// `BRDF_GGX( { lightDirection, f0, f90, roughness, normalView, f,
/// USE_IRIDESCENCE } )` — the same lobe about another surface (the clearcoat
/// layer calls it with `clearcoatRoughness` and `clearcoatNormalView`), and,
/// with `iridescence_fresnel` (`f`, `PhysicalLightingModel.iridescenceFresnel`),
/// the `defined( USE_IRIDESCENCE )` branch that blends the Schlick Fresnel
/// towards it by `Iridescence`. No graded page reaches that blend:
/// `webgpu_loader_gltf_iridescence` has no light, so `direct()` never runs
/// (`docs/nodes.md` §95).
pub(crate) fn brdf_ggx_on(
    light_direction: NodeRef,
    f0: NodeRef,
    f90: NodeRef,
    roughness_value: NodeRef,
    normal: NodeRef,
    iridescence_fresnel: Option<NodeRef>,
) -> NodeRef {
    // `roughness.max( 0.045 ).pow2()` — UE4's alpha, over the floor "punctual
    // lights need a minimum roughness to show a highlight".
    let floored = max(roughness_value, float(0.045));
    let alpha = floored.clone().mul(floored);

    let half_dir = light_direction
        .clone()
        .add(position_view_direction())
        .normalize();

    let dot_nl = normal.clone().dot(light_direction).clamp(0.0, 1.0);
    let dot_nv = normal
        .clone()
        .dot(position_view_direction())
        .clamp(0.0, 1.0);
    let dot_nh = normal.dot(half_dir.clone()).clamp(0.0, 1.0);
    let dot_vh = position_view_direction().dot(half_dir).clamp(0.0, 1.0);

    let f = phong::f_schlick(f0, f90, dot_vh);
    let f = match iridescence_fresnel {
        Some(fresnel) => mix(f, fresnel, iridescence()),
        None => f,
    };
    let v = call(
        &v_ggx_smith_correlated(),
        vec![alpha.clone(), dot_nl, dot_nv],
    );
    let d = call(&d_ggx(), vec![alpha, dot_nh]);

    f.mul(v).mul(d)
}

/// `D_Charlie( { roughness, dotNH } )` — Estevez and Kulla 2017, "Production
/// Friendly Microfacet Sheen BRDF", by way of Filament. A real WGSL `fn`,
/// because three.js gives it a layout.
fn d_charlie() -> Rc<FnDef> {
    thread_local! { static CELL: crate::nodes::node::Lazy<Rc<FnDef>> = const { crate::nodes::node::Lazy::new() }; }
    CELL.with(|c| {
        c.get(|| {
            shader_fn(
                Some("D_Charlie"),
                vec![("roughness", Type::F32), ("dotNH", Type::F32)],
                Type::F32,
                |args| {
                    let (roughness_value, dot_nh) = (args[0].clone(), args[1].clone());
                    let alpha = roughness_value.clone().mul(roughness_value);
                    let inv_alpha = float(1.0).div(alpha);
                    let cos2h = dot_nh.clone().mul(dot_nh);
                    // `2^( -14/2 )`, so `sin2h^2 > 0` in fp16.
                    let sin2h = max(cos2h.one_minus(), float(0.0078125));
                    float(2.0)
                        .add(inv_alpha.clone())
                        .mul(sin2h.pow(inv_alpha.mul(0.5)))
                        .div(2.0 * std::f64::consts::PI)
                },
            )
        })
    })
}

/// `V_Neubelt( { dotNV, dotNL } )` — Neubelt and Pettineo 2013, "Crafting a
/// Next-gen Material Pipeline for The Order: 1886".
fn v_neubelt() -> Rc<FnDef> {
    thread_local! { static CELL: crate::nodes::node::Lazy<Rc<FnDef>> = const { crate::nodes::node::Lazy::new() }; }
    CELL.with(|c| {
        c.get(|| {
            shader_fn(
                Some("V_Neubelt"),
                vec![("dotNV", Type::F32), ("dotNL", Type::F32)],
                Type::F32,
                |args| {
                    let (dot_nv, dot_nl) = (args[0].clone(), args[1].clone());
                    float(1.0)
                        .div(
                            float(4.0)
                                .mul(dot_nl.clone().add(dot_nv.clone()).sub(dot_nl.mul(dot_nv))),
                        )
                        .saturate()
                },
            )
        })
    })
}

/// `BRDF_Sheen( { lightDirection } )` — `sheen * D_Charlie * V_Neubelt`.
///
/// No page on this ladder reaches it: `webgpu_loader_gltf_sheen` has no light
/// in the scene, so `PhysicalLightingModel.direct()` is never called and
/// neither `D_Charlie` nor `V_Neubelt` appears in three's own dump for it. It
/// is written from `BRDF_Sheen.js` all the same, because `direct()`'s sheen
/// branch is not optional in three and leaving it out would make the port's
/// lighting model quietly different for the first sheen page that does light
/// its model. `docs/nodes.md` §25.
pub fn brdf_sheen(light_direction: NodeRef) -> NodeRef {
    let half_dir = light_direction
        .clone()
        .add(position_view_direction())
        .normalize();

    let dot_nl = normal_view().dot(light_direction).saturate();
    let dot_nv = normal_view().dot(position_view_direction()).saturate();
    let dot_nh = normal_view().dot(half_dir).saturate();

    let d = call(&d_charlie(), vec![sheen_roughness(), dot_nh]);
    let v = call(&v_neubelt(), vec![dot_nv, dot_nl]);

    sheen().mul(d).mul(v)
}

/// `IBLSheenBRDF( { normal, viewDir, roughness } )` — the curve-fit of the
/// Charlie sheen BRDF integrated over the hemisphere. Three gives it no
/// layout, so it is inlined at each of its four uses rather than emitted as a
/// `fn`; `r2` and `rInv` are read twice each and so become temps, which is
/// what the dump shows.
fn ibl_sheen_brdf(normal: NodeRef, view_dir: NodeRef, roughness_value: NodeRef) -> NodeRef {
    let dot_nv = normal.dot(view_dir).saturate();
    let r2 = roughness_value.clone().mul(roughness_value.clone());
    let r_inv = roughness_value.clone().add(0.1).reciprocal();

    let a = float(-1.9362)
        .add(roughness_value.clone().mul(1.0678))
        .add(r2.clone().mul(0.4573))
        .sub(r_inv.clone().mul(0.8469));
    let b = float(-0.6014)
        .add(roughness_value.mul(0.5538))
        .sub(r2.mul(0.4670))
        .sub(r_inv.mul(0.1255));

    exp(a.mul(dot_nv).add(b)).saturate()
}

/// `IBLSheenBRDF( { normalView, positionViewDirection, sheenRoughness } )`,
/// the argument triple every indirect use passes.
fn sheen_albedo() -> NodeRef {
    ibl_sheen_brdf(normal_view(), position_view_direction(), sheen_roughness())
}

/// `sheen.r.max( sheen.g ).max( sheen.b ).mul( albedo ).oneMinus()` — the
/// energy the sheen lobe took, which the layer underneath does not get.
fn sheen_energy_comp(albedo: NodeRef) -> NodeRef {
    sheen()
        .x()
        .max(sheen().y())
        .max(sheen().z())
        .mul(albedo)
        .one_minus()
}

// ---------------------------------------------------------------------------
// BRDF_EON.js — Portsmouth et al. 2025, "EON: A Practical Energy-Preserving
// Rough Diffuse BRDF", https://jcgt.org/published/0014/01/06/
// ---------------------------------------------------------------------------

/// `EON_EPSILON`.
const EON_EPSILON: f64 = 1e-7;
/// `FON_A_COEFFICIENT` — `0.5 - 2 / ( 3 * Math.PI )`.
const FON_A_COEFFICIENT: f64 = 0.5 - 2.0 / (3.0 * std::f64::consts::PI);
/// `FON_AVERAGE_ALBEDO_COEFFICIENT` — `2 / 3 - 28 / ( 15 * Math.PI )`.
const FON_AVERAGE_ALBEDO_COEFFICIENT: f64 = 2.0 / 3.0 - 28.0 / (15.0 * std::f64::consts::PI);

/// `FON_DirectionalAlbedo( { mu, roughness, A } )` — an inline `Fn()`, so
/// its arithmetic lands in the caller's flow.
fn fon_directional_albedo(mu: NodeRef, roughness_value: NodeRef, a: NodeRef) -> NodeRef {
    let mu_comp = mu.one_minus();
    let g_over_pi = mu_comp.clone().mul(
        mu_comp
            .clone()
            .mul(
                mu_comp
                    .clone()
                    .mul(mu_comp.mul(0.0714429953).sub(0.332181442))
                    .add(0.491881867),
            )
            .add(0.0571085289),
    );
    a.mul(roughness_value.mul(g_over_pi).add(1.0))
}

/// `A = roughness.mul( FON_A_COEFFICIENT ).add( 1.0 ).reciprocal()`.
fn fon_a(roughness_value: NodeRef) -> NodeRef {
    roughness_value.mul(FON_A_COEFFICIENT).add(1.0).reciprocal()
}

/// `averageAlbedo` and `rhoMultiScatter`, which `BRDF_EON` and
/// `EON_DirectionalAlbedo` build the same way.
fn eon_multi_scatter(rho: NodeRef, roughness_value: NodeRef, a: NodeRef) -> (NodeRef, NodeRef) {
    let average_albedo = a.mul(roughness_value.mul(FON_AVERAGE_ALBEDO_COEFFICIENT).add(1.0));
    let rho_multi_scatter = rho
        .clone()
        .mul(rho.clone())
        .mul(average_albedo.clone())
        .div(
            rho.mul(average_albedo.clone().one_minus())
                .one_minus()
                .max(EON_EPSILON),
        );
    (average_albedo, rho_multi_scatter)
}

/// `EON_DirectionalAlbedo( { diffuseColor, roughness, dotNV } )` — the
/// albedo of the EON lobe seen from `dotNV`, which the indirect diffuse terms
/// use in place of `DiffuseContribution` when `useDiffuseRoughness` is on.
/// The `select` becomes an `if` / `else` into a var, as three's
/// `ConditionalNode` does.
pub fn eon_directional_albedo(
    diffuse_color_value: NodeRef,
    roughness_value: NodeRef,
    dot_nv: NodeRef,
) -> NodeRef {
    let rho = diffuse_color_value.clamp(0.0, 1.0);
    let a = fon_a(roughness_value.clone());
    let directional_albedo =
        fon_directional_albedo(dot_nv.clamp(0.0, 1.0), roughness_value.clone(), a.clone());
    let (_, rho_multi_scatter) = eon_multi_scatter(rho.clone(), roughness_value.clone(), a);
    let eon_albedo = rho
        .clone()
        .mul(directional_albedo.clone())
        .add(rho_multi_scatter.mul(directional_albedo.one_minus()));

    roughness_value
        .less_than_equal(EON_EPSILON)
        .select(rho, eon_albedo)
}

/// `BRDF_EON( { lightDirection, diffuseColor, roughness } )` with the default
/// `normalView` / `positionViewDirection`. No graded page reaches it — the
/// one diffuse-roughness page is lit by its environment alone — but
/// `direct()` is ported with it so a first lit page does not find a
/// Lambert lobe where three has this one.
pub fn brdf_eon(
    light_direction: NodeRef,
    diffuse_color_value: NodeRef,
    roughness_value: NodeRef,
) -> NodeRef {
    let rho = diffuse_color_value.clamp(0.0, 1.0);
    let dot_nl = normal_view().dot(light_direction.clone()).clamp(0.0, 1.0);
    let dot_nv = normal_view().dot(position_view_direction()).clamp(0.0, 1.0);
    let s = light_direction
        .dot(position_view_direction())
        .sub(dot_nl.clone().mul(dot_nv.clone()));
    let s_over_t = s.greater_than(0.0).select(
        s.clone()
            .div(dot_nl.clone().max(dot_nv.clone()).max(EON_EPSILON)),
        s,
    );

    let a = fon_a(roughness_value.clone());
    let single_scatter = rho
        .clone()
        .mul(RECIPROCAL_PI)
        .mul(a.clone())
        .mul(roughness_value.clone().mul(s_over_t).add(1.0));

    let albedo_v = fon_directional_albedo(dot_nv, roughness_value.clone(), a.clone());
    let albedo_l = fon_directional_albedo(dot_nl, roughness_value.clone(), a.clone());
    let (average_albedo, rho_multi_scatter) =
        eon_multi_scatter(rho.clone(), roughness_value.clone(), a);
    let multi_scatter = rho_multi_scatter
        .mul(RECIPROCAL_PI)
        .mul(albedo_v.one_minus().max(EON_EPSILON))
        .mul(albedo_l.one_minus().max(EON_EPSILON))
        .div(average_albedo.one_minus().max(EON_EPSILON));
    let eon = single_scatter.add(multi_scatter);

    roughness_value
        .less_than_equal(EON_EPSILON)
        .select(rho.mul(RECIPROCAL_PI), eon)
}

/// `EON_DirectionalAlbedo( { diffuseColor: diffuseColor.rgb, roughness:
/// diffuseRoughness, dotNV: normalView.dot( positionViewDirection ).clamp() }
/// ).mul( metalness.oneMinus() )` — what both indirect terms read.
fn eon_diffuse_albedo() -> NodeRef {
    eon_directional_albedo(
        diffuse_color().rgb(),
        diffuse_roughness(),
        normal_view().dot(position_view_direction()).clamp(0.0, 1.0),
    )
    .mul(metalness().one_minus())
}

/// `DFGLUT( { roughness, dotNV } )` — the 16×16 RG16F table, sampled with an
/// explicit UV so no texture matrix is applied.
fn dfg_sample(roughness_value: NodeRef, dot_nv: NodeRef) -> NodeRef {
    let lut = dfg_lut();
    texture_uv(&lut, join(Type::Vec2, vec![roughness_value, dot_nv])).xy()
}

// ---------------------------------------------------------------------------
// PhysicalLightingModel
// ---------------------------------------------------------------------------

/// `new PhysicalLightingModel( clearcoat, sheen, iridescence, anisotropy,
/// transmission, dispersion, retroreflection, diffuseRoughness )`.
/// Dispersion and retroreflection are still off for every material the
/// ladder builds; iridescence is `MeshPhysicalNodeMaterial.useIridescence`,
/// which `webgpu_loader_gltf_iridescence`'s lamp turns on;
/// `sheen` is `MeshPhysicalNodeMaterial.useSheen`, which
/// `webgpu_loader_gltf_sheen`'s fabric turns on, and clearcoat and anisotropy
/// are the two the barn lamp turns on.
pub struct Physical {
    /// `this.dfg` — `toConst( 'dfg' )`.
    pub dfg: NodeRef,
    /// `this.multiScatteringCompensation`.
    pub multi_scattering_compensation: NodeRef,
    /// `this.sheen`. Every sheen branch below is gated on it, and with it
    /// false the emitted WGSL is what it was before sheen existed.
    pub sheen: bool,
    /// `this.clearcoat` — the flag that gives the model its three clearcoat
    /// accumulators and the extra lobe in `indirectSpecular()` / `finish()`.
    pub clearcoat: bool,
    /// `this.diffuseRoughness` — `useDiffuseRoughness`: the three diffuse
    /// terms take the EON lobe instead of Lambert's.
    pub diffuse_roughness: bool,
    /// `this.iridescenceFresnel` — `mix( dielectric, metallic, metalness )`
    /// of the two `evalIridescence` results, read only by `direct()`; `None`
    /// when the material is not iridescent.
    pub iridescence_fresnel: Option<NodeRef>,
    /// `this.iridescenceF0Dielectric` — the F0 `computeMultiscattering`
    /// blends the dielectric path towards by `Iridescence`.
    pub iridescence_f0_dielectric: Option<NodeRef>,
    /// `this.iridescenceF0Metallic` — the same for the metallic path.
    pub iridescence_f0_metallic: Option<NodeRef>,
    /// `builder.context.backdrop` — `getIBLVolumeRefraction()`'s `vec4`, set
    /// by the transmission branch of `start()` and read once more where
    /// `LightsNode` blends it into `totalDiffuse`.
    pub backdrop: Option<NodeRef>,
}

impl Physical {
    /// `PhysicalLightingModel.start()`: the DFG lookup, the direct-light
    /// multi-scattering compensation and — with sheen or clearcoat — the
    /// lobes' accumulators, with iridescence the thin-film Fresnel and F0s,
    /// plus, with transmission, the screen-space backdrop. The first two are `toConst`, so they materialise where they
    /// are first used; the accumulators are `toVar` and so land here.
    pub fn start(
        sheen: bool,
        clearcoat: bool,
        diffuse_roughness: bool,
        iridescence: bool,
        opaque_frame: Option<&transmission::OpaqueFrame>,
        out: &mut Vec<NodeRef>,
    ) -> Self {
        if sheen {
            out.push(sheen_specular_direct().assign(vec3(0.0, 0.0, 0.0)));
            out.push(sheen_specular_indirect().assign(vec3(0.0, 0.0, 0.0)));
        }

        let (iridescence_fresnel, iridescence_f0_dielectric, iridescence_f0_metallic) =
            if iridescence {
                let (fresnel, f0_dielectric, f0_metallic) = iridescence_terms();
                (Some(fresnel), Some(f0_dielectric), Some(f0_metallic))
            } else {
                (None, None, None)
            };

        // The transmission branch runs before the DFG lookup, and its
        // `diffuseColor.a.mulAssign()` is what pulls the whole screen-space
        // read into the flow here rather than at `totalDiffuse`.
        let backdrop = opaque_frame.map(|frame| {
            let v = transmission::world_view_vector();
            // Three keeps the refraction result in a var (`nodeVar42`), which
            // both the `DiffuseColor.w` write below and `total_diffuse()` read;
            // without the var the whole bicubic expression is emitted twice.
            let backdrop = to_var(
                None,
                transmission::ibl_volume_refraction(
                    &frame.texture,
                    normal_world(),
                    v,
                    position_world(),
                    Self::environment_brdf,
                ),
            );
            out.push(diffuse_color().w().assign(diffuse_color().w().mul(mix(
                float(1.0),
                backdrop.clone().w(),
                transmission(),
            ))));
            backdrop
        });

        let dot_nv = normal_view().dot(position_view_direction()).clamp(0.0, 1.0);
        let dfg = dfg_sample(roughness(), dot_nv);

        // `Ess` — the energy of the single-scattering lobe in a white furnace.
        let ess = dfg.x().add(dfg.y());
        let multi_scattering_compensation = specular_color_blended()
            .mul(ess.reciprocal().sub(1.0))
            .add(1.0);

        // The three clearcoat accumulators are vars with a zero initialiser:
        // the var as a statement emits it, once (issue #281).
        if clearcoat {
            out.push(clearcoat_radiance());
            out.push(clearcoat_specular_direct());
            out.push(clearcoat_specular_indirect());
        }

        Self {
            dfg,
            multi_scattering_compensation,
            sheen,
            clearcoat,
            diffuse_roughness,
            iridescence_fresnel,
            iridescence_f0_dielectric,
            iridescence_f0_metallic,
            backdrop,
        }
    }

    /// `LightsNode.setup()`'s backdrop blend: with a backdrop the diffuse total
    /// is `mix( vec4( totalDiffuse, 1 ), backdrop, backdropAlpha ).xyz`, where
    /// the alpha is `Transmission`.
    pub fn total_diffuse(&self, direct_plus_indirect: NodeRef) -> NodeRef {
        match &self.backdrop {
            Some(backdrop) => mix(
                vec4_join(vec![direct_plus_indirect, float(1.0)]),
                backdrop.clone(),
                transmission(),
            )
            .xyz(),
            None => direct_plus_indirect,
        }
    }

    /// `PhysicalLightingModel.finish()` — the sheen lobe is added to the
    /// outgoing light after `setupLighting()` has summed the four
    /// accumulators, and the clearcoat branch then attenuates that base lobe
    /// by the coat's Fresnel and adds the coat's own specular on top.
    pub fn finish(&self, out: &mut Vec<NodeRef>) {
        if self.sheen {
            out.push(
                outgoing_light().assign(
                    outgoing_light()
                        .add(sheen_specular_direct())
                        .add(sheen_specular_indirect()),
                ),
            );
        }

        if self.clearcoat {
            let dot_nvcc = clearcoat_normal_view()
                .dot(position_view_direction())
                .clamp(0.0, 1.0);
            let fcc = phong::f_schlick(vec3(0.04, 0.04, 0.04), float(1.0), dot_nvcc);
            let value = outgoing_light().mul(clearcoat().mul(fcc).one_minus()).add(
                clearcoat_specular_direct()
                    .add(clearcoat_specular_indirect())
                    .mul(clearcoat()),
            );
            out.push(outgoing_light().assign(value));
        }
    }

    /// `EnvironmentBRDF( { dotNV, specularColor, specularF90, roughness } )` —
    /// the split-sum approximation over the DFG table.
    pub(crate) fn environment_brdf(
        dot_nv: NodeRef,
        specular_color_value: NodeRef,
        specular_f90_value: NodeRef,
        roughness_value: NodeRef,
    ) -> NodeRef {
        let fab = dfg_sample(roughness_value, dot_nv);
        specular_color_value
            .mul(fab.x())
            .add(specular_f90_value.mul(fab.y()))
    }

    /// `computeMultiscattering( singleScatter, multiScatter, specularF90, f0,
    /// iridescenceF0 )` — Fdez-Agüera's approximation, pushed as the two
    /// `addAssign`s three.js emits.
    fn compute_multiscattering(
        &self,
        single_scatter: NodeRef,
        multi_scatter: NodeRef,
        f0: NodeRef,
        iridescence_f0: Option<NodeRef>,
        out: &mut Vec<NodeRef>,
    ) {
        let fab = self.dfg.clone();

        // `const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) :
        // f0` — a fresh `mix` per call, which the dump shows as its own
        // `nodeConst` in each of the two paths.
        let f0 = match iridescence_f0 {
            Some(iridescence_f0) => mix(f0, iridescence_f0, iridescence()),
            None => f0,
        };

        let fss_ess = f0.clone().mul(fab.x()).add(specular_f90().mul(fab.y()));

        let ess = fab.x().add(fab.y());
        let ems = ess.one_minus();

        // `Favg = Fr + ( 1 - Fr ) * 1/21`.
        let favg = f0.clone().add(f0.one_minus().mul(0.047619));
        let fms = fss_ess
            .clone()
            .mul(favg.clone())
            .div(ems.clone().mul(favg).one_minus());

        out.push(single_scatter.clone().assign(single_scatter.add(fss_ess)));
        out.push(
            multi_scatter
                .clone()
                .assign(multi_scatter.add(fms.mul(ems))),
        );
    }

    /// `PhysicalLightingModel.direct( { lightDirection, lightColor } )`.
    pub fn direct(&self, light_direction: NodeRef, light_color: NodeRef, out: &mut Vec<NodeRef>) {
        let dot_nl = normal_view().dot(light_direction.clone()).clamp(0.0, 1.0);
        // `irradiance` is `.toVar()` in three; without sheen nothing assigns
        // to it again, so the port leaves it inline there and every already
        // green example generates exactly the WGSL it did before.
        // (Clearcoat does not assign to it either, but three's clearcoat pages
        // are the only ones that show the var, so it follows them there.)
        let irradiance = if self.sheen || self.clearcoat {
            to_var(None, dot_nl.mul(light_color.clone()))
        } else {
            dot_nl.mul(light_color.clone())
        };

        if self.sheen {
            out.push(
                sheen_specular_direct().assign(
                    sheen_specular_direct()
                        .add(irradiance.clone().mul(brdf_sheen(light_direction.clone()))),
                ),
            );

            // The view and the light each see their own sheen albedo here;
            // the energy taken is the larger of the two.
            let albedo_v = sheen_albedo();
            let albedo_l =
                ibl_sheen_brdf(normal_view(), light_direction.clone(), sheen_roughness());

            out.push(
                irradiance.clone().assign(
                    irradiance
                        .clone()
                        .mul(sheen_energy_comp(albedo_v.max(albedo_l))),
                ),
            );
        }

        if self.clearcoat {
            // `clearcoatF0` is `vec3( 0.04 )` and `clearcoatF90` `float( 1 )`.
            let dot_nlcc = clearcoat_normal_view()
                .dot(light_direction.clone())
                .clamp(0.0, 1.0);
            let cc_irradiance = dot_nlcc.mul(light_color);
            out.push(
                clearcoat_specular_direct().assign(clearcoat_specular_direct().add(
                    cc_irradiance.mul(brdf_ggx_on(
                        light_direction.clone(),
                        vec3(0.04, 0.04, 0.04),
                        float(1.0),
                        clearcoat_roughness(),
                        clearcoat_normal_view(),
                        None,
                    )),
                )),
            );
        }

        // glTF's `fresnel_mix`: light reflected by the specular interface is not
        // available to the diffuse layer.
        let half_dir = light_direction
            .clone()
            .add(position_view_direction())
            .normalize();
        let dot_vh = position_view_direction().dot(half_dir).clamp(0.0, 1.0);
        let f = phong::f_schlick(specular_color(), specular_f90(), dot_vh);

        let diffuse_brdf = if self.diffuse_roughness {
            brdf_eon(
                light_direction.clone(),
                diffuse_color().rgb(),
                diffuse_roughness(),
            )
            .mul(metalness().one_minus())
        } else {
            brdf_lambert(diffuse_contribution())
        };

        let specular_brdf = brdf_ggx_on(
            light_direction,
            specular_color_blended(),
            float(1.0),
            roughness(),
            normal_view(),
            self.iridescence_fresnel.clone(),
        );

        out.push(
            direct_diffuse().assign(
                direct_diffuse().add(irradiance.clone().mul(diffuse_brdf).mul(f.one_minus())),
            ),
        );
        out.push(
            direct_specular().assign(
                direct_specular().add(
                    irradiance
                        .mul(specular_brdf)
                        .mul(self.multi_scattering_compensation.clone()),
                ),
            ),
        );
    }

    /// `PhysicalLightingModel.indirectDiffuse()` — the irradiance that reaches
    /// the diffuse layer, minus the energy the specular lobe took.
    pub fn indirect_diffuse(&self, out: &mut Vec<NodeRef>) {
        out.push(single_scattering().assign(vec3(0.0, 0.0, 0.0)));
        out.push(multi_scattering().assign(vec3(0.0, 0.0, 0.0)));

        self.compute_multiscattering(
            single_scattering(),
            multi_scattering(),
            specular_color(),
            self.iridescence_f0_dielectric.clone(),
            out,
        );

        let diffuse_brdf = if self.diffuse_roughness {
            eon_diffuse_albedo().mul(RECIPROCAL_PI)
        } else {
            brdf_lambert(diffuse_contribution())
        };
        let diffuse = irradiance()
            .mul(diffuse_brdf)
            .mul(single_scattering().add(multi_scattering()).one_minus());

        let diffuse = if self.sheen {
            let diffuse = to_var(None, diffuse);

            // Not a `toVar` in three: the node is simply read twice, and the
            // builder gives a shared node a temp of its own.
            let albedo = sheen_albedo();
            out.push(
                sheen_specular_indirect().assign(
                    sheen_specular_indirect().add(
                        irradiance()
                            .mul(sheen())
                            .mul(albedo.clone())
                            .mul(RECIPROCAL_PI),
                    ),
                ),
            );

            out.push(
                diffuse
                    .clone()
                    .assign(diffuse.clone().mul(sheen_energy_comp(albedo))),
            );
            diffuse
        } else {
            diffuse
        };

        out.push(indirect_diffuse().assign(indirect_diffuse().add(diffuse)));
    }

    /// `PhysicalLightingModel.indirectSpecular()`: dielectric and metallic
    /// multi-scattering computed separately and mixed by metalness. With no
    /// environment both `radiance` and `iblIrradiance` stay zero, so the whole
    /// block contributes nothing — three.js emits it regardless, and so do we,
    /// because the zero has to reach the pixel through the same arithmetic.
    ///
    /// `environment_specular` false is `webgpu_postprocessing_ssr_denoise`'s
    /// patch of this method (`MeshBasicNodeMaterial::environment_specular`):
    /// `builder.context.radiance = vec3( 0 )`, so the specular term reads a
    /// zero vector rather than the `radiance` var, and on a clearcoat model
    /// `clearcoatRadiance.assign( vec3( 0 ) )` ahead of the clearcoat term.
    pub fn indirect_specular(
        &self,
        has_environment: bool,
        environment_specular: bool,
        out: &mut Vec<NodeRef>,
    ) {
        if self.sheen {
            out.push(
                sheen_specular_indirect().assign(
                    sheen_specular_indirect().add(
                        ibl_irradiance()
                            .mul(sheen())
                            .mul(sheen_albedo())
                            .mul(RECIPROCAL_PI),
                    ),
                ),
            );
        }

        if self.clearcoat && !environment_specular {
            out.push(clearcoat_radiance().assign(vec3(0.0, 0.0, 0.0)));
        }

        if self.clearcoat {
            let dot_nvcc = clearcoat_normal_view()
                .dot(position_view_direction())
                .clamp(0.0, 1.0);
            let clearcoat_env = Self::environment_brdf(
                dot_nvcc,
                vec3(0.04, 0.04, 0.04),
                float(1.0),
                clearcoat_roughness(),
            );
            out.push(clearcoat_specular_indirect().assign(
                clearcoat_specular_indirect().add(clearcoat_radiance().mul(clearcoat_env)),
            ));
        }

        out.push(single_scattering_dielectric().assign(vec3(0.0, 0.0, 0.0)));
        out.push(multi_scattering_dielectric().assign(vec3(0.0, 0.0, 0.0)));
        out.push(single_scattering_metallic().assign(vec3(0.0, 0.0, 0.0)));
        out.push(multi_scattering_metallic().assign(vec3(0.0, 0.0, 0.0)));

        self.compute_multiscattering(
            single_scattering_dielectric(),
            multi_scattering_dielectric(),
            specular_color(),
            self.iridescence_f0_dielectric.clone(),
            out,
        );
        self.compute_multiscattering(
            single_scattering_metallic(),
            multi_scattering_metallic(),
            diffuse_color().rgb(),
            self.iridescence_f0_metallic.clone(),
            out,
        );

        // `radiance` / `iblIrradiance` are `vec3().toVar()` on the lighting
        // context, declared at their first use. With an environment that use
        // is `EnvironmentNode.setup()`, which runs as a lighting node before
        // `indirectSpecular` and so carries the zeros with it; with none,
        // nothing ever adds to them and they are declared here.
        // Both are vars with a zero initialiser, so the var as a statement is
        // the declaration (issue #281). With the page's patch the context's
        // `radiance` is the constant, so with no environment the var is never
        // read and never declared.
        if !has_environment {
            if environment_specular {
                out.push(radiance());
            }
            out.push(ibl_irradiance());
        }

        let single_scattering_mixed = mix(
            single_scattering_dielectric(),
            single_scattering_metallic(),
            metalness(),
        );
        let multi_scattering_mixed = mix(
            multi_scattering_dielectric(),
            multi_scattering_metallic(),
            metalness(),
        );

        let cosine_weighted_irradiance = ibl_irradiance().mul(RECIPROCAL_PI);

        let radiance = if environment_specular {
            radiance()
        } else {
            vec3(0.0, 0.0, 0.0)
        };
        let indirect_specular_value = radiance
            .mul(single_scattering_mixed)
            .add(multi_scattering_mixed.mul(cosine_weighted_irradiance.clone()));

        // Diffuse energy conservation uses the dielectric path.
        let total_scattering_dielectric =
            single_scattering_dielectric().add(multi_scattering_dielectric());
        let diffuse_albedo = if self.diffuse_roughness {
            eon_diffuse_albedo()
        } else {
            diffuse_contribution()
        };
        let diffuse = diffuse_albedo.mul(total_scattering_dielectric.one_minus());
        let indirect_diffuse_value = diffuse.mul(cosine_weighted_irradiance);

        let (indirect_specular_value, indirect_diffuse_value) = if self.sheen {
            // Both are `.toVar()` in three, so that the sheen energy
            // compensation can multiply them in place.
            let specular = to_var(None, indirect_specular_value);
            let diffuse = to_var(None, indirect_diffuse_value);

            let comp = sheen_energy_comp(sheen_albedo());
            out.push(specular.clone().assign(specular.clone().mul(comp.clone())));
            out.push(diffuse.clone().assign(diffuse.clone().mul(comp)));

            (specular, diffuse)
        } else {
            (indirect_specular_value, indirect_diffuse_value)
        };

        out.push(indirect_specular().assign(indirect_specular().add(indirect_specular_value)));
        out.push(indirect_diffuse().assign(indirect_diffuse().add(indirect_diffuse_value)));
    }

    /// `PhysicalLightingModel.ambientOcclusion()`.
    ///
    /// `has_ao_node` says whether an `AONode` already ran as a lighting node
    /// and so already declared the `ambientOcclusion` var — three builds it as
    /// `float( 1 ).toVar( 'ambientOcclusion' )`, whose initialiser is emitted
    /// at its *first* read, and with an `aoMap` that read is `AONode`'s
    /// `mulAssign`, not this method.
    pub fn ambient_occlusion(&self, has_ao_node: bool, out: &mut Vec<NodeRef>) {
        if !has_ao_node {
            out.push(ambient_occlusion().assign(float(1.0)));
        }

        if self.sheen {
            out.push(
                sheen_specular_indirect()
                    .assign(sheen_specular_indirect().mul(ambient_occlusion())),
            );
        }

        if self.clearcoat {
            out.push(
                clearcoat_specular_indirect()
                    .assign(clearcoat_specular_indirect().mul(ambient_occlusion())),
            );
        }

        out.push(indirect_diffuse().assign(indirect_diffuse().mul(ambient_occlusion())));

        let dot_nv = normal_view().dot(position_view_direction()).clamp(0.0, 1.0);
        let ao_nv = dot_nv.add(ambient_occlusion());
        let ao_exp = roughness().mul(-16.0).one_minus().negate().exp2();
        let ao_node = ambient_occlusion()
            .sub(ao_nv.pow(ao_exp).one_minus())
            .clamp(0.0, 1.0);

        out.push(indirect_specular().assign(indirect_specular().mul(ao_node)));
    }
}

/// `BRDF_Lambert( { diffuseColor } )`.
pub fn brdf_lambert(diffuse: NodeRef) -> NodeRef {
    diffuse.mul(RECIPROCAL_PI)
}

/// One light of `LightsNode`'s list through `PhysicalLightingModel`: the
/// ambient and hemisphere lights add to `irradiance`, the analytic ones go
/// through `direct()` with `LightNode.setup()`'s direction/colour pair.
pub(crate) fn direct_light(
    model: &Physical,
    light: &LightDesc,
    received_shadow_position: Option<&NodeRef>,
    out: &mut Vec<NodeRef>,
) {
    if let Some((light_direction, light_color)) =
        phong::setup_light(light, received_shadow_position, out)
    {
        model.direct(light_direction, light_color, out);
    }
}

// ---------------------------------------------------------------------------
// iridescence — `PhysicalLightingModel.js`' thin-film block
// ---------------------------------------------------------------------------

/// The iridescence branch of `PhysicalLightingModel.start()`: two
/// `evalIridescence` calls (over `specularColor` and `diffuseColor.rgb`) at
/// `dotNVi`, returned as `( iridescenceFresnel, iridescenceF0Dielectric,
/// iridescenceF0Metallic )`. Nothing here is a `toVar`, so none of it is
/// emitted until something reads it: with no light that is
/// `computeMultiscattering`, and `iridescenceFresnel` never reaches the
/// shader at all.
#[inline(never)]
fn iridescence_terms() -> (NodeRef, NodeRef, NodeRef) {
    let dot_nvi = normal_view().dot(position_view_direction()).clamp(0.0, 1.0);
    let eval = |base_f0: NodeRef| {
        call(
            &eval_iridescence(),
            vec![
                float(1.0),
                iridescence_ior(),
                dot_nvi.clone(),
                iridescence_thickness(),
                base_f0,
            ],
        )
    };
    let dielectric = eval(specular_color());
    let metallic = eval(diffuse_color().rgb());
    let fresnel = mix(dielectric.clone(), metallic.clone(), metalness());
    let f0_dielectric = schlick_to_f0(dielectric, float(1.0), dot_nvi.clone());
    let f0_metallic = schlick_to_f0(metallic, float(1.0), dot_nvi);
    (fresnel, f0_dielectric, f0_metallic)
}

/// `XYZ_TO_REC709`: three's row-major `mat3( … )` arguments, written out in
/// the column-major order WGSL's `mat3x3<f32>` constructor takes, which is
/// how the dump prints it.
fn xyz_to_rec709() -> NodeRef {
    join(
        Type::Mat3,
        vec![
            float(3.2404542),
            float(-0.9692660),
            float(0.0556434),
            float(-1.5371385),
            float(1.8760108),
            float(-0.2040259),
            float(-0.4985314),
            float(0.0415560),
            float(1.0572252),
        ],
    )
}

/// `Fresnel0ToIor( fresnel0 )` — `( 1 + sqrt( F0 ) ) / ( 1 - sqrt( F0 ) )`,
/// the IOR of an air-bounded dielectric with that normal-incidence
/// reflectance. Three does not handle `fresnel0 == 1`; its one caller clamps
/// to 0.9999 first.
fn fresnel0_to_ior(fresnel0: NodeRef) -> NodeRef {
    let sqrt_f0 = sqrt(fresnel0);
    vec3(1.0, 1.0, 1.0)
        .add(sqrt_f0.clone())
        .div(vec3(1.0, 1.0, 1.0).sub(sqrt_f0))
}

/// `IorToFresnel0( transmittedIor, incidentIor )` —
/// `( ( t - i ) / ( t + i ) ).pow2()`, which the builder emits as the ratio
/// in a temp of its own times itself.
fn ior_to_fresnel0(transmitted_ior: NodeRef, incident_ior: NodeRef) -> NodeRef {
    let r = transmitted_ior
        .clone()
        .sub(incident_ior.clone())
        .div(transmitted_ior.add(incident_ior));
    r.clone().mul(r)
}

/// `evalSensitivity( OPD, shift )` — Belcour and Barla's Fourier-space fit of
/// the XYZ colour matching functions, converted to linear sRGB. A plain JS
/// function in three, so it is inlined at its one use inside the `m` loop.
#[inline(never)]
fn eval_sensitivity(opd: NodeRef, shift: NodeRef) -> NodeRef {
    use std::f64::consts::PI;
    // `2 * PI * 1e-9` — the OPD is in nanometres.
    let phase = opd.mul(2.0 * PI * 1.0e-9);
    let val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);
    let pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);
    let var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);

    // The fourth, wider Gaussian, which only x carries. Its amplitude is
    // folded on the CPU, exactly as three writes it.
    let x = float(9.7470e-14 * (2.0 * PI * 4.5282e+09).sqrt())
        .mul(phase.clone().mul(2.2399e+06).add(shift.x()).cos())
        .mul(exp(phase.clone().mul(phase.clone()).mul(-4.5282e+09)));

    let xyz = val
        .mul(sqrt(var.clone().mul(2.0 * PI)))
        .mul(pos.mul(phase.clone()).add(shift).cos())
        .mul(exp(phase.clone().mul(phase).negate().mul(var)));
    let xyz = join(
        Type::Vec3,
        vec![xyz.clone().x().add(x), xyz.clone().y(), xyz.z()],
    )
    .div(1.0685e-7);

    xyz_to_rec709().mul(xyz)
}

/// `evalIridescence( { outsideIOR, eta2, cosTheta1, thinFilmThickness,
/// baseF0 } )` — the Airy-summed reflectance of a thin film over a base with
/// the given F0. Three gives it a layout, so it is a real WGSL `fn`, early
/// `return` and `m` loop included (`docs/nodes.md` §95).
fn eval_iridescence() -> Rc<FnDef> {
    thread_local! { static CELL: crate::nodes::node::Lazy<Rc<FnDef>> = const { crate::nodes::node::Lazy::new() }; }
    CELL.with(|c| {
        c.get(|| {
            shader_fn(
                Some("evalIridescence"),
                vec![
                    ("outsideIOR", Type::F32),
                    ("eta2", Type::F32),
                    ("cosTheta1", Type::F32),
                    ("thinFilmThickness", Type::F32),
                    ("baseF0", Type::Vec3),
                ],
                Type::Vec3,
                eval_iridescence_body,
            )
        })
    })
}

/// The body of [`eval_iridescence`], statement for statement off three's
/// `evalIridescence`.
#[inline(never)]
fn eval_iridescence_body(args: &[NodeRef]) -> NodeRef {
    use std::f64::consts::PI;
    let (outside_ior, eta2, cos_theta1, thin_film_thickness, base_f0) = (
        args[0].clone(),
        args[1].clone(),
        args[2].clone(),
        args[3].clone(),
        args[4].clone(),
    );

    // Force the film's IOR to the outside medium's as the thickness
    // vanishes, so a zero-thickness film is a no-op.
    let iridescence_ior_value = mix(
        outside_ior.clone(),
        eta2,
        smoothstep(0.0, 0.03, thin_film_thickness.clone()),
    );

    // `cosTheta` on the base layer, by Snell's law.
    let eta = outside_ior.clone().div(iridescence_ior_value.clone());
    let sin_theta2_sq = eta
        .clone()
        .mul(eta)
        .mul(cos_theta1.clone().mul(cos_theta1.clone()).one_minus());
    let cos_theta2_sq = sin_theta2_sq.one_minus();

    // Total internal reflection: everything comes back.
    let tir = if_then(
        cos_theta2_sq.clone().less_than(float(0.0)),
        vec![return_statement(vec3(1.0, 1.0, 1.0))],
    );

    let cos_theta2 = sqrt(cos_theta2_sq);

    // First interface.
    let r0 = ior_to_fresnel0(iridescence_ior_value.clone(), outside_ior.clone());
    let r12 = phong::f_schlick(r0, float(1.0), cos_theta1);
    let t121 = r12.clone().one_minus();
    let phi12 = iridescence_ior_value
        .clone()
        .less_than(outside_ior)
        .select(float(PI), float(0.0));
    let phi21 = float(PI).sub(phi12);

    // Second interface; the 0.9999 guard keeps `Fresnel0ToIor` finite.
    let base_ior = fresnel0_to_ior(base_f0.clamp(0.0, 0.9999));
    let r1 = ior_to_fresnel0(
        base_ior.clone(),
        iridescence_ior_value.clone().to(Type::Vec3),
    );
    let r23 = phong::f_schlick(r1, float(1.0), cos_theta2.clone());
    let pi_or_zero = |c: NodeRef| {
        c.less_than(iridescence_ior_value.clone())
            .select(float(PI), float(0.0))
    };
    let phi23 = join(
        Type::Vec3,
        vec![
            pi_or_zero(base_ior.clone().x()),
            pi_or_zero(base_ior.clone().y()),
            pi_or_zero(base_ior.z()),
        ],
    );

    // Phase shift: `iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 )`.
    let opd = iridescence_ior_value
        .mul(thin_film_thickness)
        .mul(cos_theta2)
        .mul(2.0);
    let phi = phi21.to(Type::Vec3).add(phi23);

    // Compound terms.
    let r123 = r12.clone().mul(r23.clone()).clamp(1e-5, 0.9999);
    let r123_sqrt = sqrt(r123.clone());
    let rs = t121
        .clone()
        .mul(t121.clone())
        .mul(r23)
        .div(vec3(1.0, 1.0, 1.0).sub(r123));

    // m = 0, the DC term.
    let i = to_var(None, r12.add(rs.clone()));
    // m > 0, the pairs of diracs:
    // `Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, … )`.
    let cm = to_var(None, rs.sub(t121));

    let body = {
        let (i, cm) = (i.clone(), cm.clone());
        loop_options("m", Type::I32, int(1), int(2), "<=", move |m| {
            let m = m.to(Type::F32);
            let sm = eval_sensitivity(m.clone().mul(opd), m.mul(phi)).mul(2.0);
            vec![
                cm.clone().assign(cm.clone().mul(r123_sqrt)),
                i.clone().assign(i.clone().add(cm.mul(sm))),
            ]
        })
    };

    // `toVar()` writes its initial value where the JS calls it, ahead of the
    // loop; the port's var would otherwise be first written at its first
    // read, inside the loop body, and reset on every iteration.
    let declarations = vec![i.clone(), cm.clone()];

    // Out-of-gamut colours can come out negative; clamp them.
    let mut statements = vec![tir];
    statements.extend(declarations);
    statements.push(body);
    block(statements, max(i, vec3(0.0, 0.0, 0.0)))
}