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
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
//! Port of `three.js/src/materials/nodes/NodeMaterial.js` — `setup()` and the
//! `setupX()` methods it dispatches to. This is where a material turns into the
//! statements the builder flows into the two shader stages.

use super::environment;
use super::fields::{Field, Flow};
use super::phong::{self, LightDesc};
use super::physical::{self, Physical};
use super::toon;
use super::transmission;
use super::{Blending, MaterialKind, MeshBasicNodeMaterial, Side, ToneMapping};
use crate::lights::LightKind;
use crate::nodes::node::{Type, UniformGroup, UniformSource};
use crate::nodes::tsl::FogNode;
use crate::nodes::tsl::*;
use crate::nodes::{MaterialFlow, NodeRef};

/// The per-render-object facts three.js reads off `builder.object` and
/// `builder.geometry` during setup.
///
/// `Hash` is the scene-dependent half of the render object's cache key —
/// `RenderObject.getDynamicCacheKey()`: the lights (with their shadow maps),
/// the instancing branch and the morph entry. Everything `setup()` reads that
/// is not on the material is here, so the derived hash is complete by
/// construction: a field added to this struct is in the key.
#[derive(Clone, Debug, Default, Hash)]
#[doc(hidden)]
pub struct SetupContext {
    /// `scene.environmentNode` — the scene-level environment map, which
    /// `NodeMaterial.setupEnvironment()` falls back to when the material has
    /// no `envNode` of its own. `None` for every pass that is not a scene
    /// draw (the background quad, the shadow pass, `render_quad`).
    pub environment: Option<environment::Environment>,
    /// `Some(count)` when the object is an `InstancedMesh`, which is what makes
    /// `NodeMaterial.setupPosition()` insert the `InstanceNode` transform.
    pub instance_count: Option<usize>,
    /// `InstancedMesh.instanceColor` is present, so `range()` resolves against
    /// the instance index.
    pub instanced: bool,
    /// `Some(count)` when the object is an `InstancedMesh` that has had
    /// `setColorAt()` called on it — `NodeMaterial.setupDiffuseColor()`'s
    /// `if ( object.instanceColor )` branch. The count sizes the instanced
    /// vertex buffer; the colours themselves travel with the draw, not with
    /// the node, so two meshes sharing a material cannot share a fill.
    pub instance_color: Option<usize>,
    /// The pass' lights in `Scene.lights` order — the default `LightsNode` list
    /// when the material sets no `lights_node`. Each entry carries the light's
    /// kind and, when this object receives its shadow, the shadow map to sample;
    /// both change the generated code, so they are part of the program's cache
    /// key by construction.
    pub lights: Vec<LightDesc>,
    /// `getEntry( geometry )` when the geometry has morph attributes: what
    /// `NodeMaterial.setupPosition()` needs to emit `morphReference()`.
    pub morph: Option<crate::nodes::morph::MorphEntry>,
    /// `Some` when the object is a `SkinnedMesh` with a skeleton, which is what
    /// makes `NodeMaterial.setupPosition()` insert `skinning( object )`.
    pub skin: Option<crate::nodes::skinning::SkinEntry>,
    /// `object.isBatchedMesh`: the three data textures `batch()` reads.
    pub batch: Option<crate::nodes::batch::BatchEntry>,
    /// `object.center && object.center.isVector2` — the object is a `Sprite`,
    /// so `SpriteNodeMaterial.setupPositionView()` offsets the quad by
    /// `center - 0.5`. A `SpriteNodeMaterial` on anything else (the
    /// instanced-mesh particles of `webgpu_compute_particles_*`) has no
    /// `center` and skips the step, which changes the WGSL.
    pub sprite: bool,
    /// `renderer.getMRT()` and the names of the bound render target's colour
    /// attachments — the pass-level half of `NodeMaterial.setup()`'s MRT
    /// branch, which only runs `if ( renderTarget !== null )`.
    ///
    /// `None` is every draw into a single-attachment target, and leaves the
    /// fragment stage's `OutputStruct { color }` shape alone.
    pub mrt: Option<MrtContext>,
    /// `geometry.getAttribute( 'color' ).itemSize` —
    /// `VertexColorNode.generate()`'s
    /// `builder.getTypeFromAttribute( geometryAttribute )`. 4 is glTF `COLOR_0`
    /// as `VEC4` and is read whole; anything else — including 0, a geometry
    /// with no `color` attribute — takes the three-component form, widened to a
    /// `vec4` with an alpha of 1. It is part of the program's cache key,
    /// because it changes the vertex attribute's WGSL type.
    pub vertex_color_size: usize,
    /// `builder.renderer.lighting.enabled === false` — the pass was rendered
    /// with its lighting disabled (`PassNode`'s `lighting: false`), so
    /// `NodeMaterial.setupLighting()`'s `sceneLighting` is false: the material
    /// collects no `materialLightings` (the environment among them) and, with
    /// an empty `LightsNode`, emits no lighting chain at all — the outgoing
    /// light is the diffuse colour. `webgpu_deferred`'s G-buffer pass is that
    /// case. The sense is inverted so that `Default` (every ordinary pass)
    /// stays "lighting enabled".
    pub lighting_disabled: bool,
    /// `builder.geometry.attributes.normal === undefined` —
    /// `getGeometryRoughness()` returns `float( 0 )` for a geometry with no
    /// normal attribute instead of the `dFdx`/`dFdy` term, because the
    /// derivative would be taken of a constant. `webgpu_deferred`'s resolve
    /// quad is exactly that case: a `MeshStandardNodeMaterial` on the
    /// two-attribute quad geometry. It changes the generated WGSL, so it
    /// belongs in the dynamic cache key.
    pub geometry_missing_normal: bool,
    /// `builder.geometry.hasAttribute( 'tangent' )`. A glTF primitive with a
    /// `TANGENT` accessor gets three's attribute tangent frame; anything else
    /// gets the screen-derivative one. It changes both stages' code, so it is
    /// part of the program's cache key.
    pub has_tangent_attribute: bool,
    /// `builder.geometry.attributes` — each attribute's name, typed-array
    /// kind, item size, `normalized`, step mode and interleaved layout, from
    /// [`BufferGeometry::attribute_descs`](crate::core::BufferGeometry::attribute_descs).
    /// `AttributeNode` declares its vertex input in the attribute's own type
    /// and the pipeline reads it in the attribute's own format, so both the
    /// WGSL and the vertex layout depend on it, and it is in the key.
    pub geometry_attributes: Vec<crate::core::AttributeDesc>,
    /// `viewportOpaqueMipTexture()` — the renderer's mipped copy of the frame
    /// as it stood when the last opaque object had been drawn, which is what a
    /// transmissive material reads through. `None` on every pass that makes no
    /// copy, which takes the transmission branch out of the shader entirely.
    pub viewport_opaque_mip: Option<transmission::OpaqueFrame>,
    /// `builder.context.getOutput` — the renderer's context node, which
    /// `DirectRenderPipeline` sets so that the output transform is applied
    /// **inside every material's fragment shader** instead of in a quad of its
    /// own. See [`OutputContext`].
    pub output: Option<OutputContext>,
    /// `camera.cameras.length` when the pass is drawn through an
    /// `ArrayCamera` (0 otherwise) — `RenderObject.getCacheKey()`'s
    /// `camera.isArrayCamera ? camera.cameras.length : 0`. It sizes the
    /// camera matrix arrays and moves the object group to `@group( 2 )`, so
    /// it is part of the program's cache key. `docs/nodes.md` §40.
    pub array_cameras: usize,
    /// `builder.camera.isOrthographicCamera` — the camera the pass is drawn
    /// through (the shadow camera for a shadow pass). `positionViewDirection`
    /// is the constant `vec3( 0, 0, 1 )` under an orthographic camera and the
    /// normalized `-positionView` otherwise, so it changes the generated WGSL
    /// of every lit material and is part of the program's cache key, beside
    /// `array_cameras`.
    pub orthographic: bool,
    /// `builder.context.getAO` — the pass's `builtinAOContext( aoNode )`,
    /// which every non-transparent material drawn by that pass multiplies into
    /// its `AmbientOcclusion`. See [`AoContext`].
    pub ambient_occlusion: Option<AoContext>,
    /// `builder.clippingContext` — the planes of the `ClippingGroup`s above
    /// the object. Its plane *counts* and whether the device clips in
    /// hardware change the generated WGSL; the plane values do not, and stay
    /// out of the key (see [`ClippingContext`]'s `Hash`).
    ///
    /// [`ClippingContext`]: crate::nodes::clipping::ClippingContext
    #[doc(hidden)]
    pub clipping: Option<std::rc::Rc<crate::nodes::clipping::ClippingContext>>,
}

impl SetupContext {
    /// `builder.hasGeometryAttribute( name )`, over
    /// [`geometry_attributes`](Self::geometry_attributes).
    pub(crate) fn has_geometry_attribute(&self, name: &str) -> bool {
        self.geometry_attributes
            .iter()
            .any(|desc| desc.name == name)
    }
}

/// `builtinAOContext( aoNode )` — the `getAO` hook a pass installs on the
/// renderer's context node (`passNode.contextNode = builtinAOContext( ao )`).
///
/// three.js passes a closure:
///
/// ```js
/// getAO: ( inputNode, { material } ) => {
///     if ( material.transparent === true ) return inputNode;
///     return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
/// }
/// ```
///
/// where `inputNode` is the material's own `aoNode` (`materialAO` with an
/// `aoMap`, otherwise `null`). The closure's body is fixed, so what travels
/// here is only `aoNode`; `NodeMaterial.setupAmbientOcclusion()`'s port
/// applies the closure itself.
///
/// It is part of `SetupContext`, so it is part of the program's cache key by
/// construction, keyed on the node's identity exactly like [`OutputContext`].
#[derive(Clone, Debug)]
#[doc(hidden)]
pub struct AoContext {
    pub node: NodeRef,
}

impl std::hash::Hash for AoContext {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.node.key().hash(state);
    }
}

/// `context.getOutput( materialOutputNode, builder )`.
///
/// three.js passes a closure, which can look at the builder and hand the
/// material's own output straight back when the draw is not going to the
/// output target. The port makes that decision on the renderer instead — the
/// hook only ever reaches a material that is being drawn into the canvas, so
/// what travels here is just the node the closure would return: the
/// pipeline's `outputNode`, already wrapped in `renderOutput( …, toneMapping,
/// outputColorSpace )`, reading the material's result back through the
/// `Output` property (`output_property()`).
///
/// It is part of `SetupContext`, so it is part of the program's cache key by
/// construction, which is what keeps a material drawn with the hook and the
/// same material drawn without it on two different programs.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub struct OutputContext {
    pub node: NodeRef,
}

impl std::hash::Hash for OutputContext {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.node.key().hash(state);
    }
}

/// What a draw into an MRT render target knows about it: the pass's MRT node
/// (`renderer.getMRT()`) and `renderTarget.textures.map( t => t.name )`, which
/// is what `MRTNode.setup()` resolves its output names against.
#[derive(Clone, Debug, Default, Hash)]
#[doc(hidden)]
pub struct MrtContext {
    pub node: crate::nodes::MrtNode,
    pub attachments: Vec<String>,
    /// `builder.getOutputType( index )` per attachment — the type
    /// `MRTNode.setup()` converts that member to. Empty is `vec4` for every
    /// attachment, which is every `RGBAFormat` target.
    pub output_types: Vec<crate::nodes::Type>,
}

impl MrtContext {
    /// `node` over `render_target`, as the renderer resolves it for a render
    /// into that target: its attachment names, and `getOutputType( index )`
    /// for each attachment ([`RenderTarget::output_types`]).
    ///
    /// [`RenderTarget::output_types`]: crate::renderer::RenderTarget::output_types
    pub fn for_target(
        node: crate::nodes::MrtNode,
        render_target: &crate::renderer::RenderTarget,
    ) -> Self {
        Self {
            node,
            attachments: render_target.attachment_names(),
            output_types: render_target.output_types(),
        }
    }
}

/// `Renderer._getShadowNodes( material )` composed with
/// `ShadowBaseNode._getShadowMaterial()`: the per-object shadow-pass material.
///
/// three.js mutates one shared `ShadowMaterial` per light in place; the port
/// builds a fresh material per object instead, which is the same thing because
/// the program is keyed on the generated WGSL.
#[doc(hidden)]
pub fn shadow_material(source: &MeshBasicNodeMaterial) -> MeshBasicNodeMaterial {
    shadow_material_for(source, crate::lights::ShadowMapType::Pcf)
}

/// [`shadow_material`] for a given `renderer.shadowMap.type`.
/// `Renderer._renderObjectDirect`'s override differs by one line:
///
/// ```js
/// if ( this.shadowMap.type === VSMShadowMap ) {
///     overrideMaterial.side = material.shadowSide ?? material.side;
/// } else {
///     overrideMaterial.side = material.shadowSide ?? _shadowSide[ material.side ];
/// }
/// ```
///
/// — VSM draws the faces the material itself draws, where every other type
/// draws the opposite ones. (The port has no `material.shadowSide`; it is
/// always `null` on the ladder.)
#[doc(hidden)]
pub fn shadow_material_for(
    source: &MeshBasicNodeMaterial,
    shadow_type: crate::lights::ShadowMapType,
) -> MeshBasicNodeMaterial {
    let mut material = MeshBasicNodeMaterial::new();
    material.name = "ShadowMaterial";
    material.blending = Blending::No;
    material.fog = false;
    // `overrideMaterial.transparent = material.transparent`, and
    // `_shadowSide[ material.side ]` — the shadow pass draws the *back* faces
    // of a front-sided material, which is where the shadow pipelines'
    // `frontFace: cw` comes from.
    material.transparent = source.transparent;
    material.side = match (shadow_type.resolved(), source.side) {
        (crate::lights::ShadowMapType::Vsm, side) => side,
        (_, Side::Front) => Side::Back,
        (_, Side::Back) => Side::Front,
        // `_shadowSide = { [ DoubleSide ]: DoubleSide }`.
        (_, Side::Double) => Side::Double,
    };

    // `shadowRGB = vec3( 0 )`, `shadowAlpha = float( 1 )` — or the
    // `castShadowNode`'s `.rgb` / `.a` — and the source material's own colour
    // only contributes its alpha.
    let cast = &source.cast_shadow_node;
    material.color_node = Some(
        match (&source.color_node, &source.map, &source.mask_node, cast) {
            // `hasMap || hasColorNode || hasCastShadowNode || hasMaskNode` is
            // false: the override material keeps its own `vec4( 0, 0, 0, 1 )`,
            // which is a flat four-component constant rather than a join.
            (None, None, None, None) => vec4(0.0, 0.0, 0.0, 1.0),
            (color, map, _, cast) => {
                // `castShadowNode.a` of a `vec3` is `vec4( node, 1 ).w`, as
                // three's `.a` on a three-component node emits it.
                let (rgb, alpha) = match cast {
                    Some(cast) => (cast.clone().rgb(), to_vec4(cast.clone()).w()),
                    None => (vec3(0.0, 0.0, 0.0), float(1.0)),
                };
                // The colour node's alpha when there is one, else the map's.
                let alpha = match (color, map) {
                    (Some(color), _) => alpha.mul(to_vec4(color.clone()).w()),
                    (None, Some(map)) => alpha.mul(texture(map).a()),
                    (None, None) => alpha,
                };
                vec4_join(vec![rgb, alpha])
            }
        },
    );
    // `overrideMaterial.alphaTest = material.alphaTest` and `.alphaMap =
    // material.alphaMap`: a cut-away texel casts no shadow.
    material.alpha_test = source.alpha_test;
    material.alpha_map = source.alpha_map.clone();
    // `Fn( ( [ color ] ) => { maskNode.not().discard(); return color; } )`.
    material.mask_node = source.mask_node.clone();
    material
}

/// `materialOpacity` — `MaterialNode.OPACITY`: the `opacity` uniform, times
/// `texture( alphaMap )` when the material has one. The product is a `vec4`
/// (three multiplies by the whole texel, not its green channel), and the
/// `DiffuseColor.w` assign narrows it back to `.x`.
fn material_opacity_for(material: &MeshBasicNodeMaterial) -> NodeRef {
    match &material.alpha_map {
        Some(map) => material_opacity().mul(texture(map)),
        None => material_opacity(),
    }
}

/// `vec4( node )` the way `setupDiffuseColor` builds it: a scalar splats, a
/// `vec3` gains an alpha of 1, a `vec4` passes through.
fn to_vec4(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec4 => node,
        Type::Vec3 => vec4_join(vec![node, float(1.0)]),
        _ => node.to(Type::Vec4),
    }
}

/// `NodeMaterial.setupDiffuseColor()` — the step every lighting model shares.
///
/// `materialColor` is `MaterialNode.COLOR`, which is the material's colour
/// *times the map's texel* when the material has one (`MaterialNode.js:126`):
/// that is why `DiffuseColor` is assigned a `vec4` product rather than a `vec3`
/// promoted to one, and why an unlit `MeshBasicNodeMaterial { map }` is
/// textured on exactly the same terms as a Standard one. A `colorNode`
/// replaces the pair outright, map included —
/// `this.colorNode ? vec4( this.colorNode ) : materialColor`.
fn setup_diffuse_color(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fragment: &mut Vec<NodeRef>,
) {
    let color = match &material.color_node {
        // A deferred `Fn()` colour runs here, in this material's context
        // (see `resolve_fn_call`).
        Some(node) => to_vec4(resolve_fn_call(node)),
        // `materialColor` is a vec3 (times `map` when there is one) and stays
        // one until `diffuseColor.assign()` widens it, which is what puts the
        // `vec4<f32>( … , 1.0 )` on the outside of the instance-colour product
        // rather than around the uniform alone.
        None => {
            let base = material_color();
            match &material.map {
                Some(map) => base.mul(texture(map)),
                None => base,
            }
        }
    };

    // `if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) )
    // colorNode = colorNode.mul( vertexColor() )` — the same step for every
    // lighting model, which is what lets one `LineSegments` carry a hue per
    // vertex. See `vertex_color()` for the `hasAttribute` half.
    // `Line2NodeMaterial` is the exception: a `LineSegmentsGeometry` has no
    // `color` attribute (it carries `instanceColorStart` / `instanceColorEnd`),
    // so three's `geometry.hasAttribute( 'color' )` is false and the base
    // multiply is skipped. Its own `setupDiffuseColor()` selects the colour per
    // end instead — see [`crate::materials::line2::setup_diffuse_color`].
    let color = match material.vertex_colors && material.kind != MaterialKind::Line2 {
        true => color.mul(vertex_color(ctx.vertex_color_size)),
        false => color,
    };

    // `if ( object.instanceColor ) colorNode = instanceColor.mul( colorNode )`
    // — the varying multiplies on the *left*, which is what puts
    // `vInstanceColor` first in the dump's `DiffuseColor = vec4<f32>( (
    // vInstanceColor * object.nodeUniform2 ), 1.0 )`.
    let color = match ctx.instance_color {
        Some(count) => instance_color(count).mul(color),
        None => color,
    };

    // `if ( object.isBatchedMesh && object._colorsTexture )
    // colorNode = batchColor.mul( colorNode )` — the varying is the *left*
    // operand, which is what puts `vBatchColor` first in the generated line.
    // three.js runs this after the instanced-colour step, so the port does too.
    let color = match ctx.batch.as_ref().and_then(|b| b.colors.as_ref()) {
        Some(_) => crate::nodes::batch::batch_color().mul(color),
        None => color,
    };

    fragment.push(diffuse_color().assign(color));

    // `const opacityNode = this.opacityNode ? float( this.opacityNode ) :
    // materialOpacity` — a node *replaces* the uniform rather than scaling it,
    // so a material with an `opacityNode` never reads `material.opacity`.
    let opacity = match &material.opacity_node {
        Some(node) => to_float(node.clone()),
        None => material_opacity_for(material),
    };
    fragment.push(diffuse_color().w().assign(diffuse_color().w().mul(opacity)));

    // `if ( this.alphaTestNode !== null || this.alphaTest > 0 )
    // diffuseColor.a.lessThanEqual( alphaTestNode ).discard()`. It is *after*
    // the opacity multiply and *before* the opaque clamp, so the alpha the test
    // sees is the one the opacity node produced, and the fragments that survive
    // still get `w = 1.0` on an opaque material — the alpha-test teapot is not
    // `transparent`, and the dump shows both lines.
    let alpha_test = match &material.alpha_test_node {
        Some(node) => Some(to_float(node.clone())),
        None if material.alpha_test > 0.0 => Some(material_alpha_test()),
        None => None,
    };
    if let Some(alpha_test) = alpha_test {
        fragment.push(if_then(
            diffuse_color().w().less_than_equal(alpha_test),
            vec![discard()],
        ));
    }

    // `if ( this.alphaHash === true ) diffuseColor.a.lessThan(
    // getAlphaHashThreshold( positionLocal ) ).discard()` — after the alpha
    // test, before the opaque clamp. `lessThan`, where the alpha test is
    // `lessThanEqual`.
    if material.alpha_hash {
        fragment.push(if_then(
            diffuse_color()
                .w()
                .less_than(crate::nodes::alpha_hash::get_alpha_hash_threshold(
                    position_local(),
                )),
            vec![discard()],
        ));
    }

    // `builder.isOpaque()` — the material is not transparent, blending is
    // NormalBlending and alphaToCoverage is off. A transparent or blended
    // material keeps its per-fragment alpha instead, all the way to `Output`.
    if material.is_opaque() {
        fragment.push(diffuse_color().w().assign(float(1.0)));
    }

    // `Line2NodeMaterial.setupDiffuseColor()` runs `super.setupDiffuseColor()`
    // first and then adds the coverage multiply and the per-end colour. Its
    // `blending = NoBlending` is why `is_opaque()` above is false and the
    // `DiffuseColor.w = 1.0` line is absent from three's dump.
    if material.kind == MaterialKind::Line2 && ctx.has_geometry_attribute("instanceStart") {
        crate::materials::line2::setup_diffuse_color(
            material.alpha_to_coverage,
            material.world_units,
            material.vertex_colors && ctx.has_geometry_attribute("instanceColorStart"),
            fragment,
        );
    }
}

/// `float( node )` — `NodeBuilder.format()` narrowing to one component, which
/// is what `setupDiffuseColor()` wraps `opacityNode` and `alphaTestNode` in.
fn to_float(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::F32 => node,
        Type::Vec2 | Type::Vec3 | Type::Vec4 => node.x(),
        _ => node.to(Type::F32),
    }
}

/// `NodeMaterial.setup()`.
#[doc(hidden)]
pub fn setup(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    // `builder.geometry.hasAttribute( 'tangent' )` — installed first, because
    // the material's normal node below already reads the TBN frame.
    // `builder.camera.isOrthographicCamera`, which `positionViewDirection`
    // branches on, is in scope for the whole build in three.
    crate::nodes::tsl::with_orthographic_camera(ctx.orthographic, || {
        with_tangent_attribute(ctx.has_tangent_attribute, || {
            setup_tangent(material, ctx, fog)
        })
    })
}

fn setup_tangent(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    // `builder.context.setupNormal = () => subBuild( this.setupNormal( builder
    // ), 'NORMAL' )` — installed for the whole of the material's setup, so that
    // every `normalView` the lighting flow reaches resolves to this material's
    // normal map. See `docs/nodes.md` §7.
    // `MaterialNode.NORMAL`: with no `normalNode` of its own, a material with a
    // `bumpMap` normal-maps through `BumpMapNode`.
    // `MaterialNode.NORMAL`: `normalMap` first, then `bumpMap`, then the
    // geometry's own `normalView`.
    // `material.contextNode = overrideNodes( [ … ] )`: the replacements are
    // installed for the whole of the material's setup, so every accessor the
    // lighting flow reaches resolves to the G-buffer texture instead of to the
    // geometry. See `docs/nodes.md` §27.
    crate::nodes::tsl::with_override_nodes(material.context_overrides.as_ref(), || {
        // `material.contextNode = context( { … } )`: its keys are in force for
        // the material's whole setup, so every map tap made below sees them.
        let _context = material
            .context_node
            .as_ref()
            .map(crate::nodes::builder::push_context_value);
        setup_overridden(material, ctx, fog)
    })
}

fn setup_overridden(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    let normal = with_material_side(material.side, || {
        match (
            &material.normal_node,
            &material.normal_map,
            &material.bump_map,
        ) {
            (Some(node), _, _) => Some(node.clone()),
            (None, Some(map), _) => Some(normal_map_scaled(texture(map), material_normal_scale())),
            (None, None, Some(bump)) => Some(bump_map(bump, material_bump_scale())),
            (None, None, None) => None,
        }
    });
    // `builder.context.setupPositionView = () => this.setupPositionView(
    // builder )` — the seam `SpriteNodeMaterial` overrides. Built here, before
    // either stage is flowed, exactly as `NodeMaterial.setup()` installs it.
    let position_view = match material.kind {
        MaterialKind::Sprite => Some(setup_position_view_sprite(material, ctx.sprite)),
        MaterialKind::Points => Some(setup_position_view_points(material)),
        _ => None,
    };
    // `MeshPhysicalNodeMaterial.setup()`'s
    // `builder.context.setupClearcoatNormal = () => subBuild( …, 'NORMAL' )`.
    // `MaterialNode.CLEARCOAT_NORMAL` is the clearcoat normal map through the
    // same `NORMAL` sub-build the base normal map uses, which is why the two
    // share one `NORMAL_TBNViewMatrix` in the dump.
    let clearcoat_normal = with_material_side(material.side, || {
        material
            .clearcoat_normal_map
            .as_ref()
            .map(|map| normal_map_scaled(texture(map), material_clearcoat_normal_scale()))
    });
    // `materialMetalness` / `materialRoughness`, one node each for the whole
    // setup — the material's own `Metalness` / `Roughness` and a deferred MRT
    // output share the map read, as three's cached `MaterialNode`s do.
    // glTF packing: metalness in blue, roughness in green.
    //
    // The `MaterialNode` is a `ReferenceNode`, not a `TempNode`: reached
    // three times (`Metalness`, `DiffuseContribution`, the MRT member) it is
    // what is counted, its product only once, so three spells the product out
    // at each read over the one texture var. An empty context is the port's
    // counted-but-never-a-var wrapper (`webgpu_postprocessing_ssr_denoise`'s
    // `Floor_Stone`).
    let reference = |node: NodeRef| context(node, crate::nodes::node::ContextValue::new());
    let metalness_value = match &material.metalness_map {
        Some(map) => reference(material_metalness().mul(texture(map).z())),
        None => material_metalness(),
    };
    let roughness_value = match &material.roughness_map {
        Some(map) => reference(material_roughness().mul(texture(map).y())),
        None => material_roughness(),
    };
    with_material_normal(normal, material.flat_shading, material.side, || {
        with_clearcoat_normal(clearcoat_normal, || {
            with_material_values(metalness_value, roughness_value, || {
                with_material_position_view(position_view, || setup_inner(material, ctx, fog))
            })
        })
    })
}

fn setup_inner(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fog: Option<&FogNode>,
) -> MaterialFlow {
    let mut pre_vertex = Vec::new();
    let mut fragment = Vec::new();

    // `Line2NodeMaterial.setupPosition()` overrides the whole thing and calls
    // `super.setupPosition()` last, so its `positionLocal.assign()` is the
    // first statement of the vertex flow — ahead of morphing and skinning,
    // neither of which a fat line has.
    if material.kind == MaterialKind::Line2 && ctx.has_geometry_attribute("instanceStart") {
        pre_vertex.push(crate::materials::line2::setup_position(
            material.world_units,
        ));
    }

    // --- setupPosition: the `context.position` stack, flowed into the vertex
    // stage before either stage's own flow. Morphing, skinning and batching
    // plug in here too.
    // `if ( object.morphTargetInfluences ) morphReference( object ).append()` —
    // first in `setupPosition`, before skinning, displacement, batching and
    // instancing.
    if let Some(entry) = &ctx.morph {
        pre_vertex.extend(crate::nodes::morph::morph_reference(entry));
    }

    // `if ( object.isSkinnedMesh === true ) skinning( object ).append()` —
    // second, so the bind matrix sees the morphed position.
    if let Some(entry) = &ctx.skin {
        pre_vertex.extend(crate::nodes::skinning::skinning(entry));
    }

    //
    // `material.positionNode` is applied *before* the instance transform. three
    // r186 does the reverse (`NodeMaterial.js:798` instancing, then `:804`
    // `positionLocal.assign( positionNode )`), which throws the instance matrix
    // away; lib3's `BatchedText` was written against the order here. On the unit
    // `PlaneGeometry( 1, 1 )` the two formulations agree vertex for vertex, so
    // this also reproduces d33's baked-matrix workaround exactly. Recorded as a
    // deviation in `docs/nodes.md` §10 and plan §5.2.
    if let Some(node) = &material.position_node {
        pre_vertex.push(position_local().assign(to_vec3(node.clone())));
    }
    // `if ( object.isBatchedMesh ) batch( object )` — `NodeMaterial.js:792`,
    // after morphing and displacement and before instancing.
    if let Some(entry) = &ctx.batch {
        pre_vertex.extend(crate::nodes::batch::batch(entry));
    }

    if let Some(count) = ctx.instance_count {
        let matrix = instance_matrix(count);
        pre_vertex.push(
            position_local().assign(
                matrix
                    .mul(vec4_join(vec![position_local(), float(1.0)]))
                    .xyz(),
            ),
        );
        // `InstanceNode`: the normal is transformed by the inverse transpose of
        // the instance matrix' upper 3x3.
        let m3 = join(
            Type::Mat3,
            vec![
                matrix.element(0).xyz(),
                matrix.element(1).xyz(),
                matrix.element(2).xyz(),
            ],
        );
        let inv_t = transpose(inverse(m3));
        pre_vertex.push(normal_local().assign(inv_t.mul(normal_local()).normalize()));
    }

    // `setupHardwareClipping()` and `setupClipping()`: a `ClippingGroup`'s
    // planes. `clipping()` is the first statement of the fragment flow, with
    // or without a `fragmentNode`; `clippingAlpha()` waits for the lighting
    // setup below. (Three pushes `clipping()` ahead of `setupDepth()` too;
    // the port writes a `depthNode`'s `output.depth` before every fragment
    // statement, so a material with both has the two the other way round.)
    let clipping = crate::nodes::clipping::MaterialClipping::new(
        ctx.clipping.as_deref(),
        material.alpha_to_coverage
            && crate::nodes::builder::current_context(|cx| cx.alpha_to_coverage_samples),
    );
    fragment.extend(clipping.first);
    let clip_alpha = clipping.alpha;

    // --- setupDiscard: `If( maskNode.not(), () => Discard() )`, the first
    // thing in the fragment flow, before `setupDiffuseColor`.
    if let Some(mask) = &material.mask_node {
        fragment.push(discard_if(mask.clone()));
    }

    // --- the fragment flow
    let output = if let Some(fragment_node) = &material.fragment_node {
        fragment_node.clone()
    } else {
        // The kind's flow, from its row of the per-kind table — an exhaustive
        // `match`, so a new kind has to say which flow it takes.
        match material.kind.table().flow {
            Flow::Phong { specular } => {
                setup_phong(material, ctx, specular, clip_alpha, &mut fragment)
            }
            Flow::Physical => setup_standard(material, ctx, clip_alpha, &mut fragment),
            Flow::Normal => setup_normal_flow(material, ctx, clip_alpha, &mut fragment),
            Flow::Unlit => setup_unlit_flow(material, ctx, clip_alpha, &mut fragment),
        }
    };

    // `NodeMaterial.setupOutput()`: `scene.fogNode` mixes over the colour only,
    // leaving the alpha — `vec4( mix( output.rgb, fogColor, factor ), output.a )`.
    let output = match fog.filter(|_| material.fog) {
        Some(fog) => {
            fragment.push(output_property().assign(output));
            let mixed = vec4_join(vec![
                mix(
                    output_property().xyz(),
                    fog.color.clone(),
                    // Built now, inside this material's `setupPositionView`
                    // scope, as three builds `Fog.js`' `Fn()` (§41).
                    crate::nodes::tsl::resolve_fog_factor(&fog.factor),
                ),
                output_property().w(),
            ]);
            // The builder's own `emit_output_property` writes the second
            // `Output = …`, so pushing it here too would double the line.
            mixed
        }
        None => output,
    };

    // `NodeMaterial.setupOutput()`'s second half: `if ( this.premultipliedAlpha
    // === true ) outputNode = premultiplyAlpha( outputNode )`, after the fog
    // and before the output assignment. The SSAA accumulation quad is the one
    // caller — its dump is `output.color = fn0( fn1( … ) )` with `fn0` the
    // premultiply and `fn1` `unpremultiplyAlpha` from its own fragment node.
    let output = if material.premultiplied_alpha {
        premultiply_alpha(output)
    } else {
        output
    };

    // `NodeMaterial.setup()`'s MRT branch, which runs only `if ( renderTarget
    // !== null )`: the pass's MRT and the material's are merged with the
    // material's winning, and the merged node — not the colour — becomes the
    // fragment stage's result. The `Output` property assignment above has
    // already happened, which is what lets the MRT's `output` member read it
    // back (`output.m0 = Output;` in three's dump).
    let mrt = ctx.mrt.as_ref().map(|context| {
        let merged = match &material.mrt_node {
            Some(material_mrt) => context.node.merge(material_mrt),
            None => context.node.clone(),
        };
        merged.members(&context.attachments, &context.output_types)
    });

    // --- the vertex flow
    let position = match &material.vertex_node {
        Some(node) => node.clone(),
        None => model_view_projection(),
    };
    // `PointsNodeMaterial.setupVertex()`: on anything but `Points` — a
    // `Sprite` with `count` instances — the clip position is offset into a
    // screen-space quad.
    let position = if material.kind == MaterialKind::Points && ctx.sprite {
        setup_vertex_sprite(material, position)
    } else {
        position
    };

    // `if ( builder.context.getOutput ) resultNode = builder.context.getOutput(
    // resultNode, builder );` — `DirectRenderPipeline`'s hook, which does
    // `output.assign( materialOutputNode )` and then returns its own node. The
    // assign is a *second* write to the `Output` property, on top of
    // `NodeMaterial.setup()`'s own, and three's dump has both lines.
    //
    // The MRT branch runs only with a render target bound, and the hook only
    // without one, so the two never meet.
    // A deferred `Fn()` output node runs here, in this material's context
    // (see `resolve_fn_call`).
    let material_output = material
        .output_node
        .as_ref()
        .map(crate::nodes::tsl::resolve_fn_call);
    // `material.outputNode = outputStruct( … )`: the struct *is* the fragment
    // stage's result, written member by member as an MRT's is, but with each
    // member's own type: each member carries it (see `MaterialFlow::mrt`).
    let (mrt, material_output) = match material_output {
        Some(node) => match node.node() {
            crate::nodes::Node::OutputStruct { members } => (
                Some(members.iter().map(|m| (m.clone(), m.ty())).collect()),
                None,
            ),
            _ => (mrt, Some(node)),
        },
        None => (mrt, None),
    };
    let (output_assign, output_node) = match &ctx.output {
        Some(context) => (
            Some(material_output.unwrap_or_else(|| output.clone())),
            Some(context.node.clone()),
        ),
        None => (None, material_output),
    };

    MaterialFlow {
        pre_vertex_statements: pre_vertex,
        // `if ( this.depthWrite === true || this.depthTest === true )` —
        // three's own guard on `setupDepth()`. The port carries only the
        // explicit `depthNode` branch; the logarithmic / orthographic
        // fallbacks want `renderer.logarithmicDepthBuffer`, which no rung sets.
        depth: material
            .depth_node
            .clone()
            .filter(|_| material.depth_write || material.depth_test),
        fragment_statements: fragment,
        output,
        output_assign,
        output_node,
        mrt,
        emit_output_property: material.fragment_node.is_none(),
        // `setupHardwareClipping()`: after the vertex node, so the loop
        // reads the varyings the fragment stage asked for.
        vertex_statements: clipping.hardware.iter().map(|(l, _)| l.clone()).collect(),
        position,
        geometry_has_tangent: ctx.has_tangent_attribute,
        geometry_attributes: ctx.geometry_attributes.clone(),
        clip_distances: clipping.hardware.map_or(0, |(_, count)| count),
    }
}

/// `vec3( node )`: a scalar splats, a wider vector narrows, a `vec3` passes
/// through — `NodeBuilder.format()`'s two cases.
fn to_vec3(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec3 => node,
        Type::Vec4 => node.xyz(),
        _ => node.to(Type::Vec3),
    }
}

/// `vec2( node )`.
fn to_vec2(node: NodeRef) -> NodeRef {
    match node.ty() {
        Type::Vec2 => node,
        Type::Vec3 | Type::Vec4 => node.xy(),
        _ => node.to(Type::Vec2),
    }
}

/// `SpriteNodeMaterial.setupPositionView()`
/// (`src/materials/nodes/SpriteNodeMaterial.js:110`) — the sprite vertex
/// shader, in view space:
///
/// ```ignore
/// const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
/// let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(),
///                   modelWorldMatrix[ 1 ].xyz.length() );
/// if ( scaleNode !== null ) scale = scale.mul( vec2( scaleNode ) );
/// if ( camera.isPerspectiveCamera && sizeAttenuation === false )
///     scale = scale.mul( mvPosition.z.negate() );
/// let alignedPosition = positionGeometry.xy;
/// if ( object.center && object.center.isVector2 )
///     alignedPosition = alignedPosition.sub( reference( 'center', 'vec2', object ).sub( 0.5 ) );
/// alignedPosition = alignedPosition.mul( scale );
/// const rotation = float( rotationNode || materialRotation );
/// return vec4( mvPosition.xy.add( rotate( alignedPosition, rotation ) ),
///              mvPosition.zw );
/// ```
///
/// `object.center` exists only on a [`Sprite`](crate::objects::Sprite), so
/// `has_center` is [`SetupContext::sprite`].
fn setup_position_view_sprite(material: &MeshBasicNodeMaterial, has_center: bool) -> NodeRef {
    let position = match &material.position_node {
        Some(node) => to_vec3(node.clone()),
        None => vec3(0.0, 0.0, 0.0),
    };
    let mv_position = model_view_matrix().mul(position);

    let mut scale = join(
        Type::Vec2,
        vec![
            length(model_world_matrix().element(0).xyz()),
            length(model_world_matrix().element(1).xyz()),
        ],
    );
    if let Some(scale_node) = &material.scale_node {
        scale = scale.mul(to_vec2(scale_node.clone()));
    }
    if !material.size_attenuation {
        // The perspective-camera branch; the ladder's only sprite material
        // leaves `sizeAttenuation` at its default `true`, which omits it.
        scale = scale.mul(mv_position.z().negate());
    }

    let mut aligned = position_geometry().xy();
    if has_center {
        let center = uniform(
            UniformSource::ObjectCenter,
            Type::Vec2,
            UniformGroup::Object,
            None,
        );
        aligned = aligned.sub(center.sub(0.5));
    }
    let aligned = aligned.mul(scale);
    let rotation = match &material.rotation_node {
        Some(node) => node.clone(),
        None => material_rotation(),
    };

    join(
        Type::Vec4,
        vec![
            mv_position.xy().add(rotate(aligned, rotation)),
            mv_position.zw(),
        ],
    )
}

/// `PointsNodeMaterial.setupVertexSprite()`
/// (`src/materials/nodes/PointsNodeMaterial.js:89-150`) — each instance's
/// quad corner pushed out from the clip position by `sizeNode` pixels:
///
/// ```ignore
/// let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
/// pointSize = pointSize.mul( screenDPR );
/// if ( camera.isPerspectiveCamera && sizeAttenuation === true )
///     pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
/// if ( scaleNode ) pointSize = pointSize.mul( vec2( scaleNode ) );
/// let offset = positionGeometry.xy;
/// if ( rotationNode ) offset = rotate( offset, float( rotationNode ) );
/// offset = offset.mul( pointSize ).div( viewportSize.div( 2 ) ).mul( mvp.w );
/// return mvp.add( vec4( offset, 0, 0 ) );
/// ```
///
/// Ported for what the ladder sets: a `sizeNode` and `sizeAttenuation =
/// false`. `materialPointSize` (no `sizeNode`) and the attenuated branch are
/// reported by the renderer's unsupported-field warning and draw as if
/// `sizeNode` were 1 and attenuation off. `viewportSize` is `viewport.zw`,
/// which is what three's dump reads.
fn setup_vertex_sprite(material: &MeshBasicNodeMaterial, mvp: NodeRef) -> NodeRef {
    let size = match &material.size_node {
        Some(node) => to_vec2(node.clone()),
        None => vec2(1.0, 1.0),
    };
    let mut point_size = size.mul(to_vec2(screen_dpr()));
    if let Some(scale) = &material.scale_node {
        point_size = point_size.mul(to_vec2(scale.clone()));
    }
    let mut offset = position_geometry().xy();
    if let Some(rotation) = &material.rotation_node {
        offset = rotate(offset, rotation.clone());
    }
    let offset = offset
        .mul(point_size)
        .div(viewport().zw().div(vec2(2.0, 2.0)))
        .mul(to_vec2(mvp.w()));
    mvp.add(vec4_join(vec![offset, float(0.0), float(0.0)]))
}

/// `PointsNodeMaterial.setupPositionView()`
/// (`src/materials/nodes/PointsNodeMaterial.js:81-87`):
///
/// ```ignore
/// return modelViewMatrix.mul( vec3( this.positionNode || positionLocal ) ).xyz;
/// ```
///
/// It is `NodeMaterial`'s own formula with one difference that shows in the
/// generated WGSL: the position node is read *again* here rather than through
/// the `positionLocal` var `setupPosition()` just assigned it to, so the
/// vertex shader indexes the storage buffer twice. `mul` on a `mat4` and a
/// `vec3` is `NodeBuilder.format( snippet, 'vec3', 'vec4' )`, i.e.
/// `vec4<f32>( v, 1.0 )` — spelt out here, as
/// [`transform_direction`](crate::nodes::tsl::transform_direction) does.
fn setup_position_view_points(material: &MeshBasicNodeMaterial) -> NodeRef {
    let position = match &material.position_node {
        Some(node) => to_vec3(node.clone()),
        None => position_local(),
    };
    model_view_matrix()
        .mul(vec4_join(vec![position, float(1.0)]))
        .xyz()
}

/// `Background.update()`'s skybox material: the cube map sampled along
/// `normalWorldGeometry` with the background rotation and LOD, on a sphere
/// pinned to the far plane.
#[doc(hidden)]
pub fn background_color_node(map: &crate::textures::CubeTexture) -> NodeRef {
    let dir = material_env_rotation()
        .mul(background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)])));
    let sample = cube_texture_level(map, dir, background_blurriness());
    sample.mul(background_intensity())
}

/// `scene.background = <a generated PMREM>`: the skybox sphere sampling the
/// PMREM cube, which is the `isNode` branch with
/// `NodeManager.getBackgroundNode()`'s `pmremTexture( background )` inside it
/// and the node context supplying the two accessors.
///
/// `getUV: () => backgroundRotation.mul( normalWorldGeometry )` and
/// `getTextureLevel: () => backgroundBlurriness` are the context; the port has
/// no node context, so they are passed as arguments, which is the same graph.
/// `backgroundRotation` is a `mat4`, so the product is a `vec4`, which
/// `materialEnvRotation` multiplies as it is — three's own dump reads
/// `object.nodeUniform1 * ( render.nodeUniform2 * vec4( normalWorldGeometry,
/// 1.0 ) )` off exactly that.
#[doc(hidden)]
pub fn background_pmrem_color_node(pmrem: &crate::materials::environment::PmremHandle) -> NodeRef {
    let uv = background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)]));
    background_node_color_node(pmrem.sample(uv, background_blurriness()))
}

/// `scene.backgroundNode` set to an environment graph: the same context as
/// [`background_pmrem_color_node`] — `backgroundRotation.mul(
/// normalWorldGeometry )` and `backgroundBlurriness` — handed to every
/// `pmremTexture()` in it. A `.context( { getTextureLevel } )` on the node
/// itself ([`EnvironmentNode::with_texture_level`]) is inside this one and
/// wins, as the inner context does in three.
///
/// Three calls `getUV()` once per leaf, and its dump repeats the rotation for
/// each; the port builds it once and shares it, which is the same value.
///
/// [`EnvironmentNode::with_texture_level`]: crate::materials::environment::EnvironmentNode::with_texture_level
#[doc(hidden)]
pub fn background_environment_color_node(
    node: &crate::materials::environment::EnvironmentNode,
) -> NodeRef {
    let uv = background_rotation().mul(vec4_join(vec![normal_world_geometry(), float(1.0)]));
    background_node_color_node(node.sample(uv, background_blurriness()))
}

/// `Background.update()`'s `isNode` branch:
/// `vec4( backgroundNode ).mul( backgroundIntensity )`. `vec4()` of a node
/// that already is one is the node itself — `webgpu_equirectangular`'s
/// `texture( map, equirectUV(), 0 )` — and of a colour it appends `1.0`.
///
/// A background node held in an argument-less inline `Fn()` call (see
/// `tsl::resolve_fn_call`) stays deferred: the whole colour is wrapped in a
/// call of its own, which `setup_diffuse_color` runs inside the skybox
/// material's build. three.js runs every `Fn` body there, so `normalWorld` in
/// `webgpu_postprocessing_retro`'s sky reads the `BackSide` material's
/// negated `normalView`; built eagerly, it would read the front-sided one.
#[doc(hidden)]
pub fn background_node_color_node(node: NodeRef) -> NodeRef {
    if let crate::nodes::Node::Call { def, args } = node.node() {
        if !def.layout && args.is_empty() {
            let deferred = node.clone();
            return call(
                &inline_fn(0, Type::Vec4, move |_| {
                    background_node_color_node(resolve_fn_call(&deferred))
                }),
                Vec::new(),
            );
        }
    }
    let color = match node.ty() {
        Type::Vec4 => node,
        _ => vec4_join(vec![node, float(1.0)]),
    };
    color.mul(background_intensity())
}

#[doc(hidden)]
pub fn background_vertex_node() -> NodeRef {
    let is_ortho = camera_projection_matrix()
        .element(3)
        .element(3)
        .equal(float(1.0));
    let ortho_scale = float(1.0)
        .div(camera_projection_matrix().element(1).element(1))
        .mul(float(3.0));
    let modified = is_ortho.select(position_local().mul(ortho_scale), position_local());
    let view_position = model_view_matrix().mul(vec4_join(vec![modified, float(0.0)]));
    let view_proj =
        camera_projection_matrix().mul(vec4_join(vec![view_position.xyz(), float(1.0)]));
    view_proj.set_z(view_proj.w())
}

/// `QuadMesh.render()`'s temporary `vertexNode`: a full-screen triangle driven
/// entirely by `vertexIndex`.
#[doc(hidden)]
pub fn quad_vertex_node() -> NodeRef {
    let x = const_array(vec![-1.0, -1.0, 3.0]).element_node(vertex_index());
    let y = const_array(vec![3.0, -1.0, -1.0]).element_node(vertex_index());
    join(Type::Vec4, vec![x, y, float(0.0), float(1.0)])
}

/// `RangeNode` on an instanced mesh: one `vec4` per instance, from a uniform
/// buffer indexed by a flat `instanceIndex` varying or, past the uniform buffer
/// limit, from an instanced vertex attribute.
pub fn instanced_range(
    min: impl Into<crate::nodes::tsl::RangeValue>,
    max: impl Into<crate::nodes::tsl::RangeValue>,
    count: usize,
) -> NodeRef {
    crate::nodes::tsl::instanced_range(min, max, count)
}

/// `Renderer._renderOutput()`'s material: the framebuffer texture sampled at
/// the fragment coordinate, through `renderOutput()`.
#[doc(hidden)]
pub fn output_fragment_node(
    framebuffer: &crate::textures::Texture,
    tone_mapping: ToneMapping,
) -> NodeRef {
    let coord = frag_coord().xy().div(viewport_size());
    let color = texture_uv(framebuffer, coord);
    render_output(color, tone_mapping)
}

/// `RenderOutputNode.setup()` with an sRGB output space: the alpha clamp and
/// unpremultiply, then `toneMapping` — which `ToneMappingNode` applies to the
/// colour only — then the sRGB OETF and the premultiply back.
pub fn render_output(color: NodeRef, tone_mapping: ToneMapping) -> NodeRef {
    let clamped = vec4_join(vec![color.rgb(), color.a().clamp(float(0.0), float(1.0))]);
    let unpremultiplied = unpremultiply_alpha(clamped);
    // `outputNode.toneMapping( toneMapping )` with the renderer's
    // `toneMappingExposure` uniform.
    let mapped = tone_mapping_node(tone_mapping, tone_mapping_exposure(), unpremultiplied);
    let encoded = vec4_join(vec![srgb_transfer_oetf(mapped.clone().rgb()), mapped.a()]);
    premultiply_alpha(encoded)
}

/// `color.toneMapping( mode, exposure )` —
/// `three.js/src/nodes/display/ToneMappingNode.js`.
///
/// `NoToneMapping` returns the colour untouched; every other mode is
/// `vec4( toneMappingFn( color.rgb, exposure ), color.a )`. The exposure is a
/// node, so `scenePass.toneMapping( ACESFilmicToneMapping, 1 )` bakes the
/// literal `1.0` into the shader rather than reading the renderer's uniform
/// (`webgpu_custom_fog_background`; `docs/nodes.md` §24).
pub fn tone_mapping_node(mode: ToneMapping, exposure: NodeRef, color: NodeRef) -> NodeRef {
    match mode {
        ToneMapping::None => color,
        ToneMapping::Linear => vec4_join(vec![
            linear_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::Reinhard => vec4_join(vec![
            reinhard_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::AcesFilmic => vec4_join(vec![
            aces_filmic_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::Neutral => vec4_join(vec![
            neutral_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::AgX => vec4_join(vec![
            agx_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
        ToneMapping::Cineon => vec4_join(vec![
            cineon_tone_mapping(color.clone().rgb(), exposure),
            color.a(),
        ]),
    }
}

/// `MeshNormalNodeMaterial`'s fragment flow ([`Flow::Normal`]).
#[inline(never)]
fn setup_normal_flow(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    clip_alpha: Vec<NodeRef>,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    // `MeshNormalNodeMaterial.setupDiffuseColor()` replaces the base
    // implementation outright: no `colorNode`, no vertex colours, no alpha
    // test, and no `builder.isOpaque()` clamp — the opacity node (or the
    // `materialOpacity` uniform) lands directly in the `vec4`'s `w`.
    //
    // "By convention, a normal packed to RGB is in sRGB color space", so
    // the packed value is decoded into the working space on the way in;
    // that is where `sRGBTransferEOTF` comes from, and it is the only
    // material on the ladder that emits the EOTF rather than the OETF.
    let opacity = match &material.opacity_node {
        Some(node) => to_float(node.clone()),
        None => material_opacity_for(material),
    };
    fragment.push(diffuse_color().assign(srgb_to_working(vec4_join(vec![
        pack_normal_to_rgb(normal_view()),
        opacity,
    ]))));
    // `setupAmbientOcclusion()` still runs; nothing lit reads it.
    setup_ambient_occlusion(material, ctx, fragment);
    fragment.extend(clip_alpha);
    vec4_join(vec![diffuse_color().xyz(), diffuse_color().w()]).max(float(0.0))
}

/// The fragment flow of a kind with no lighting model of its own
/// ([`Flow::Unlit`]): Basic, Sprite, Points and Line2.
#[inline(never)]
fn setup_unlit_flow(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    clip_alpha: Vec<NodeRef>,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    setup_diffuse_color(material, ctx, fragment);
    // `setupAmbientOcclusion()` runs for every material without a
    // `fragmentNode`; only `MeshBasicNodeMaterial` (whose `lights` is true
    // in three) then reads it, through `BasicLightingModel.indirect()`.
    let has_ao = setup_ambient_occlusion(material, ctx, fragment);
    let basic_ao = has_ao && material.kind == MaterialKind::Basic && !ctx.lighting_disabled;
    // Only `MeshBasicNodeMaterial.setupEnvironment()` wraps the env map in
    // a `BasicEnvironmentNode`. `SpriteNodeMaterial`, `PointsNodeMaterial`
    // and `Line2NodeMaterial` also reach this flow but override no
    // `setupEnvironment()`, and `NodeMaterial.lights` is false for them,
    // so three never samples their `envMap` (#253).
    let basic_env_map = material
        .env_map
        .as_ref()
        .filter(|_| material.kind.table().reads(Field::EnvMap));

    // `NodeMaterial.setupLighting()` for a material with no lighting model
    // of its own: `lights = this.lights || this.lightsNode !== null`, and
    // the `LightsNode` runs only `if ( lightsNode.getScope().hasLights )`.
    // The model then comes from the `lightsNode.context( { lightingModel
    // } )` the example wrapped the lights in.
    let custom_lighting = material.lighting_model.as_ref().and_then(|model| {
        let lights = (material.lights && !ctx.lighting_disabled) || material.lights_node.is_some();
        let list = material_lights(material, ctx);
        (lights && !list.is_empty()).then_some((model, list))
    });

    // `MeshBasicNodeMaterial.lights` is true in three, so a backdrop
    // takes the `LightsNode` path whenever the scene has a light. The
    // port's basic material defaults `lights` off and only takes that
    // path for a backdrop or an environment map — for anything else the
    // `BasicLightingModel` sum is `DiffuseColor.rgb` again, and the
    // ladder's basic dumps were matched without it.
    let basic_lit = !ctx.lighting_disabled && !material_lights(material, ctx).is_empty();

    let outgoing = if let Some((model, lights)) = custom_lighting {
        crate::materials::lighting_model::lights_node(
            model.as_ref(),
            &lights,
            material.received_shadow_position_node.as_ref(),
            &|base| backdrop_blend(material, base),
            fragment,
        )
    } else if basic_env_map.is_some() || basic_ao || (material.backdrop_node.is_some() && basic_lit)
    {
        // `BasicLightingModel`: `indirect()` makes the diffuse colour
        // the indirect light, and `LightsNode.setup()` sums it — or
        // blends a `backdropNode` over it. The `AONode` is a material
        // lighting, so it alone is enough to take this path.
        if basic_ao {
            ao_lighting_node(fragment);
        }
        fragment.push(indirect_diffuse().assign(vec4(0.0, 0.0, 0.0, 0.0).xyz()));
        fragment.push(
            indirect_diffuse().assign(
                vec4_join(vec![indirect_diffuse(), float(1.0)])
                    .add(vec4(1.0, 1.0, 1.0, 0.0))
                    .xyz(),
            ),
        );
        fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(ambient_occlusion())));
        fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(diffuse_color().xyz())));
        fragment.push(total_diffuse().assign(backdrop_blend(
            material,
            direct_diffuse().add(indirect_diffuse()),
        )));
        fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
        fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));

        // `MeshBasicNodeMaterial.setupEnvironment()` →
        // `BasicEnvironmentNode( cubeTexture( envMap ) )`, sampled along the
        // reflect vector and blended in by `reflectivity`.
        if let Some(env_map) = basic_env_map {
            let dir = material_env_rotation().mul(vec4_join(vec![reflect_vector(), float(1.0)]));
            let env = cube_texture(env_map, dir);
            fragment.push(outgoing_light().assign(mix(
                outgoing_light(),
                outgoing_light().mul(env.xyz()),
                float(1.0).mul(material_reflectivity()),
            )));
        }
        outgoing_light()
    } else {
        // `setupOutgoingLight()` with no lights: `diffuseColor.rgb`, or
        // `setupLighting()`'s `else if ( backdropNode !== null )` arm.
        backdrop_blend(material, diffuse_color().xyz())
    };

    // `setupLighting()`'s EMISSIVE tail. `MeshBasicMaterial` has no
    // `emissive` colour, so an unlit material reaches it only through
    // `emissiveNode`: `EmissiveColor = vec3( emissiveNode )`, then
    // `outgoingLight = outgoingLight + EmissiveColor`.
    let outgoing = match &material.emissive_node {
        Some(node) => {
            fragment.push(emissive_color().assign(to_vec3(node.clone())));
            outgoing.add(emissive_color())
        }
        None => outgoing,
    };

    // `clippingAlpha()`, after `setupLighting()`. Three's `LightsNode`
    // builds lazily, so its statements follow these; the port's lit
    // paths above have already pushed theirs. They read only the
    // diffuse colour's `rgb`, and the alpha these write is read by the
    // output below, so the order changes nothing the shader computes.
    fragment.extend(clip_alpha);

    // `basicOutput = vec4( outgoingLight, diffuseColor.a ).max( 0 )`.
    vec4_join(vec![outgoing, diffuse_color().w()]).max(float(0.0))
}

/// `MeshPhongNodeMaterial`'s fragment flow: `setupDiffuseColor`,
/// `setupVariants` (shininess / specular / emissive), then either the
/// `LightsNode` loop with `PhongLightingModel` or, when `lights === false`,
/// nothing but the diffuse colour. Read off the dumps in
/// `docs/rung5-progress.md` §4; the fog step (§5) is not wired yet.
///
/// `specular == false` is `MeshLambertNodeMaterial`, which is this same flow
/// under `new PhongLightingModel( false )`. Three things fall out of the flag,
/// all of them visible in `dump-postprocessing_ca/m07`:
///
/// * `MeshPhongNodeMaterial.setupVariants()`'s `shininess` and `specularColor`
///   are not emitted — they are the Phong *material*'s, not the model's;
/// * `PhongLightingModel.direct()` skips its `directSpecular.addAssign`;
/// * and so `directSpecular` / `indirectSpecular` are first *read* in the
///   shared tail, which is where three's `PropertyNode` declares them, after
///   `totalDiffuse` rather than before the light loop.
fn setup_phong(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    specular: bool,
    clip_alpha: Vec<NodeRef>,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    setup_diffuse_color(material, ctx, fragment);
    // `setupAmbientOcclusion()`, between `setupDiffuseColor()` and
    // `setupVariants()`.
    let has_ao = setup_ambient_occlusion(material, ctx, fragment);

    // setupVariants: `PhongLightingModel` reads these three properties.
    if specular {
        fragment.push(shininess().assign(max(material_shininess(), float(0.0001))));
        let specular_value = match &material.specular_node {
            Some(node) => node.clone().xyz(),
            None => material_specular(),
        };
        fragment.push(specular_color().assign(specular_value));
    }
    fragment.push(emissive_color().assign(material_emissive_value(material)));
    // `clippingAlpha()`: the `LightsNode` below is built lazily in three, so
    // its statements land after this.
    fragment.extend(clip_alpha);

    let outgoing = if material.lights {
        // `LightsNode`: the scene's lights, or the selective subset the
        // material's `lights( [ … ] )` node names.
        let lights = material_lights(material, ctx);
        let ambient: Vec<usize> = lights
            .iter()
            .filter(|light| light.kind == LightKind::Ambient)
            .map(|light| light.index)
            .collect();

        // No accumulator is zeroed explicitly. Each is a var with a `vec3( 0
        // )` initialiser (`LightingContextNode.getContext()`'s `vec3().toVar(
        // name )`), and an assign generates its target first, so the zero
        // lands right above the statement that first touches it — as three
        // has it, and only once (issue #281). That keeps the order the dumps
        // show: `AmbientLightNode` sorts first in `LightsNode`'s list, so its
        // `irradiance.addAssign()` puts `irradiance = vec3( 0 )` ahead of the
        // loop; a hemisphere light or a probe adding to `irradiance` from
        // inside the loop puts it there too, never after what they added;
        // with none of them it lands in the indirect tail. `directDiffuse`
        // lands in the first direct light, `directSpecular` after that
        // light's diffuse term, and Lambert's `directSpecular` /
        // `indirectSpecular` in `totalSpecular`'s line.
        if !ambient.is_empty() {
            phong::ambient_lights(&ambient, fragment);
        }

        for light in &lights {
            if light.kind == LightKind::Ambient {
                continue;
            }
            // `ToonLightingModel` is Lambert with its own `direct()`; the
            // rest of the flow — `indirect()` included — is shared.
            if material.kind == MaterialKind::Toon {
                toon::direct_light(
                    light,
                    material.received_shadow_position_node.as_ref(),
                    material.gradient_map.as_ref(),
                    fragment,
                );
            } else {
                phong::direct_light(
                    light,
                    material.received_shadow_position_node.as_ref(),
                    specular,
                    fragment,
                );
            }
        }

        // `AONode`, after the scene's lights and before `indirect()`. A pass
        // with lighting disabled collects no `materialLightings`, so no
        // `AONode` either.
        if has_ao && !ctx.lighting_disabled {
            ao_lighting_node(fragment);
        }

        // The tail every lit material shares.
        fragment.push(
            indirect_diffuse().assign(
                vec4_join(vec![indirect_diffuse(), float(1.0)])
                    .add(
                        vec4_join(vec![irradiance(), float(1.0)])
                            .mul(diffuse_color().mul(phong::RECIPROCAL_PI)),
                    )
                    .xyz(),
            ),
        );
        fragment.push(indirect_diffuse().assign(indirect_diffuse().mul(ambient_occlusion())));
        fragment.push(total_diffuse().assign(backdrop_blend(
            material,
            direct_diffuse().add(indirect_diffuse()),
        )));
        fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
        fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));
        outgoing_light()
    } else {
        // `lights = false` — the example's light spheres.
        diffuse_color().xyz()
    };

    // `Output = max( vec4( outgoingLight + EmissiveColor, DiffuseColor.w ), 0 )`.
    vec4_join(vec![outgoing.add(emissive_color()), diffuse_color().w()]).max(float(0.0))
}

/// `material.backdropNode` over `base`: `LightsNode.setup()`'s blend into
/// `totalDiffuse` on a lit material, and `setupLighting()`'s `else if (
/// backdropNode !== null )` arm on an unlit one —
/// `vec3( backdropAlpha ? mix( base, backdrop, backdropAlpha ) : backdrop )`.
/// `base` unchanged without a backdrop.
///
/// A `vec4` backdrop (a viewport texture tap) makes the `mix` a `vec4` one,
/// over `vec4( base, 1 )`, as three's type promotion has it.
fn backdrop_blend(material: &MeshBasicNodeMaterial, base: NodeRef) -> NodeRef {
    let Some(backdrop) = &material.backdrop_node else {
        return base;
    };
    let blended = match &material.backdrop_alpha_node {
        Some(alpha) if backdrop.ty().components() == 4 => mix(
            vec4_join(vec![base, float(1.0)]),
            backdrop.clone(),
            alpha.clone(),
        ),
        Some(alpha) => mix(base, backdrop.clone(), alpha.clone()),
        None => backdrop.clone(),
    };
    to_vec3(blended)
}

/// `LightsNode`'s list as one material sees it: the scene's lights, or the
/// selective subset the material's `lights( [ … ] )` node names.
fn material_lights(material: &MeshBasicNodeMaterial, ctx: &SetupContext) -> Vec<LightDesc> {
    match &material.lights_node {
        Some(subset) => ctx
            .lights
            .iter()
            .filter(|light| subset.contains(&light.index))
            .cloned()
            .collect(),
        None => ctx.lights.clone(),
    }
}

/// `NodeMaterial.setupAmbientOcclusion()` — `AmbientOcclusion.assign( aoNode )`
/// when the material has an `aoMap`, the pass has a `builtinAOContext`, or
/// both. Returns whether it assigned, which is three's
/// `builder.context.ambientOcclusion` being set — what makes
/// `setupMaterialLightings()` push the `AONode` the lighting models multiply
/// their `ambientOcclusion` var by.
///
/// `materialAO` is `texture( aoMap ).r.sub( 1 ).mul( aoMapIntensity ).add( 1 )`.
/// The context's `getAO( materialAO )` then hands back `materialAO` untouched
/// for a transparent material, and otherwise `materialAO.mul( ao )`, or `ao`
/// alone without a map. The node goes in as it is: the var in
/// `webgpu_postprocessing_ao`'s dump (`nodeVar0 = textureSample( … ).x;
/// AmbientOcclusion = nodeVar0;`) is `TextureNode.generate()`'s own, which
/// caches every tap, and the `.x` sits inside it because the GTAO target is
/// `RedFormat` and so the texture node is a `float`.
///
/// Nothing is emitted without either: three leaves `aoNode` null, so the
/// property is never declared and the lighting model's own `ambientOcclusion`
/// var stays a bare `1`.
fn setup_ambient_occlusion(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    fragment: &mut Vec<NodeRef>,
) -> bool {
    let map_ao = material.ao_map.as_ref().map(|_| material_ao(material));
    // `builtinAOContext`'s `getAO`: `if ( material.transparent === true )
    // return inputNode;`.
    let context_ao = ctx
        .ambient_occlusion
        .as_ref()
        .filter(|_| !material.transparent)
        .map(|ao| ao.node.clone());
    let ao_node = match (map_ao, context_ao) {
        (Some(map_ao), Some(context_ao)) => map_ao.mul(context_ao),
        (Some(ao), None) | (None, Some(ao)) => ao,
        (None, None) => return false,
    };

    fragment.push(ambient_occlusion_property().assign(ao_node));
    true
}

/// `AONode( context.ambientOcclusion )` — the last of
/// `setupMaterialLightings()`' lighting nodes, built after the scene's lights
/// and the environment and before the lighting model's `indirect()`:
/// `ambientOcclusion.mulAssign( AmbientOcclusion )`. The var's `float( 1 )`
/// initialiser is emitted here, at its first read.
fn ao_lighting_node(fragment: &mut Vec<NodeRef>) {
    fragment
        .push(ambient_occlusion().assign(ambient_occlusion().mul(ambient_occlusion_property())));
}

/// `MaterialNode.EMISSIVE` — `emissive * emissiveIntensity`, times the
/// `emissiveMap` when there is one.
///
/// The map multiply is three's `emissiveNode.mul( this.getTexture( scope ) )`:
/// a `vec3` times a `vec4`, which `MathNode`'s type resolution widens to
/// `vec4( emissive, 1 ) * tex` before the assignment to the `vec3` property
/// takes `.xyz`. That is what the dump's
/// `( vec4<f32>( ( emissive * intensity ), 1.0 ) * tex ).xyz` is, and why the
/// port builds the `vec4` explicitly rather than multiplying three components.
///
/// An `emissiveNode` replaces all of it: `setupLighting()` assigns `vec3(
/// emissiveNode ? emissiveNode : materialEmissive )` on every lit kind.
fn material_emissive_value(material: &MeshBasicNodeMaterial) -> NodeRef {
    if let Some(node) = &material.emissive_node {
        return to_vec3(node.clone());
    }
    let emissive = material_emissive().mul(material_emissive_intensity());

    match &material.emissive_map {
        Some(map) => vec4_join(vec![emissive, float(1.0)])
            .mul(texture(map))
            .xyz(),
        None => emissive,
    }
}

/// `MeshStandardNodeMaterial`'s fragment flow: `setupDiffuseColor`,
/// `setupVariants` (metalness / roughness / specular / diffuse contribution),
/// then the `LightsNode` loop with `PhysicalLightingModel`. Read off
/// `handoff/scouts/rung8/MeshStandardMaterial_1{7,8,9}.frag-r186.wgsl`.
fn setup_standard(
    material: &MeshBasicNodeMaterial,
    ctx: &SetupContext,
    clip_alpha: Vec<NodeRef>,
    fragment: &mut Vec<NodeRef>,
) -> NodeRef {
    // --- setupDiffuseColor
    setup_diffuse_color(material, ctx, fragment);

    // --- setupAmbientOcclusion, between `setupDiffuseColor` and
    // `setupVariants` exactly as `NodeMaterial.setup()` orders them.
    let has_ao = setup_ambient_occlusion(material, ctx, fragment);

    // --- setupVariants. `metalnessNode` is reached twice — once for the
    // `Metalness` property and once for `DiffuseContribution` — so the node is
    // shared, exactly as three.js shares the `materialMetalness` node.
    // `const metalnessNode = this.metalnessNode ? float( this.metalnessNode )
    // : materialMetalness` — the explicit node replaces the uniform *and* its
    // map, because `materialMetalness` is what folds the map in.
    //
    // The `float()` matters when the node is wider than a float, as a bare
    // `texture( map )` is: `DiffuseContribution` then takes `1 - map.x` on
    // every channel, not `1 - map.rgb` (`webgpu_lights_selective`, §46).
    let metalness_node = match &material.metalness_node {
        Some(node) => node.to_float(),
        None => material_metalness_value(),
    };
    fragment.push(metalness().assign(metalness_node.clone()));

    let roughness_node = match &material.roughness_node {
        Some(node) => node.to_float(),
        None => material_roughness_value(),
    };
    fragment.push(roughness().assign(physical::get_roughness(
        roughness_node,
        !ctx.geometry_missing_normal,
    )));

    let table = material.kind.table();
    if table.reads(Field::Ior) {
        // `MeshPhysicalNodeMaterial.setupSpecular()`: F0 from the index of
        // refraction rather than the dielectric constant 0.04, tinted by
        // `specularColor` (times `specularColorMap`) and scaled by
        // `specularIntensity` — which is also the F90. This block is the entire
        // delta over the Standard material above.
        fragment.push(ior().assign(material_ior()));
        // `pow2( ior.sub( 1 ).div( ior.add( 1 ) ) )` — the quotient is read
        // twice, so it is a var.
        let f0 = to_var(None, ior().sub(float(1.0)).div(ior().add(float(1.0))));
        let specular = match &material.specular_color_map {
            Some(map) => material_specular_color().mul(texture(map).xyz()),
            None => material_specular_color(),
        };
        fragment.push(
            specular_color().assign(
                f0.clone()
                    .mul(f0)
                    .mul(specular)
                    .min(vec3(1.0, 1.0, 1.0))
                    .mul(material_specular_intensity()),
            ),
        );
        fragment.push(specular_color_blended().assign(mix(
            specular_color(),
            diffuse_color().xyz(),
            metalness(),
        )));
        fragment.push(specular_f90().assign(mix(
            material_specular_intensity(),
            float(1.0),
            metalness(),
        )));
    } else {
        // `setupSpecular()`: a dielectric F0 of 0.04, blended towards the
        // albedo by metalness, and an F90 of 1.
        fragment.push(specular_color().assign(vec3(0.04, 0.04, 0.04)));
        fragment.push(specular_color_blended().assign(mix(
            vec3(0.04, 0.04, 0.04),
            diffuse_color().rgb(),
            metalness(),
        )));
        fragment.push(specular_f90().assign(float(1.0)));
    }
    fragment
        .push(diffuse_contribution().assign(diffuse_color().rgb().mul(metalness_node.one_minus())));

    // `MeshPhysicalNodeMaterial.setupVariants()`, after
    // `MeshStandardNodeMaterial`'s: diffuse roughness, clearcoat, sheen,
    // iridescence, then anisotropy.
    //
    // DIFFUSE ROUGHNESS — `useDiffuseRoughness` is `diffuseRoughness > 0`, and
    // `DiffuseRoughness` is `materialDiffuseRoughness.clamp()`.
    let use_diffuse_roughness =
        table.reads(Field::DiffuseRoughness) && material.diffuse_roughness > 0.0;
    if use_diffuse_roughness {
        fragment.push(diffuse_roughness().assign(material_diffuse_roughness().clamp(0.0, 1.0)));
    }

    let use_clearcoat = table.reads(Field::Clearcoat) && material.clearcoat > 0.0;
    let use_anisotropy = table.reads(Field::Anisotropy) && material.anisotropy > 0.0;

    if use_clearcoat {
        // `MaterialNode.CLEARCOAT` / `.CLEARCOAT_ROUGHNESS`: the factor
        // times the map's red channel, the roughness times its green one.
        let clearcoat_value = match &material.clearcoat_map {
            Some(map) => material_clearcoat().mul(texture(map).x()),
            None => material_clearcoat(),
        };
        let clearcoat_roughness_value = match &material.clearcoat_roughness_map {
            Some(map) => material_clearcoat_roughness().mul(texture(map).y()),
            None => material_clearcoat_roughness(),
        };
        fragment.push(clearcoat().assign(clearcoat_value));
        fragment.push(clearcoat_roughness().assign(physical::get_roughness(
            clearcoat_roughness_value,
            !ctx.geometry_missing_normal,
        )));
    }

    // `setupVariants()`' SHEEN block, gated on
    // `useSheen` — `this.sheen > 0`. `MaterialNode.SHEEN` is `sheenColor.mul(
    // sheen )` with the multiply left in the shader, and
    // `MaterialNode.SHEEN_ROUGHNESS` clamps to `[ 0.0001, 1 ]` so `1 / alpha`
    // in `D_Charlie` cannot divide by zero.
    let use_sheen = table.reads(Field::Sheen) && material.sheen > 0.0;
    if use_sheen {
        fragment.push(sheen().assign(material_sheen_color().mul(material_sheen())));
        fragment.push(sheen_roughness().assign(material_sheen_roughness().clamp(0.0001, 1.0)));
    }

    // IRIDESCENCE, gated on `useIridescence` — `this.iridescence > 0`.
    // `MaterialNode.IRIDESCENCE_THICKNESS` is the odd one: with no thickness
    // map it is the *maximum* of `iridescenceThicknessRange` alone (the
    // minimum is not even referenced), and with a map it interpolates between
    // the two by the map's green channel.
    let use_iridescence = table.reads(Field::Iridescence) && material.iridescence > 0.0;
    if use_iridescence {
        fragment.push(iridescence().assign(material_iridescence()));
        fragment.push(iridescence_ior().assign(material_iridescence_ior()));
        let thickness_value = match &material.iridescence_thickness_map {
            // One `iridescenceThicknessMinimum` uniform, read twice.
            Some(map) => {
                let minimum = material_iridescence_thickness_min();
                material_iridescence_thickness_max()
                    .sub(minimum.clone())
                    .mul(texture(map).y())
                    .add(minimum)
            }
            None => material_iridescence_thickness_max(),
        };
        fragment.push(iridescence_thickness().assign(thickness_value));
    }

    if use_anisotropy {
        // `materialAnisotropy` — `MaterialNode.ANISOTROPY`.
        let anisotropy_v = to_var(None, material_anisotropy(material));

        fragment.push(anisotropy().assign(length(anisotropy_v.clone())));
        fragment.push(if_else(
            anisotropy().equal(float(0.0)),
            vec![anisotropy_v.assign(vec2(1.0, 0.0))],
            vec![
                anisotropy_v.assign(anisotropy_v.div(anisotropy())),
                anisotropy().assign(anisotropy().clamp(0.0, 1.0)),
            ],
        ));
        // Roughness along the anisotropy bitangent is the material roughness;
        // along the tangent it grows with anisotropy.
        fragment.push(alpha_t().assign(mix(
            roughness().mul(roughness()),
            float(1.0),
            anisotropy().mul(anisotropy()),
        )));
        fragment.push(
            anisotropy_t().assign(
                tbn_view_matrix()
                    .element(0)
                    .mul(anisotropy_v.clone().x())
                    .add(tbn_view_matrix().element(1).mul(anisotropy_v.clone().y())),
            ),
        );
        fragment.push(
            anisotropy_b().assign(
                tbn_view_matrix()
                    .element(1)
                    .mul(anisotropy_v.clone().x())
                    .sub(tbn_view_matrix().element(0).mul(anisotropy_v.y())),
            ),
        );
    }

    // TRANSMISSION. `useTransmission` is `transmission > 0`; the volume
    // fields ride with it whether or not `KHR_materials_volume` set them,
    // because three assigns all four unconditionally inside the branch.
    let opaque_frame = if table.reads(Field::Transmission) && material.transmission > 0.0 {
        ctx.viewport_opaque_mip.as_ref()
    } else {
        None
    };
    if opaque_frame.is_some() {
        // `MaterialNode.TRANSMISSION`: the factor times the map's red channel.
        let transmission_value = match &material.transmission_map {
            Some(map) => material_transmission().mul(texture(map).x()),
            None => material_transmission(),
        };
        fragment.push(transmission().assign(transmission_value));
        // `MaterialNode.THICKNESS`: the factor times the map's green channel.
        let thickness_value = match &material.thickness_map {
            Some(map) => material_thickness().mul(texture(map).y()),
            None => material_thickness(),
        };
        fragment.push(thickness().assign(thickness_value));
        fragment.push(attenuation_distance().assign(material_attenuation_distance()));
        fragment.push(attenuation_color().assign(material_attenuation_color()));
    }

    fragment.push(emissive_color().assign(material_emissive_value(material)));
    // `clippingAlpha()`, ahead of the lazily built `LightsNode`.
    fragment.extend(clip_alpha);

    // `NodeMaterial.setupLighting()`: `sceneLighting = this.lights === true &&
    // builder.renderer.lighting.enabled`, `materialLightings = sceneLighting ?
    // this.setupMaterialLightings( builder ) : []` — the environment is one of
    // those, so a pass with lighting disabled drops it too — and the chain is
    // built only `if ( lightsNode && ( materialLightings.length > 0 ||
    // lightsNode.getScope().hasLights ) )`. With neither, `setupOutgoingLight()`
    // stands as it is: `DiffuseColor.rgb`.
    let scene_lighting = material.lights && !ctx.lighting_disabled;
    let material_environment = material
        .pmrem_env
        .clone()
        .map(environment::Environment::Pmrem);
    let environment = material_environment
        .as_ref()
        .or(ctx.environment.as_ref())
        .filter(|_| scene_lighting);
    let lights = if scene_lighting {
        material_lights(material, ctx)
    } else {
        Vec::new()
    };

    // The `AONode` is one of the `materialLightings` too, so an occluded
    // material runs the chain even with no light and no environment.
    let outgoing = if scene_lighting && (environment.is_some() || has_ao || !lights.is_empty()) {
        let model = Physical::start(
            use_sheen,
            use_clearcoat,
            use_diffuse_roughness,
            use_iridescence,
            opaque_frame,
            fragment,
        );

        // `LightingContextNode`'s five accumulators. three.js declares each at
        // the point of its first use; hoisting the zeros here is the one
        // reordering in this flow (see `docs/nodes.md` §8) and reads nothing
        // before it is written either way. Each is a var whose initialiser is
        // the zero, so the var itself, as a statement, is the whole of it: an
        // `assign( vec3( 0 ) )` would emit the initialiser and then the same
        // zero again (issue #281).
        fragment.push(direct_diffuse());
        fragment.push(direct_specular());
        fragment.push(irradiance());
        fragment.push(indirect_diffuse());
        fragment.push(indirect_specular());

        for light in &lights {
            physical::direct_light(
                &model,
                light,
                material.received_shadow_position_node.as_ref(),
                fragment,
            );
        }

        model.indirect_diffuse(fragment);
        // `EnvironmentNode` is a lighting node, so its two `addAssign`s land
        // between `indirectDiffuse()` and `indirectSpecular()` — and with them
        // the declarations of `radiance` and `iblIrradiance`.
        if let Some(environment) = environment {
            environment::setup(environment, use_anisotropy, use_clearcoat, fragment);
        }
        // `AONode( context.ambientOcclusion )`, the last entry
        // `setupLightsNode()` pushes, reading the `AmbientOcclusion` property
        // `setup_ambient_occlusion` wrote above.
        if has_ao {
            ao_lighting_node(fragment);
        }
        model.indirect_specular(
            environment.is_some(),
            material.environment_specular,
            fragment,
        );
        model.ambient_occlusion(has_ao, fragment);

        // Transmission's own backdrop wins over `material.backdropNode`:
        // `PhysicalLightingModel.start()` overwrites `context.backdrop`.
        let direct_plus_indirect = direct_diffuse().add(indirect_diffuse());
        let total = if model.backdrop.is_some() {
            model.total_diffuse(direct_plus_indirect)
        } else {
            backdrop_blend(material, direct_plus_indirect)
        };
        fragment.push(total_diffuse().assign(total));
        fragment.push(total_specular().assign(direct_specular().add(indirect_specular())));
        fragment.push(outgoing_light().assign(total_diffuse().add(total_specular())));
        // `LightingModel.finish()`, which `NodeMaterial.setupLighting()` runs
        // last: the sheen lobe and the clearcoat lobe's Fresnel blend over
        // `outgoingLight`.
        model.finish(fragment);
        outgoing_light()
    } else {
        diffuse_color().xyz()
    };

    vec4_join(vec![outgoing.add(emissive_color()), diffuse_color().w()]).max(float(0.0))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::math::Color;
    use crate::nodes::NodeBuilder;
    use crate::renderer::RenderTarget;
    use crate::textures::Texture;

    /// `webgpu_postprocessing_ao`'s context:
    /// `builtinAOContext( aoPass.getTextureNode().sample( screenUV ).r )`,
    /// over a `RedFormat` target as `GTAONode`'s is.
    fn ao_context() -> AoContext {
        let target = RenderTarget::new(16, 16);
        target.texture().set_format(wgpu::TextureFormat::R8Unorm);
        AoContext {
            node: texture_uv(&target.texture(), screen_uv()).x(),
        }
    }

    fn lit(ambient_occlusion: Option<AoContext>) -> SetupContext {
        SetupContext {
            lights: vec![LightDesc {
                index: 0,
                kind: LightKind::Directional,
                shadow_map: None,
            }],
            ambient_occlusion,
            ..SetupContext::default()
        }
    }

    fn fragment(material: &MeshBasicNodeMaterial, ctx: &SetupContext) -> String {
        NodeBuilder::new()
            .build(&setup(material, ctx, None))
            .fragment_wgsl
    }

    fn standard() -> MeshBasicNodeMaterial {
        MeshBasicNodeMaterial::standard(Color::from_hex(0xe0d8d0), 0.9, 0.0)
    }

    const AO_LIGHTING: &str = "ambientOcclusion = ( ambientOcclusion * AmbientOcclusion );";

    /// The trimmed body lines of `wgsl`, for order checks.
    fn lines(wgsl: &str) -> Vec<&str> {
        wgsl.lines().map(str::trim).collect()
    }

    fn position(lines: &[&str], needle: &str) -> usize {
        lines
            .iter()
            .position(|line| line.contains(needle))
            .unwrap_or_else(|| panic!("no line contains {needle:?}"))
    }

    #[test]
    fn builtin_ao_context_occludes_a_standard_material() {
        let wgsl = fragment(&standard(), &lit(Some(ao_context())));
        let body = lines(&wgsl);

        // `setupAmbientOcclusion()` right after `setupDiffuseColor()`: the
        // tap, cached in the texture node's var, then the property — the
        // dump's `nodeVar0 = textureSample( … ).x; AmbientOcclusion =
        // nodeVar0;`. (Where the `.x` lands depends on the texture node's
        // type for a one-channel format, which is not this flow's business.)
        let alpha = position(&body, "DiffuseColor.w = 1.0;");
        let tap = position(&body, "( fragCoord.xy / render.");
        assert!(
            body[tap].starts_with("nodeVar0 = textureSample( "),
            "{wgsl}"
        );
        assert_eq!(tap, alpha + 1, "{wgsl}");
        assert!(
            body[tap + 1].starts_with("AmbientOcclusion = nodeVar0"),
            "{wgsl}"
        );

        // `AONode`: the lighting var's initialiser, then the multiply, ahead of
        // the lighting model's occlusion of the indirect terms.
        let ao = position(&body, AO_LIGHTING);
        assert_eq!(body[ao - 1], "ambientOcclusion = 1.0;", "{wgsl}");
        let indirect = position(
            &body,
            "indirectDiffuse = ( indirectDiffuse * vec3<f32>( ambientOcclusion ) );",
        );
        assert!(ao < indirect, "{wgsl}");
        assert_eq!(wgsl.matches("ambientOcclusion = 1.0;").count(), 1, "{wgsl}");
    }

    #[test]
    fn builtin_ao_context_skips_transparent_materials() {
        let mut material = standard();
        material.transparent = true;
        let wgsl = fragment(&material, &lit(Some(ao_context())));
        assert!(!wgsl.contains("AmbientOcclusion = "), "{wgsl}");
        assert!(!wgsl.contains(AO_LIGHTING), "{wgsl}");
        assert!(!wgsl.contains("fragCoord.xy / render."), "{wgsl}");
        // The same program as with no context at all.
        assert_eq!(wgsl, fragment(&material, &lit(None)));
    }

    #[test]
    fn builtin_ao_context_multiplies_into_an_ao_map() {
        let mut material = standard();
        material.ao_map = Some(Texture::new(4, 4, None));

        // `aoMap` alone: `materialAO`, no context tap.
        let map_only = fragment(&material, &lit(None));
        assert!(
            map_only.contains("AmbientOcclusion = ( ( ( nodeVar0.x - 1.0 ) * object."),
            "{map_only}"
        );
        assert!(map_only.contains(AO_LIGHTING), "{map_only}");
        assert!(!map_only.contains("fragCoord.xy / render."), "{map_only}");

        // Both: `materialAO.mul( ao )`.
        let both = fragment(&material, &lit(Some(ao_context())));
        let line = lines(&both)
            .into_iter()
            .find(|line| line.starts_with("AmbientOcclusion = "))
            .expect("AmbientOcclusion is assigned")
            .to_owned();
        assert!(
            line.contains("* object.") && line.contains(") * nodeVar"),
            "{line}"
        );
        assert!(both.contains(AO_LIGHTING), "{both}");

        // A transparent material keeps its map and drops the context.
        material.transparent = true;
        let transparent = fragment(&material, &lit(Some(ao_context())));
        assert_eq!(transparent, fragment(&material, &lit(None)));
    }

    #[test]
    fn builtin_ao_context_occludes_phong_and_basic() {
        let phong = MeshBasicNodeMaterial::phong(Color::from_hex(0x808080));
        let wgsl = fragment(&phong, &lit(Some(ao_context())));
        let body = lines(&wgsl);
        let ao = position(&body, AO_LIGHTING);
        let indirect = position(
            &body,
            "indirectDiffuse = ( indirectDiffuse * vec3<f32>( ambientOcclusion ) );",
        );
        assert!(
            position(&body, "AmbientOcclusion = nodeVar") < ao && ao < indirect,
            "{wgsl}"
        );

        // `MeshBasicNodeMaterial`: the `AONode` alone takes the
        // `BasicLightingModel` path, whose indirect light is the diffuse
        // colour times the occlusion.
        let basic = MeshBasicNodeMaterial::new();
        let wgsl = fragment(
            &basic,
            &SetupContext {
                ambient_occlusion: Some(ao_context()),
                ..SetupContext::default()
            },
        );
        assert!(wgsl.contains(AO_LIGHTING), "{wgsl}");
        assert!(
            wgsl.contains("indirectDiffuse = ( indirectDiffuse * vec3<f32>( ambientOcclusion ) );"),
            "{wgsl}"
        );
        assert!(!fragment(&basic, &SetupContext::default()).contains("ambientOcclusion"));
    }

    #[test]
    fn builtin_ao_context_is_part_of_the_cache_key() {
        use std::hash::{BuildHasher, RandomState};
        let hasher = RandomState::new();
        let ao = ao_context();
        let with = hasher.hash_one(lit(Some(ao.clone())));
        assert_eq!(with, hasher.hash_one(lit(Some(ao.clone()))));
        assert_ne!(with, hasher.hash_one(lit(None)));
        // `ao` stays alive to here: the key is the node's address, and a
        // fresh node allocated after `ao` was dropped can reuse it.
        assert_ne!(with, hasher.hash_one(lit(Some(ao_context()))));
        drop(ao);
    }
    /// A plain `envMap` is sampled only by `MeshBasicNodeMaterial`: Sprite,
    /// Points and Line2 reach the same unlit flow but three never wraps their
    /// `envMap` in a `BasicEnvironmentNode`, so with `env_map` set they bind
    /// no cube texture and sample nothing along the reflect vector (#253).
    #[test]
    fn env_map_is_sampled_by_basic_only() {
        use crate::nodes::builder::BindingDesc;
        use crate::nodes::node::TextureSource;
        use crate::textures::{CubeTexture, Image};
        let cube = CubeTexture::new(
            (0..6)
                .map(|_| Image::rgba8(1, 1, vec![255, 255, 255, 255]))
                .collect(),
        );
        let binds_cube = |material: &MeshBasicNodeMaterial| {
            let program =
                NodeBuilder::new().build(&setup(material, &SetupContext::default(), None));
            let bound = program.groups.iter().flatten().any(|binding| {
                matches!(
                    binding,
                    BindingDesc::Texture {
                        source: TextureSource::Cube(_),
                        ..
                    }
                )
            });
            (bound, program.fragment_wgsl)
        };

        let mut basic = MeshBasicNodeMaterial::new();
        basic.env_map = Some(cube.clone());
        let (bound, wgsl) = binds_cube(&basic);
        assert!(bound && wgsl.contains("texture_cube"), "{wgsl}");

        for mut material in [
            MeshBasicNodeMaterial::sprite(),
            MeshBasicNodeMaterial::points(),
            MeshBasicNodeMaterial::line2(Color::from_hex(0xffffff)),
        ] {
            material.env_map = Some(cube.clone());
            let kind = material.kind;
            let (bound, wgsl) = binds_cube(&material);
            assert!(!bound, "{kind:?} binds the env map");
            assert!(!wgsl.contains("texture_cube"), "{kind:?}:\n{wgsl}");
            assert!(!wgsl.contains("Reflectivity"), "{kind:?}:\n{wgsl}");
            // Still warned about, as before.
            assert_eq!(material.unsupported_fields(), ["envMap"]);
            // The same program as with no env map at all.
            material.env_map = None;
            assert_eq!(wgsl, binds_cube(&material).1, "{kind:?}");
        }
    }
}