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
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
//! wgpu scene renderer: pipelines, resource caches, shadows, and post-processing.
//!
//! Walks a [`Scene`](crate::Scene), batches draw calls by material and topology,
//! and writes to a swapchain view or [`super::RenderTarget`]. Post-fx passes
//! share WGSL in [`super::shader`] (`POSTFX_SHADER`, effect kinds 0–30).
use bytemuck::{Pod, Zeroable};
use crate::lights::shadow::{cascade_frusta, shadow_layer_size, Caster, MAX_SHADOW_RECORDS};
use std::collections::HashMap;
use std::sync::Arc;
use super::gpu_mesh::{geom_cache_key, GpuMesh};
use super::gpu_timer::GpuTimer;
use super::gpu_texture::{
cube_cache_key, tex_cache_key, GpuCubeTexture, GpuTexture, MipGenerator, TexCacheKey,
};
/// Identity of the texture set a bind group binds.
///
/// `external_rt_id` is folded in because RT-backed textures bypass the texture
/// cache entirely and resolve through `rt_view_cache`, so two textures with the
/// same upload key can still bind different views.
/// The second half is the morph texture bound at binding 10 — the geometry's
/// cache key and version, `(0, 0)` for the empty default.
/// The last part is the shared sampler's [`sampler_index`].
/// Then the geometry's uv-set texture ([`Renderer::uv_key`]).
type TexBgKey = ([Option<(TexCacheKey, u32)>; 8], (usize, u32), usize, (usize, u32));
/// A material variant's group 2: the variant, then each of its maps' upload
/// key, render-target id, sampler state and uv transform (bit patterns), then
/// the morph texture, then `Material::map_uniforms` and the `envMap`'s identity.
type VariantBgKey = (
super::material_maps::MapVariant,
Vec<(TexCacheKey, u32, u32, [u32; 6])>,
(usize, u32),
[[u32; 4]; 6],
usize,
);
/// One draw of a mesh: its material, and the index range it covers (`None`
/// for all of it), as three.js's render list holds a mesh with groups.
type DrawItem<M> = (M, Option<(u32, u32)>);
fn variant_bg_key(
slots: &MaterialTextureSlots,
v: super::material_maps::MapVariant,
morph: (usize, u32),
uniforms: [[f32; 4]; 6],
) -> VariantBgKey {
let maps = super::material_maps::role_textures(slots)
.into_iter()
.filter(|(r, _)| v.contains(*r))
.filter_map(|(_, t)| t)
.map(|t| {
let sampler = sampler_index(t) as u32;
let [r0, r1] = t.uv_transform_rows();
let xform = [r0[0].to_bits(), r0[1].to_bits(), r0[2].to_bits(), r1[0].to_bits(), r1[1].to_bits(), r1[2].to_bits()];
(tex_cache_key(t), t.external_rt_id.unwrap_or(u32::MAX), sampler, xform)
})
.collect();
let env = slots.env_map.as_ref().map_or(0, |c| std::sync::Arc::as_ptr(c) as usize);
(v, maps, morph, uniforms.map(|r| r.map(f32::to_bits)), env)
}
fn tex_slot_key(slot: &Option<std::sync::Arc<crate::Texture>>) -> Option<(TexCacheKey, u32)> {
slot.as_ref()
.map(|t| (tex_cache_key(t), t.external_rt_id.unwrap_or(u32::MAX)))
}
fn tex_bg_key(slots: &MaterialTextureSlots) -> TexBgKey {
([
tex_slot_key(&slots.map),
tex_slot_key(&slots.normal_map),
tex_slot_key(&slots.roughness_map),
tex_slot_key(&slots.metalness_map),
tex_slot_key(&slots.ao_map),
tex_slot_key(&slots.emissive_map),
tex_slot_key(&slots.matcap_map),
tex_slot_key(&slots.cloud_shadow_map),
], (0, 0), slots.sampler_source().map_or(SAMPLER_DEFAULT, |t| sampler_index(t)), (0, 0))
}
/// Every combination of filter and wrap a texture can ask for: mag × min
/// filter (2 × 2) × `wrapS` × `wrapT` (3 × 3) × mipmap mode (3: linear,
/// nearest, none). three.js gives each texture its own sampler state, so a
/// texture's sampler is looked up, never approximated.
const SAMPLER_COUNT: usize = 108;
/// A map-less material's sampler: linear, trilinear, clamped — three.js's
/// defaults for a `DataTexture`.
const SAMPLER_DEFAULT: usize = 0;
/// `mipmap_filter` as a sampler-table digit: 0 linear (three.js's default),
/// 1 nearest, 2 none.
fn mip_code(m: Option<crate::textures::TextureFilter>) -> usize {
match m {
Some(crate::textures::TextureFilter::Linear) => 0,
Some(crate::textures::TextureFilter::Nearest) => 1,
None => 2,
}
}
/// Index into `Renderer::samplers` for `t`'s `mag_filter`, `min_filter`,
/// `mipmap_filter`, `wrap_s` and `wrap_t`.
fn sampler_index(t: &Texture) -> usize {
use crate::textures::{TextureFilter, TextureWrap};
let wrap = |w: TextureWrap| match w {
TextureWrap::ClampToEdge => 0,
TextureWrap::Repeat => 1,
TextureWrap::MirroredRepeat => 2,
};
(t.mag_filter == TextureFilter::Nearest) as usize
+ ((t.min_filter == TextureFilter::Nearest) as usize) * 2
+ wrap(t.wrap_s) * 4
+ wrap(t.wrap_t) * 12
+ mip_code(t.mipmap_filter) * 36
}
/// [`sampler_index`] for a cube texture: its filters, clamped — a cube map's
/// seams are its faces' edges.
fn cube_sampler_index(c: &crate::textures::CubeTexture) -> usize {
use crate::textures::TextureFilter;
(c.mag_filter == TextureFilter::Nearest) as usize
+ ((c.min_filter == TextureFilter::Nearest) as usize) * 2
+ mip_code(c.mipmap_filter) * 36
}
/// The sampler [`sampler_index`] `i` names. With no mipmaps the level of detail
/// is held at 0, so minification samples the full-size image as three.js's
/// `LinearFilter` / `NearestFilter` do; anisotropic filtering only where every
/// filter is linear (wgpu allows it nowhere else).
fn make_sampler(device: &wgpu::Device, i: usize) -> wgpu::Sampler {
let filter = |nearest: bool| if nearest { wgpu::FilterMode::Nearest } else { wgpu::FilterMode::Linear };
let address = |w: usize| match w {
1 => wgpu::AddressMode::Repeat,
2 => wgpu::AddressMode::MirrorRepeat,
_ => wgpu::AddressMode::ClampToEdge,
};
let (mag_nearest, min_nearest) = (i & 1 != 0, i & 2 != 0);
let mip = i / 36;
let all_linear = !mag_nearest && !min_nearest && mip == 0;
device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers map sampler"),
address_mode_u: address((i / 4) % 3),
address_mode_v: address((i / 12) % 3),
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: filter(mag_nearest),
min_filter: filter(min_nearest),
mipmap_filter: if mip == 0 { wgpu::MipmapFilterMode::Linear } else { wgpu::MipmapFilterMode::Nearest },
lod_max_clamp: if mip == 2 { 0.0 } else { 32.0 },
anisotropy_clamp: if all_linear { 16 } else { 1 },
..Default::default()
})
}
/// A draw's index (or vertex) range: its span, clamped to `count`, or all of
/// it.
/// Make `current` the `w × h` pair if it or `spare` already is (swapping
/// them), and say whether a new one has to be made. When it does, the old
/// current one is kept as the spare.
fn take_sized<T>(current: &mut Option<(u32, u32, T, T)>, spare: &mut Option<(u32, u32, T, T)>, w: u32, h: u32) -> bool {
let fits = |t: &Option<(u32, u32, T, T)>| matches!(t, Some((cw, ch, ..)) if *cw == w && *ch == h);
if fits(current) {
return false;
}
std::mem::swap(current, spare);
!fits(current)
}
fn draw_span(range: Option<(u32, u32)>, count: u32) -> std::ops::Range<u32> {
match range {
Some((start, end)) => start.min(count)..end.min(count),
None => 0..count,
}
}
/// One geometry's morph targets on the GPU: three.js's morph texture, an
/// `Rgba32Float` 2D array with a layer per target (see
/// [`crate::core::MorphTexels`]).
/// three.js's transmission render target (`transmissionRenderTarget`): the
/// opaque scene drawn linear and untone-mapped at the main target's size, with
/// a full mip chain the transmissive materials read blurred by roughness.
struct TransmissionCapture {
texture: wgpu::Texture,
/// Every level, for sampling.
view: wgpu::TextureView,
/// Level 0, for drawing into.
target_view: wgpu::TextureView,
_depth: wgpu::Texture,
depth_view: wgpu::TextureView,
/// A copy the back-face pass samples while it draws into `texture`.
copy: wgpu::Texture,
copy_view: wgpu::TextureView,
size: (u32, u32),
levels: u32,
}
/// A geometry's extra uv sets — three.js's `uv1`, `uv2` and `uv3` — as one
/// texture the vertex stage reads by vertex index (`vertex_uv_sets` in the
/// shader): two `Rgba32Float` texels a vertex, `(uv1, uv2)` and `(uv3, 0, 0)`,
/// row-major. A texture rather than vertex attributes so the interleaved
/// vertex layout [`Renderer::vertex_buffer`] publishes stays as it is, and so
/// no pipeline grows a vertex buffer that most geometry would leave unbound.
struct UvSetTexture {
version: u32,
_texture: wgpu::Texture,
view: wgpu::TextureView,
}
/// The three.js names of the extra uv sets, in channel order from 1.
const UV_SET_NAMES: [&str; 3] = ["uv1", "uv2", "uv3"];
/// The group-2 layout entry for [`UvSetTexture`] (binding 8), which every
/// layout the shared vertex stage runs under declares.
fn uv_sets_entry() -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}
}
struct MorphTexture {
version: u32,
_texture: wgpu::Texture,
view: wgpu::TextureView,
/// For an `InstancedMesh` with a morph texture: the layer holding the
/// per-instance rows and the texture's width, so the rows can be
/// rewritten in place when only the influences change.
instance_layer: Option<(u32, u32)>,
}
use super::shader::{
MAX_DIR_LIGHTS, MAX_HEMI_LIGHTS, MAX_POINT_LIGHTS, MAX_RECT_LIGHTS, MAX_SPOT_LIGHTS,
};
use crate::cameras::Camera;
use crate::core::{BufferGeometry, ObjectKind};
use crate::lights::Light;
use crate::materials::{Material, MaterialKind, MaterialTextureSlots};
use crate::math::{Frustum, Matrix3, Matrix4, Sphere, Vector3};
use crate::scene::Scene;
use crate::textures::{CubeTexture, Texture, TextureFormat};
// Post-fx draws described as data, for the composer in `crate::postprocessing`.
mod postfx_op;
pub use postfx_op::{PostFxBlend, PostFxNoise, PostFxOp, PostFxOutput};
fn rt_sample_format(format: wgpu::TextureFormat) -> wgpu::TextureFormat {
if format == wgpu::TextureFormat::Rgba16Float {
format
} else {
format.add_srgb_suffix()
}
}
// ---------- GPU layout types ----------
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct DirLightGpu {
direction: [f32; 4],
color: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct PointLightGpu {
position: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct SpotLightGpu {
position: [f32; 4],
direction: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct HemiLightGpu {
sky_color: [f32; 4],
ground_color: [f32; 4],
direction: [f32; 4],
}
/// A rectangular area light. `right`/`up` are **half-extent** vectors in world
/// space, so the four corners are `position ± right ± up` and the emitting face
/// normal is `normalize(cross(right, up))`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct RectLightGpu {
position: [f32; 4],
color: [f32; 4],
right: [f32; 4],
up: [f32; 4],
}
/// Group 3's `EnvUniforms` (binding 13): the environment one draw's
/// image-based light reads — the scene's or a Standard/Physical material's own
/// `envMap` — with its sampling parameters, intensity and rotation. See the
/// WGSL struct of the same name.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct EnvUniforms {
/// PMREM atlas texel width and height, its top mip (or the plain cube's
/// last mip), and 1 when it is an atlas.
params: [f32; 4],
/// x: 1 when there is an environment; y: its intensity.
info: [f32; 4],
/// Rows of the lookup rotation.
rot: [[f32; 4]; 3],
}
impl EnvUniforms {
/// No environment: the image-based light is off.
const NONE: Self = Self {
params: [0.0; 4],
info: [0.0, 1.0, 0.0, 0.0],
rot: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
};
/// `cube`, uploaded as `gpu`, at `intensity` and `rotation`.
fn of(cube: &CubeTexture, gpu: &GpuCubeTexture, intensity: f32, rotation: crate::math::Euler) -> Self {
let params = match &cube.cube_uv_atlas {
Some(a) => [a.texel_width, a.texel_height, a.lod_max as f32, 1.0],
None => [0.0, 0.0, gpu.texture.mip_level_count().saturating_sub(1) as f32, 0.0],
};
Self {
params,
info: [1.0, intensity, 0.0, 0.0],
rot: crate::materials::environment_lookup_rows(rotation, cube.cube_uv_atlas.is_none()),
}
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct FrameUniforms {
view: [f32; 16],
projection: [f32; 16],
view_proj: [f32; 16],
camera_position: [f32; 4],
ambient: [f32; 4],
light_counts: [u32; 4],
/// x: tone-mapping mode (0 none, 1 linear, 2 ACES), y: exposure, z: IBL on,
/// w: linear framebuffer (1 = HalfFloat RT, skip sRGB encode on write)
tone_mapping_exposure: [f32; 4],
/// Fog color rgb + a (a unused). Multiplied with the mix factor in shader.
fog_color: [f32; 4],
/// x: near (linear), y: far (linear), z: density (exp2), w: mode (0/1/2)
fog_params: [f32; 4],
/// x: viewport width (pixels), y: viewport height (pixels), zw: reserved.
viewport_size: [f32; 4],
/// CubeUV PMREM: x/y texel size, z max mip, w = 1 when CubeUV active.
/// The shader reads these from `EnvUniforms` now, per environment; kept
/// here for the custom-shader preamble's `Frame` layout.
env_map_params: [f32; 4],
dir_lights: [DirLightGpu; MAX_DIR_LIGHTS],
point_lights: [PointLightGpu; MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu; MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu; MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu; MAX_RECT_LIGHTS],
/// x: rect-area light count, y: geometric specular antialiasing on,
/// z: reflective transparency on, w: the transmission capture's mip count
/// (0 = none). `light_counts` was already full.
light_counts2: [u32; 4],
/// x: shadow records in use.
shadow_info: [u32; 4],
/// One per shadow-casting light, which names it in its own `color[3]`
/// (record + 1). See `ShadowRecordGpu`.
shadows: [ShadowRecordGpu; MAX_SHADOW_RECORDS],
}
impl Default for FrameUniforms {
fn default() -> Self {
Self {
view: [0.0; 16],
projection: [0.0; 16],
view_proj: [0.0; 16],
camera_position: [0.0; 4],
ambient: [0.0; 4],
light_counts: [0; 4],
// Default: NoToneMapping, exposure 1.0 — matches three.js default.
tone_mapping_exposure: [0.0, 1.0, 0.0, 0.0],
fog_color: [1.0, 1.0, 1.0, 1.0],
fog_params: [1.0, 1000.0, 0.0, 0.0],
viewport_size: [1.0, 1.0, 0.0, 0.0],
env_map_params: [0.0; 4],
dir_lights: [DirLightGpu::default(); MAX_DIR_LIGHTS],
point_lights: [PointLightGpu::default(); MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu::default(); MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu::default(); MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu::default(); MAX_RECT_LIGHTS],
light_counts2: [0; 4],
shadow_info: [0; 4],
shadows: [ShadowRecordGpu::zeroed(); MAX_SHADOW_RECORDS],
}
}
}
/// Build the environment `@group(3)` bind group. The layout (13 bindings: env
/// cube + samplers, three shadow maps + comparison samplers, the CubeUV atlas,
/// and the screen-space glass color/depth/back-depth) is fixed here in one place,
/// so the four construction sites (default, shadow-dummies, per-frame, glass)
/// just pass the 13 views/samplers in binding order and a new binding is added
/// once. Texture vs. sampler wrapping is encoded by the arg position.
/// The environment/shadow bind group.
///
/// The screen-space capture is deliberately not here. It belongs to the
/// refraction pass's own group 3, built by hand at its call site, because a
/// declared binding costs a texture unit whether or not the entry point reads it
/// — so carrying it here would have cost every pipeline three units it never
/// uses, which is one more than WebGL2 has to spare.
macro_rules! env_bind_group {
($device:expr, $bgl:expr, $label:expr,
$t0:expr, $s1:expr, $t2:expr, $s3:expr, $t4:expr, $s5:expr,
$t6:expr, $s7:expr, $t8:expr, $u13:expr, $ltc14:expr $(,)?) => {{
let entries = [
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView($t0),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler($s1),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView($t2),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler($s3),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView($t4),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::Sampler($s5),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView($t6),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler($s7),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView($t8),
},
wgpu::BindGroupEntry {
binding: 13,
resource: $u13.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 14,
resource: wgpu::BindingResource::TextureView($ltc14),
},
];
$device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some($label),
layout: $bgl,
entries: &entries,
})
}};
}
/// A material's own environment: the cube's upload, its intensity and its
/// rotation (angle bit patterns, then the axis order's index).
type MaterialEnvKey = (super::gpu_texture::CubeCacheKey, u32, [u32; 4]);
fn material_env_key(env: (&std::sync::Arc<CubeTexture>, f32, crate::math::Euler)) -> MaterialEnvKey {
let (cube, intensity, r) = env;
let order = crate::math::EulerOrder::ALL.iter().position(|o| *o == r.order).unwrap_or(0) as u32;
(
cube_cache_key(cube),
intensity.to_bits(),
[r.x.to_bits(), r.y.to_bits(), r.z.to_bits(), order],
)
}
/// Views and bind groups the temporal pass reuses across an accumulation run.
///
/// Keyed by nothing: it is dropped whenever `ensure_taa_targets` rebuilds the
/// history, which is the only thing any of it depends on.
struct TaaBindCache {
/// Resolve bind groups, indexed by `taa_frame % 2` — the history buffers
/// ping-pong, so there are exactly two arrangements.
resolve: [wgpu::BindGroup; 2],
/// Blit bind groups, same indexing.
blit: [wgpu::BindGroup; 2],
}
/// One cached instance buffer: see `Renderer::instance_buffer`.
struct InstanceBuffer {
buffer: wgpu::Buffer,
/// What it holds, to skip rewriting unchanged data.
data: Vec<f32>,
/// The `instance_frame` it was last used in.
frame: u64,
/// The mesh's `instance_version` and instance count when written, for
/// a mesh that declares one.
version: Option<(u64, usize)>,
/// Changes whenever what it holds does: what the shadow fingerprint
/// reads to tell a still instanced caster from a moving one.
stamp: u64,
}
/// Uniform for the TAA resolve pass — see `TAA_SHADER`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct TaaUniforms {
inv_view_proj: [f32; 16],
prev_view_proj: [f32; 16],
/// x: width, y: height, z: history weight, w: first-frame flag.
params: [f32; 4],
/// xyz: how far the camera moved since the previous frame. w: converge
/// mode — 0 for the feedback blend, 1 for a running mean over
/// sRGB-encoded bytes, 2 for a running mean over linear light.
cam_delta: [f32; 4],
/// x: 1 when the depth it reads is reversed (`set_reversed_z`).
flags: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct MeshUniforms {
model: [f32; 16],
normal_matrix: [f32; 16],
color: [f32; 4],
emissive: [f32; 4],
specular: [f32; 4],
/// x: shininess/depth_near, y: opacity/depth_far, z: roughness, w: metalness
params: [f32; 4],
/// x: ao_intensity, y/z: normal_scale, w: unused
params2: [f32; 4],
/// Physical layers: x: clearcoat, y: clearcoat_roughness, z: ior, w: transmission
params3: [f32; 4],
/// Physical volume: x: thickness (glass refraction/march depth),
/// y: dispersion, z: vertex_emissive, w: anisotropy_rotation (radians).
params4: [f32; 4],
/// Physical layers 2: x: iridescence, y: iridescence_ior,
/// z: iridescence_thickness (nm), w: sheen strength.
params5: [f32; 4],
/// x/y/z: sheen_color, w: sheen_roughness.
params6: [f32; 4],
/// x/y/z: attenuation_color, w: attenuation_distance (0 = disabled, which
/// keeps the legacy "tint transmission by base color" behaviour).
params7: [f32; 4],
/// x: displacement_scale, y: displacement_bias, z: emissive_night_side
/// (w reserved).
params8: [f32; 4],
/// UV transform from the primary map: xy offset, zw repeat.
params9: [f32; 4],
/// x: cloud shell height, y: cloud shadow strength, z: cloud longitude
/// offset (turns), w: twilight wrap width.
params10: [f32; 4],
/// xyz: twilight colour, w: the sun's angular radius in radians.
params11: [f32; 4],
/// Eclipse occluder: world-space xyz centre, w radius (0 = none).
params12: [f32; 4],
/// x: cloud forward-scatter strength, y: scattering anisotropy g,
/// z: ozone absorption strength, w: aurora strength.
params13: [f32; 4],
/// xyz: aurora colour, w: geomagnetic colatitude of the auroral oval, in
/// degrees from the pole.
params14: [f32; 4],
/// x: material kind, y: texture flags
flags: [u32; 4],
/// Morph targets: (count, base influence, texels per vertex, flags) — see
/// `MeshUniforms.morph` in the shader and [`crate::core::morph_uniforms`].
morph: [f32; 4],
/// `morphTargetInfluences`, zero-padded to `MAX_MORPH_TARGETS`, four to
/// a vector.
morph_weights: [[f32; 4]; crate::core::MAX_MORPH_TARGETS / 4],
/// `Object3D::clip_plane` as (normal, constant); all zero clips nothing.
clip_plane: [f32; 4],
}
/// `Object3D::clip_plane` for `MeshUniforms`: the shader treats an all-zero
/// plane as none (no real plane has a zero normal).
fn clip_plane_of(obj: &crate::core::Object3D) -> [f32; 4] {
obj.clip_plane
.map_or([0.0; 4], |p| [p.normal.x, p.normal.y, p.normal.z, p.constant])
}
// Texture-flag bits — keep in sync with shader.rs FLAG_*.
const FLAG_MAP: u32 = 1;
const FLAG_NORMAL_MAP: u32 = 2;
const FLAG_ROUGHNESS_MAP: u32 = 4;
const FLAG_METALNESS_MAP: u32 = 8;
const FLAG_AO_MAP: u32 = 16;
const FLAG_EMISSIVE_MAP: u32 = 32;
const FLAG_MATCAP_MAP: u32 = 64;
const FLAG_DASHED: u32 = 128;
const FLAG_SHADOW_MAT: u32 = 256;
const FLAG_RECEIVE_SHADOW: u32 = 512;
const FLAG_CLOUD_SHADOW: u32 = 4096;
/// The draw writes into a plain (`Unorm`) view of an sRGB target, so the shader
/// encodes its output itself — the encoded-blend pass, see `encoded_pass`.
const FLAG_ENCODED_OUT: u32 = 8192;
/// three.js `toneMapped: false` (see `apply_tone_mapping` in the shader).
const FLAG_NO_TONE_MAP: u32 = 16384;
/// `mesh.flags.z`: a sprite or point drawn on the blended pipeline whose
/// material is not `transparent` — written with alpha 1, which blends to a
/// plain write, as three.js draws an opaque sprite.
const FLAG_OPAQUE_OUT: u32 = 32768;
/// `mesh.flags.z`: a transmissive `PhysicalMaterial` in `TransparencyMode::Glass`
/// or `Oit`. Those modes blend, so the background arrives through the blend
/// rather than from the transmission capture, which is only made for
/// three.js's own transmission.
const FLAG_BLENDED_GLASS: u32 = 65536;
/// `mesh.flags.z`: thin transmissive glass — a `PhysicalMaterial` with
/// `transmission` and either `thickness` 0 (three.js's thin-walled) or
/// `TransparencyMode::Glass`. Light goes straight through it, so its shadow
/// casting drops the share of shadow-map texels that gets through and the
/// shadow filter averages it into a partial shadow (`shadow_cut` in the
/// shader). Solid glass bends that light into a caustic instead, and keeps a
/// full shadow.
const FLAG_SHADOW_TRANSMITS: u32 = 131072;
/// Shadow pipelines for casters cut by `alphaTest` and a map (three.js's
/// shadow depth material takes both): `fs_shadow_cut` discards where the map's
/// alpha is under the test.
/// `base` for a draw on material variant `v` — itself for `None`. A free
/// function over the renderer's fields, because it is called inside render
/// passes that hold other borrows of the renderer. The variant must already be
/// built (`Renderer::ensure_map_variant`, done for every draw before the
/// passes).
/// `m` remapped to reversed depth: clip `z' = w - z`, so NDC depth runs from
/// 1 at the near plane to 0 at the far one, with x, y and w untouched.
fn reverse_depth(m: &crate::math::Matrix4) -> crate::math::Matrix4 {
let mut out = *m;
for c in 0..4 {
out.elements[c * 4 + 2] = m.elements[c * 4 + 3] - m.elements[c * 4 + 2];
}
out
}
fn variant_pipeline(
pipes: &mut super::pipeline_state::StatePipelines,
variants: &HashMap<super::material_maps::MapVariant, (wgpu::ShaderModule, wgpu::BindGroupLayout)>,
device: &wgpu::Device,
main: &wgpu::ShaderModule,
base: &wgpu::RenderPipeline,
v: Option<super::material_maps::MapVariant>,
) -> wgpu::RenderPipeline {
let Some(v) = v else {
return base.clone();
};
let Some((module, bgl)) = variants.get(&v) else {
log::error!("threers: a draw names material variant {v:?}, which was not built");
return base.clone();
};
pipes.relayout(device, base, v.key(), 2, bgl, main, module).unwrap_or_else(|| {
// Every pipeline that binds a material's group 2 is recorded, so this
// is a bug: the bind group will not match the pipeline. Say so.
log::error!("threers: a material-variant draw reached an unrecorded pipeline");
base.clone()
})
}
/// three.js `WebGLShadowMap`'s `shadowSide` for a material `side`: a
/// front-sided caster records its back faces, a back-sided one its front
/// faces, and a double-sided one both.
/// three.js `side` for a mesh drawn as faces in the colour passes: FrontSide
/// culls back faces, BackSide front faces, DoubleSide none. `None` for what is
/// not faces (lines, points, sprites, the sky).
fn side_cull(faces: bool, side: u32) -> Option<Option<wgpu::Face>> {
faces.then_some(match side {
1 => Some(wgpu::Face::Front),
2 => None,
_ => Some(wgpu::Face::Back),
})
}
fn shadow_cull(side: u32) -> Option<wgpu::Face> {
match side {
1 => Some(wgpu::Face::Back),
2 => None,
_ => Some(wgpu::Face::Front),
}
}
/// [`shadow_cull`] for the point-light pass, whose cube faces negate clip y
/// (cube maps are left-handed): that one mirror reverses every triangle's
/// winding, so the faces to cull swap.
fn shadow_cull_point(side: u32) -> Option<wgpu::Face> {
match shadow_cull(side) {
Some(wgpu::Face::Front) => Some(wgpu::Face::Back),
Some(wgpu::Face::Back) => Some(wgpu::Face::Front),
None => None,
}
}
struct ShadowCutPipelines {
dir: wgpu::RenderPipeline,
spot: wgpu::RenderPipeline,
dir_skinned: wgpu::RenderPipeline,
spot_skinned: wgpu::RenderPipeline,
dir_instanced: wgpu::RenderPipeline,
spot_instanced: wgpu::RenderPipeline,
}
struct CachedGpuMesh {
version: u32,
mesh: GpuMesh,
/// Object-space bounds, for frustum culling. `None` when the geometry has
/// no position attribute, which is the one case that must never be culled
/// — there is nothing to test it against.
sphere: Option<Sphere>,
}
/// A bounding sphere for `geom` without mutating it.
///
/// `BufferGeometry::compute_bounding_sphere` caches into the geometry and so
/// needs `&mut`; geometries reach the renderer behind an `Arc` and are shared,
/// so this recomputes instead. Same construction: centre of the AABB, radius
/// the furthest vertex from it.
fn local_bounding_sphere(geom: &BufferGeometry) -> Option<Sphere> {
if let Some(s) = geom.bounding_sphere {
return Some(s);
}
let mut lo = Vector3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
let mut hi = Vector3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
for p in geom.positions()? {
lo = Vector3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
hi = Vector3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
}
if !lo.x.is_finite() {
return None;
}
let centre = (lo + hi) * 0.5;
let mut r2 = 0.0f32;
for p in geom.positions()? {
r2 = r2.max((p - centre).length_sq());
}
Some(Sphere::new(centre, r2.sqrt()))
}
/// Camera parameters forwarded into SSAO / SSR post-fx uniforms.
#[derive(Clone, Debug)]
pub struct PostFxCamera {
pub near: f32,
pub far: f32,
pub kernel_radius: f32,
pub kernel_size: u32,
pub proj: [f32; 16],
pub inv_proj: [f32; 16],
}
impl Default for PostFxCamera {
fn default() -> Self {
let mut id = [0f32; 16];
id[0] = 1.0;
id[5] = 1.0;
id[10] = 1.0;
id[15] = 1.0;
Self {
near: 0.1,
far: 100.0,
kernel_radius: 8.0,
kernel_size: 32,
proj: id,
inv_proj: id,
}
}
}
/// How the renderer compresses linear HDR radiance into displayable range.
///
/// Defaults to [`ToneMapping::None`], which matches the renderer's historical
/// behaviour — values above 1.0 hard-clip. That is fine for LDR content but
/// destroys hue in highlights: a clipped gold specular goes white, not gold.
/// Any scene using an HDR environment wants [`ToneMapping::AcesFilmic`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToneMapping {
/// No curve; linear values are clamped to [0, 1] at output.
#[default]
None,
/// Plain exposure scale, then clamp.
Linear,
/// ACES filmic approximation — rolls highlights off smoothly and keeps
/// their hue, which is what makes bright metal read as metal.
AcesFilmic,
/// Khronos PBR Neutral — what glTF viewers use, and what to reach for when
/// the authored colour is the point.
///
/// Below the shoulder it is **almost the identity**: it subtracts a small
/// black offset and otherwise leaves the value alone (0.18 comes out at
/// 0.14, 0.45 at 0.432), so a material's colour survives to the screen
/// instead of being restyled. [`AcesFilmic`](Self::AcesFilmic) lifts the
/// same midtones hard — 0.18 to 0.267 — which is flattering on a lit scene
/// and wrong on a colour chart.
///
/// Only the top is compressed, and it desaturates as it compresses, so an
/// over-exposed highlight resolves towards white the way an over-exposed
/// highlight does. ACES, as the Narkowicz fit used here, is a *per-channel*
/// curve with no cross-channel term at all, so a blown red stays a blown
/// red rather than going white.
Neutral,
/// AgX, as three.js ships it.
///
/// A long shoulder — it holds 3.0 down at 0.82 where ACES is already at
/// 0.95 — so a very bright environment keeps detail in its highlights
/// instead of flaring to a flat patch. It pays for that with its shadows,
/// which it desaturates noticeably: a near-black saturated colour comes
/// back closer to grey than it went in. That is the AgX look, not a defect.
AgX,
}
impl ToneMapping {
/// The mode index the WGSL side switches on.
pub(crate) fn shader_mode(self) -> f32 {
match self {
ToneMapping::None => 0.0,
ToneMapping::Linear => 1.0,
ToneMapping::AcesFilmic => 2.0,
ToneMapping::Neutral => 3.0,
ToneMapping::AgX => 4.0,
}
}
/// The same curves on the CPU, for the renderers that have no shader to run
/// them in (`SvgRenderer`) and the path tracer's film. Takes an *exposed*
/// linear colour, like the WGSL `apply_tone_mapping` does after it scales.
pub fn apply(self, c: [f32; 3]) -> [f32; 3] {
match self {
ToneMapping::None | ToneMapping::Linear => c,
ToneMapping::AcesFilmic => aces_cpu(c),
ToneMapping::Neutral => neutral_cpu(c),
ToneMapping::AgX => agx_cpu(c),
}
}
}
/// three.js r165 `ACESFilmicToneMapping` on an exposed colour, matching
/// `aces_tonemap` in the shader: the 1/0.6 pre-scale, the input matrix, Hill's
/// RRT + ODT fit, the output matrix, then a clamp. Column-major matrices as in
/// the GLSL, so the rows below are its columns.
fn aces_cpu(c: [f32; 3]) -> [f32; 3] {
const INPUT: [[f32; 3]; 3] = [
[0.59719, 0.07600, 0.02840],
[0.35458, 0.90834, 0.13383],
[0.04823, 0.01566, 0.83777],
];
const OUTPUT: [[f32; 3]; 3] = [
[1.60475, -0.10208, -0.00327],
[-0.53108, 1.10813, -0.07276],
[-0.07367, -0.00605, 1.07602],
];
let mul = |m: [[f32; 3]; 3], v: [f32; 3]| -> [f32; 3] {
[
m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2],
m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2],
m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2],
]
};
let v = mul(INPUT, [c[0] / 0.6, c[1] / 0.6, c[2] / 0.6]);
let fit = v.map(|x| (x * (x + 0.0245786) - 0.000090537) / (x * (0.983729 * x + 0.432951) + 0.238081));
mul(OUTPUT, fit).map(|x| x.clamp(0.0, 1.0))
}
/// Khronos PBR Neutral, matching `neutral_tonemap` in the shader.
fn neutral_cpu(c: [f32; 3]) -> [f32; 3] {
const START: f32 = 0.8 - 0.04;
const DESAT: f32 = 0.15;
let x = c[0].min(c[1]).min(c[2]);
let offset = if x < 0.08 { x - 6.25 * x * x } else { 0.04 };
let mut c = [c[0] - offset, c[1] - offset, c[2] - offset];
let peak = c[0].max(c[1]).max(c[2]);
if peak < START {
return c;
}
let d = 1.0 - START;
let new_peak = 1.0 - d * d / (peak + d - START);
for v in c.iter_mut() {
*v *= new_peak / peak.max(1e-6);
}
let g = 1.0 - 1.0 / (DESAT * (peak - new_peak) + 1.0);
[
c[0] + (new_peak - c[0]) * g,
c[1] + (new_peak - c[1]) * g,
c[2] + (new_peak - c[2]) * g,
]
}
/// AgX, matching `agx_tonemap` in the shader. Column-major 3x3s, applied as
/// `m * v`, so the rows below are the shader's columns.
fn agx_cpu(c: [f32; 3]) -> [f32; 3] {
fn mul(m: [[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
[
m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2],
m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2],
m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2],
]
}
const TO_2020: [[f32; 3]; 3] = [
[0.6274, 0.0691, 0.0164],
[0.3293, 0.9195, 0.0880],
[0.0433, 0.0113, 0.8956],
];
const TO_SRGB: [[f32; 3]; 3] = [
[1.6605, -0.1246, -0.0182],
[-0.5876, 1.1329, -0.1006],
[-0.0728, -0.0083, 1.1187],
];
const INSET: [[f32; 3]; 3] = [
[0.856_627_2, 0.137_318_97, 0.111_898_21],
[0.095_121_24, 0.761_242, 0.076_799_42],
[0.048_251_607, 0.101_439_04, 0.811_302_4],
];
const OUTSET: [[f32; 3]; 3] = [
[1.127_100_6, -0.141_329_76, -0.141_329_76],
[-0.110_606_64, 1.157_823_7, -0.110_606_64],
[-0.016_493_939, -0.016_493_939, 1.251_936_4],
];
const MIN_EV: f32 = -12.473_93;
const MAX_EV: f32 = 4.026_069;
let mut v = mul(INSET, mul(TO_2020, c));
for x in v.iter_mut() {
*x = ((x.max(1e-10).log2() - MIN_EV) / (MAX_EV - MIN_EV)).clamp(0.0, 1.0);
let (x2, x4) = (*x * *x, *x * *x * *x * *x);
*x = 15.5 * x4 * x2 - 40.14 * x4 * *x + 31.96 * x4 - 6.868 * x2 * *x
+ 0.4298 * x2
+ 0.1191 * *x
- 0.00232;
}
let mut v = mul(OUTSET, v);
for x in v.iter_mut() {
*x = x.max(0.0).powf(2.2);
}
let v = mul(TO_SRGB, v);
[
v[0].clamp(0.0, 1.0),
v[1].clamp(0.0, 1.0),
v[2].clamp(0.0, 1.0),
]
}
/// Everything the custom pipeline descriptor branches on. Anything left out of
/// this is a material silently drawing with another material's pipeline.
/// The material's `RenderState` is not in it: that is applied over the stock
/// pipeline as a state variant (see `pipeline_state`).
type CustomPipelineKey = (u64, bool, bool, bool, u32);
/// GPU renderer: scene draws, shadow maps, environment sampling, post-fx.
pub struct Renderer {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
pipeline_tri: wgpu::RenderPipeline,
pipeline_tri_alpha: wgpu::RenderPipeline,
// Single-layer glass (depth prepass + LessEqual color pass), sRGB + f16.
pipeline_glass_depth: wgpu::RenderPipeline,
pipeline_glass_color: wgpu::RenderPipeline,
pipeline_glass_depth_f16: wgpu::RenderPipeline,
pipeline_glass_color_f16: wgpu::RenderPipeline,
pipeline_glass_depth_msaa: wgpu::RenderPipeline,
pipeline_glass_color_msaa: wgpu::RenderPipeline,
/// The tint half of the glass colour pass (`GLASS_OUTPUT` 1), drawn just
/// before the colour half: what is behind times the glass's per-channel
/// transmittance.
pipeline_glass_tint: wgpu::RenderPipeline,
pipeline_glass_tint_f16: wgpu::RenderPipeline,
pipeline_glass_tint_msaa: wgpu::RenderPipeline,
/// `[depth, color, tint]` glass for the encoded-blend pass under MSAA
/// (sRGB targets only, as `encoded_blend_pipelines`).
encoded_glass_msaa: Option<[wgpu::RenderPipeline; 3]>,
// Weighted-blended OIT: accumulation pipeline (MRT) + resolve (sRGB + f16).
/// Order-independent transparency accumulation. `None` where attachments
/// cannot blend independently — see
/// [`caps::supports_independent_blend`](crate::renderer::caps::supports_independent_blend).
pipeline_oit: Option<wgpu::RenderPipeline>,
/// `[tint, light]`: the OIT composite's two halves.
pipeline_oit_resolve: [wgpu::RenderPipeline; 2],
pipeline_oit_resolve_f16: [wgpu::RenderPipeline; 2],
pipeline_oit_resolve_msaa: [wgpu::RenderPipeline; 2],
/// OIT accumulation under MSAA, and its multisampled `(width, height,
/// accum, reveal)`, resolved into `oit_targets` at the end of the pass.
pipeline_oit_msaa: Option<wgpu::RenderPipeline>,
oit_msaa_targets: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
/// As `msaa_targets_spare`, for these.
oit_msaa_targets_spare: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
/// The multisampled opaque depth to the single-sampled one, for the
/// refraction pass under MSAA (`DEPTH_RESOLVE_SHADER`). `None` where a
/// shader cannot read a multisampled texture.
depth_resolve: Option<(wgpu::BindGroupLayout, wgpu::RenderPipeline)>,
oit_resolve_bgl: wgpu::BindGroupLayout,
// accum(Rgba16F) + revealage(R16F) targets + the resolve bind group, keyed by size.
oit_targets: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
wgpu::BindGroup,
)>,
/// No-cull triangle pipeline, used for `side: BackSide` / `side: DoubleSide`
/// materials. Without this, three.js apps using BackSide for skybox-style
/// "inside of a box" rendering silently get culled-to-nothing.
pipeline_tri_nocull: wgpu::RenderPipeline,
/// Sky dome: no cull, no depth write, LessEqual (matches three.js Sky depthWrite:false).
pipeline_tri_sky: wgpu::RenderPipeline,
pipeline_tri_wire: wgpu::RenderPipeline,
pipeline_line: wgpu::RenderPipeline,
pipeline_point: wgpu::RenderPipeline,
pipeline_point_alpha: wgpu::RenderPipeline,
pipeline_sprite: wgpu::RenderPipeline,
// Hardware-MSAA variants of the opaque forward pipelines (surface path).
pipeline_tri_msaa: wgpu::RenderPipeline,
pipeline_skinned_msaa: wgpu::RenderPipeline,
pipeline_instanced_msaa: wgpu::RenderPipeline,
pipeline_tri_alpha_msaa: wgpu::RenderPipeline,
pipeline_tri_nocull_msaa: wgpu::RenderPipeline,
pipeline_tri_sky_msaa: wgpu::RenderPipeline,
pipeline_tri_wire_msaa: wgpu::RenderPipeline,
pipeline_line_msaa: wgpu::RenderPipeline,
pipeline_point_msaa: wgpu::RenderPipeline,
/// MSAA sample count for the surface pass: 1 = off, else `MSAA_SAMPLES`.
msaa: u32,
/// See [`set_specular_antialiasing`](Self::set_specular_antialiasing).
specular_antialiasing: bool,
tone_mapping: ToneMapping,
/// Whether this pass's destination is the picture itself, and so gets
/// [`tone_mapping`](Self::tone_mapping). three.js applies tone mapping to
/// the final output only: a pass into a [`RenderTarget`](super::RenderTarget)
/// that does not [present](super::RenderTarget::presents) — and into a
/// cube face — stores untone-mapped light.
tone_map_pass: bool,
exposure: f32,
/// Lazily-created multisampled color + depth targets, keyed by size.
msaa_targets: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
/// The previous size's, kept for a frame that alternates two sizes — a
/// multisampled canvas and a multisampled render target — rather than
/// reallocating both every frame.
msaa_targets_spare: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
/// Whether the last frame's main pass drew into `msaa_targets` — which
/// attachments [`overlay_attachments`](Self::overlay_attachments) hands out.
overlay_msaa: bool,
/// Whether the last frame drawn multisampled. A frame with `Oit` or
/// `Refract` glass cannot, whatever `msaa` asks; `render_to_multisampled`
/// then antialiases it with FXAA instead (`fxaa_fallback`).
last_frame_msaa: bool,
/// What FXAA reads from in that fallback: a copy of the target.
fxaa_scratch: Option<(wgpu::Texture, wgpu::TextureView)>,
/// Half-float color-target variants for EffectComposer / postfx RTs.
pipeline_tri_f16: wgpu::RenderPipeline,
pipeline_tri_alpha_f16: wgpu::RenderPipeline,
pipeline_tri_nocull_f16: wgpu::RenderPipeline,
pipeline_tri_sky_f16: wgpu::RenderPipeline,
pipeline_tri_wire_f16: wgpu::RenderPipeline,
pipeline_line_f16: wgpu::RenderPipeline,
pipeline_point_f16: wgpu::RenderPipeline,
pipeline_point_alpha_f16: wgpu::RenderPipeline,
pipeline_sprite_f16: wgpu::RenderPipeline,
pipeline_instanced_f16: wgpu::RenderPipeline,
pipeline_skinned_f16: wgpu::RenderPipeline,
pipeline_shadow: wgpu::RenderPipeline,
pipeline_shadow_spot: wgpu::RenderPipeline,
pipeline_shadow_point: wgpu::RenderPipeline,
/// The three shadow passes for skinned casters: the posed mesh, on the
/// skinned layout.
pipeline_shadow_skinned: wgpu::RenderPipeline,
pipeline_shadow_spot_skinned: wgpu::RenderPipeline,
pipeline_shadow_point_skinned: wgpu::RenderPipeline,
/// The three shadow passes for an `InstancedMesh` caster: the instance
/// matrices (and per-instance morphs) from vertex slot 1.
pipeline_shadow_instanced: wgpu::RenderPipeline,
pipeline_shadow_spot_instanced: wgpu::RenderPipeline,
/// The directional and spot shadow pipelines for cut-out casters.
shadow_cut: ShadowCutPipelines,
pipeline_shadow_point_instanced: wgpu::RenderPipeline,
pipeline_instanced: wgpu::RenderPipeline,
pipeline_skinned: wgpu::RenderPipeline,
/// `wireframe: true` variants of the instanced and skinned pipelines:
/// LineList over the mesh's wire index buffer, like `pipeline_tri_wire`.
pipeline_instanced_wire: wgpu::RenderPipeline,
pipeline_instanced_wire_f16: wgpu::RenderPipeline,
/// Transparent instanced and skinned draws: alpha-blended, no depth
/// write, as `pipeline_tri_alpha` is for plain meshes.
pipeline_instanced_alpha: wgpu::RenderPipeline,
pipeline_instanced_alpha_f16: wgpu::RenderPipeline,
pipeline_skinned_alpha: wgpu::RenderPipeline,
pipeline_skinned_alpha_f16: wgpu::RenderPipeline,
/// The blended draws' pipelines into the `Unorm` view of an sRGB target,
/// for the encoded-blend pass (see `encoded_pass`): sprite, transparent
/// instanced, transparent skinned. `None` on a target that is not sRGB.
encoded_blend_pipelines: Option<[wgpu::RenderPipeline; 7]>,
pipeline_skinned_wire: wgpu::RenderPipeline,
pipeline_skinned_wire_f16: wgpu::RenderPipeline,
/// Post-fx fullscreen-quad pipeline. Reads one input texture, writes to
/// one output attachment, applies the effect selected by the postfx
/// uniform's effect-kind field.
pipeline_postfx: wgpu::RenderPipeline,
/// Additive-blend variant of the postfx pipeline. Used for bloom composite
/// where the bloom contribution adds to the existing framebuffer content.
pipeline_postfx_add: wgpu::RenderPipeline,
/// Outline overlay: SrcAlpha + One (three.js AdditiveBlending).
pipeline_postfx_outline_add: wgpu::RenderPipeline,
/// Multiply-blend variant (DstColor * SrcColor). Used for SSAO composite.
pipeline_postfx_multiply: wgpu::RenderPipeline,
/// Half-float postfx variants for outline intermediates (Rgba16Float RTs).
pipeline_postfx_f16: wgpu::RenderPipeline,
pipeline_postfx_add_f16: wgpu::RenderPipeline,
postfx_bgl: wgpu::BindGroupLayout,
postfx_sampler: wgpu::Sampler,
postfx_nearest_sampler: wgpu::Sampler,
/// Repeat + nearest sampler for SSAO noise (matches three.js RepeatWrapping).
postfx_noise_sampler: wgpu::Sampler,
/// Pipelines for [`Renderer::run_postfx`], built on first use.
postfx_ext: postfx_op::PostFxExt,
/// Uploaded by SSAOPass — 32 hemisphere samples (vec4 stride).
ssao_kernel_buffer: wgpu::Buffer,
ssao_noise_tex: wgpu::Texture,
ssao_noise_view: wgpu::TextureView,
/// GlitchPass's displacement map (DigitalGlitch `tDisp`): R32Float,
/// `dt_size` square, read nearest as three.js's `DataTexture` is.
glitch_disp_tex: wgpu::Texture,
glitch_disp_view: wgpu::TextureView,
/// RGBA8 staging for [`Renderer::blit_rgba8`].
rgba_upload_tex: wgpu::Texture,
rgba_upload_view: wgpu::TextureView,
/// Alpha-blended 2D overlay pass, built on the first caption draw so
/// projects that never draw one allocate nothing.
/// Only [`Renderer::draw_caption_overlay`] uses this, so without the
/// `captions` feature there is nothing to hold it for.
#[cfg(feature = "captions")]
caption_pass: Option<super::caption_pass::CaptionPass>,
/// A second instance for [`Renderer::draw_overlay`]. Separate from the
/// caption one because that pass owns a persistent texture and the overlay
/// path uploads only the rows that changed — sharing one would mean each
/// drawing over the other's half-updated contents.
overlay_pass: Option<super::caption_pass::CaptionPass>,
mesh_skinned_bgl: wgpu::BindGroupLayout,
sprite_quad: GpuMesh,
frame_bgl: wgpu::BindGroupLayout,
mesh_bgl: wgpu::BindGroupLayout,
tex_bgl: wgpu::BindGroupLayout,
env_bgl: wgpu::BindGroupLayout,
/// three.js's `RectAreaLight` lookup tables (`RectAreaLightUniformsLib`'s
/// `ltc_1`, `ltc_2`) as the two layers of one texture — see [`upload_ltc`].
ltc: (wgpu::Texture, wgpu::TextureView),
/// Group 3 for the refraction pass: the screen-space capture in place of the
/// shadow maps `fs_ss_glass` never samples, so the pass fits in WebGL2's
/// sixteen texture units.
env_bgl_glass: wgpu::BindGroupLayout,
/// Group 2 for shader materials: the sampler and the displacement slot only,
/// shared by every custom draw because neither is per-material for a
/// `ShaderMaterial`.
custom_tex_bind_group: wgpu::BindGroup,
/// Its layout, for the per-draw variant a morphed `ShaderMaterial` binds
/// (the geometry's morph texture at binding 10).
custom_tex_bgl: wgpu::BindGroupLayout,
/// The mesh shader and pipeline layout, kept to build the depth-biased
/// triangle pipelines three.js's `polygonOffset` asks for, on demand.
mesh_shader: wgpu::ShaderModule,
mesh_pipeline_layout: wgpu::PipelineLayout,
/// Those pipelines, by (topology code — see `build_biased_pipeline` —, target
/// variant: 0 colour format, 1 half float, 2 multisampled; factor bits,
/// units).
biased_pipelines: HashMap<(u8, u8, u32, i32), wgpu::RenderPipeline>,
/// The descriptors of every material pipeline, and the variants built
/// from them for materials with a non-default `depthTest` / `depthWrite`
/// / `depthFunc` / `colorWrite`. See `pipeline_state`.
state_pipelines: super::pipeline_state::StatePipelines,
/// A `Unorm` view of the multisampled colour, when that is sRGB — the
/// encoded-blend pass draws through it.
msaa_color_unorm: Option<wgpu::TextureView>,
/// Where the encoded-blend pass draws on a device that cannot view an
/// sRGB texture as `Unorm` (WebGL2): a `Unorm` copy of the target, made
/// and copied back by `encoded_copy`'s two passes. `(width, height, view)`.
encoded_scratch: Option<(u32, u32, wgpu::TextureView)>,
/// The scratch copy's pipelines: in (sRGB target → `Unorm` scratch, bytes
/// kept) and out (back again), with their bind group layout.
encoded_copy: Option<(wgpu::BindGroupLayout, wgpu::RenderPipeline, wgpu::RenderPipeline)>,
/// Bind group layout for custom-shader draws: mesh uniform (binding 0) plus
/// `ShaderMaterial` user data (binding 1 uniform + bindings 2-4 storage), all
/// in @group(1) to stay within WebGPU's 4-bind-group limit.
custom_mesh_bgl: wgpu::BindGroupLayout,
/// Pipeline layout for custom-shader materials ([frame, custom_mesh, tex, env]).
/// `None` where the device cannot hold the custom layout; shader materials
/// are then skipped rather than failing validation on every draw.
custom_pipeline_layout: Option<wgpu::PipelineLayout>,
/// The same for a screen-space shader material
/// (`ShaderMaterial::screen_space`): its group 3 is the refraction pass's
/// (`env_bgl_glass`), which carries the capture at bindings 9–12 that the
/// main layout leaves out.
custom_ss_pipeline_layout: Option<wgpu::PipelineLayout>,
/// Lazily-compiled custom-shader pipelines. See [`CustomPipelineKey`].
custom_pipelines: HashMap<CustomPipelineKey, wgpu::RenderPipeline>,
/// Transparent custom-shader pipelines into the `Unorm` view of an sRGB
/// target, for the encoded-blend pass; keyed as `custom_pipelines` is,
/// less the framebuffer flag.
custom_encoded_pipelines: HashMap<(u64, bool, bool, u32), wgpu::RenderPipeline>,
/// Custom pipelines multisampled, for an opaque shader material in a
/// frame drawn under MSAA; keyed as `custom_encoded_pipelines` is.
custom_msaa_pipelines: HashMap<(u64, bool, bool, u32), wgpu::RenderPipeline>,
/// Shaders that would not compile. Remembered so the error is logged once
/// rather than every frame, and so the draw is skipped rather than retried.
custom_failed: std::collections::HashSet<CustomPipelineKey>,
depth_view: wgpu::TextureView,
/// The renderer's own depth texture (COPY_SRC) for the direct-`render` path.
depth_texture: wgpu::Texture,
/// 1×1 placeholder depth texture for postfx binding 6 when hw depth is unused.
hw_depth_tex: wgpu::Texture,
depth_size: (u32, u32),
geom_cache: HashMap<*const BufferGeometry, CachedGpuMesh>,
/// Whether to skip colour-pass draws the camera cannot see. On by default,
/// matching three.js, where `Object3D.frustumCulled` starts true.
frustum_culling: bool,
/// `(drawn, culled)` for the last frame. Culling is defined to leave the
/// image alone, so a pixel comparison cannot tell whether it did anything
/// — this is the only way to see that it is working, and the only way a
/// test can tell a correct frustum from one that never rejects anything.
cull_stats: (usize, usize),
/// GPU time for the main pass, when the adapter can measure it.
timer: Option<GpuTimer>,
/// GPU time from the first shadow pass to the last, when one ran.
shadow_timer: Option<GpuTimer>,
/// three.js `shadowMap.autoUpdate` / `needsUpdate`.
shadow_map: super::viewport::ShadowMap,
/// What the shadow maps were last drawn for — which caster kinds, at
/// which directional map size. A render needing anything else redraws
/// them whatever [`shadow_map`](Self::shadow_map) says.
shadow_sig: Option<ShadowSig>,
/// What the shadow maps were last drawn from (`shadow_fingerprint`), or
/// `None` when it could not be told — skinned, instanced or custom-shader
/// casters, which change without anything here changing.
/// Each shadow pass's content hash when last drawn (see the update
/// below), so an unchanged pass is skipped.
shadow_pass_hashes: Vec<Option<u64>>,
/// Shadow passes drawn and caster draws issued into them, ever.
shadow_stats: (u64, u64),
/// Renders that drew the shadow maps.
shadow_updates: u64,
skin_attr_cache: HashMap<*const BufferGeometry, wgpu::Buffer>,
/// Morph-target textures, by geometry (rebuilt on a version change).
morph_cache: HashMap<*const BufferGeometry, MorphTexture>,
/// Each `InstancedMesh`'s instance buffers (matrices and tints in slot
/// 0, custom columns in slot 1), kept across frames and rewritten only
/// when the data changes — they used to be allocated anew every frame.
instance_cache: HashMap<(crate::core::ObjectId, u8), InstanceBuffer>,
/// Counts `render_inner` calls; an instance buffer unused for a few of
/// them belonged to a mesh no longer drawn and is dropped.
instance_frame: u64,
/// Source of `InstanceBuffer::stamp`.
instance_stamps: u64,
/// Each geometry's [`UvSetTexture`], for those with `uv1`/`uv2`/`uv3`.
uv_cache: HashMap<*const BufferGeometry, UvSetTexture>,
/// Bound for geometry without extra uv sets (they read zero, as an
/// attribute a geometry lacks does in three.js).
default_uv_sets: (wgpu::Texture, wgpu::TextureView),
/// Bound at the morph slot for every draw without morph targets.
default_morph: (wgpu::Texture, wgpu::TextureView),
/// Wireframe line lists for partial spans (a group or a draw range of a
/// `wireframe: true` mesh), by (geometry, version, start, end).
wire_span_cache: HashMap<(*const BufferGeometry, u32, u32, u32), (wgpu::Buffer, u32)>,
/// Uploaded textures, by [`Texture::id`].
tex_cache: HashMap<TexCacheKey, GpuTexture>,
/// Builds mip chains with the GPU rather than the CPU. See [`MipGenerator`].
mipgen: Option<MipGenerator>,
/// Lookup table for render-target-backed textures, keyed by RT id.
rt_view_cache: HashMap<u32, wgpu::TextureView>,
/// Linear (non-sRGB-decode) sample views for AO/depth/normal postfx buffers.
rt_linear_view_cache: HashMap<u32, wgpu::TextureView>,
/// Render targets keyed by id (for creating per-pass sample views).
rt_registry: HashMap<u32, Arc<super::RenderTarget>>,
/// GPU depth-buffer views for SSAO (Depth32Float, depth-only aspect).
rt_depth_view_cache: HashMap<u32, wgpu::TextureView>,
/// Lookup table for cube render targets' cube views, keyed by RT id.
cube_rt_view_cache: HashMap<u32, wgpu::TextureView>,
/// Highest mip index of the cube currently bound to `env_tex`.
///
/// Carried in a uniform because the shader cannot ask: `textureNumLevels`
/// has no GLSL ES 3.0 equivalent, so on WebGL2 the chain length has to come
/// from the CPU. Recomputed when the environment bind group is rebuilt and
/// applied every frame, since `FrameUniforms` starts from `Default`.
env_max_mip: f32,
cube_cache: HashMap<super::gpu_texture::CubeCacheKey, GpuCubeTexture>,
env_bind_group: wgpu::BindGroup,
shadow_env_bind_group: wgpu::BindGroup,
/// The scene environment's `EnvUniforms`, written each frame.
env_uniform: wgpu::Buffer,
/// Group 3 for Standard/Physical materials with an `envMap` of their own,
/// keyed by the cube, its intensity and its rotation. Rebuilt with the
/// scene's group, whose shadow-map views they share.
material_env_groups: HashMap<MaterialEnvKey, (wgpu::Buffer, wgpu::BindGroup)>,
env_sampler: wgpu::Sampler,
default_env_cube: GpuCubeTexture,
default_cube_uv_view: wgpu::TextureView,
/// The shadow passes' uniforms and group 0 — see
/// `ensure_shadow_pass_buffer` — and the layout and slot stride.
shadow_pass_buffer: Option<(wgpu::Buffer, wgpu::BindGroup)>,
/// The opaque depth redrawn single-sampled (see `depth_replay` where it
/// is built), and its pass uniform: the camera's view-projection.
depth_replay: Vec<wgpu::RenderPipeline>,
depth_replay_pass: Option<(wgpu::Buffer, wgpu::BindGroup)>,
/// Redraw the depth even where it could be resolved: so a test on a
/// native device runs the path WebGL2 takes.
force_depth_replay: bool,
/// This render is a multisampled render target's (`render_to` with
/// `RenderTarget::samples`): the target's depth, which the multisampled
/// depth is resolved into and the glass march copies.
msaa_depth_out: Option<wgpu::Texture>,
shadow_pass_bgl: wgpu::BindGroupLayout,
shadow_pass_stride: u64,
/// three.js `renderer.shadowMap.type`; a light's
/// `ShadowSettings::filter` overrides it.
shadow_type: crate::lights::ShadowType,
env_cached_key: Option<super::gpu_texture::CubeCacheKey>,
/// Rebuild the environment bind group on the next frame regardless of the
/// cache keys.
///
/// Needed because "invalidate" cannot be expressed by clearing those keys: a
/// scene with no environment map already has `None` for both, so `None !=
/// None` detects nothing and the group survives a shadow-texture
/// reallocation still pointing at the old view.
env_dirty: bool,
/// When the env source is a CubeRenderTarget, this is its id. Used to
/// invalidate the env bind group when the RT changes.
env_cached_rt_id: Option<u32>,
/// The shadow maps: a layer per shadow-casting light of each kind, six
/// per point light. See [`ShadowArray`].
dir_shadows: ShadowArray,
spot_shadows: ShadowArray,
point_shadows: ShadowArray,
/// True while rendering one face of an environment cube. Screen-space
/// passes that assume the frame's dimensions are skipped.
cube_pass: bool,
/// `set_viewport` / `set_scissor` / `set_scissor_test` / pixel ratio /
/// auto-clear. See [`super::viewport`].
viewport_state: super::viewport::ViewportState,
shadow_sampler: wgpu::Sampler,
spot_shadow_sampler: wgpu::Sampler,
point_shadow_sampler: wgpu::Sampler,
frame_buffer: wgpu::Buffer,
frame_bind_group: wgpu::BindGroup,
/// The frame group with the stand-in capture, for the capture passes.
frame_bind_group_dummy: wgpu::BindGroup,
frame_buffer_for_bg: wgpu::Buffer,
transmission_sampler: wgpu::Sampler,
transmission: Option<TransmissionCapture>,
/// Which capture pass is running: `None` outside them, `Some(false)` the
/// opaque scene, `Some(true)` double-sided transmissive back faces.
capturing_transmission: Option<bool>,
/// See [`set_reflective_transparency`](Self::set_reflective_transparency).
reflective_transparency: bool,
/// Per draw: its uniforms' offset in `mesh_arena`, its mesh bind group
/// (over that slice) and its texture bind group.
per_mesh: Vec<(u64, wgpu::BindGroup, std::sync::Arc<wgpu::BindGroup>)>,
/// Every draw's `MeshUniforms`, one after another at `mesh_stride`, written
/// with one call a frame. One small buffer per draw meant one
/// `write_buffer` per draw — two thousand meshes, two thousand staging
/// copies, and the largest single cost of a frame on the CPU.
mesh_arena: Option<wgpu::Buffer>,
/// `MeshUniforms` rounded up to the device's uniform offset alignment.
mesh_stride: u64,
/// The frame's uniforms on their way to `mesh_arena`.
mesh_bytes: Vec<u8>,
/// Texture bind groups, keyed on the textures they bind.
///
/// These used to be rebuilt from scratch once per draw per frame — ten
/// texture views and two samplers looked up and a `create_bind_group` for
/// every mesh, every frame, whether or not anything about it had changed.
/// Measured at 0.3 ms for 73 draws, and it grows with the draw count, so
/// a scene with several hundred meshes was paying milliseconds a frame to
/// rebuild bind groups that were bit-for-bit what they had been.
///
/// A bind group is a pure function of the textures it binds, so this is
/// keyed on exactly those and invalidated whenever a texture is uploaded,
/// evicted, or re-registered as a render target.
tex_bg_cache: HashMap<TexBgKey, std::sync::Arc<wgpu::BindGroup>>,
/// The main shader module, on the legacy material-map layout — the module
/// a material shader variant replaces.
main_shader: wgpu::ShaderModule,
/// Material shader variants built so far: each one's module and group-2
/// layout (see `material_maps`).
map_variants: HashMap<super::material_maps::MapVariant, (wgpu::ShaderModule, wgpu::BindGroupLayout)>,
/// three.js `WebGLCubeUVMaps`: each cube texture lighting a
/// Standard/Physical material, prefiltered through PMREM once, by its
/// source's upload key.
pmrem_cache: HashMap<super::gpu_texture::CubeCacheKey, std::sync::Arc<CubeTexture>>,
/// Group-2 bind groups of variant draws.
variant_bg_cache: HashMap<(VariantBgKey, (usize, u32)), std::sync::Arc<wgpu::BindGroup>>,
sampler_linear_repeat: wgpu::Sampler,
/// Material map samplers, by [`sampler_index`].
samplers: Vec<wgpu::Sampler>,
// Default fallbacks (1x1 textures used when a material slot is empty).
default_white_srgb: GpuTexture,
default_white_linear: GpuTexture,
/// 1x1 `Rgba32Float`, bound to the data-texture slots on devices that have
/// storage buffers and therefore never read them. The layout declares the
/// slots either way, so every backend gets the same bind group shape.
default_data_tex_view: wgpu::TextureView,
/// 1x1x1 `R8Unorm` 3D texture for a `ShaderMaterial`'s empty volume slots.
default_volume_view: wgpu::TextureView,
/// Linear, clamp-to-edge: a volume's `u_vol_samp`. Repeat would wrap the
/// far face of a scan onto the near one at the boundary.
sampler_volume: wgpu::Sampler,
/// `(near, far)` of the camera the last frame was drawn with.
last_camera_planes: (f32, f32),
/// `(tan(fov/2), aspect)` of the same camera, read back off its projection.
last_camera_lens: (f32, f32),
default_normal: GpuTexture, // (0.5, 0.5, 1.0, 1.0) — straight up tangent normal
/// The empty cloud-shadow slot. An opaque black default would not do: a cover map
/// is read from *alpha* — so an unset slot there would read as total
/// overcast and black out the planet.
default_transparent: GpuTexture,
// --- Screen-space refraction glass (TransparencyMode::Refract) ---
/// Mipmapped capture of the opaque scene, sampled by the glass shader for
/// screen-space refraction/reflection. `(w, h, texture, all-mips view,
/// per-mip render views, mip count, format)`.
ss_color: Option<SsColor>,
/// Filtering sampler (trilinear) for `ss_color` — roughness selects the LOD.
ss_glass_sampler: wgpu::Sampler,
/// Sampleable copy of the opaque depth (COPY_DST | TEXTURE_BINDING), marched
/// by the glass shader. `(w, h, texture, view)`.
ss_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
/// Nearest glass **back-face** depth (RENDER_ATTACHMENT | TEXTURE_BINDING),
/// used to derive the per-pixel glass thickness for two-surface refraction.
ss_back_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
/// Scratch the size and format of the capture, which a layer of
/// overlapping glass draws into before it becomes the next layer's
/// capture (see `set_refraction_layers`).
ss_layer: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
/// How many layers overlapping refraction glass composites in.
refraction_layers: usize,
/// Depth-only pipeline rendering glass back faces (cull front) into ss_back_depth.
pipeline_ss_back_depth: wgpu::RenderPipeline,
/// Fullscreen "sample one texture → write" pipeline (mip downsample + blit),
/// one per framebuffer format.
pipeline_ss_blit: wgpu::RenderPipeline,
pipeline_ss_blit_f16: wgpu::RenderPipeline,
/// Glass surface pipelines (screen-space refraction/reflection).
pipeline_ss_glass: wgpu::RenderPipeline,
pipeline_ss_glass_f16: wgpu::RenderPipeline,
/// `fs_glass_shadow`: each light's shadow on the refracting surfaces,
/// into `ss_glass_shadow`.
pipeline_glass_shadow: wgpu::RenderPipeline,
ss_glass_shadow: Option<(wgpu::Texture, wgpu::TextureView)>,
/// BGL for the blit/downsample pipeline (texture + sampler).
ss_blit_bgl: wgpu::BindGroupLayout,
// --- Temporal anti-aliasing (opt-in via `set_taa`) ---
taa_enabled: bool,
taa_frame: u32,
/// Accumulate a running mean instead of a feedback blend — see the converge
/// branch in `TAA_SHADER`, and [`Renderer::set_taa_converge`].
taa_converge: bool,
/// Whether the accumulated image is copied back into the frame target this
/// render. Lowered for every sample but the last of an accumulation run —
/// see [`Renderer::set_taa_blit`].
taa_blit: bool,
/// Format the history buffers were built with; see `ensure_taa_targets`.
taa_hist_format: Option<wgpu::TextureFormat>,
/// Sub-pixel offset to use instead of the Halton sequence, in pixels.
///
/// For a caller doing its own accumulation — it needs the jitter without
/// the temporal pass that normally comes with it.
jitter_override: Option<(f32, f32)>,
/// Views of the colour and depth the temporal pass reads, and its two bind
/// groups — one per history parity — kept across samples.
///
/// An accumulation run calls `render` `n` times against textures that do
/// not change, and these were being rebuilt every one of them: two texture
/// views and two bind groups a sample, sixteen samples a frame, three
/// hundred frames. None of it depends on anything but the targets.
taa_bind_cache: Option<TaaBindCache>,
taa_prev_view_proj: [f32; 16],
/// Camera matrices tracked EVERY frame, not just when TAA is on, so a pass
/// running after the render can reproject: `mb_inv_vp` inverts the frame
/// just drawn and `mb_prev_vp` is the one before it. Motion blur needs both
/// and must not depend on whether temporal AA happens to be enabled.
mb_inv_vp: [f32; 16],
mb_prev_vp: [f32; 16],
mb_last_vp: [f32; 16],
/// Camera position at the previous TAA frame, for the sky reprojection.
taa_prev_cam: [f32; 3],
/// Ping-pong history: `(w, h, texA, viewA, texB, viewB)`; frame parity picks
/// read vs. write.
taa_history: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
)>,
taa_uniform: wgpu::Buffer,
taa_bgl: wgpu::BindGroupLayout,
taa_sampler: wgpu::Sampler,
pipeline_taa: wgpu::RenderPipeline,
pipeline_taa_f16: wgpu::RenderPipeline,
color_format: wgpu::TextureFormat,
}
/// Mipmapped opaque-scene capture used by the screen-space glass pass.
struct SsColor {
width: u32,
height: u32,
texture: wgpu::Texture,
/// View over all mips — bound to the glass shader for LOD sampling.
all_mips_view: wgpu::TextureView,
/// One single-mip view per level — render targets for the downsample chain.
mip_render_views: Vec<wgpu::TextureView>,
/// One single-mip sample view per level — sources for the downsample chain.
mip_sample_views: Vec<wgpu::TextureView>,
/// Mip 0 as its `Unorm` twin when the capture is sRGB: the encoded-blend
/// pass draws a refraction frame's blended surfaces into it.
mip0_unorm: Option<wgpu::TextureView>,
mips: u32,
format: wgpu::TextureFormat,
}
/// A hemisphere of sample offsets for SSAO, clustered towards the origin.
///
/// Points are drawn on the +Z hemisphere — the shader rotates them into the
/// fragment's tangent frame — and scaled by a quadratic so that most samples
/// sit close in, which is where occlusion actually varies.
fn default_ssao_kernel() -> Vec<f32> {
let mut out = Vec::with_capacity(32 * 3);
// A fixed integer hash rather than a PRNG crate: the kernel has to be the
// same on every run or the same scene renders differently each launch.
let hash = |i: u32, salt: u32| -> f32 {
let mut h = i.wrapping_mul(747_796_405).wrapping_add(salt.wrapping_mul(2_891_336_453));
h ^= h >> 16;
h = h.wrapping_mul(2_246_822_519);
h ^= h >> 13;
(h >> 8) as f32 / 16_777_216.0
};
for i in 0..32u32 {
let mut v = [
hash(i, 1) * 2.0 - 1.0,
hash(i, 2) * 2.0 - 1.0,
// Hemisphere: never below the surface.
hash(i, 3),
];
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-4);
// Scale in towards the origin, quadratically.
let t = i as f32 / 32.0;
let scale = (0.1 + 0.9 * t * t) / len;
v[0] *= scale;
v[1] *= scale;
v[2] *= scale;
out.extend_from_slice(&v);
}
out
}
/// Sixteen rotation values, one per texel of the 4x4 noise texture.
///
/// Never zero: the shader builds its tangent from this, and a zero would make
/// it `normalize(vec3(0))` — a NaN that spreads through the whole kernel.
fn default_ssao_noise() -> Vec<f32> {
(0..16)
.map(|i| {
let mut h = (i as u32).wrapping_mul(2_654_435_761);
h ^= h >> 15;
h = h.wrapping_mul(2_246_822_519);
h ^= h >> 13;
let u = (h >> 8) as f32 / 16_777_216.0;
// Away from zero, and signed, so neighbouring texels decorrelate.
if u < 0.5 {
-0.35 - u
} else {
0.35 + (u - 0.5)
}
})
.collect()
}
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
/// Hardware MSAA sample count used when antialiasing is enabled for the
/// direct-to-surface opaque forward pass. 4× is universally supported.
const MSAA_SAMPLES: u32 = 4;
/// One step of a cheap word mix (FxHash's): for fingerprints over trusted
/// data, run every frame, where SipHash's resistance to chosen input buys
/// nothing.
fn mix_word(h: u64, x: u64) -> u64 {
(h.rotate_left(5) ^ x).wrapping_mul(0x517c_c1b7_2722_0a95)
}
/// A sequence of words, mixed.
fn hash_words(words: impl Iterator<Item = u64>) -> u64 {
words.fold(0xcbf2_9ce4_8422_2325, mix_word)
}
/// The spot shadow map's size (and the directional map's until a light asks
/// for another), texels.
const SPOT_SHADOW_SIZE: u32 = 4096;
/// Each face of the point shadow cube, texels.
const POINT_SHADOW_SIZE: u32 = 512;
/// The OIT revealage: the layers' transmittance multiplied up per channel,
/// and their coverage's complement in alpha.
const OIT_REVEAL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// `make_glass_pipeline`'s passes: the depth prepass, and the tint and light
/// halves of the colour (`GLASS_OUTPUT` 1 and 2 in the shader).
const GLASS_DEPTH: u8 = 0;
const GLASS_TINT: u8 = 1;
const GLASS_LIGHT: u8 = 2;
/// What `fs_glass_shadow` packs each light's shadow on the glass into.
const GLASS_SHADOW_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Uint;
/// What the shadow maps were last drawn for: the casters of each kind and
/// the directional and spot map sizes.
type ShadowSig = (usize, usize, usize, u32, u32);
/// One kind's shadow maps: a 2D depth array, a layer per light (six per
/// point light, its cube faces), sampled through one view.
struct ShadowArray {
texture: wgpu::Texture,
view: wgpu::TextureView,
size: u32,
layers: u32,
}
impl ShadowArray {
fn new(device: &wgpu::Device, label: &str, size: u32, layers_needed: u32) -> Self {
// Never one layer, nor a multiple of six on a square texture: the GL
// backend makes those a plain 2D texture or a cube map, and neither
// can be bound as the 2D array the shader declares.
let mut layers = layers_needed.max(2);
if layers.is_multiple_of(6) {
layers += 1;
}
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: layers },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(label),
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
Self { texture, view, size, layers }
}
/// Layer `layer`, as a pass's depth attachment.
fn layer_view(&self, layer: u32) -> wgpu::TextureView {
self.texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers shadow layer"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: layer,
array_layer_count: Some(1),
..Default::default()
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ShadowKind {
Dir,
Spot,
Point,
}
/// A shadow-casting light's shadow, as the shader's `ShadowRecord`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ShadowRecordGpu {
/// `[kind (0 directional, 1 spot, 2 point), first layer, cascades, filter]`.
info: [u32; 4],
/// `[depth bias, normal bias, filter radius, one texel]`, the last two in
/// map uv (direction units for a point light).
params: [f32; 4],
/// Directional: each cascade's far edge, view depth. Point: position and
/// radius.
extra: [f32; 4],
/// PCSS: `[search radius, spot near, spot far, penumbra scale]`.
pcss: [f32; 4],
/// World → light clip: a cascade each, or the light's.
vp: [[f32; 16]; 4],
}
/// What one shadow pass draws with, at its own offset in one buffer — the
/// shader's `ShadowPass`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ShadowPassGpu {
vp: [f32; 16],
light: [f32; 4],
}
/// One shadow pass: a light's layer and the matrix it is drawn with (for a
/// point light, one cube face, with the light's position and radius).
struct ShadowPass {
kind: ShadowKind,
layer: u32,
vp: [f32; 16],
pos: [f32; 4],
}
/// Cube face `face` of a point light's shadow: world → clip.
fn point_face_vp(pos: Vector3, radius: f32, face: usize) -> [f32; 16] {
let face_lookat: [(Vector3, Vector3); 6] = [
(Vector3::new(1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(-1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 1.0, 0.0), Vector3::new(0.0, 0.0, 1.0)),
(Vector3::new(0.0, -1.0, 0.0), Vector3::new(0.0, 0.0, -1.0)),
(Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 0.0, -1.0), Vector3::new(0.0, -1.0, 0.0)),
];
let fov = std::f32::consts::FRAC_PI_2;
let proj = Matrix4::perspective(fov, 1.0, 0.1, radius.max(1.0));
let (forward, up) = face_lookat[face];
let view = Matrix4::look_at(pos, pos + forward, up);
// NOTE: the Metal backend negates clip-space x here and this
// path must not — the two disagree about the cube's handedness
// somewhere further down, and mirroring this one takes its
// shadow from weak to absent (0.0021 of darkening to 0.0000).
// That asymmetry is unexplained and is the thread to pull on
// next; see `metal_casts_a_point_shadow`.
// Negate clip-space y.
//
// Cube maps are left-handed in every graphics API and
// `Matrix4::look_at` is right-handed, so a face rendered with
// it is laid down flipped against what the sampler will later
// expect. Each face looks perfectly reasonable alone, which is
// what makes this invisible: the shadow simply lands somewhere
// else.
//
// *Which* axis differs by backend, and that is not a guess —
// `tests/shadow_fixtures.rs` measures the shadow's distance
// from where the geometry puts it, in pixels:
//
// ```text
// none x y xy
// wgpu 79.2 133.1 2.1 107.0
// metal 107.0 2.1 133.1 79.2
// ```
//
// The two tables are each other's, shifted by one flip: the
// backends' framebuffer-y conventions are opposite, so the
// correction is too. Anything but the 2.1 here is a shadow of
// something that is not there.
let mut vp = proj.multiply(&view).elements;
vp[1] = -vp[1];
vp[5] = -vp[5];
vp[9] = -vp[9];
vp[13] = -vp[13];
vp
}
// ---- ShaderMaterial (custom-shader) support ----------------------------------
/// Cache key for a custom shader = a hash of *both* stages. Keying on the
/// fragment alone would hand two materials that differ only in their vertex
/// source the same compiled pipeline, and the second one would silently draw
/// with the first one's geometry.
/// Mixed into a custom shader's hash when it draws an `InstancedMesh`, whose
/// pipeline has the instanced vertex layout.
const INSTANCED_CUSTOM_SALT: u64 = 0x9e37_79b9_7f4a_7c15;
/// Salted into a custom pipeline's key when its material takes
/// alpha-to-coverage: the same source, another pipeline.
const COVERAGE_CUSTOM_SALT: u64 = 0xc2b2_ae3d_27d4_eb4f;
fn custom_shader_hash(fragment: &str, vertex: Option<&str>) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
fragment.hash(&mut h);
vertex.hash(&mut h);
h.finish()
}
/// Assemble a full WGSL module for a custom shader: the built-in preamble
/// (everything before the built-in `fs_main` — structs, `vs_main`, bindings for
/// groups 0-3, and all helper functions), then the `@group(4)` user bindings,
/// then the user's fragment.
pub(crate) fn custom_shader_module_source(
fragment: &str,
vertex: Option<&str>,
storage_buffers: bool,
coverage: bool,
samples: u32,
) -> String {
let source = super::shader::legacy_shader_source();
let preamble = source.split("@fragment").next().unwrap_or(source);
// User data lives in @group(1) alongside the mesh uniform (binding 0), to
// stay within WebGPU's 4-bind-group limit.
let user_bindings = "\n\
struct ThreersUserData { data: array<vec4<f32>, 16>, };\n\
@group(1) @binding(1) var<uniform> u_data: ThreersUserData;\n\
@group(1) @binding(5) var u_tex0: texture_2d<f32>;\n\
@group(1) @binding(6) var u_tex1: texture_2d<f32>;\n\
@group(1) @binding(7) var u_tex2: texture_2d<f32>;\n\
@group(1) @binding(8) var u_tex3: texture_2d<f32>;\n\
@group(1) @binding(9) var u_samp: sampler;\n\
@group(1) @binding(10) var u_s0_tex: texture_2d<f32>;\n\
@group(1) @binding(11) var u_s1_tex: texture_2d<f32>;\n\
@group(1) @binding(12) var u_s2_tex: texture_2d<f32>;\n";
// The volume slots, where they fit: see
// `caps::supports_shader_material_volumes`, which comes to the same test
// as `storage_buffers`. Module, layout and bind group agree on it.
let volume_bindings = if storage_buffers {
"@group(1) @binding(13) var u_vol0: texture_3d<f32>;\n\
@group(1) @binding(14) var u_vol1: texture_3d<f32>;\n\
@group(1) @binding(15) var u_vol_samp: sampler;\n"
} else {
""
};
// WebGL2 has no storage buffers at all, so on that backend these three are
// left out of the module *and* out of the layout and bind group that go with
// it — all three have to agree or the pipeline is rejected. A shader that
// reads `u_s0` simply will not compile there, which is the honest outcome:
// the data has nowhere to live.
let storage_bindings = if storage_buffers {
"@group(1) @binding(2) var<storage, read> u_s0: array<f32>;\n\
@group(1) @binding(3) var<storage, read> u_s1: array<f32>;\n\
@group(1) @binding(4) var<storage, read> u_s2: array<f32>;\n"
} else {
""
};
// `s0`/`s1`/`s2` are the portable way to read the storage arrays: they are
// defined on every backend, and on one without storage buffers they read
// the same data out of a texture instead. `u_s0`..`u_s2` stay for the
// shaders that already index them directly, but they only exist where the
// device does.
let accessors = if storage_buffers {
"fn s0(i: u32) -> f32 { return u_s0[i]; }\n\
fn s1(i: u32) -> f32 { return u_s1[i]; }\n\
fn s2(i: u32) -> f32 { return u_s2[i]; }\n\
fn s_len(slot: u32) -> u32 {\n\
if (slot == 0u) { return arrayLength(&u_s0); }\n\
if (slot == 1u) { return arrayLength(&u_s1); }\n\
return arrayLength(&u_s2);\n\
}\n"
} else {
"fn s_fetch(t: texture_2d<f32>, i: u32) -> f32 {\n\
let w = u32(textureDimensions(t).x);\n\
let texel = i / 4u;\n\
let p = vec2<i32>(i32(texel % w), i32(texel / w));\n\
let v = textureLoad(t, p, 0);\n\
let c = i % 4u;\n\
if (c == 0u) { return v.x; }\n\
if (c == 1u) { return v.y; }\n\
if (c == 2u) { return v.z; }\n\
return v.w;\n\
}\n\
fn s0(i: u32) -> f32 { return s_fetch(u_s0_tex, i); }\n\
fn s1(i: u32) -> f32 { return s_fetch(u_s1_tex, i); }\n\
fn s2(i: u32) -> f32 { return s_fetch(u_s2_tex, i); }\n\
fn s_len(slot: u32) -> u32 {\n\
var d = textureDimensions(u_s0_tex);\n\
if (slot == 1u) { d = textureDimensions(u_s1_tex); }\n\
if (slot == 2u) { d = textureDimensions(u_s2_tex); }\n\
return u32(d.x) * u32(d.y) * 4u;\n\
}\n"
};
// The pipeline the module is built for, for a shader that draws its own
// anti-aliasing:
//
// - three.js `alphaToCoverage` — a fragment's alpha as the share of the
// pixel's samples it covers. `coverage_alpha` is what a shader returns
// as its alpha for that: the coverage itself in a multisampled pipeline
// with alpha-to-coverage on, a cut at half (discard below, 1 above) in
// any other, so the same shader is right in both.
// - `THREERS_SAMPLES` and `threers_sample_offset(i)`: the samples a pixel
// has (1, or 4 under MSAA) and where sample `i` sits from its centre,
// in pixels (the standard 4× pattern), for a shader that works out which
// samples it covers itself — and returns them in `frag_out(colour,
// mask)`, as `@builtin(sample_mask)` where the backend has it
// (`THREERS_SAMPLE_MASK`; not WebGL2, where the alpha is the share of
// samples, for alpha-to-coverage to place).
//
// The same number of lines in every variant, so error lines stay put.
let mask = samples > 1 && storage_buffers && sample_mask_is_cheap();
let (mask_field, mask_set) = if mask {
("@builtin(sample_mask) mask : u32, ", "o.mask = mask; ")
} else {
("", "")
};
let coverage = format!(
"const THREERS_COVERAGE : bool = {coverage};\n\
const THREERS_SAMPLES : u32 = {samples}u;\n\
const THREERS_SAMPLE_MASK : bool = {mask};\n\
fn coverage_alpha(coverage : f32) -> f32 {{\n\
if (THREERS_COVERAGE) {{ return clamp(coverage, 0.0, 1.0); }}\n\
if (coverage < 0.5) {{ discard; }}\n\
return 1.0;\n\
}}\n\
struct ThreersFragOut {{ @location(0) color : vec4<f32>, {mask_field}}};\n\
fn frag_out(color : vec4<f32>, mask : u32) -> ThreersFragOut {{ var o : ThreersFragOut; o.color = color; {mask_set}return o; }}\n\
fn threers_sample_offset(i : u32) -> vec2<f32> {{\n\
if (THREERS_SAMPLES == 1u) {{ return vec2<f32>(0.0); }}\n\
return select(select(select(vec2<f32>(0.125, 0.375), vec2<f32>(-0.375, 0.125), i == 2u), vec2<f32>(0.375, -0.125), i == 1u), vec2<f32>(-0.125, -0.375), i == 0u);\n\
}}\n"
);
let vertex = vertex.map(|v| format!("\n{v}\n")).unwrap_or_default();
format!("{preamble}{user_bindings}{volume_bindings}{storage_bindings}{accessors}{coverage}{vertex}\n{fragment}\n")
}
/// Parse and validate an assembled custom-shader module, before wgpu sees it.
///
/// Worth doing because of *where* the failure otherwise lands. A bad
/// `ShaderMaterial` reaches `create_shader_module`, which does not return an
/// error — it goes to the device's uncaptured-error handler and takes the
/// process down, from inside the draw loop, with line numbers into a module the
/// caller has never seen: the user wrote forty lines and the error says
/// `wgsl:1707`. Checking here turns that into a message naming the user's own
/// line, and lets the renderer skip one material instead of ending the program.
///
/// Set `THREERS_DUMP_SHADER` to a path to also write the assembled module out;
/// that is the only way to read line 1707 for yourself.
/// On `wasm32` there is nothing to check against: naga is not in wgpu's browser
/// build, so the browser's own WGSL compiler does this job and reports to the
/// console. This returns `Ok` there rather than pretending otherwise — see
/// `ShaderMaterial::VALIDATION_AVAILABLE`.
#[cfg(target_arch = "wasm32")]
pub(crate) fn validate_custom_shader(_source: &str, _preamble_lines: usize) -> Result<(), String> {
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn validate_custom_shader(source: &str, preamble_lines: usize) -> Result<(), String> {
if let Ok(path) = std::env::var("THREERS_DUMP_SHADER") {
let _ = std::fs::write(&path, source);
}
let module = match wgpu::naga::front::wgsl::parse_str(source) {
Ok(m) => m,
Err(e) => return Err(annotate(&e.emit_to_string(source), source, preamble_lines)),
};
let mut validator = wgpu::naga::valid::Validator::new(
wgpu::naga::valid::ValidationFlags::all(),
wgpu::naga::valid::Capabilities::all(),
);
match validator.validate(&module) {
Ok(_) => Ok(()),
Err(e) => Err(annotate(
&e.emit_to_string(source),
source,
preamble_lines,
)),
}
}
/// Rewrite naga's `wgsl:<n>` positions into the caller's own numbering.
///
/// The assembled module is the built-in preamble plus the user's source, so
/// every line number naga reports is off by the length of the preamble — about
/// seventeen hundred lines of it. Unmapped, the number is not merely useless,
/// it points at a file the user does not have.
#[cfg(not(target_arch = "wasm32"))]
fn annotate(message: &str, source: &str, preamble_lines: usize) -> String {
let total = source.lines().count();
let mut out = String::from(message);
out.push_str(&format!(
"\n\nline numbers above are in the assembled module ({total} lines): the \
built-in preamble is the first {preamble_lines}, so subtract that for a \
position in your own source. Set THREERS_DUMP_SHADER=/tmp/shader.wgsl \
to write the whole module out."
));
out
}
/// Compile a custom-shader pipeline (alpha-blended, no depth write — treated as
/// transparent for correct compositing).
fn build_custom_pipeline(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
fragment: &str,
vertex: Option<&str>,
format: wgpu::TextureFormat,
transparent: bool,
screen_space: bool,
side: u32,
instanced: bool,
samples: u32,
alpha_to_coverage: bool,
pipes: &mut super::pipeline_state::StatePipelines,
) -> Result<wgpu::RenderPipeline, String> {
// Alpha-to-coverage needs samples to cover; single-sampled, the shader's
// `coverage_alpha` cuts at half instead. And not with a shader that
// writes its samples itself (`frag_out`, where `@builtin(sample_mask)`
// exists): WebGPU allows one or the other, and it has said already.
let writes_mask = samples > 1
&& crate::renderer::caps::supports_storage_buffers(device)
&& sample_mask_is_cheap()
&& fragment.contains("ThreersFragOut");
let coverage = alpha_to_coverage && samples > 1 && !writes_mask;
let source = custom_shader_module_source(
fragment,
vertex,
crate::renderer::caps::supports_storage_buffers(device),
coverage,
samples,
);
validate_custom_shader(&source, custom_preamble_lines())?;
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers custom shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let vertex_buffers = [wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
}];
// `buffers` takes a slice of `Option` in wgpu 30.
let [base] = vertex_buffers;
// On an `InstancedMesh`: the instance matrix and tint in slot 1, as the
// built-in instanced pipeline has them, and the two custom columns in
// slot 2 (`InstancedCustomIn`).
let instance_attrs = [
(0, 4),
(16, 5),
(32, 6),
(48, 7),
(64, 9),
]
.map(|(offset, shader_location)| wgpu::VertexAttribute {
offset,
shader_location,
format: wgpu::VertexFormat::Float32x4,
});
let custom_attrs = [(0, 10), (16, 11)].map(|(offset, shader_location)| wgpu::VertexAttribute {
offset,
shader_location,
format: wgpu::VertexFormat::Float32x4,
});
let vertex_buffers: Vec<Option<wgpu::VertexBufferLayout>> = if instanced {
vec![
Some(base),
Some(wgpu::VertexBufferLayout {
array_stride: 80,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &instance_attrs,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &custom_attrs,
}),
]
} else {
vec![Some(base)]
};
Ok(pipes.create(device, &wgpu::RenderPipelineDescriptor {
label: Some("threers custom pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &module,
// The built-in entry stays `vs_main`; a material that brings its own
// declares `vs_custom`, so both can live in the module and the
// custom one can start from `standard_vertex`.
entry_point: Some(if vertex.is_some() {
"vs_custom"
} else if instanced {
"vs_instanced_custom"
} else {
"vs_main"
}),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
// Transparent: alpha-blend, no depth write (sorted back-to-front).
// Opaque: replace + depth write, so the surface self-occludes.
// Screen-space surfaces composite over the already-blitted opaque
// scene, so they blend — but they still write depth, so anything
// drawn later sorts against the surface rather than through it.
blend: Some(if transparent || screen_space {
wgpu::BlendState::ALPHA_BLENDING
} else if coverage {
// The alpha went to coverage; what is stored is opaque —
// the blend constant, set white where these draw. (Only
// then: blending costs a tiled GPU even when it is moot.)
wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Constant,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
}
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
// three.js `side`: 0 FrontSide, 1 BackSide, 2 DoubleSide. Previously
// hardcoded to front, which silently culls anything meant to be seen from
// the inside — a sky dome, or a water surface viewed from below it.
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
match side {
1 => Some(wgpu::Face::Front),
2 => None,
_ => Some(wgpu::Face::Back),
},
),
// The material's `depthWrite` (and the rest of its `RenderState`) is
// applied over this as a state variant at draw time.
depth_stencil: Some(depth_stencil(
screen_space || !transparent,
wgpu::CompareFunction::LessEqual,
)),
multisample: wgpu::MultisampleState {
count: samples,
alpha_to_coverage_enabled: coverage,
..Default::default()
},
multiview_mask: None,
cache: None,
}))
}
/// Whether a fragment shader may write `@builtin(sample_mask)` without being
/// shaded once per sample. Natively (naga → MSL, SPIR-V, HLSL) it is just an
/// output: a fur shader under 4× MSAA cost 1.4× its single-sampled self.
/// Safari's WebGPU shades such a shader per sample — a heavy fragment ran at
/// 17 fps against 59 without the output — so in the browser a shader's
/// samples go out as alpha-to-coverage instead (the share of samples
/// covered, which the hardware places: grainier, still well ahead of one
/// sample).
const fn sample_mask_is_cheap() -> bool {
!cfg!(target_arch = "wasm32")
}
/// How many lines of built-in preamble sit above a custom shader's own source.
pub(crate) fn custom_preamble_lines() -> usize {
custom_shader_module_source("", None, true, false, 1).lines().count()
}
/// Pack a flat `f32` array into an `Rgba32Float` texture, four values a texel.
///
/// This is the storage array for devices that have no storage buffers — WebGL2
/// being all of them. A `ShaderMaterial` whose data does not fit the 16 `vec4`
/// uniform block had nowhere else to put it there, which ruled the feature out
/// for anything data-driven on the web.
///
/// `textureLoad` needs no filtering and no sampler, so this works on the
/// baseline float-texture support every WebGL2 context has.
fn upload_data_texture(
device: &wgpu::Device,
queue: &wgpu::Queue,
data: &[f32],
) -> wgpu::Texture {
let texels = data.len().div_ceil(4).max(1);
// 2048 is the smallest `max_texture_dimension_2d` anything still shipping
// reports, so a row never has to be checked against the device.
let width = texels.clamp(1, 2048) as u32;
let height = (texels as u32).div_ceil(width).max(1);
let mut padded = vec![0.0f32; (width * height * 4) as usize];
padded[..data.len()].copy_from_slice(data);
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers user data texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&padded),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * 16),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
tex
}
/// Build the custom @group(1) bind group: the mesh uniform (binding 0, shared
/// with the standard path), the `ShaderMaterial` user uniform (binding 1), the
/// three storage arrays (bindings 2-4) and the same three as textures
/// (bindings 10-12) for devices with no storage buffers. Returns the bind group
/// plus the resources it owns, which the caller keeps alive until submit.
#[allow(clippy::too_many_arguments)]
fn build_user_bind_group(
device: &wgpu::Device,
queue: &wgpu::Queue,
bgl: &wgpu::BindGroupLayout,
mesh_uniform: wgpu::BufferBinding<'_>,
data: &[[f32; 4]; 16],
storage: &[Vec<f32>; 3],
textures: &[std::sync::Arc<wgpu::TextureView>],
placeholder: &wgpu::TextureView,
data_placeholder: &wgpu::TextureView,
sampler: &wgpu::Sampler,
volumes: &[std::sync::Arc<wgpu::TextureView>],
volume_placeholder: &wgpu::TextureView,
volume_sampler: &wgpu::Sampler,
) -> (wgpu::BindGroup, Vec<wgpu::Buffer>, Vec<wgpu::Texture>) {
use wgpu::util::DeviceExt;
let flat: Vec<f32> = data.iter().flat_map(|v| v.iter().copied()).collect();
let mut buffers = vec![
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("threers user uniform"),
contents: bytemuck::cast_slice(&flat),
usage: wgpu::BufferUsages::UNIFORM,
}),
];
let storage_buffers = crate::renderer::caps::supports_storage_buffers(device);
if storage_buffers {
for s in storage.iter() {
buffers.push(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("threers user storage"),
contents: bytemuck::cast_slice(s),
usage: wgpu::BufferUsages::STORAGE,
}),
);
}
}
let tex =
|i: usize| -> &wgpu::TextureView { textures.get(i).map(|t| &**t).unwrap_or(placeholder) };
let mut entries = vec![
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(mesh_uniform),
},
wgpu::BindGroupEntry {
binding: 1,
resource: buffers[0].as_entire_binding(),
},
];
if storage_buffers {
for (i, buffer) in buffers[1..4].iter().enumerate() {
entries.push(wgpu::BindGroupEntry {
binding: 2 + i as u32,
resource: buffer.as_entire_binding(),
});
}
}
entries.extend([
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(tex(0)),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(tex(1)),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::TextureView(tex(2)),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(tex(3)),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::Sampler(sampler),
},
]);
// The data textures are only built where they are the only option; with
// storage buffers present these bind a 1x1 placeholder nothing reads, so
// the layout is the same shape on every backend and the module is not.
let mut data_textures: Vec<wgpu::Texture> = Vec::new();
let mut data_views: Vec<wgpu::TextureView> = Vec::new();
if !storage_buffers {
for s in storage.iter() {
let t = upload_data_texture(device, queue, s);
data_views.push(t.create_view(&wgpu::TextureViewDescriptor::default()));
data_textures.push(t);
}
}
for i in 0..3 {
entries.push(wgpu::BindGroupEntry {
binding: 10 + i as u32,
resource: wgpu::BindingResource::TextureView(
data_views.get(i).unwrap_or(data_placeholder),
),
});
}
if crate::renderer::caps::supports_shader_material_volumes(device) {
for i in 0..2 {
entries.push(wgpu::BindGroupEntry {
binding: 13 + i as u32,
resource: wgpu::BindingResource::TextureView(
volumes.get(i).map(|v| &**v).unwrap_or(volume_placeholder),
),
});
}
entries.push(wgpu::BindGroupEntry {
binding: 15,
resource: wgpu::BindingResource::Sampler(volume_sampler),
});
}
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers custom mesh+user bg"),
layout: bgl,
entries: &entries,
});
(bg, buffers, data_textures)
}
impl Renderer {
/// The near and far planes of the camera this renderer last drew with.
///
/// Anything that linearises the depth buffer afterwards needs exactly
/// these, and nothing else does. Defaults to `(0.1, 1000.0)` before the
/// first frame, which is only ever read by a post pass configured and then
/// never rendered.
pub fn camera_planes(&self) -> (f32, f32) {
self.last_camera_planes
}
/// `(tan(fov/2), aspect)` of the camera this renderer last drew with,
/// recovered from its projection matrix. Meaningless for an orthographic
/// camera, which has no field of view to speak of.
pub fn camera_lens(&self) -> (f32, f32) {
self.last_camera_lens
}
/// Shared device handle. Used by callers (e.g. async readback) that need
/// to encode commands or allocate buffers outside the renderer's own loop.
pub fn device_arc(&self) -> Arc<wgpu::Device> {
self.device.clone()
}
/// Shared queue handle (same use case as `device_arc`).
pub fn queue_arc(&self) -> Arc<wgpu::Queue> {
self.queue.clone()
}
/// Upload `geom` to the GPU now, instead of waiting for the first draw.
///
/// Only needed when something outside the renderer wants the buffer up
/// front — a compute pass that writes it, typically. See
/// [`vertex_buffer`](Self::vertex_buffer).
pub fn upload_geometry(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
self.ensure_geometry(geom);
}
/// The GPU vertex buffer backing `geom`, if it has been uploaded.
///
/// Interleaved, `GpuMesh::VERTEX_STRIDE` bytes per vertex, laid out
/// position(3), normal(3), uv(2), colour(4), tangent(4) as `f32`.
///
/// Writing it from a compute pass requires
/// [`BufferGeometry::gpu_writable`], and the handle is only valid until the
/// geometry is re-uploaded — which happens whenever
/// [`geometry_version`](BufferGeometry::geometry_version) changes. Drive a
/// mesh one way or the other, not both.
pub fn vertex_buffer(&self, geom: &std::sync::Arc<BufferGeometry>) -> Option<&wgpu::Buffer> {
self.geom_cache
.get(&geom_cache_key(geom))
.map(|e| &e.mesh.vertex_buffer)
}
/// three.js r165's `renderTransmissionPass`, when the scene has a visible
/// transmissive material: the opaque scene drawn linear and untone-mapped
/// into a half-float target the size of this one, its mips filled; then,
/// for double-sided transmissive materials, their back faces drawn over it
/// (reading a copy of it) and the mips filled again. The frame group then
/// binds it for the colour pass that follows.
fn capture_transmission(&mut self, scene: &mut Scene, camera: &dyn Camera) {
let (mut any, mut double) = (false, false);
let mut see = |m: &Material| {
if m.transmissive() {
any = true;
double |= m.side() == 2;
}
};
scene.arena.traverse_visible(scene.root, &mut |_, obj| match &obj.kind {
ObjectKind::Mesh(mesh) => mesh.draws().into_iter().for_each(|i| see(i.material)),
ObjectKind::InstancedMesh(im) if !im.transforms.is_empty() => {
im.draws().into_iter().for_each(|i| see(i.material))
}
ObjectKind::SkinnedMesh(sm) => sm.draws().into_iter().for_each(|i| see(i.material)),
_ => {}
});
if !any {
if self.transmission.take().is_some() {
self.frame_bind_group = self.frame_bind_group_dummy.clone();
}
return;
}
let (w, h) = self.depth_size;
if self.transmission.as_ref().map(|c| c.size) != Some((w, h)) {
let levels = 32 - w.max(h).max(1).leading_zeros();
let make = |label: &str, usage: wgpu::TextureUsages| {
self.device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage,
view_formats: &[],
})
};
let texture = make(
"threers transmission capture",
wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
);
let copy = make(
"threers transmission capture copy",
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
);
let depth = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers transmission depth"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
self.transmission = Some(TransmissionCapture {
view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
target_view: texture.create_view(&wgpu::TextureViewDescriptor {
base_mip_level: 0,
mip_level_count: Some(1),
..Default::default()
}),
copy_view: copy.create_view(&wgpu::TextureViewDescriptor::default()),
depth_view: depth.create_view(&wgpu::TextureViewDescriptor::default()),
texture,
copy,
_depth: depth,
size: (w, h),
levels,
});
}
let cap = self.transmission.as_ref().expect("just made");
let (target, depth_view) = (cap.target_view.clone(), cap.depth_view.clone());
let orig_depth = std::mem::replace(&mut self.depth_view, depth_view);
let tone = std::mem::replace(&mut self.tone_map_pass, false);
self.frame_bind_group = self.frame_bind_group_dummy.clone();
self.capturing_transmission = Some(false);
self.render_inner(scene, camera, &target, true, None, None);
self.fill_capture_mips();
if double {
let cap = self.transmission.as_ref().expect("made above");
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers transmission copy"),
});
for level in 0..cap.levels {
let size = wgpu::Extent3d {
width: (w >> level).max(1),
height: (h >> level).max(1),
depth_or_array_layers: 1,
};
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: &cap.texture,
mip_level: level,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
texture: &cap.copy,
mip_level: level,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
size,
);
}
self.queue.submit([encoder.finish()]);
self.frame_bind_group = frame_bg(
&self.device,
&self.frame_bgl,
&self.frame_buffer_for_bg,
&cap.copy_view,
&self.transmission_sampler,
"threers frame bg (back faces)",
);
let clear = std::mem::replace(&mut self.viewport_state.settings.auto_clear, false);
self.capturing_transmission = Some(true);
self.render_inner(scene, camera, &target, true, None, None);
self.viewport_state.settings.auto_clear = clear;
self.fill_capture_mips();
}
self.capturing_transmission = None;
self.tone_map_pass = tone;
self.depth_view = orig_depth;
let cap = self.transmission.as_ref().expect("made above");
self.frame_bind_group = frame_bg(
&self.device,
&self.frame_bgl,
&self.frame_buffer_for_bg,
&cap.view,
&self.transmission_sampler,
"threers frame bg",
);
}
fn fill_capture_mips(&mut self) {
let Some(cap) = &self.transmission else { return };
let mipgen = self.mipgen.get_or_insert_with(|| MipGenerator::new(&self.device));
mipgen.generate(&self.device, &self.queue, &cap.texture, wgpu::TextureFormat::Rgba16Float, cap.levels);
}
/// threers's reflective transparency on Standard and Physical (off by
/// default): a transparent surface's alpha raised by its specular
/// reflectance, `opacity + (1 − opacity) · reflectance`, so its reflection
/// — which is in front of it and not transmitted — keeps its strength.
/// three.js blends the whole colour by `opacity`, which fades a highlight
/// on glass faked with `alphaMode: BLEND` into grey film.
pub fn set_reflective_transparency(&mut self, on: bool) {
self.reflective_transparency = on;
}
pub fn reflective_transparency(&self) -> bool {
self.reflective_transparency
}
fn ensure_geometry(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
let key = geom_cache_key(geom);
let ver = geom.geometry_version;
let stale = self
.geom_cache
.get(&key)
.map(|e| e.version != ver)
.unwrap_or(true);
if stale {
let mesh = GpuMesh::upload(&self.device, geom);
let sphere = local_bounding_sphere(geom);
self.geom_cache.insert(
key,
CachedGpuMesh {
version: ver,
mesh,
sphere,
},
);
}
self.ensure_uv_sets(geom);
}
/// Upload `geom`'s `uv1`/`uv2`/`uv3` as its [`UvSetTexture`], once per
/// geometry version; drop it when the geometry no longer has any.
fn ensure_uv_sets(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
let key = geom_cache_key(geom);
let ver = geom.geometry_version;
if self.uv_cache.get(&key).is_some_and(|u| u.version == ver) {
return;
}
let sets = UV_SET_NAMES.map(|n| geom.get_attribute(n).filter(|a| a.item_size >= 2));
let count = geom.get_attribute("position").map_or(0, |p| p.count());
if sets.iter().all(Option::is_none) || count == 0 {
self.uv_cache.remove(&key);
return;
}
let texels = (count * 2) as u32;
let max = self.device.limits().max_texture_dimension_2d.max(1);
let width = texels.min(max);
let height = texels.div_ceil(width);
let mut data = vec![0.0f32; (width * height * 4) as usize];
for (set, attr) in sets.iter().enumerate() {
let Some(a) = attr else { continue };
for v in 0..count.min(a.count()) {
let at = (v * 2 + set / 2) * 4 + (set % 2) * 2;
data[at] = a.array[v * a.item_size];
data[at + 1] = a.array[v * a.item_size + 1];
}
}
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers uv sets"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&data),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * 16),
rows_per_image: Some(height),
},
wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.uv_cache.insert(key, UvSetTexture { version: ver, _texture: texture, view });
self.tex_bg_cache.retain(|k, _| k.3 .0 != key as usize);
self.variant_bg_cache.retain(|k, _| k.1 .0 != key as usize);
}
/// The identity of the uv-set texture a draw of geometry `key` binds —
/// part of its bind group's cache key; `(0, 0)` for none.
fn uv_key(&self, key: *const BufferGeometry) -> (usize, u32) {
self.uv_cache.get(&key).map_or((0, 0), |u| (key as usize, u.version))
}
/// Upload `geom`'s morph targets as three.js's morph texture, once per
/// geometry version. Returns the cache key and version to bind, or `None`
/// when the geometry has no morph targets.
fn ensure_morph(&mut self, geom: &std::sync::Arc<BufferGeometry>) -> Option<(usize, u32)> {
let key = geom_cache_key(geom);
let ver = geom.geometry_version;
if self.morph_cache.get(&key).is_some_and(|m| m.version == ver) {
return Some((key as usize, ver));
}
let texels = crate::core::MorphTexels::build(geom)?;
if texels.targets == 0 || texels.vertex_count == 0 {
return None;
}
// three.js: one row of `vertexCount · stride` texels, wrapped onto
// more rows when that passes the maximum texture width.
let per_layer = texels.vertex_count * texels.stride;
let max = self.device.limits().max_texture_dimension_2d.max(1);
let width = per_layer.min(max);
let height = per_layer.div_ceil(width);
// At least two layers: WebGL2 (wgpu's GL backend) makes a
// one-layer texture a plain `TEXTURE_2D`, and the shader's
// `sampler2DArray` then reads zeros from it — a single morph target
// collapsed every vertex to the origin there. The spare layer is
// never read.
let layers = texels.targets.max(2);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers morph texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: layers,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
// Each layer padded out to whole rows.
let row = (width * 4) as usize;
let mut padded = vec![0.0f32; row * height as usize * layers as usize];
let layer_len = (per_layer * 4) as usize;
for t in 0..texels.targets as usize {
let src = &texels.data[t * layer_len..(t + 1) * layer_len];
let dst = t * row * height as usize;
padded[dst..dst + layer_len].copy_from_slice(src);
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&padded),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * 16),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: layers,
},
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
self.morph_cache.insert(
key,
MorphTexture {
version: ver,
_texture: texture,
view,
instance_layer: None,
},
);
Some((key as usize, ver))
}
/// An `InstancedMesh`'s morph texture: `geom`'s targets as in
/// [`ensure_morph`](Self::ensure_morph), plus one more layer holding
/// three.js's `InstancedMesh.morphTexture` — `instances` rows of
/// `row_len` floats (base influence, then the influences), one float a
/// texel in `.x`, row-major over the layer's width. Cached under `owner`
/// (the object), rebuilt when the geometry or the row layout changes and
/// otherwise only the rows are rewritten.
///
/// One texture rather than a second binding because the mesh layout is
/// already at WebGL2's sixteen texture units.
/// The GPU buffer for `obj`'s instance data `slot`, holding `data`: last
/// frame's buffer when it is big enough, rewritten only if `data`
/// changed, else a new one with room to grow.
fn instance_buffer(
&mut self,
obj: crate::core::ObjectId,
slot: u8,
data: Vec<f32>,
version: Option<(u64, usize)>,
) -> wgpu::Buffer {
let frame = self.instance_frame;
let bytes = (data.len() * 4) as u64;
if let Some(c) = self.instance_cache.get_mut(&(obj, slot)) {
if c.buffer.size() >= bytes.max(4) {
// A versioned mesh got here because its version moved: write.
if version.is_some() || c.data != data {
self.queue.write_buffer(&c.buffer, 0, bytemuck::cast_slice(&data));
c.data = if version.is_some() { Vec::new() } else { data };
self.instance_stamps += 1;
c.stamp = self.instance_stamps;
}
c.frame = frame;
c.version = version;
return c.buffer.clone();
}
}
// Half again, so a mesh that grows a little each frame is not
// reallocated every frame.
let size = ((bytes + bytes / 2).max(16)).div_ceil(4) * 4;
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers instance buffer"),
size,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&data));
self.instance_stamps += 1;
self.instance_cache.insert(
(obj, slot),
InstanceBuffer {
buffer: buffer.clone(),
// A versioned mesh is never compared, so keep no copy.
data: if version.is_some() { Vec::new() } else { data },
frame,
version,
stamp: self.instance_stamps,
},
);
buffer
}
/// The content stamp of `obj`'s instance slot, 0 when it has none.
fn instance_stamp(&self, obj: crate::core::ObjectId, slot: u8) -> u64 {
self.instance_cache.get(&(obj, slot)).map_or(0, |c| c.stamp)
}
/// Last frame's buffer for `obj`'s slot when its `instance_version` (and
/// count) say nothing changed — without reading the instance data.
fn cached_instances(
&mut self,
obj: crate::core::ObjectId,
slot: u8,
version: Option<(u64, usize)>,
) -> Option<wgpu::Buffer> {
let v = version?;
let c = self.instance_cache.get_mut(&(obj, slot))?;
if c.version != Some(v) {
return None;
}
c.frame = self.instance_frame;
Some(c.buffer.clone())
}
fn ensure_instance_morph(
&mut self,
owner: usize,
geom: &std::sync::Arc<BufferGeometry>,
rows: &[f32],
instances: u32,
row_len: u32,
) -> Option<(usize, u32)> {
let key = owner as *const BufferGeometry;
// High bit set, so it can never equal a plain geometry version.
let ver = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
(geom_cache_key(geom), geom.geometry_version, instances, row_len).hash(&mut h);
(h.finish() as u32) | 0x8000_0000
};
let texel_rows = |width: u32| -> Vec<f32> {
let n = (instances * row_len) as usize;
let rows_needed = (n as u32).div_ceil(width).max(1);
let mut out = vec![0.0f32; (width * rows_needed * 4) as usize];
for (i, v) in rows.iter().take(n).enumerate() {
out[i * 4] = *v;
}
out
};
if let Some(m) = self.morph_cache.get(&key).filter(|m| m.version == ver) {
let (layer, width) = m.instance_layer?;
let data = texel_rows(width);
let rows_needed = (data.len() / 4) as u32 / width;
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &m._texture,
mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: 0, z: layer },
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&data),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * 16),
rows_per_image: Some(rows_needed),
},
wgpu::Extent3d { width, height: rows_needed, depth_or_array_layers: 1 },
);
return Some((owner, ver));
}
let texels = crate::core::MorphTexels::build(geom)?;
if texels.targets == 0 || texels.vertex_count == 0 || instances == 0 {
return None;
}
let per_layer = texels.vertex_count * texels.stride;
let max = self.device.limits().max_texture_dimension_2d.max(1);
let width = per_layer.min(max);
let height = per_layer
.div_ceil(width)
.max((instances * row_len).div_ceil(width));
if height > max {
return None;
}
let layers = (texels.targets + 1).max(2);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers instanced morph texture"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: layers },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let row = (width * 4) as usize;
let layer_size = row * height as usize;
let mut padded = vec![0.0f32; layer_size * layers as usize];
let layer_len = (per_layer * 4) as usize;
for t in 0..texels.targets as usize {
let src = &texels.data[t * layer_len..(t + 1) * layer_len];
padded[t * layer_size..t * layer_size + layer_len].copy_from_slice(src);
}
let inst = texel_rows(width);
let at = texels.targets as usize * layer_size;
padded[at..at + inst.len()].copy_from_slice(&inst);
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&padded),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * 16),
rows_per_image: Some(height),
},
wgpu::Extent3d { width, height, depth_or_array_layers: layers },
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
self.morph_cache.insert(
key,
MorphTexture {
version: ver,
_texture: texture,
view,
instance_layer: Some((texels.targets, width)),
},
);
Some((owner, ver))
}
/// The wireframe line list of one partial span of `geom` — a group or a
/// draw range — cached by geometry version and span.
fn ensure_wire_span(&mut self, geom: &std::sync::Arc<BufferGeometry>, start: u32, end: u32) {
let k = (geom_cache_key(geom), geom.geometry_version, start, end);
if self.wire_span_cache.contains_key(&k) {
return;
}
// A runaway guard: spans are few and stable per geometry, and a
// stale version's entries are simply never asked for again.
if self.wire_span_cache.len() > 1024 {
self.wire_span_cache.clear();
}
let flat = geom.wireframe_indices_in(start, end);
let buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers wireframe span index buffer"),
// An empty buffer cannot be bound; one dummy index, drawn zero
// times, stands in.
contents: bytemuck::cast_slice(if flat.is_empty() { &[0u32] } else { &flat }),
usage: wgpu::BufferUsages::INDEX,
},
);
self.wire_span_cache.insert(k, (buf, flat.len() as u32));
}
/// Give `geom`'s cached upload its wireframe line list. Call after
/// [`ensure_geometry`](Self::ensure_geometry) for a `wireframe: true`
/// material; a re-upload drops the list, so it follows `geometry_version`.
fn ensure_wire_indices(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
if let Some(e) = self.geom_cache.get_mut(&geom_cache_key(geom)) {
e.mesh.ensure_wire_indices(&self.device, geom);
}
}
/// (Re)create the OIT accumulation + revealage targets at `w×h` and their
/// resolve bind group. No-op if already the right size.
/// (Re)create the mipmapped opaque-scene capture used by the screen-space
/// glass pass. Sized `w×h` in `format` (must match the framebuffer format so
/// the opaque pipelines can render into mip 0). The mip chain feeds the
/// roughness→LOD blur of the refracted/reflected image.
/// The scratch a layer of overlapping glass draws into (`ss_layer`), the
/// capture's size and format.
fn ensure_ss_layer(&mut self) {
let Some(c) = self.ss_color.as_ref() else { return };
if matches!(&self.ss_layer, Some((w, h, t, _)) if *w == c.width && *h == c.height && t.format() == c.format) {
return;
}
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss glass layer"),
size: wgpu::Extent3d { width: c.width, height: c.height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: c.format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_layer = Some((c.width, c.height, texture, view));
}
/// How many layers overlapping refraction glass (`TransparencyMode::Refract`)
/// is composited in. The refracting objects are drawn back to front in
/// up to this many groups, each refracting a capture of everything drawn
/// before it — so glass seen through glass shows; within a group, a
/// pixel shows only the front-most surface. Each layer past the first
/// costs a capture (a copy and a mip chain) and a back-face pass. 2 by
/// default; 1 is three.js's single capture.
pub fn set_refraction_layers(&mut self, layers: usize) {
self.refraction_layers = layers.max(1);
}
pub fn refraction_layers(&self) -> usize {
self.refraction_layers
}
fn ensure_ss_targets(&mut self, w: u32, h: u32, format: wgpu::TextureFormat) {
let (w, h) = (w.max(1), h.max(1));
if let Some(c) = &self.ss_color {
if c.width == w && c.height == h && c.format == format {
return;
}
}
// ~8 mips is plenty for a roughness blur; cap so the smallest is ≥1px.
let max_mips = 32 - (w.max(h)).leading_zeros();
let mips = max_mips.clamp(1, 8);
let unorm = format.remove_srgb_suffix();
let reinterpret = unorm != format && super::caps::supports_view_formats(&self.device);
let unorm_formats = [unorm];
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss color capture"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
// COPY_DST: a layer of overlapping glass is copied in (`ss_layer`).
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: if reinterpret { &unorm_formats } else { &[] },
});
let all_mips_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let mip0_unorm = reinterpret.then(|| {
texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers ss mip 0 unorm"),
format: Some(unorm),
base_mip_level: 0,
mip_level_count: Some(1),
..Default::default()
})
});
let mut mip_render_views = Vec::with_capacity(mips as usize);
let mut mip_sample_views = Vec::with_capacity(mips as usize);
for m in 0..mips {
mip_render_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers ss mip render"),
base_mip_level: m,
mip_level_count: Some(1),
..Default::default()
}));
mip_sample_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers ss mip sample"),
base_mip_level: m,
mip_level_count: Some(1),
..Default::default()
}));
}
self.ss_color = Some(SsColor {
width: w,
height: h,
texture,
all_mips_view,
mip_render_views,
mip_sample_views,
mip0_unorm,
mips,
format,
});
// Sampleable copy of the opaque depth (marched by the glass shader).
let need_depth = match &self.ss_depth {
Some((cw, ch, ..)) => *cw != w || *ch != h,
None => true,
};
if need_depth {
let dtex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss depth copy"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let dview = dtex.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_depth = Some((w, h, dtex, dview));
// Glass back-face depth target (rendered into, then sampled).
let btex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss back depth"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let bview = btex.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_back_depth = Some((w, h, btex, bview));
let stex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glass shadows"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: GLASS_SHADOW_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let sview = stex.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_glass_shadow = Some((stex, sview));
}
}
/// Enable/disable temporal anti-aliasing. When enabled, the renderer jitters
/// the projection each frame and blends against a reprojected history buffer.
/// Only active on the `render_to` path (needs a sampleable color target).
/// The depth buffer the last `render` wrote, for passes that run after it.
///
/// Not the offscreen target's depth: with MSAA the renderer takes a
/// surface-style path and writes its own, leaving a target's depth texture
/// untouched. A pass that read that one would sample an empty buffer and
/// produce nothing, silently — which is the whole reason this accessor
/// exists rather than callers reaching for the obvious field.
/// Inverse view-projection of the frame just drawn, and the view-projection
/// of the one before it — for passes that reproject after the render.
pub fn reprojection(&self) -> ([f32; 16], [f32; 16]) {
(self.mb_inv_vp, self.mb_prev_vp)
}
pub fn depth_texture(&self) -> &wgpu::Texture {
&self.depth_texture
}
/// What the last [`render`](Self::render) drew into, for a pass drawn over
/// the frame that depth-tests against it — [`marks`](crate::marks) use
/// this. `(multisampled colour, depth, samples)`: the colour is `Some` only
/// when that frame went through MSAA, and must then be drawn into and
/// resolved to the frame; otherwise the frame view itself is the colour
/// and the depth is the renderer's own, single-sampled.
///
/// After [`render_to`](Self::render_to) the frame's depth is the target's
/// own `depth_view`, not this.
pub fn overlay_attachments(&self) -> (Option<&wgpu::TextureView>, &wgpu::TextureView, u32) {
match (&self.msaa_targets, self.overlay_msaa) {
(Some((_, _, color, depth)), true) => (Some(color), depth, self.msaa),
_ => (None, &self.depth_view, 1),
}
}
/// Whether the temporal pass is enabled.
pub fn taa(&self) -> bool {
self.taa_enabled
}
pub fn set_taa(&mut self, enabled: bool) {
if !enabled {
self.taa_frame = 0;
self.taa_history = None;
}
self.taa_enabled = enabled;
}
/// Accumulate a running mean of jittered frames instead of blending with a
/// fixed feedback weight.
///
/// Turn this on when the camera and the scene are both **held still** and
/// the renderer is being asked for one converged image — an offline frame,
/// a product shot, a thumbnail. Each call to `render` then adds one more
/// jittered sample to the mean, so `n` renders give the quality of `n`
/// samples a pixel, and the frame target holds the result after every one
/// of them. Call [`reset_taa`](Self::reset_taa) before each new pose.
///
/// The point of it over [`supersample`](crate::renderer::HeadlessBuilder::supersample)
/// is memory. Supersampling renders at `size x factor`, which at 8K runs
/// out of texture long before it runs out of usefulness — 3x of 4320x7680
/// asks for 23040x12960. This holds one buffer at output size no matter how
/// many samples are taken, so the same convergence is available at any
/// resolution. The pixel throughput is the same either way; what changes is
/// what has to exist at once.
///
/// Leave it off for anything animated: without the neighbourhood clamp a
/// moving image smears.
pub fn set_taa_converge(&mut self, converge: bool) {
self.taa_converge = converge;
}
/// Whether the TAA pass is accumulating a running mean.
pub fn taa_converge(&self) -> bool {
self.taa_converge
}
/// Whether to copy the accumulated image back into the frame target at the
/// end of each render.
///
/// Only the last sample of an accumulation run needs it: the mean lives in
/// the history buffer, and every copy before the final one is a
/// full-resolution blit of an image nobody reads. At 8K that is 133
/// megapixels moved twice per sample.
/// [`HeadlessRenderer::render_accumulated`](super::HeadlessRenderer::render_accumulated)
/// manages this; set it by hand only if you are driving the loop yourself,
/// and put it back before the sample you intend to read.
pub fn set_taa_blit(&mut self, on: bool) {
self.taa_blit = on;
}
/// Jitter the projection by `(x, y)` pixels on the next render, instead of
/// by the Halton sequence, and whether or not TAA is on.
///
/// For a caller accumulating frames itself: the jitter is the only part of
/// the temporal machinery it needs, and it wants to choose the offsets.
/// `None` restores the sequence.
pub fn set_jitter_override(&mut self, offset: Option<(f32, f32)>) {
self.jitter_override = offset;
}
/// Reset TAA accumulation (call on a hard cut / scene change to avoid ghosting).
pub fn reset_taa(&mut self) {
self.taa_frame = 0;
}
fn ensure_taa_targets(&mut self, w: u32, h: u32, format: wgpu::TextureFormat) {
let (w, h) = (w.max(1), h.max(1));
// The format is part of the match, not just the size: turning
// convergence on switches the history to float, and a pair of buffers
// kept because they were merely the right *shape* would leave the
// accumulation back in eight bits with nothing to show for it.
if let Some((cw, ch, ..)) = &self.taa_history {
if *cw == w && *ch == h && self.taa_hist_format == Some(format) {
return;
}
}
self.taa_hist_format = Some(format);
// The cached views and bind groups point at the buffers about to be
// replaced.
self.taa_bind_cache = None;
let mk = || {
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers taa history"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
};
let (a, av) = mk();
let (b, bv) = mk();
self.taa_history = Some((w, h, a, av, b, bv));
self.taa_frame = 0;
}
fn ensure_oit_targets(&mut self, w: u32, h: u32) {
let (w, h) = (w.max(1), h.max(1));
if let Some((cw, ch, ..)) = &self.oit_targets {
if *cw == w && *ch == h {
return;
}
}
let mk = |fmt: wgpu::TextureFormat, label: &str| {
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: fmt,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
};
let (accum, accum_view) = mk(wgpu::TextureFormat::Rgba16Float, "threers oit accum");
let (reveal, reveal_view) = mk(OIT_REVEAL_FORMAT, "threers oit reveal");
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers oit resolve bg"),
layout: &self.oit_resolve_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&accum_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&reveal_view),
},
],
});
self.oit_targets = Some((w, h, accum, accum_view, reveal, reveal_view, bg));
}
/// The OIT accumulation's multisampled targets, resolved into
/// `oit_targets`.
fn ensure_oit_msaa_targets(&mut self, w: u32, h: u32) {
let (w, h) = (w.max(1), h.max(1));
if !take_sized(&mut self.oit_msaa_targets, &mut self.oit_msaa_targets_spare, w, h) {
return;
}
let mk = |format: wgpu::TextureFormat, label: &str| {
self.device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: MSAA_SAMPLES,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
.create_view(&wgpu::TextureViewDescriptor::default())
};
let accum = mk(wgpu::TextureFormat::Rgba16Float, "threers oit accum msaa");
let reveal = mk(OIT_REVEAL_FORMAT, "threers oit reveal msaa");
self.oit_msaa_targets = Some((w, h, accum, reveal));
}
/// Create pipelines and default 1×1 fallback textures.
///
/// `color_format` is the swapchain or render-target format (typically
/// `Rgba8Unorm` or `Rgba8UnormSrgb` on web, `Bgra8UnormSrgb` on some desktops).
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
color_format: wgpu::TextureFormat,
width: u32,
height: u32,
) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::legacy_shader_source().into()),
});
let uniform_entry = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
// 1–2: the transmission capture and its trilinear sampler.
let frame_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers frame bgl"),
entries: &[
uniform_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let mesh_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers mesh bgl"),
entries: &[uniform_entry(0)],
});
// Skinned variant of the mesh BGL: same uniform at binding 0, plus a
// storage buffer of bone matrices at binding 1. This lets the skinned
// pipeline stay within the 4-bind-group WebGPU default limit.
let mesh_skinned_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers mesh skinned bgl"),
entries: &[
uniform_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
// 7 fragment textures (albedo, normal, roughness, metalness, ao,
// emissive, matcap) + 1 sampler, and for the vertex stage the morph
// texture and the uv sets. Every other map — displacement included —
// is a shader variant's (`material_maps`): with the frame group's
// transmission capture and the environment group, this layout is at
// WebGL2's sixteen texture units.
let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
// Binding 10: three.js's morph-target texture, read in the vertex
// stage with `textureLoad` — unfilterable float, so `Rgba32Float`
// works everywhere and it lowers to `texelFetch` on WebGL2. Eleven
// textures here plus the environment group's five stays inside
// WebGL2's sixteen units.
let morph_entry = wgpu::BindGroupLayoutEntry {
binding: 10,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
};
let tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers tex bgl"),
entries: &[
tex_entry(0),
tex_entry(1),
tex_entry(2),
tex_entry(3),
tex_entry(4),
tex_entry(5),
tex_entry(6),
uv_sets_entry(),
wgpu::BindGroupLayoutEntry {
binding: 7,
// The displacement sample needs the same sampler, from the
// vertex stage.
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
morph_entry,
],
});
// Bindings 9..12 are the screen-space capture the refraction pass reads.
// They are left out where that pass cannot be compiled, and the reason is
// the texture budget rather than tidiness: WebGL2 allots sixteen units,
// and this group together with the nine material maps asks for
// seventeen.
let ltc = upload_ltc(&device, &queue);
let env_entries: Vec<wgpu::BindGroupLayoutEntry> = vec![
// 14: the `RectAreaLight` tables, filtered as three.js reads
// them (`LinearFilter`).
wgpu::BindGroupLayoutEntry {
binding: 14,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::Cube,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
// 13: `EnvUniforms`, this group's environment's parameters.
wgpu::BindGroupLayoutEntry {
binding: 13,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
];
// The main layout stops here, deliberately. Bindings 9..12 are the
// screen-space capture, and no entry point outside the refraction pass
// reads them — but a declared binding is not free: wgpu-hal's GL backend
// assigns a texture unit per *layout* entry, not per use, which is why a
// lit draw that samples none of them still ran out of units. They live
// in a second layout below, used only by the pass that needs them.
let env_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers env bgl"),
entries: &env_entries,
});
// The refraction pass's own group 3: the environment and the capture, and
// *not* the three shadow maps, which `fs_ss_glass` never samples. Those
// three units are exactly what makes room for the capture's three, so
// both layouts come to the same total and both fit inside WebGL2's
// sixteen.
let mut env_glass_entries: Vec<wgpu::BindGroupLayoutEntry> = env_entries
.iter()
.filter(|e| matches!(e.binding, 0 | 1 | 8 | 13))
.cloned()
.collect();
env_glass_entries.extend([
// 9/10: screen-space glass — mipmapped opaque-scene capture +
// its trilinear sampler (only read by the fs_ss_glass entry).
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 10,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
// 11: sampleable opaque depth; 12: glass back-face depth (both
// marched/read by fs_ss_glass via textureLoad, no sampler).
// 1×1 placeholders bound otherwise.
// Unfilterable *float*, not `Depth`, even though the views are
// depth-format — a depth format permits either. The shader reads
// these with `textureLoad`, and GLSL has no `texelFetch` for a
// depth sampler, so declared as depth the module cannot be
// lowered for WebGL2 at all. As float textures the same reads
// become `texelFetch` and the pass compiles everywhere.
wgpu::BindGroupLayoutEntry {
binding: 11,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 12,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
// 15: each light's shadow on the glass, packed by
// `fs_glass_shadow` — the one unit left, standing in for the
// three shadow maps.
wgpu::BindGroupLayoutEntry {
binding: 15,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Uint,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
]);
let env_bgl_glass = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers env bgl (refraction)"),
entries: &env_glass_entries,
});
let ss_glass_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers ss glass layout"),
bind_group_layouts: &[
Some(&frame_bgl),
Some(&mesh_bgl),
Some(&tex_bgl),
Some(&env_bgl_glass),
],
immediate_size: 0,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
// Skinned pipeline layout: same as the base 4 groups, but group 1 uses
// the skinned mesh BGL (uniform + bones storage). Stays at 4 groups —
// WebGPU's default `maxBindGroups` limit.
let pipeline_layout_skinned =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers skinned layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_skinned_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
// The shadow passes' group 0: the frame uniforms and, at a dynamic
// offset, the pass's own matrix (`ShadowPassGpu`). Their pipelines
// get layouts of their own with it in place of the frame group.
let shadow_pass_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers shadow pass bgl"),
entries: &[
uniform_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true,
min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<ShadowPassGpu>() as u64),
},
count: None,
},
],
});
let shadow_pass_stride = {
let align = device.limits().min_uniform_buffer_offset_alignment as u64;
(std::mem::size_of::<ShadowPassGpu>() as u64).div_ceil(align) * align
};
let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers shadow layout"),
bind_group_layouts: &[Some(&shadow_pass_bgl), Some(&mesh_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
let shadow_layout_skinned = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers skinned shadow layout"),
bind_group_layouts: &[Some(&shadow_pass_bgl), Some(&mesh_skinned_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
// Point passes: no environment group.
let shadow_layout_point = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers point shadow layout"),
bind_group_layouts: &[Some(&shadow_pass_bgl), Some(&mesh_bgl), Some(&tex_bgl)],
immediate_size: 0,
});
// ShaderMaterial data rides in @group(1) alongside the mesh uniform
// (WebGPU's default maxBindGroups is 4, so we can't add a 5th group):
// binding 0 = mesh uniform (as usual), binding 1 = user uniform block,
// bindings 2..4 = read-only storage arrays.
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let uniform_entry = |binding: u32, vis: wgpu::ShaderStages| wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let volume_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D3,
multisampled: false,
},
count: None,
};
let custom_tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
// The storage arrays again, as textures, for the devices that have no
// storage buffers. `textureLoad` needs no filtering, so these stay
// non-filterable and work with `Rgba32Float` everywhere.
let data_tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
// The storage entries are omitted where the device has none — WebGL2's
// limit is zero, and declaring them anyway fails layout creation
// outright, which takes the whole renderer down before a frame is drawn.
let mut custom_entries = vec![
uniform_entry(0, wgpu::ShaderStages::VERTEX_FRAGMENT),
// The user's own data is visible to the vertex stage as well, which
// is what makes a custom vertex stage worth having: a ribbon or a
// strand needs its control points there, not in the fragment.
uniform_entry(1, wgpu::ShaderStages::VERTEX_FRAGMENT),
];
if crate::renderer::caps::supports_storage_buffers(&device) {
custom_entries.extend([storage_entry(2), storage_entry(3), storage_entry(4)]);
}
custom_entries.extend([
// User textures + their sampler. Unbound slots get a 1x1 white
// placeholder, so a shader that ignores them costs nothing.
custom_tex_entry(5),
custom_tex_entry(6),
custom_tex_entry(7),
custom_tex_entry(8),
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
data_tex_entry(10),
data_tex_entry(11),
data_tex_entry(12),
]);
// `ShaderMaterial::volumes`: two 3D textures and their clamp-to-edge
// sampler, where they fit (not on WebGL2).
if crate::renderer::caps::supports_shader_material_volumes(&device) {
custom_entries.extend([
volume_entry(13),
volume_entry(14),
wgpu::BindGroupLayoutEntry {
binding: 15,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
]);
}
let custom_mesh_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers custom mesh+user bgl"),
entries: &custom_entries,
});
// Group 2 for shader materials: the sampler and the per-geometry
// vertex data, and nothing else.
//
// `ShaderMaterial` has no standard maps — it carries a fragment source,
// a uniform block and its own textures — so the eight material textures
// in `tex_bgl` are definitionally unused by a custom shader. Declaring
// them anyway cost eight fragment texture units, which is what put the
// custom layout over the per-stage limit of sixteen and made shader
// materials unavailable on baseline WebGPU altogether.
//
// Binding 7 stays for the shared `vs_main`'s sampler; the morph
// texture and uv sets are the geometry's. A `ShaderMaterial` has no
// displacement map, so one bind group serves every custom draw.
let custom_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers custom tex bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
// The shared vertex stage reads the morph texture and the uv
// sets too; a shader material binds the geometry's or the
// empty defaults.
morph_entry,
uv_sets_entry(),
],
});
// Built only when the device can hold it.
//
// The four groups together declare 20 sampled textures in the fragment
// stage. WebGPU's floor is 16 and Chrome reports exactly that, so this
// layout cannot be created there at all — and creating it unconditionally
// meant every browser session logged a validation error at startup even
// though nothing had asked for a shader material:
//
// The number of sampled textures (20) in the Fragment stage exceeds
// the maximum per-stage limit (16).
//
// The other three groups already account for 16 of those, so this is not
// a matter of trimming a slot or two; the split would have to change for
// shader materials to work on WebGPU. Until then the feature is absent
// there rather than broken, and `None` is what says so.
// Nine before the data-texture slots, twelve with them, fourteen with
// the two volume slots. WebGPU's floor and WebGL2's are both sixteen,
// so this is a check for the genuinely old rather than a limit anything
// current runs into. WebGL2 counts differently — every texture in the
// layout, sixteen without the volumes — which is why it has none (see
// `caps::supports_shader_material_volumes`).
const CUSTOM_LAYOUT_TEXTURES: u32 = 14;
let custom_pipeline_layout = if device.limits().max_sampled_textures_per_shader_stage
>= CUSTOM_LAYOUT_TEXTURES
{
Some(
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers custom (shader material) layout"),
bind_group_layouts: &[
Some(&frame_bgl),
Some(&custom_mesh_bgl),
Some(&custom_tex_bgl),
Some(&env_bgl),
],
immediate_size: 0,
}),
)
} else {
log::warn!(
"shader materials unavailable: this device allows {} sampled textures per \
fragment stage and the custom layout needs {CUSTOM_LAYOUT_TEXTURES}",
device.limits().max_sampled_textures_per_shader_stage
);
None
};
let custom_ss_pipeline_layout = custom_pipeline_layout.as_ref().map(|_| {
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers custom (screen-space shader material) layout"),
bind_group_layouts: &[
Some(&frame_bgl),
Some(&custom_mesh_bgl),
Some(&custom_tex_bgl),
Some(&env_bgl_glass),
],
immediate_size: 0,
})
});
let vertex_buffers = [wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
}];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers = vertex_buffers.map(Some);
// `Points`: the same vertex buffer, one vertex per *instance* — each
// point is expanded to a quad by `vs_points`.
let vertex_buffers_points = vertex_buffers.clone().map(|b| {
b.map(|mut b| {
b.step_mode = wgpu::VertexStepMode::Instance;
b
})
});
// Every pipeline a material draws with is created through this, which
// keeps its descriptor so a material's `depthTest` / `depthWrite` /
// `depthFunc` / `colorWrite` can be applied to it later — see
// `pipeline_state`.
let state_pipes =
std::cell::RefCell::new(super::pipeline_state::StatePipelines::default());
let record = |desc: &wgpu::RenderPipelineDescriptor| {
state_pipes.borrow_mut().create(&device, desc)
};
// The layouts whose group 2 is the material's maps, registered so a
// pipeline on them can be rebuilt for a material shader variant
// (`material_maps`, `StatePipelines::relayout`).
{
let mut sp = state_pipes.borrow_mut();
sp.register_layout(
&pipeline_layout,
vec![Some(frame_bgl.clone()), Some(mesh_bgl.clone()), Some(tex_bgl.clone()), Some(env_bgl.clone())],
);
sp.register_layout(
&pipeline_layout_skinned,
vec![Some(frame_bgl.clone()), Some(mesh_skinned_bgl.clone()), Some(tex_bgl.clone()), Some(env_bgl.clone())],
);
sp.register_layout(
&shadow_layout,
vec![Some(shadow_pass_bgl.clone()), Some(mesh_bgl.clone()), Some(tex_bgl.clone()), Some(env_bgl.clone())],
);
sp.register_layout(
&shadow_layout_skinned,
vec![Some(shadow_pass_bgl.clone()), Some(mesh_skinned_bgl.clone()), Some(tex_bgl.clone()), Some(env_bgl.clone())],
);
sp.register_layout(
&shadow_layout_point,
vec![Some(shadow_pass_bgl.clone()), Some(mesh_bgl.clone()), Some(tex_bgl.clone())],
);
sp.register_layout(
&ss_glass_pipeline_layout,
vec![Some(frame_bgl.clone()), Some(mesh_bgl.clone()), Some(tex_bgl.clone()), Some(env_bgl_glass.clone())],
);
}
let make_pipeline = |fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
label: &str| {
let alpha = label.contains("alpha");
// Note: PolygonMode::Line needs the POLYGON_MODE_LINE feature, which
// is generally unavailable in browser WebGPU. The wireframe pipeline
// instead uses LineList primitives over the triangle indices (fed as
// edge indices at draw time), so every pipeline stays Fill.
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(topology, cull),
// Transparent: don't write depth, so back fragments behind a
// transparent surface still composite correctly. LessEqual is
// three.js's default `depthFunc`.
depth_stencil: Some(depth_stencil(!alpha, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// Single-layer "glass" pipelines. `GLASS_DEPTH` (the prepass) writes
// the nearest glass depth with no color; the tint and light halves of
// the colour pass (`GLASS_OUTPUT` in the shader) blend only the
// fragments at that nearest depth (LessEqual) and don't write depth:
// the tint multiplies what is behind by the glass's transmittance, the
// light adds its reflection, highlights and emission.
let make_glass_pipeline = |fmt: wgpu::TextureFormat, pass: u8, count: u32, label: &str| {
let depth_only = pass == GLASS_DEPTH;
let blend = match pass {
GLASS_TINT => wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::Src,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
},
GLASS_LIGHT => wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
},
_ => wgpu::BlendState::ALPHA_BLENDING,
};
let constants: &[(&str, f64)] = match pass {
GLASS_TINT => &[("GLASS_OUTPUT", 1.0)],
GLASS_LIGHT => &[("GLASS_OUTPUT", 2.0)],
_ => &[],
};
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(blend),
write_mask: if depth_only {
wgpu::ColorWrites::empty()
} else {
wgpu::ColorWrites::ALL
},
})],
compilation_options: wgpu::PipelineCompilationOptions {
constants,
..Default::default()
},
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(
depth_only,
if depth_only {
wgpu::CompareFunction::Less
} else {
wgpu::CompareFunction::LessEqual
},
)),
multisample: wgpu::MultisampleState {
count,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let f16_format = wgpu::TextureFormat::Rgba16Float;
let pipeline_glass_depth =
make_glass_pipeline(color_format, GLASS_DEPTH, 1, "threers glass depth pipeline");
let pipeline_glass_color =
make_glass_pipeline(color_format, GLASS_LIGHT, 1, "threers glass color pipeline");
let pipeline_glass_tint =
make_glass_pipeline(color_format, GLASS_TINT, 1, "threers glass tint pipeline");
let pipeline_glass_depth_f16 =
make_glass_pipeline(f16_format, GLASS_DEPTH, 1, "threers glass depth f16 pipeline");
let pipeline_glass_color_f16 =
make_glass_pipeline(f16_format, GLASS_LIGHT, 1, "threers glass color f16 pipeline");
let pipeline_glass_tint_f16 =
make_glass_pipeline(f16_format, GLASS_TINT, 1, "threers glass tint f16 pipeline");
// Single-layer glass multisampled, so a scene with glass keeps MSAA.
let pipeline_glass_depth_msaa =
make_glass_pipeline(color_format, GLASS_DEPTH, MSAA_SAMPLES, "threers glass depth msaa pipeline");
let pipeline_glass_color_msaa =
make_glass_pipeline(color_format, GLASS_LIGHT, MSAA_SAMPLES, "threers glass color msaa pipeline");
let pipeline_glass_tint_msaa =
make_glass_pipeline(color_format, GLASS_TINT, MSAA_SAMPLES, "threers glass tint msaa pipeline");
// And for the encoded-blend pass into the multisampled `Unorm` view.
let encoded_glass_msaa = color_format.is_srgb().then(|| {
let unorm = color_format.remove_srgb_suffix();
[
make_glass_pipeline(unorm, GLASS_DEPTH, MSAA_SAMPLES, "threers glass depth encoded msaa pipeline"),
make_glass_pipeline(unorm, GLASS_LIGHT, MSAA_SAMPLES, "threers glass color encoded msaa pipeline"),
make_glass_pipeline(unorm, GLASS_TINT, MSAA_SAMPLES, "threers glass tint encoded msaa pipeline"),
]
});
// Screen-space refraction glass: opaque single-surface pass (writes depth,
// Less test, no blend — it composites the refracted/reflected background
// itself), sampling the captured ss-color from env-group binding 9.
let make_ss_glass_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&ss_glass_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_ss_glass"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
// `LessEqual`: `fs_glass_shadow` has just written the front-most
// glass depth, and this shades exactly that surface.
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// Built everywhere. It has its own group 3 — the screen-space capture in
// place of the shadow maps it never samples — so it comes to the same
// fourteen texture units the main layout does, inside WebGL2's sixteen.
let pipeline_ss_glass = make_ss_glass_pipeline(color_format, "threers ss glass pipeline");
// Each light's shadow on the refracting surfaces, for the pass above
// (`fs_glass_shadow`): the lit layout, which has the shadow maps.
let pipeline_glass_shadow = record(&wgpu::RenderPipelineDescriptor {
label: Some("threers glass shadow pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_glass_shadow"),
targets: &[Some(wgpu::ColorTargetState {
format: GLASS_SHADOW_FORMAT,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, Some(wgpu::Face::Back)),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_ss_glass_f16 =
make_ss_glass_pipeline(f16_format, "threers ss glass f16 pipeline");
// Fullscreen "sample one texture → write" pipeline, used both to build
// the ss-color mip chain (downsample) and to blit the capture back to the
// frame target before the glass draws over it.
let ss_blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers ss blit bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let ss_blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers ss blit layout"),
bind_group_layouts: &[Some(&ss_blit_bgl)],
immediate_size: 0,
});
let ss_blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers ss blit shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::SS_BLIT_SHADER.into()),
});
let make_ss_blit_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&ss_blit_layout),
vertex: wgpu::VertexState {
module: &ss_blit_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &ss_blit_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_ss_blit = make_ss_blit_pipeline(color_format, "threers ss blit pipeline");
let pipeline_ss_blit_f16 =
make_ss_blit_pipeline(f16_format, "threers ss blit f16 pipeline");
// Depth-only pass over glass back faces (cull front) → the exit depth of
// the glass volume, for two-surface (thick) refraction. `vs_main` reads
// the displacement map out of group 2, so this needs the texture layout
// too — otherwise displaced glass would write back-face depth for
// geometry that is not where it is drawn.
let ss_back_depth_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers ss back depth layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_bgl), Some(&tex_bgl)],
immediate_size: 0,
});
state_pipes.borrow_mut().register_layout(
&ss_back_depth_layout,
vec![Some(frame_bgl.clone()), Some(mesh_bgl.clone()), Some(tex_bgl.clone())],
);
let pipeline_ss_back_depth =
record(&wgpu::RenderPipelineDescriptor {
label: Some("threers ss back depth pipeline"),
layout: Some(&ss_back_depth_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: None,
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Front),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// --- Temporal anti-aliasing resolve ---
let taa_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers taa uniform"),
size: std::mem::size_of::<TaaUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let taa_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers taa sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let tex_entry = |binding, depth| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
// Unfilterable float for the depth slot rather than `Depth`: the
// resolve reads it with `textureLoad`, which has no GLSL
// equivalent for a depth sampler. A depth format allows either
// sample type, so this costs nothing and lets the pass compile
// on WebGL2 as well.
sample_type: if depth {
wgpu::TextureSampleType::Float { filterable: false }
} else {
wgpu::TextureSampleType::Float { filterable: true }
},
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let taa_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers taa bgl"),
entries: &[
tex_entry(0, false), // current
tex_entry(1, false), // history
tex_entry(2, true), // depth
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let taa_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers taa layout"),
bind_group_layouts: &[Some(&taa_bgl)],
immediate_size: 0,
});
let taa_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers taa shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::TAA_SHADER.into()),
});
let make_taa = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&taa_layout),
vertex: wgpu::VertexState {
module: &taa_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &taa_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// Built everywhere, including WebGL2: the resolve's depth slot is an
// unfilterable float texture rather than a depth texture, so its
// `textureLoad` lowers to `texelFetch` and the module compiles there too.
let pipeline_taa = make_taa(color_format, "threers taa pipeline");
let pipeline_taa_f16 = make_taa(f16_format, "threers taa f16 pipeline");
// --- Weighted-blended OIT ---
// Accumulation pass: fs_oit writes to accum (additive) + revealage
// (multiplicative), depth-tested against opaque but not writing depth.
let oit_accum_format = wgpu::TextureFormat::Rgba16Float;
let oit_reveal_format = OIT_REVEAL_FORMAT;
let add_blend = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
};
let mul_blend = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
};
// The accumulation pass writes weighted colour and coverage to two
// attachments with different blend equations, which WebGL2 cannot do —
// it blends every attachment alike. Where that is the case the pipeline
// is not built and the pass does not run; transparency falls back to the
// sorted path.
let make_oit = |count: u32, label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_oit"),
targets: &[
Some(wgpu::ColorTargetState {
format: oit_accum_format,
blend: Some(wgpu::BlendState {
color: add_blend,
alpha: add_blend,
}),
write_mask: wgpu::ColorWrites::ALL,
}),
Some(wgpu::ColorTargetState {
format: oit_reveal_format,
blend: Some(wgpu::BlendState {
color: mul_blend,
alpha: mul_blend,
}),
write_mask: wgpu::ColorWrites::ALL,
}),
],
// The light half of a blend, premultiplied, and the transmittance
// beside it (`shade_main`'s `GLASS_OUTPUT`).
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("GLASS_OUTPUT", 2.0)],
..Default::default()
},
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState { count, ..Default::default() },
multiview_mask: None,
cache: None,
})
};
let independent_blend = crate::renderer::caps::supports_independent_blend(&device);
let pipeline_oit = independent_blend.then(|| make_oit(1, "threers oit accum pipeline"));
// Multisampled, against the multisampled opaque depth, resolved
// before the composite: a frame with OIT glass keeps its MSAA.
let pipeline_oit_msaa =
independent_blend.then(|| make_oit(MSAA_SAMPLES, "threers oit accum msaa pipeline"));
// Resolve pass: composite accum/revealage over the opaque image.
let oit_resolve_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers oit resolve bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let resolve_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers oit resolve shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::OIT_RESOLVE_SHADER.into()),
});
let resolve_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers oit resolve layout"),
bind_group_layouts: &[Some(&oit_resolve_bgl)],
immediate_size: 0,
});
// Two halves, as the glass colour pass is: the transmittance
// multiplied over what is behind, then the light added.
let make_resolve = |fmt: wgpu::TextureFormat, pass: u32, count: u32, label: &str| {
let blend = if pass == 0 {
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::Src,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
}
} else {
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
}
};
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&resolve_layout),
vertex: wgpu::VertexState {
module: &resolve_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &resolve_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("RESOLVE_PASS", pass as f64)],
..Default::default()
},
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState { count, ..Default::default() },
multiview_mask: None,
cache: None,
})
};
let pipeline_oit_resolve = [
make_resolve(color_format, 0, 1, "threers oit resolve tint pipeline"),
make_resolve(color_format, 1, 1, "threers oit resolve light pipeline"),
];
let pipeline_oit_resolve_f16 = [
make_resolve(f16_format, 0, 1, "threers oit resolve tint f16 pipeline"),
make_resolve(f16_format, 1, 1, "threers oit resolve light f16 pipeline"),
];
// Into the multisampled colour, resolved to the frame: a pass drawn
// over the frame afterwards (`overlay_attachments`) resolves the
// multisampled colour again, and has to find the composite in it.
let pipeline_oit_resolve_msaa = [
make_resolve(color_format, 0, MSAA_SAMPLES, "threers oit resolve tint msaa pipeline"),
make_resolve(color_format, 1, MSAA_SAMPLES, "threers oit resolve light msaa pipeline"),
];
// A multisampled depth to a single-sampled one, for the refraction
// pass under MSAA. Not where shaders cannot read multisampled
// textures (WebGL2); there a refraction frame stays single-sampled.
let depth_resolve = crate::renderer::caps::supports_multisampled_textures(&device).then(|| {
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers depth resolve bgl"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: true,
},
count: None,
}],
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers depth resolve shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::DEPTH_RESOLVE_SHADER.into()),
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers depth resolve layout"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers depth resolve pipeline"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Always)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
(bgl, pipeline)
});
let pipeline_tri = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri pipeline",
);
let pipeline_tri_alpha = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha pipeline",
);
let pipeline_tri_nocull = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull pipeline",
);
let make_sky_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_tri_sky = make_sky_pipeline(color_format, "threers tri sky pipeline");
// `wireframe: true` materials: a LineList pipeline (Fill polygon mode, so no
// NON_FILL_POLYGON_MODE feature needed and it works in browser WebGPU) drawn
// over the mesh's separate wire index buffer — `BufferGeometry::wireframe_indices`,
// i.e. polygon outlines when the geometry carries a polygon table, else every
// triangle edge as three.js draws them. See `GpuMesh::wire_index_buffer`.
let pipeline_tri_wire = make_pipeline(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire pipeline",
);
let pipeline_line = make_pipeline(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line pipeline",
);
// three.js `Points`: a quad per point (`vs_points`), opaque — replace,
// depth written — or blended, in either target format, single- or
// multisampled.
let make_point_pipeline = |fmt: wgpu::TextureFormat, blend: bool, samples: u32, label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_points"),
buffers: &vertex_buffers_points,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(if blend { wgpu::BlendState::ALPHA_BLENDING } else { wgpu::BlendState::REPLACE }),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(!blend, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState { count: samples, ..Default::default() },
multiview_mask: None,
cache: None,
})
};
let pipeline_point = make_point_pipeline(color_format, false, 1, "threers point pipeline");
let pipeline_point_alpha = make_point_pipeline(color_format, true, 1, "threers point alpha pipeline");
// --- Hardware-MSAA variants of the opaque forward pipelines (surface
// path only). Identical to the ones above but with `count = MSAA_SAMPLES`;
// used when antialiasing is enabled and the scene has no glass/OIT/refract
// /instanced/skinned/custom draws (those fall back to the 1× path). ---
let make_pipeline_ms = |fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
label: &str| {
let alpha = label.contains("alpha");
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(topology, cull),
depth_stencil: Some(depth_stencil(!alpha, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState {
count: MSAA_SAMPLES,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let make_sky_pipeline_ms = |fmt: wgpu::TextureFormat, label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState {
count: MSAA_SAMPLES,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let pipeline_tri_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri msaa",
);
let pipeline_tri_alpha_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha msaa",
);
let pipeline_tri_nocull_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull msaa",
);
let pipeline_tri_wire_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire msaa",
);
let pipeline_line_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line msaa",
);
let pipeline_point_msaa = make_point_pipeline(color_format, false, MSAA_SAMPLES, "threers point msaa");
let pipeline_tri_sky_msaa = make_sky_pipeline_ms(color_format, "threers tri sky msaa");
let pipeline_tri_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri f16 pipeline",
);
let pipeline_tri_alpha_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha f16 pipeline",
);
let pipeline_tri_nocull_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull f16 pipeline",
);
let pipeline_tri_sky_f16 = make_sky_pipeline(f16_format, "threers tri sky f16 pipeline");
let pipeline_tri_wire_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire f16 pipeline",
);
let pipeline_line_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line f16 pipeline",
);
let pipeline_point_f16 = make_point_pipeline(f16_format, false, 1, "threers point f16 pipeline");
let pipeline_point_alpha_f16 =
make_point_pipeline(f16_format, true, 1, "threers point alpha f16 pipeline");
// Instanced pipeline: vertex layout slot 0 (per-vertex), slot 1 per-instance mat4.
let vertex_buffers_instanced = [
wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
},
wgpu::VertexBufferLayout {
// Sixteen floats of matrix plus four of tint.
array_stride: 80,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 16,
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 6,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 7,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 64,
shader_location: 9,
format: wgpu::VertexFormat::Float32x4,
},
],
},
];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers_instanced = vertex_buffers_instanced.map(Some);
// Skinned vertex layout: slot 0 = standard vertex, slot 1 = joints+weights.
let vertex_buffers_skinned = [
wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
},
wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 16,
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
],
},
];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers_skinned = vertex_buffers_skinned.map(Some);
// Skinned and instanced pipelines, each in a filled (back-face culled)
// and a `wireframe: true` LineList variant, for the surface format and
// the half-float postfx format. The two kinds differ only in layout,
// vertex entry point and vertex buffers.
type MeshKind<'a> = (
&'a wgpu::PipelineLayout,
&'a str,
&'a [Option<wgpu::VertexBufferLayout<'a>>],
);
let skinned: MeshKind = (&pipeline_layout_skinned, "vs_skinned", &vertex_buffers_skinned);
let instanced: MeshKind = (&pipeline_layout, "vs_instanced", &vertex_buffers_instanced);
let make_mesh_pipeline_samples = |(layout, entry, buffers): MeshKind,
fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
samples: u32,
label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(topology, cull),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState {
count: samples,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let make_mesh_pipeline = |kind: MeshKind,
fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
label: &str| {
make_mesh_pipeline_samples(kind, fmt, topology, cull, 1, label)
};
let tris = wgpu::PrimitiveTopology::TriangleList;
let lines = wgpu::PrimitiveTopology::LineList;
let back = Some(wgpu::Face::Back);
// Multisampled, so a frame holding a skinned or instanced mesh keeps
// its MSAA.
let pipeline_skinned_msaa = make_mesh_pipeline_samples(
skinned,
color_format,
tris,
back,
MSAA_SAMPLES,
"threers skinned msaa pipeline",
);
let pipeline_instanced_msaa = make_mesh_pipeline_samples(
instanced,
color_format,
tris,
back,
MSAA_SAMPLES,
"threers instanced msaa pipeline",
);
let pipeline_skinned =
make_mesh_pipeline(skinned, color_format, tris, back, "threers skinned pipeline");
let pipeline_skinned_f16 =
make_mesh_pipeline(skinned, f16_format, tris, back, "threers skinned f16 pipeline");
let pipeline_skinned_wire =
make_mesh_pipeline(skinned, color_format, lines, None, "threers skinned wire pipeline");
let pipeline_skinned_wire_f16 = make_mesh_pipeline(
skinned,
f16_format,
lines,
None,
"threers skinned wire f16 pipeline",
);
let pipeline_instanced =
make_mesh_pipeline(instanced, color_format, tris, back, "threers instanced pipeline");
let pipeline_instanced_f16 =
make_mesh_pipeline(instanced, f16_format, tris, back, "threers instanced f16 pipeline");
let pipeline_instanced_wire = make_mesh_pipeline(
instanced,
color_format,
lines,
None,
"threers instanced wire pipeline",
);
let pipeline_instanced_wire_f16 = make_mesh_pipeline(
instanced,
f16_format,
lines,
None,
"threers instanced wire f16 pipeline",
);
let pipeline_sprite = record(&wgpu::RenderPipelineDescriptor {
label: Some("threers sprite pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_sprite"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_sprite_f16 = record(&wgpu::RenderPipelineDescriptor {
label: Some("threers sprite f16 pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_sprite"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: f16_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// Alpha-blended draws on the skinned, instanced and sprite layouts:
// the transparent instanced and skinned pipelines in both target
// formats, and — on an sRGB target — all three into its `Unorm` view
// for the encoded-blend pass. No depth write, as `pipeline_tri_alpha`.
let make_blend_pipeline = |(layout, entry, buffers): MeshKind,
fmt: wgpu::TextureFormat,
cull: Option<wgpu::Face>,
compare: wgpu::CompareFunction,
label: &str| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, cull),
depth_stencil: Some(depth_stencil(false, compare)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// three.js's default `depthFunc`.
let less = wgpu::CompareFunction::LessEqual;
let pipeline_instanced_alpha =
make_blend_pipeline(instanced, color_format, back, less, "threers instanced alpha pipeline");
let pipeline_instanced_alpha_f16 =
make_blend_pipeline(instanced, f16_format, back, less, "threers instanced alpha f16 pipeline");
let pipeline_skinned_alpha =
make_blend_pipeline(skinned, color_format, back, less, "threers skinned alpha pipeline");
let pipeline_skinned_alpha_f16 =
make_blend_pipeline(skinned, f16_format, back, less, "threers skinned alpha f16 pipeline");
let sprite_kind: MeshKind = (&pipeline_layout, "vs_sprite", &vertex_buffers);
let encoded_blend_pipelines = color_format.is_srgb().then(|| {
let unorm = color_format.remove_srgb_suffix();
[
make_blend_pipeline(
sprite_kind,
unorm,
None,
wgpu::CompareFunction::LessEqual,
"threers sprite encoded pipeline",
),
make_blend_pipeline(instanced, unorm, back, less, "threers instanced encoded pipeline"),
make_blend_pipeline(skinned, unorm, back, less, "threers skinned encoded pipeline"),
make_point_pipeline(unorm, true, 1, "threers point encoded pipeline"),
make_glass_pipeline(unorm, GLASS_DEPTH, 1, "threers glass depth encoded pipeline"),
make_glass_pipeline(unorm, GLASS_LIGHT, 1, "threers glass color encoded pipeline"),
make_glass_pipeline(unorm, GLASS_TINT, 1, "threers glass tint encoded pipeline"),
]
});
// Depth-only pipeline used to render the scene from each shadow-casting
// light's POV. Reuses the per-vertex layout + per-mesh uniforms.
let make_shadow_pipeline = |entry: &str, label: &str, cut: bool| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&shadow_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
// A cut-out caster (`alphaTest` with a map) tests the map's
// alpha per fragment; every other caster is depth-only.
fragment: cut.then(|| wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_shadow_cut"),
targets: &[],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Front),
),
// Shadow bias reduces acne; keep the explicit DepthStencilState.
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: wgpu::DepthBiasState {
constant: 2,
slope_scale: 2.0,
clamp: 0.0,
},
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_shadow = make_shadow_pipeline("vs_shadow", "threers shadow pipeline", false);
let pipeline_shadow_spot =
make_shadow_pipeline("vs_shadow_spot", "threers spot shadow pipeline", false);
// The only shadow pipeline with a fragment stage: see `fs_shadow_point`.
let pipeline_shadow_point = {
record(&wgpu::RenderPipelineDescriptor {
label: Some("threers point shadow pipeline"),
layout: Some(&shadow_layout_point),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_shadow_point"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_shadow_point"),
targets: &[],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// Shadow casters that are skinned: the same three passes on the
// skinned layout and vertex buffers, so the map holds the pose the
// colour pass draws rather than the bind pose (or nothing).
let make_skinned_shadow_pipeline = |entry: &str, label: &str, point: bool, cut: bool| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&shadow_layout_skinned),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers: &vertex_buffers_skinned,
compilation_options: Default::default(),
},
fragment: (point || cut).then(|| wgpu::FragmentState {
module: &shader,
entry_point: Some(if point { "fs_shadow_point" } else { "fs_shadow_cut" }),
targets: &[],
compilation_options: Default::default(),
}),
primitive: if point {
wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
}
} else {
primitive(wgpu::PrimitiveTopology::TriangleList, Some(wgpu::Face::Front))
},
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: if point {
Default::default()
} else {
wgpu::DepthBiasState {
constant: 2,
slope_scale: 2.0,
clamp: 0.0,
}
},
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_shadow_skinned = make_skinned_shadow_pipeline(
"vs_shadow_skinned",
"threers skinned shadow pipeline",
false,
false,
);
let pipeline_shadow_spot_skinned = make_skinned_shadow_pipeline(
"vs_shadow_spot_skinned",
"threers skinned spot shadow pipeline",
false,
false,
);
let pipeline_shadow_point_skinned = make_skinned_shadow_pipeline(
"vs_shadow_point_skinned",
"threers skinned point shadow pipeline",
true,
false,
);
// Instanced casters: the same three passes on the instanced vertex
// layout. The point pass's layout is the point pipeline's — frame,
// mesh and the morph texture's group — and the other two share the
// mesh pipelines' layout, as their non-instanced twins do.
let make_instanced_shadow_pipeline = |entry: &str, label: &str, point: bool, cut: bool| {
record(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(if point { &shadow_layout_point } else { &shadow_layout }),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers: &vertex_buffers_instanced,
compilation_options: Default::default(),
},
fragment: (point || cut).then(|| wgpu::FragmentState {
module: &shader,
entry_point: Some(if point { "fs_shadow_point" } else { "fs_shadow_cut" }),
targets: &[],
compilation_options: Default::default(),
}),
primitive: if point {
wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
}
} else {
primitive(wgpu::PrimitiveTopology::TriangleList, Some(wgpu::Face::Front))
},
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: if point {
Default::default()
} else {
wgpu::DepthBiasState {
constant: 2,
slope_scale: 2.0,
clamp: 0.0,
}
},
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_shadow_instanced = make_instanced_shadow_pipeline(
"vs_shadow_instanced",
"threers instanced shadow pipeline",
false,
false,
);
let pipeline_shadow_spot_instanced = make_instanced_shadow_pipeline(
"vs_shadow_spot_instanced",
"threers instanced spot shadow pipeline",
false,
false,
);
let pipeline_shadow_point_instanced = make_instanced_shadow_pipeline(
"vs_shadow_point_instanced",
"threers instanced point shadow pipeline",
true,
false,
);
// Cut-out casters: the directional and spot passes again, with
// `fs_shadow_cut` testing the map's alpha against `alphaTest`.
let shadow_cut = ShadowCutPipelines {
dir: make_shadow_pipeline("vs_shadow", "threers cut-out shadow pipeline", true),
spot: make_shadow_pipeline("vs_shadow_spot", "threers cut-out spot shadow pipeline", true),
dir_skinned: make_skinned_shadow_pipeline(
"vs_shadow_skinned",
"threers skinned cut-out shadow pipeline",
false,
true,
),
spot_skinned: make_skinned_shadow_pipeline(
"vs_shadow_spot_skinned",
"threers skinned cut-out spot shadow pipeline",
false,
true,
),
dir_instanced: make_instanced_shadow_pipeline(
"vs_shadow_instanced",
"threers instanced cut-out shadow pipeline",
false,
true,
),
spot_instanced: make_instanced_shadow_pipeline(
"vs_shadow_spot_instanced",
"threers instanced cut-out spot shadow pipeline",
false,
true,
),
};
// The opaque scene's depth again, single-sampled: for screen-space
// refraction under MSAA where a shader cannot read the multisampled
// depth to resolve it (WebGL2). The caster vertex stages, given the
// camera's view-projection for their matrix; no colour, no bias.
// `[plain, skinned, instanced]`, then the same with the cut-out
// fragment stage for `alphaTest` with a map.
let make_replay = |which: usize, cut: bool| {
let (entry, layout, buffers): (&str, &wgpu::PipelineLayout, &[Option<wgpu::VertexBufferLayout>]) =
match which {
0 => ("vs_shadow", &shadow_layout, &vertex_buffers[..]),
1 => ("vs_shadow_skinned", &shadow_layout_skinned, &vertex_buffers_skinned[..]),
_ => ("vs_shadow_instanced", &shadow_layout, &vertex_buffers_instanced[..]),
};
record(&wgpu::RenderPipelineDescriptor {
label: Some("threers depth replay pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers,
compilation_options: Default::default(),
},
fragment: cut.then(|| wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_shadow_cut"),
targets: &[],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, Some(wgpu::Face::Back)),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let depth_replay: Vec<wgpu::RenderPipeline> =
[(0, false), (1, false), (2, false), (0, true), (1, true), (2, true)]
.iter()
.map(|&(w, c)| make_replay(w, c))
.collect();
// Post-fx fullscreen-quad pipeline. Reads one input texture, writes
// to a render attachment matching the surface format.
let postfx_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers postfx shader"),
source: wgpu::ShaderSource::Wgsl(crate::renderer::shader::POSTFX_SHADER.into()),
});
let postfx_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers postfx bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
// Unfilterable float rather than `Depth`, so the
// `textureLoad` in `sample_postfx_depth` lowers to
// `texelFetch`. A depth format allows either.
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
count: None,
},
],
});
let postfx_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers postfx pipeline layout"),
bind_group_layouts: &[Some(&postfx_bgl)],
immediate_size: 0,
});
let pipeline_postfx = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let postfx_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
let postfx_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx nearest sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let postfx_noise_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx noise sampler"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let ssao_kernel_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers ssao kernel buffer"),
size: (32 * 16) as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let ssao_noise_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ssao noise"),
size: wgpu::Extent3d {
width: 4,
height: 4,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let ssao_noise_view = ssao_noise_tex.create_view(&wgpu::TextureViewDescriptor::default());
let glitch_disp_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glitch disp"),
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let glitch_disp_view = glitch_disp_tex.create_view(&wgpu::TextureViewDescriptor::default());
let rgba_upload_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers rgba upload"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let rgba_upload_view = rgba_upload_tex.create_view(&wgpu::TextureViewDescriptor::default());
// Same pipeline as `pipeline_postfx`, but with additive blending so
// the shader output adds to existing framebuffer pixels (bloom composite).
let pipeline_postfx_add = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx additive pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_outline_add =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx outline additive pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_multiply =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx multiply pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Dst,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let postfx_f16_format = wgpu::TextureFormat::Rgba16Float;
let pipeline_postfx_f16 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx f16 pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: postfx_f16_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_add_f16 =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx additive f16 pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: postfx_f16_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let sprite_quad = {
let mut g = crate::core::BufferGeometry::new();
g.set_attribute(
"position",
crate::core::BufferAttribute::new(
vec![
-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.5, 0.5, 0.0, -0.5, 0.5, 0.0,
],
3,
),
);
g.set_attribute(
"uv",
crate::core::BufferAttribute::new(vec![0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], 2),
);
g.set_index(vec![0, 1, 2, 0, 2, 3]);
GpuMesh::upload(&device, &g)
};
let (depth_texture, depth_view) = create_depth_view(&device, width, height);
let hw_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers postfx hw depth placeholder"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let frame_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers frame uniform"),
size: std::mem::size_of::<FrameUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let transmission_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers transmission sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
let transmission_dummy = {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers transmission stand-in"),
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, view)
};
let frame_buffer_for_bg = frame_buffer.clone();
let frame_bind_group =
frame_bg(&device, &frame_bgl, &frame_buffer, &transmission_dummy.1, &transmission_sampler, "threers frame bg");
let frame_bind_group_dummy =
frame_bg(&device, &frame_bgl, &frame_buffer, &transmission_dummy.1, &transmission_sampler, "threers frame bg (capture)");
let sampler_linear_repeat = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers linear-repeat sampler"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
// Anisotropic filtering. Mip-mapping alone still blurs a texture seen
// at a grazing angle — the whole surface of a sphere near its limb —
// because the sampler has to pick one level for a footprint that is
// long in one direction and short in the other.
anisotropy_clamp: 16,
..Default::default()
});
let samplers = (0..SAMPLER_COUNT).map(|i| make_sampler(&device, i)).collect();
let default_white_srgb = GpuTexture::upload(
&device,
&queue,
&Texture::solid([255, 255, 255, 255], TextureFormat::Rgba8UnormSrgb),
);
let default_data_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers user data placeholder"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let default_data_tex_view =
default_data_tex.create_view(&wgpu::TextureViewDescriptor::default());
let default_volume_view = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("threers user volume placeholder"),
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D3,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&wgpu::TextureViewDescriptor::default());
let sampler_volume = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers volume sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let default_white_linear = GpuTexture::upload(
&device,
&queue,
&Texture::solid([255, 255, 255, 255], TextureFormat::Rgba8Unorm),
);
// The morph slot's placeholder: one texel, one layer, never read
// (a draw without morph targets uploads a zero count).
let default_morph = {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers default morph texture"),
// Two layers so the GL backend makes it an array texture,
// matching the shader's declaration (see `ensure_morph`).
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 2,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
(texture, view)
};
let default_uv_sets = {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers default uv sets"),
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, view)
};
let custom_tex_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers custom tex bg"),
layout: &custom_tex_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(&default_uv_sets.1),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler(&sampler_linear_repeat),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(&default_morph.1),
},
],
});
let default_normal = GpuTexture::upload(
&device,
&queue,
&Texture::solid([128, 128, 255, 255], TextureFormat::Rgba8Unorm),
);
let default_transparent = GpuTexture::upload(
&device,
&queue,
&Texture::solid([0, 0, 0, 0], TextureFormat::Rgba8Unorm),
);
// Default 1x1 environment cubemap: all-black faces (zero env contribution).
let default_env_cube = {
let face_data = [0u8; 4];
let faces = [
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
];
let src = CubeTexture::new(1, TextureFormat::Rgba8UnormSrgb, faces);
GpuCubeTexture::upload(&device, &queue, &src)
};
let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers env sampler"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
// Trilinear sampler for the screen-space glass capture — roughness maps
// to a mip LOD so rough glass blurs its refracted/reflected image.
let ss_glass_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers ss glass sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
// Shadow depth texture for the directional light's depth pre-pass.
//
// 4096, up from 1024. The map covers whatever the light's `camera_size`
// spans, so its resolution is only meaningful as a ratio: a vehicle
// 8 m across got 8 mm of shadow per texel at 1024, which is coarse
// enough to see as staircase edges on every strut. At 4096 it is 2 mm,
// and the cost is one 64 MB depth target and a depth pass over the same
// geometry — nothing next to the colour pass at 8K.
//
// KEEP IN STEP with SHADOW_TEXEL in shader.rs, which sizes the PCF
// kernel and cannot read this constant.
let dir_shadows = ShadowArray::new(&device, "threers shadow depth", SPOT_SHADOW_SIZE, 1);
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let spot_shadows = ShadowArray::new(&device, "threers spot shadow depth", SPOT_SHADOW_SIZE, 1);
let spot_shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers spot shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
// Point shadows: six faces per light, in a 2D array.
let point_shadows = ShadowArray::new(&device, "threers point shadow depth", POINT_SHADOW_SIZE, 6);
let point_shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers point shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let default_cube_uv_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers default cube uv"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &default_cube_uv_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&[0u8, 0, 0, 255],
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4),
rows_per_image: Some(1),
},
wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
);
let default_cube_uv_view =
default_cube_uv_tex.create_view(&wgpu::TextureViewDescriptor::default());
let make_env_uniform = |u: EnvUniforms, label: &str| {
wgpu::util::DeviceExt::create_buffer_init(
&*device,
&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: bytemuck::bytes_of(&u),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
},
)
};
// The scene's, rewritten every frame; and one with no environment,
// for the shadow passes, which read none.
let env_uniform = make_env_uniform(EnvUniforms::NONE, "threers scene env uniforms");
let no_env_uniform = make_env_uniform(EnvUniforms::NONE, "threers no env uniforms");
let env_bind_group = env_bind_group!(
device,
&env_bgl,
"threers env bg",
&default_env_cube.view,
&env_sampler,
&dir_shadows.view,
&shadow_sampler,
&spot_shadows.view,
&spot_shadow_sampler,
&point_shadows.view,
&point_shadow_sampler,
&default_cube_uv_view,
&env_uniform,
<c.1,
);
// Dummy 1x1 depth textures used by `shadow_env_bind_group` so the
// shadow passes can satisfy the pipeline layout without binding the
// textures they're currently writing to (WebGPU forbids simultaneous
// RenderAttachment + TextureBinding usage of the same resource).
let dummy_depth = ShadowArray::new(&device, "threers dummy depth", 1, 1);
let shadow_env_bind_group = env_bind_group!(
device,
&env_bgl,
"threers shadow env bg (dummies)",
&default_env_cube.view,
&env_sampler,
&dummy_depth.view,
&shadow_sampler,
&dummy_depth.view,
&spot_shadow_sampler,
&dummy_depth.view,
&point_shadow_sampler,
&default_cube_uv_view,
&no_env_uniform,
<c.1,
);
// Each draw's uniforms at an offset the device accepts for a binding.
let mesh_stride = {
let align = device.limits().min_uniform_buffer_offset_alignment as u64;
(std::mem::size_of::<MeshUniforms>() as u64).div_ceil(align) * align
};
let mut renderer = Self {
device,
queue,
pipeline_glass_depth,
pipeline_glass_color,
pipeline_glass_depth_f16,
pipeline_glass_color_f16,
pipeline_glass_depth_msaa,
pipeline_glass_color_msaa,
pipeline_glass_tint,
pipeline_glass_tint_f16,
pipeline_glass_tint_msaa,
encoded_glass_msaa,
pipeline_oit,
pipeline_oit_resolve,
pipeline_oit_resolve_f16,
pipeline_oit_resolve_msaa,
pipeline_oit_msaa,
oit_msaa_targets: None,
oit_msaa_targets_spare: None,
depth_resolve,
oit_resolve_bgl,
oit_targets: None,
ss_color: None,
ss_glass_sampler,
ss_depth: None,
ss_back_depth: None,
ss_layer: None,
refraction_layers: 2,
pipeline_ss_back_depth,
pipeline_ss_blit,
pipeline_ss_blit_f16,
pipeline_ss_glass,
pipeline_ss_glass_f16,
pipeline_glass_shadow,
ss_glass_shadow: None,
ss_blit_bgl,
taa_enabled: false,
taa_frame: 0,
taa_converge: false,
taa_blit: true,
taa_hist_format: None,
jitter_override: None,
taa_bind_cache: None,
taa_prev_view_proj: [0.0; 16],
mb_inv_vp: [0.0; 16],
mb_prev_vp: [0.0; 16],
mb_last_vp: [0.0; 16],
taa_prev_cam: [0.0; 3],
taa_history: None,
taa_uniform,
taa_bgl,
taa_sampler,
pipeline_taa,
pipeline_taa_f16,
pipeline_tri,
pipeline_tri_alpha,
pipeline_tri_nocull,
pipeline_tri_sky,
pipeline_tri_wire,
pipeline_line,
pipeline_point,
pipeline_point_alpha,
pipeline_sprite,
pipeline_tri_msaa,
pipeline_skinned_msaa,
pipeline_instanced_msaa,
pipeline_tri_alpha_msaa,
pipeline_tri_nocull_msaa,
pipeline_tri_sky_msaa,
pipeline_tri_wire_msaa,
pipeline_line_msaa,
pipeline_point_msaa,
msaa: 1,
// Off by default: enabling tone mapping would silently re-grade
// every existing scene and the parity renders along with them.
tone_mapping: ToneMapping::None,
specular_antialiasing: false,
tone_map_pass: true,
exposure: 1.0,
msaa_targets: None,
msaa_targets_spare: None,
overlay_msaa: false,
last_frame_msaa: false,
fxaa_scratch: None,
pipeline_tri_f16,
pipeline_tri_alpha_f16,
pipeline_tri_nocull_f16,
pipeline_tri_sky_f16,
pipeline_tri_wire_f16,
pipeline_line_f16,
pipeline_point_f16,
pipeline_point_alpha_f16,
pipeline_sprite_f16,
pipeline_instanced_f16,
pipeline_skinned_f16,
pipeline_shadow,
pipeline_shadow_spot,
pipeline_shadow_point,
pipeline_shadow_skinned,
pipeline_shadow_spot_skinned,
pipeline_shadow_point_skinned,
pipeline_shadow_instanced,
pipeline_shadow_spot_instanced,
shadow_cut,
pipeline_shadow_point_instanced,
pipeline_instanced,
pipeline_skinned,
pipeline_instanced_wire,
pipeline_instanced_wire_f16,
pipeline_instanced_alpha,
pipeline_instanced_alpha_f16,
pipeline_skinned_alpha,
pipeline_skinned_alpha_f16,
encoded_blend_pipelines,
pipeline_skinned_wire,
pipeline_skinned_wire_f16,
pipeline_postfx,
pipeline_postfx_add,
pipeline_postfx_outline_add,
pipeline_postfx_multiply,
pipeline_postfx_f16,
pipeline_postfx_add_f16,
postfx_bgl,
postfx_sampler,
postfx_nearest_sampler,
postfx_noise_sampler,
postfx_ext: Default::default(),
ssao_kernel_buffer,
ssao_noise_tex,
ssao_noise_view,
glitch_disp_tex,
glitch_disp_view,
rgba_upload_tex,
rgba_upload_view,
#[cfg(feature = "captions")]
caption_pass: None,
overlay_pass: None,
mesh_skinned_bgl,
sprite_quad,
frame_bgl,
mesh_bgl,
tex_bgl,
env_bgl,
env_bgl_glass,
ltc,
custom_tex_bind_group,
custom_tex_bgl,
mesh_shader: shader.clone(),
mesh_pipeline_layout: pipeline_layout.clone(),
biased_pipelines: HashMap::new(),
state_pipelines: state_pipes.into_inner(),
msaa_color_unorm: None,
encoded_scratch: None,
encoded_copy: None,
custom_mesh_bgl,
custom_pipeline_layout,
custom_ss_pipeline_layout,
custom_pipelines: HashMap::new(),
custom_encoded_pipelines: HashMap::new(),
custom_msaa_pipelines: HashMap::new(),
custom_failed: std::collections::HashSet::new(),
depth_view,
depth_texture,
hw_depth_tex,
depth_size: (width, height),
geom_cache: HashMap::new(),
frustum_culling: true,
cull_stats: (0, 0),
timer: None,
shadow_timer: None,
shadow_map: Default::default(),
shadow_sig: None,
shadow_pass_hashes: Vec::new(),
shadow_stats: (0, 0),
shadow_updates: 0,
skin_attr_cache: HashMap::new(),
morph_cache: HashMap::new(),
instance_cache: HashMap::new(),
instance_frame: 0,
instance_stamps: 0,
uv_cache: HashMap::new(),
default_uv_sets,
default_morph,
wire_span_cache: HashMap::new(),
tex_cache: HashMap::new(),
mipgen: None,
rt_view_cache: HashMap::new(),
rt_linear_view_cache: HashMap::new(),
rt_registry: HashMap::new(),
rt_depth_view_cache: HashMap::new(),
cube_rt_view_cache: HashMap::new(),
env_max_mip: 0.0,
cube_cache: HashMap::new(),
env_bind_group,
shadow_env_bind_group,
env_uniform,
material_env_groups: HashMap::new(),
pmrem_cache: HashMap::new(),
env_sampler,
default_env_cube,
default_cube_uv_view,
shadow_pass_buffer: None,
depth_replay,
depth_replay_pass: None,
force_depth_replay: false,
msaa_depth_out: None,
shadow_pass_bgl,
shadow_pass_stride,
shadow_type: crate::lights::ShadowType::default(),
env_cached_key: None,
env_dirty: true,
env_cached_rt_id: None,
dir_shadows,
spot_shadows,
point_shadows,
cube_pass: false,
viewport_state: Default::default(),
shadow_sampler,
spot_shadow_sampler,
point_shadow_sampler,
frame_buffer,
frame_bind_group,
frame_bind_group_dummy,
frame_buffer_for_bg,
transmission_sampler,
transmission: None,
capturing_transmission: None,
reflective_transparency: false,
per_mesh: Vec::new(),
mesh_arena: None,
mesh_stride,
mesh_bytes: Vec::new(),
tex_bg_cache: HashMap::new(),
main_shader: shader.clone(),
map_variants: HashMap::new(),
variant_bg_cache: HashMap::new(),
sampler_linear_repeat,
samplers,
default_white_srgb,
default_white_linear,
default_data_tex_view,
default_volume_view,
sampler_volume,
last_camera_planes: (0.1, 1000.0),
last_camera_lens: (0.414, 1.0),
default_normal,
default_transparent,
color_format,
};
// Screen-space ambient occlusion needs a sample kernel and a rotation
// noise texture, and until now the only code that ever uploaded them
// was `wasm.rs`. Every native caller got a zero kernel — so every
// sample offset was the zero vector, every sample landed on the
// fragment it started from, `delta` never exceeded `min_dist`, and the
// effect returned a constant for every pixel whatever radius it was
// given. That is why SSAO has been switched off by default: it was not
// subtle, it was doing nothing.
//
// Defaults are installed here so the feature works out of the box; the
// setters still override them.
renderer.timer = GpuTimer::new(&renderer.device, &renderer.queue);
renderer.shadow_timer = GpuTimer::new(&renderer.device, &renderer.queue);
renderer.set_ssao_kernel(&default_ssao_kernel());
renderer.set_ssao_noise(&default_ssao_noise());
renderer
}
/// Turn frustum culling off, drawing every mesh whether the camera can see
/// it or not.
///
/// On by default. The only reason to switch it off is a geometry whose
/// vertex positions are not where its buffer says they are — the renderer
/// already exempts skinned, instanced and custom-shader draws, so this is
/// an escape hatch rather than a knob worth turning.
pub fn set_frustum_culling(&mut self, on: bool) {
self.frustum_culling = on;
}
pub fn frustum_culling(&self) -> bool {
self.frustum_culling
}
/// `(drawn, culled)` meshes for the most recent `render` call.
///
/// `culled` counts draws the camera frustum rejected. They were still
/// submitted to the shadow passes — an off-screen caster shadows the view
/// — so this is a count of skipped *colour* draws, not of skipped work
/// altogether.
pub fn cull_stats(&self) -> (usize, usize) {
self.cull_stats
}
pub fn color_format(&self) -> wgpu::TextureFormat {
self.color_format
}
pub fn resize(&mut self, width: u32, height: u32) {
if (width, height) != self.depth_size && width > 0 && height > 0 {
let (tex, view) = create_depth_view(&self.device, width, height);
self.depth_texture = tex;
self.depth_view = view;
self.depth_size = (width, height);
// Recreated on the next MSAA pass at the new size.
self.msaa_targets = None;
self.msaa_targets_spare = None;
}
}
/// three.js `setViewport`: draw the next renders into this rectangle of
/// the target. **Bottom-left origin, logical pixels** (multiplied by
/// [`pixel_ratio`](Self::set_pixel_ratio)), as in three.js. The rectangle
/// may hang off the target; the visible part is drawn with the projection
/// adjusted so the picture does not squash. The default is the whole
/// target; [`reset_viewport`](Self::reset_viewport) goes back to it.
///
/// Applies to [`render`](Self::render), [`render_to`](Self::render_to) and
/// [`render_to_multisampled`](Self::render_to_multisampled) alike — to
/// whatever target the next render draws into — but never to cube-camera
/// faces. See [`super::viewport`] for what a sub-rectangle turns off.
pub fn set_viewport(&mut self, x: f32, y: f32, width: f32, height: f32) {
self.viewport_state.settings.viewport = Some(super::ViewportRect::new(x, y, width, height));
}
/// The viewport set by [`set_viewport`](Self::set_viewport), `None` for the
/// whole target.
pub fn viewport(&self) -> Option<super::ViewportRect> {
self.viewport_state.settings.viewport
}
/// Back to drawing over the whole target.
pub fn reset_viewport(&mut self) {
self.viewport_state.settings.viewport = None;
}
/// three.js `setScissor`. Same coordinates as
/// [`set_viewport`](Self::set_viewport); only takes effect while
/// [`set_scissor_test`](Self::set_scissor_test) is on. With the test on and
/// no rectangle set, the scissor is the whole target.
pub fn set_scissor(&mut self, x: f32, y: f32, width: f32, height: f32) {
self.viewport_state.settings.scissor = Some(super::ViewportRect::new(x, y, width, height));
}
pub fn scissor(&self) -> Option<super::ViewportRect> {
self.viewport_state.settings.scissor
}
/// Forget the scissor rectangle: with the test on, scissor the whole target.
pub fn reset_scissor(&mut self) {
self.viewport_state.settings.scissor = None;
}
/// three.js `setScissorTest`. While on, the colour clear and every draw are
/// confined to the scissor rectangle — which is what lets several renders
/// share one target without each clearing the others away.
pub fn set_scissor_test(&mut self, enabled: bool) {
self.viewport_state.settings.scissor_test = enabled;
}
pub fn scissor_test(&self) -> bool {
self.viewport_state.settings.scissor_test
}
/// three.js `setPixelRatio`, for the viewport and scissor only: their
/// rectangles are multiplied by this to get device pixels. It does not
/// resize anything — [`resize`](Self::resize) still takes device pixels.
/// [`HeadlessRenderer`](super::HeadlessRenderer) sets it to its supersample
/// factor, so rectangles stay in output pixels.
pub fn set_pixel_ratio(&mut self, ratio: f32) {
self.viewport_state.settings.set_pixel_ratio(ratio);
}
pub fn pixel_ratio(&self) -> f32 {
self.viewport_state.settings.pixel_ratio()
}
/// The drawing buffer in logical pixels — device size over
/// [`pixel_ratio`](Self::pixel_ratio). three.js `getSize`.
pub fn size(&self) -> (f32, f32) {
let pr = self.viewport_state.settings.pixel_ratio();
(self.depth_size.0 as f32 / pr, self.depth_size.1 as f32 / pr)
}
/// The drawing buffer in device pixels. three.js `getDrawingBufferSize`.
pub fn drawing_buffer_size(&self) -> (u32, u32) {
self.depth_size
}
/// three.js `autoClear`. On (the default), each render clears colour to the
/// scene background — the scissor rectangle when the scissor test is on,
/// the whole target otherwise. Off, colour is kept and the scene draws over
/// it. Depth is cleared either way.
pub fn set_auto_clear(&mut self, enabled: bool) {
self.viewport_state.settings.auto_clear = enabled;
}
pub fn auto_clear(&self) -> bool {
self.viewport_state.settings.auto_clear
}
/// three.js `renderer.clear()` for colour: fill `target_view` with `color`
/// — the scissor rectangle when the scissor test is on, the whole target
/// otherwise. `target_view` is taken to be drawing-buffer sized, as for
/// [`render`](Self::render); `linear_framebuffer` means the same as there.
pub fn clear(
&mut self,
target_view: &wgpu::TextureView,
linear_framebuffer: bool,
color: crate::math::Color,
alpha: f32,
) {
let size = self.depth_size;
let format = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
self.clear_inner(target_view, size, format, color, alpha);
}
/// [`clear`](Self::clear) into an offscreen [`RenderTarget`](super::RenderTarget).
pub fn clear_render_target(
&mut self,
target: &super::RenderTarget,
color: crate::math::Color,
alpha: f32,
) {
self.clear_inner(
&target.color_view,
(target.width, target.height),
target.format,
color,
alpha,
);
}
fn clear_inner(
&mut self,
view: &wgpu::TextureView,
(w, h): (u32, u32),
format: wgpu::TextureFormat,
color: crate::math::Color,
alpha: f32,
) {
use super::viewport::ClearMode;
let Some(mode) = self.viewport_state.settings.clear_mode(w, h) else {
return;
};
let value = super::clear_value(format, color, alpha);
if let ClearMode::Rect(_) = mode {
self.viewport_state
.ensure_clear_pipeline(&self.device, format, None);
}
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers clear"),
});
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers clear"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: if mode == ClearMode::Full {
wgpu::LoadOp::Clear(value)
} else {
wgpu::LoadOp::Load
},
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
if let ClearMode::Rect(r) = mode {
self.viewport_state.fill_rect(&mut pass, format, false, r, value);
}
}
self.queue.submit(Some(encoder.finish()));
}
/// Enable/disable hardware MSAA on the **direct-to-surface** forward pass.
/// `samples <= 1` turns it off; anything else selects `MSAA_SAMPLES` (4×).
/// Render-to-texture, shadows, and scenes using glass/OIT/refraction stay
/// single-sampled (they transparently fall back).
pub fn set_msaa(&mut self, samples: u32) {
let s = if samples > 1 { MSAA_SAMPLES } else { 1 };
if s != self.msaa {
self.msaa = s;
self.msaa_targets = None;
self.msaa_targets_spare = None;
}
}
pub fn msaa(&self) -> u32 {
self.msaa
}
/// `(passes, caster draws)`: how many shadow-map passes have been drawn
/// and how many casters drawn into them, since the renderer was made. A
/// pass whose light and casters have not changed is skipped, and a caster
/// outside a pass's light frustum is not drawn into it — this says how
/// much that saved.
pub fn shadow_stats(&self) -> (u64, u64) {
self.shadow_stats
}
/// How shadow maps are filtered — three.js's `renderer.shadowMap.type`.
/// A light's `ShadowSettings::filter` overrides it for that light.
pub fn set_shadow_type(&mut self, kind: crate::lights::ShadowType) {
self.shadow_type = kind;
}
pub fn shadow_type(&self) -> crate::lights::ShadowType {
self.shadow_type
}
/// Take WebGL2's path to a single-sampled depth under MSAA — the opaque
/// scene's depth redrawn, rather than the multisampled one resolved —
/// on any device. For testing that path where it is not the default.
#[doc(hidden)]
pub fn force_depth_replay(&mut self, on: bool) {
self.force_depth_replay = on;
}
/// Whether the last render was multisampled. MSAA asked for
/// ([`set_msaa`](Self::set_msaa)) is not always MSAA delivered: a frame
/// drawn into a float target, or with a live depth to read back
/// ([`render_to`](Self::render_to) draws a render target that way), or
/// holding draws that have no multisampled pipeline (custom shaders,
/// instanced and skinned meshes) is single-sampled. Refraction glass is
/// multisampled on every backend, WebGL2 included.
pub fn last_frame_multisampled(&self) -> bool {
self.last_frame_msaa
}
/// Set the tone-mapping curve and exposure multiplier.
///
/// Off by default so existing scenes render byte-identically. Turn it on
/// whenever the scene carries an HDR environment, otherwise everything
/// above 1.0 clips flat:
///
/// ```no_run
/// # use threers::renderer::ToneMapping;
/// # fn f(renderer: &mut threers::Renderer) {
/// renderer.set_tone_mapping(ToneMapping::AcesFilmic, 1.0);
/// # }
/// ```
pub fn set_tone_mapping(&mut self, mode: ToneMapping, exposure: f32) {
self.tone_mapping = mode;
self.exposure = exposure;
}
pub fn tone_mapping(&self) -> (ToneMapping, f32) {
(self.tone_mapping, self.exposure)
}
/// What the view's depth buffer is cleared to: the far plane.
fn depth_clear(&self) -> f32 {
if self.state_pipelines.reversed() {
0.0
} else {
1.0
}
}
/// Reversed depth: the view's depth runs 1 at the near plane to 0 at
/// the far one, cleared to 0, nearer passing `Greater`.
///
/// Standard `f32` depth crowds its precision against the near plane, so
/// with a near plane of a metre the depth buffer cannot tell apart
/// surfaces tens of metres apart a hundred kilometres away — a planet
/// seen at an angle z-fights across whole mountains. Reversed, the
/// float's own spacing cancels the projection's and precision is nearly
/// even with distance.
///
/// Off by default. Shadow maps stay standard. Everything that reads the
/// view's depth back — post effects through `apply_postfx`, glass and
/// screen-space reflection, TAA — converts it, so they see what they did
/// before; [`Ssao`](super::ssao::Ssao), which takes the depth texture
/// itself, needs [`Ssao::set_reversed_depth`](super::ssao::Ssao::set_reversed_depth).
/// [`depth_texture`](Self::depth_texture) holds reversed values: `1 - d`
/// is the standard depth.
pub fn set_reversed_z(&mut self, on: bool) {
self.state_pipelines.set_reversed(on);
}
pub fn reversed_z(&self) -> bool {
self.state_pipelines.reversed()
}
/// Geometric specular antialiasing on Standard and Physical materials
/// (off by default).
///
/// Off, roughness gains three.js r165's `geometryRoughness` — the largest
/// screen-space change in the surface normal — as three.js renders it. On,
/// it gains the variance of the *shading* normal across the pixel instead
/// (Kaplanyan et al. 2016, as Filament does it), which also absorbs a
/// normal map's variance: crinkled foil or a fine normal map stops
/// sparkling and crawling under motion, and highlights no longer match
/// three.js's.
pub fn set_specular_antialiasing(&mut self, on: bool) {
self.specular_antialiasing = on;
}
pub fn specular_antialiasing(&self) -> bool {
self.specular_antialiasing
}
/// Ensure the multisampled color+depth targets exist at `w×h` for the MSAA pass.
/// The `Unorm` scratch target and the copy pipelines for the encoded-blend
/// pass on a device without view-format reinterpretation (WebGL2).
fn ensure_encoded_scratch(&mut self, w: u32, h: u32) {
let unorm = self.color_format.remove_srgb_suffix();
if !matches!(self.encoded_scratch, Some((cw, ch, _)) if cw == w && ch == h) {
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers encoded blend scratch"),
size: wgpu::Extent3d {
width: w.max(1),
height: h.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
self.encoded_scratch = Some((w, h, tex.create_view(&Default::default())));
}
if self.encoded_copy.is_some() {
return;
}
// `textureLoad` of the sRGB target decodes; `fs_in` encodes again, so
// the `Unorm` scratch holds the target's bytes. `fs_out` reads the
// scratch's bytes raw and decodes them, and the sRGB target encodes
// on write: the bytes come back as they are. Both directions are
// exact for 8-bit values.
const COPY: &str = r#"
@group(0) @binding(0) var src : texture_2d<f32>;
@vertex
fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
}
@fragment
fn fs_in(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
let v = textureLoad(src, vec2<i32>(p.xy), 0);
let c = clamp(v.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
let e = select(pow(c, vec3<f32>(1.0 / 2.4)) * 1.055 - vec3<f32>(0.055), c * 12.92, c <= vec3<f32>(0.0031308));
return vec4<f32>(e, v.a);
}
@fragment
fn fs_out(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
let v = textureLoad(src, vec2<i32>(p.xy), 0);
let d = select(pow((v.rgb + 0.055) / 1.055, vec3<f32>(2.4)), v.rgb / 12.92, v.rgb <= vec3<f32>(0.04045));
return vec4<f32>(d, v.a);
}
"#;
let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers encoded blend copy"),
source: wgpu::ShaderSource::Wgsl(COPY.into()),
});
let bgl = self.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers encoded blend copy bgl"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}],
});
let layout = self.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers encoded blend copy layout"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipe = |entry: &str, format: wgpu::TextureFormat| {
self.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers encoded blend copy"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some(entry),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let copy_in = pipe("fs_in", unorm);
let copy_out = pipe("fs_out", self.color_format);
self.encoded_copy = Some((bgl, copy_in, copy_out));
}
/// One fullscreen copy for the encoded-blend scratch (see
/// [`ensure_encoded_scratch`](Self::ensure_encoded_scratch)).
fn encoded_copy_pass(
&self,
encoder: &mut wgpu::CommandEncoder,
out: bool,
src: &wgpu::TextureView,
dst: &wgpu::TextureView,
) {
let Some((bgl, copy_in, copy_out)) = &self.encoded_copy else {
return;
};
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers encoded blend copy bg"),
layout: bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(src),
}],
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers encoded blend copy pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: dst,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(if out { copy_out } else { copy_in });
pass.set_bind_group(0, &bg, &[]);
pass.draw(0..3, 0..1);
}
fn ensure_msaa_targets(&mut self, w: u32, h: u32) {
if !take_sized(&mut self.msaa_targets, &mut self.msaa_targets_spare, w, h) {
return;
}
// The colour also viewable as its `Unorm` twin when it is sRGB, for
// the encoded-blend pass.
let unorm = self.color_format.remove_srgb_suffix();
let reinterpret = unorm != self.color_format
&& super::caps::supports_view_formats(&self.device);
let extra = [unorm];
// The depth also sampled where the refraction pass resolves it.
let sampled_depth = self.depth_resolve.is_some();
let mk = |label, format, view_formats: &[wgpu::TextureFormat]| {
let sampled = sampled_depth && format == DEPTH_FORMAT;
self.device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: self.msaa,
dimension: wgpu::TextureDimension::D2,
format,
usage: if sampled {
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING
} else {
wgpu::TextureUsages::RENDER_ATTACHMENT
},
view_formats,
})
};
// wgpu keeps a texture alive as long as one of its views exists, so we can
// store only the views.
let color = mk(
"threers msaa color",
self.color_format,
if reinterpret { &extra } else { &[] },
);
let cv = color.create_view(&Default::default());
self.msaa_color_unorm = reinterpret.then(|| {
color.create_view(&wgpu::TextureViewDescriptor {
format: Some(unorm),
..Default::default()
})
});
let dv = mk("threers msaa depth", DEPTH_FORMAT, &[]).create_view(&Default::default());
self.msaa_targets = Some((w, h, cv, dv));
}
/// Apply a post-fx pass from a registered render-target id (wasm path).
///
/// Same as [`Self::apply_postfx`] but resolves `input_rt_id` internally so
/// the caller does not hold a borrow against `&mut self`. When `additive`
/// is true, output is blended onto existing framebuffer pixels.
///
/// `kind` selects the WGSL branch in [`super::shader::POSTFX_SHADER`].
/// `time` carries effect-specific data (e.g. glitch RNG seed). `params2` /
/// `params3` are four-vectors whose meaning depends on `kind`.
///
/// Every kind keeps the picture the right way up, into a render target
/// (`output_rt_id != 0`) and onto the canvas (`0`) alike, so passes chain
/// in any number without compensating flips.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx_by_id(
&mut self,
input_rt_id: u32,
output_rt_id: u32,
output_view: &wgpu::TextureView,
depth_rt_id: u32,
normal_rt_id: u32,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
additive: bool,
camera: PostFxCamera,
) {
let output_format = if output_rt_id != 0 {
self.rt_registry
.get(&output_rt_id)
.map(|rt| rt.format)
.unwrap_or(self.color_format)
} else {
self.color_format
};
let input_view = if let Some(v) = self.rt_view_cache.remove(&input_rt_id) {
v
} else if let Some(rt) = self.rt_registry.get(&input_rt_id) {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx input fallback"),
format: Some(rt_sample_format(rt.format)),
..Default::default()
})
} else {
return;
};
let depth_owned = if depth_rt_id != 0 && depth_rt_id != input_rt_id {
self.rt_view_cache.remove(&depth_rt_id).or_else(|| {
self.rt_registry.get(&depth_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx depth fallback"),
format: Some(rt_sample_format(rt.format)),
..Default::default()
})
})
})
} else {
None
};
let normal_owned = if normal_rt_id != 0 {
self.rt_view_cache.remove(&normal_rt_id)
} else {
None
};
let depth_ref = depth_owned.as_ref().unwrap_or(&input_view);
let input_is_f16 = self
.rt_registry
.get(&input_rt_id)
.map(|rt| rt.format == wgpu::TextureFormat::Rgba16Float)
.unwrap_or(false);
// Kind 0 copies stored RT texels 1:1. Default: linear (non-sRGB-decode)
// view so textureLoad returns the gamma-encoded bytes the main shader
// wrote (matches direct-to-canvas). params2.y > 0.5 selects the legacy
// sRGB-decode view for OutlinePass scene copy (three.js darkens there).
let kind0_legacy = kind == 0 && params2[1] > 0.5;
let output_is_f16 = output_format == wgpu::TextureFormat::Rgba16Float;
let kind0_byte_copy = kind == 0 && !kind0_legacy && !input_is_f16 && !output_is_f16;
let use_linear_input = if kind == 0 {
input_is_f16 && !kind0_legacy
} else {
(matches!(kind, 13 | 15) && !kind0_legacy)
|| input_is_f16
|| matches!(kind, 16 | 18 | 19)
};
let use_linear_depth = matches!(kind, 11 | 12 | 14);
let input_linear = if use_linear_input {
self.rt_registry.get(&input_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear input"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let input_raw = if kind0_byte_copy {
self.rt_registry.get(&input_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx raw input"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let depth_linear = if use_linear_depth && depth_rt_id != 0 {
self.rt_registry.get(&depth_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear depth"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let normal_linear = if use_linear_depth {
self.rt_registry.get(&normal_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear normal"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let input_bind = input_raw
.as_ref()
.or(input_linear.as_ref())
.unwrap_or(&input_view);
let depth_bind = depth_linear.as_ref().unwrap_or(depth_ref);
let mut params2 = params2;
if kind0_byte_copy {
params2[2] = 1.0;
}
// SSAO (11) and bokeh (26) read the hardware depth of the prepass
// target, which the caller names as both depth and normal.
let use_hw_depth =
matches!(kind, 11 | 26) && depth_rt_id != 0 && depth_rt_id == normal_rt_id;
let hw_depth_local = if use_hw_depth {
self.rt_depth_view_cache.remove(&normal_rt_id)
} else {
None
};
let hw_depth_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx hw depth fallback"),
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
let hw_depth_bind = hw_depth_local.as_ref().unwrap_or(&hw_depth_fallback);
// A "raw" view above is the target's own format: without view formats
// (WebGL2) an sRGB target cannot be viewed as anything else, so the
// view decodes and the shader has to re-encode what it reads.
let srgb_rt = |id: u32| {
self.rt_registry
.get(&id)
.is_some_and(|rt| rt.format.is_srgb())
};
let mut raw_srgb = 0u32;
if (input_raw.is_some() || input_linear.is_some()) && srgb_rt(input_rt_id) {
raw_srgb |= 2;
}
if depth_linear.is_some() && srgb_rt(depth_rt_id) {
raw_srgb |= 4;
}
if normal_linear.is_some() && srgb_rt(normal_rt_id) {
raw_srgb |= 8;
}
match normal_owned {
Some(n) => {
let normal_bind = normal_linear.as_ref().unwrap_or(&n);
self.apply_postfx_views(
input_bind,
output_view,
depth_bind,
normal_bind,
hw_depth_bind,
kind,
time,
params2,
params3,
width,
height,
additive,
camera,
use_hw_depth,
output_format,
raw_srgb,
);
self.rt_view_cache.insert(normal_rt_id, n);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
}
None => {
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let normal_bind = normal_linear.as_ref().unwrap_or(&fallback_normal);
self.apply_postfx_views(
input_bind,
output_view,
depth_bind,
normal_bind,
hw_depth_bind,
kind,
time,
params2,
params3,
width,
height,
additive,
camera,
use_hw_depth,
output_format,
raw_srgb,
);
}
}
if let Some(v) = hw_depth_local {
self.rt_depth_view_cache.insert(normal_rt_id, v);
}
self.rt_view_cache.insert(input_rt_id, input_view);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
if let Some(d) = depth_owned {
self.rt_view_cache.insert(depth_rt_id, d);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
}
}
/// Apply a post-fx pass: read from `input_view`, write to `output_view`.
/// Defaults to REPLACE blend / clear on load. Use `apply_postfx_ex` for
/// additive blend (bloom composite) or load-preserve behavior.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx(
&mut self,
input_view: &wgpu::TextureView,
output_view: &wgpu::TextureView,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
) {
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let hw_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.apply_postfx_ex(
input_view,
output_view,
input_view,
&fallback_normal,
&hw_fallback,
kind,
time,
params2,
params3,
width,
height,
false,
PostFxCamera::default(),
false,
self.color_format,
);
}
/// Extended post-fx pass with `additive` blend toggle.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx_ex(
&mut self,
input_view: &wgpu::TextureView,
output_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
normal_view: &wgpu::TextureView,
hw_depth_view: &wgpu::TextureView,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
additive: bool,
camera: PostFxCamera,
use_hw_depth: bool,
output_format: wgpu::TextureFormat,
) {
self.apply_postfx_views(
input_view,
output_view,
depth_view,
normal_view,
hw_depth_view,
kind,
time,
params2,
params3,
width,
height,
additive,
camera,
use_hw_depth,
output_format,
0,
);
}
/// [`Self::apply_postfx_ex`], told which bound views were meant to show
/// the stored bytes but decode them: `raw_srgb` holds `POSTFX_SHADER`'s
/// `postfx_flag` bits 2 (input), 4 (depth) and 8 (normal). Bit 1 — the
/// output is an sRGB format — is worked out here from `output_format`.
///
/// Each branch of the shader is written for a plain `Unorm` target: what
/// it returns is the byte stored. An sRGB target encodes on write, so
/// without bit 1 every computed pass was encoded once more on WebGL2 —
/// where every 8-bit target and the canvas are sRGB — than on WebGPU.
#[allow(clippy::too_many_arguments)]
fn apply_postfx_views(
&mut self,
input_view: &wgpu::TextureView,
output_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
normal_view: &wgpu::TextureView,
hw_depth_view: &wgpu::TextureView,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
additive: bool,
camera: PostFxCamera,
use_hw_depth: bool,
output_format: wgpu::TextureFormat,
raw_srgb: u32,
) {
let linear_output = output_format == wgpu::TextureFormat::Rgba16Float;
// Bit 16: the hardware depth is reversed (`set_reversed_z`), and
// `sample_postfx_depth` hands back `1 - d`.
let srgb_bits = raw_srgb
| u32::from(output_format.is_srgb())
| if self.state_pipelines.reversed() { 16 } else { 0 };
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct PostFxUniforms {
params: [f32; 4],
params2: [f32; 4],
params3: [f32; 4],
resolution: [f32; 4],
ssao0: [f32; 4],
inv_proj: [f32; 16],
proj: [f32; 16],
}
let uniforms = PostFxUniforms {
params: [
kind as f32,
time,
if matches!(kind, 5 | 31) {
params3[3]
} else {
0.0
},
if use_hw_depth { 1.0 } else { 0.0 },
],
params2,
params3,
resolution: [
width as f32,
height as f32,
if linear_output { 1.0 } else { 0.0 },
srgb_bits as f32,
],
ssao0: [
camera.near,
camera.far,
camera.kernel_radius,
camera.kernel_size as f32,
],
inv_proj: camera.inv_proj,
proj: camera.proj,
};
let buffer = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers postfx uniforms"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsages::UNIFORM,
},
);
let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers postfx bg"),
layout: &self.postfx_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(input_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.postfx_sampler),
},
wgpu::BindGroupEntry {
binding: 2,
resource: buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(depth_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(
if matches!(kind, 5 | 31) {
&self.postfx_sampler
} else {
&self.postfx_nearest_sampler
},
),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(normal_view),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(hw_depth_view),
},
wgpu::BindGroupEntry {
binding: 7,
resource: self.ssao_kernel_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(if kind == 5 || kind == 31 {
&self.glitch_disp_view
} else {
&self.ssao_noise_view
}),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::Sampler(&self.postfx_noise_sampler),
},
],
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers postfx encoder"),
});
{
let multiply = kind == 15;
let load_op = if additive || multiply {
wgpu::LoadOp::Load
} else {
wgpu::LoadOp::Clear(wgpu::Color::BLACK)
};
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers postfx pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: output_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: load_op,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
let output_is_f16 = output_format == wgpu::TextureFormat::Rgba16Float;
let pipe = if multiply {
&self.pipeline_postfx_multiply
} else if additive {
if kind == 17 {
&self.pipeline_postfx_outline_add
} else if output_is_f16 {
&self.pipeline_postfx_add_f16
} else {
&self.pipeline_postfx_add
}
} else if output_is_f16 {
&self.pipeline_postfx_f16
} else {
&self.pipeline_postfx
};
pass.set_pipeline(pipe);
pass.set_bind_group(0, &bind_group, &[]);
pass.draw(0..3, 0..1);
}
self.queue.submit(std::iter::once(encoder.finish()));
}
/// Upload SSAO hemisphere kernel samples (32 vec3 values, padded to vec4).
pub fn set_ssao_kernel(&mut self, kernel: &[f32]) {
let mut data = [0f32; 128];
for i in 0..32 {
let base = i * 3;
if base + 2 < kernel.len() {
data[i * 4] = kernel[base];
data[i * 4 + 1] = kernel[base + 1];
data[i * 4 + 2] = kernel[base + 2];
}
}
self.queue
.write_buffer(&self.ssao_kernel_buffer, 0, bytemuck::cast_slice(&data));
}
/// Blit tightly-packed RGBA8 bytes (row-major, top-first) to an output view.
pub fn blit_rgba8(
&mut self,
data: &[u8],
width: u32,
height: u32,
output_view: &wgpu::TextureView,
output_format: wgpu::TextureFormat,
) {
let w = width.max(1);
let h = height.max(1);
let need = (w * h * 4) as usize;
if data.len() < need {
return;
}
// RGBA8 bytes from a canvas or an image are sRGB-encoded and are to
// reach the screen as they came. They are uploaded as plain `Unorm`,
// so the copy reads the bytes themselves; onto an sRGB target the
// post-fx pass decodes its output (`postfx_flag` bit 1) and the
// target's encode gives the same bytes back.
let upload_format = wgpu::TextureFormat::Rgba8Unorm;
if self.rgba_upload_tex.width() != w
|| self.rgba_upload_tex.height() != h
|| self.rgba_upload_tex.format() != upload_format
{
self.rgba_upload_tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers rgba upload"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: upload_format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.rgba_upload_view = self
.rgba_upload_tex
.create_view(&wgpu::TextureViewDescriptor::default());
}
const ALIGN: u32 = 256;
let unpadded = w * 4;
let padded = unpadded.div_ceil(ALIGN) * ALIGN;
let mut upload = vec![0u8; (padded * h) as usize];
for row in 0..h {
let src = (row * w * 4) as usize;
let dst = (row * padded) as usize;
upload[dst..dst + (w * 4) as usize].copy_from_slice(&data[src..src + (w * 4) as usize]);
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.rgba_upload_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&upload,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(h),
},
wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
);
let upload_view = self
.rgba_upload_tex
.create_view(&wgpu::TextureViewDescriptor::default());
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let hw_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.apply_postfx_ex(
&upload_view,
output_view,
&upload_view,
&fallback_normal,
&hw_fallback,
0,
0.0,
// A raw texel copy (`params2.z`): the bytes are already what the
// screen should show, so no gamma is applied on the way out.
[1.0, 0.0, 1.0, 0.0],
[0.0; 4],
w,
h,
false,
PostFxCamera::default(),
false,
output_format,
);
}
/// Drop every cached GPU mesh, freeing their buffers.
///
/// The cache is keyed by the address of the geometry's `Arc`, which is
/// stable only while that `Arc` is alive. Code that feeds the renderer a
/// *fresh* geometry every frame — a CAD model re-evaluated per frame, say —
/// must call this between frames: without it the cache grows without bound,
/// and an allocator that reuses a freed address could serve the old mesh
/// for the new geometry.
///
/// Scenes that keep their geometry alive (the usual case) never need this.
pub fn clear_geometry_cache(&mut self) {
self.geom_cache.clear();
self.skin_attr_cache.clear();
self.morph_cache.clear();
self.wire_span_cache.clear();
}
/// How many GPU meshes are currently cached.
pub fn cached_geometry_count(&self) -> usize {
self.geom_cache.len()
}
/// Drop every cached GPU texture.
///
/// The texture cache has exactly the same shape, and the same hazard, as
/// the geometry one: it is keyed by the address of the `Texture`'s `Arc`,
/// so code that builds fresh textures every frame must clear it or risk an
/// allocator handing a new texture the address of a freed one and getting
/// the previous upload back.
/// Upload a texture now, without drawing anything with it.
///
/// Textures normally upload lazily, on the first draw that binds them. That
/// is the wrong moment when the pixels are large and numerous: each has to
/// be held in system memory until something draws it, so the peak is the
/// sum of all of them. Preloading one at a time and swapping in
/// [`Texture::handle`] keeps the peak at one.
///
/// ```no_run
/// # use threers::{HeadlessRenderer, Texture, TextureFormat};
/// # use std::sync::Arc;
/// # let mut hr = HeadlessRenderer::builder().size(64, 64).build().unwrap();
/// # let load = |_: &str| Texture::new(1, 1, TextureFormat::Rgba8Unorm, vec![0; 4]);
/// let full = Arc::new(load("tile.tex"));
/// hr.renderer().preload_texture(&full);
/// let light = Arc::new(full.handle()); // same id, no pixels
/// drop(full); // system memory released
/// ```
pub fn preload_texture(&mut self, tex: &std::sync::Arc<crate::textures::Texture>) {
self.ensure_slot_uploaded(&Some(tex.clone()));
}
pub fn clear_texture_cache(&mut self) {
self.tex_cache.clear();
self.cube_cache.clear();
}
/// How many GPU textures are currently cached.
pub fn cached_texture_count(&self) -> usize {
self.tex_cache.len()
}
/// Blend a straight-alpha RGBA8 overlay over an already-rendered target.
///
/// Unlike [`blit_rgba8`](Self::blit_rgba8), which replaces the target, this
/// loads the existing contents and composites `data` on top — the 3D image
/// stays visible wherever the overlay is transparent. `data` must be
/// `width * height * 4` bytes, row-major from the top-left.
///
/// Draw it after [`render`](Self::render) and before presenting the frame.
pub fn draw_overlay_rgba8(
&mut self,
data: &[u8],
width: u32,
height: u32,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
self.composite_overlay(data, width, height, None, target, format);
}
/// Blend an [`Overlay`](crate::overlay::Overlay) over an already-rendered
/// target, uploading only the rows that changed.
///
/// Prefer this to [`draw_overlay_rgba8`](Self::draw_overlay_rgba8) when the
/// pixels come from an `Overlay`. A full-frame upload is most of what
/// compositing one costs — at 1920x1080 the upload alone measures 728 µs
/// against ~124 µs for the quad and the submit together — and a read-out in
/// the corner changes 95 rows out of 1080. Measured over a frame that
/// clears the overlay, draws a two-line panel and composites it:
/// **1.1 ms against 223 µs, 4.9x**.
///
/// Taking the `Overlay` rather than its bytes is what makes that safe. The
/// band to upload and the acknowledgement that it happened are two halves
/// of one step, and a caller doing them by hand could skip a composite and
/// leave the texture holding a frame nobody remembers.
///
/// Draw it after [`render`](Self::render) and before presenting. Use one
/// `Overlay` per `Renderer`: the dirty band describes what *this*
/// renderer's texture is missing.
pub fn draw_overlay(
&mut self,
overlay: &mut crate::overlay::Overlay,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
let (width, height) = overlay.size();
// An empty band uploads nothing and still composites, which is what a
// frame wants when the overlay has not changed: the image underneath it
// is new even when the overlay is not.
let rows = overlay.dirty_rows().unwrap_or((0, 0));
self.composite_overlay(overlay.pixels(), width, height, Some(rows), target, format);
overlay.mark_uploaded();
}
fn composite_overlay(
&mut self,
data: &[u8],
width: u32,
height: u32,
rows: Option<(u32, u32)>,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
let pass = self
.overlay_pass
.get_or_insert_with(|| super::caption_pass::CaptionPass::new(&self.device));
pass.draw(
&self.device,
&self.queue,
data,
width,
height,
rows,
target,
format,
);
}
/// Draw the caption showing at `time` seconds over an already-rendered target.
///
/// Sizes the overlay to `target_width × target_height`, rasterizes the
/// active cue only when it changes, and blends it in. Cheap enough to call
/// every frame — a frame with no cue change costs one texture upload, and a
/// frame with no cue at all costs nothing.
///
/// ```no_run
/// # use threers::{Renderer, Scene, PerspectiveCamera, captions::{CaptionOverlay, CaptionTrack}};
/// # fn demo(renderer: &mut Renderer, scene: &mut Scene, camera: &PerspectiveCamera,
/// # view: &wgpu::TextureView, format: wgpu::TextureFormat, time: f64) {
/// let mut overlay = CaptionOverlay::new(CaptionTrack::new().cue(0.0, 3.0, "Hello"))
/// .auto_scale(true);
/// renderer.render(scene, camera, view, false);
/// renderer.draw_caption_overlay(&mut overlay, time, 1280, 720, view, format);
/// # }
/// ```
#[cfg(feature = "captions")]
pub fn draw_caption_overlay(
&mut self,
overlay: &mut crate::captions::CaptionOverlay,
time: f64,
target_width: u32,
target_height: u32,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
overlay.set_size(target_width, target_height);
overlay.update(time);
if !overlay.is_visible() {
return;
}
let (w, h) = overlay.size();
// Borrow the buffer out of the overlay for the upload; the pass only
// reads it, but the borrow checker needs the copy-free split.
let pass = self
.caption_pass
.get_or_insert_with(|| super::caption_pass::CaptionPass::new(&self.device));
pass.draw(
&self.device,
&self.queue,
overlay.rgba(),
w,
h,
None,
target,
format,
);
}
/// Upload GlitchPass's `size × size` displacement heightmap (R32Float, read
/// nearest, as three.js's `DataTexture` defaults to).
pub fn set_glitch_disp(&mut self, data: &[f32], size: u32) {
let sz = size.max(1);
if data.len() < (sz * sz) as usize {
return;
}
if self.glitch_disp_tex.width() != sz {
self.glitch_disp_tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glitch disp"),
size: wgpu::Extent3d {
width: sz,
height: sz,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.glitch_disp_view = self
.glitch_disp_tex
.create_view(&wgpu::TextureViewDescriptor::default());
}
let data = &data[..(sz * sz) as usize];
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.glitch_disp_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(data),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(sz * 4),
rows_per_image: Some(sz),
},
wgpu::Extent3d {
width: sz,
height: sz,
depth_or_array_layers: 1,
},
);
}
/// Upload 4×4 SSAO rotation noise (R channel, repeat-wrapped).
pub fn set_ssao_noise(&mut self, noise: &[f32]) {
let mut texels = [0f32; 16];
for (dst, src) in texels.iter_mut().zip(noise.iter()) {
*dst = *src;
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.ssao_noise_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&texels),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16),
rows_per_image: Some(4),
},
wgpu::Extent3d {
width: 4,
height: 4,
depth_or_array_layers: 1,
},
);
}
/// Render `scene` from `camera` into one face of a cube render target.
/// Used by `CubeCamera.update()` which calls this 6 times per frame.
/// Reallocate the directional shadow map if a caster asks for a different
/// size. Powers of two only, and bounded: this is a render target, and a
/// caller who types 65536 should get the largest sane map rather than an
/// allocation failure three frames later.
/// Size the shadow arrays for this frame's casters: a layer per
/// directional and spot light, six per point light, at the size the
/// directional lights ask for (`ShadowSettings::map_size`, the largest)
/// and [`SPOT_SHADOW_SIZE`] for spots, shrunk when several share a kind
/// ([`shadow_layer_size`]). Reallocated only to grow or resize.
fn ensure_shadow_arrays(&mut self, dir_size: u32, n_dir: usize, n_spot: usize, n_point: usize) {
let mut changed = false;
let mut fit = |array: &mut ShadowArray, label: &str, size: u32, layers: u32| {
if array.size != size || array.layers < layers {
*array = ShadowArray::new(&self.device, label, size, layers);
changed = true;
}
};
if n_dir > 0 {
fit(&mut self.dir_shadows, "threers shadow depth", shadow_layer_size(dir_size, n_dir), n_dir as u32);
}
if n_spot > 0 {
fit(&mut self.spot_shadows, "threers spot shadow depth", shadow_layer_size(SPOT_SHADOW_SIZE, n_spot), n_spot as u32);
}
if n_point > 0 {
fit(&mut self.point_shadows, "threers point shadow depth", POINT_SHADOW_SIZE, 6 * n_point as u32);
}
if changed {
// The environment bind group holds the old views. Invalidating the
// cache key is what makes the next frame rebuild it; without this
// the shader would keep sampling a texture nothing renders into
// any more.
self.env_cached_key = None;
self.env_cached_rt_id = None;
self.env_dirty = true;
}
}
/// Room for `n` shadow passes' uniforms (`ShadowPassGpu`), one aligned
/// slot each, and the group 0 the shadow pipelines read them through at
/// a dynamic offset — beside the frame uniforms, which the passes' vertex
/// stages may read too.
///
/// One buffer for every pass, written once a frame, rather than a copy
/// of the whole frame uniforms per pass: the passes are all encoded
/// before anything runs and `queue.write_buffer` lands before any
/// submitted command, so each pass needs its own slot either way.
fn ensure_shadow_pass_buffer(&mut self, n: usize) {
let need = self.shadow_pass_stride * n.max(1) as u64;
if self.shadow_pass_buffer.as_ref().is_some_and(|(b, _)| b.size() >= need) {
return;
}
let size = need.max(self.shadow_pass_stride * 8);
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers shadow pass uniforms"),
size,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers shadow pass bg"),
layout: &self.shadow_pass_bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: self.frame_buffer.as_entire_binding() },
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &buffer,
offset: 0,
size: wgpu::BufferSize::new(std::mem::size_of::<ShadowPassGpu>() as u64),
}),
},
],
});
self.shadow_pass_buffer = Some((buffer, bg));
}
pub fn render_to_cube_face(
&mut self,
scene: &mut crate::scene::Scene,
camera: &dyn Camera,
target: &super::CubeRenderTarget,
face: usize,
) {
// Tell the frame passes they are drawing a probe, not the picture.
let was_cube = std::mem::replace(&mut self.cube_pass, true);
let (orig_w, orig_h) = self.depth_size;
let orig_depth = std::mem::replace(
&mut self.depth_view,
target
.depth_texture
.create_view(&wgpu::TextureViewDescriptor::default()),
);
self.depth_size = (target.side, target.side);
let face_view = &target.face_views[face % 6];
self.render(scene, camera, face_view, false);
self.depth_view = orig_depth;
self.depth_size = (orig_w, orig_h);
self.cube_pass = was_cube;
}
/// Render `scene` from `camera` into an offscreen [`RenderTarget`](crate::RenderTarget). Uses
/// the target's own depth buffer (required even when RT size matches the canvas).
pub fn render_to(
&mut self,
scene: &mut crate::scene::Scene,
camera: &dyn Camera,
target: &super::RenderTarget,
) {
let (orig_w, orig_h) = self.depth_size;
let orig_depth = std::mem::replace(&mut self.depth_view, target.depth_view_clone());
self.depth_size = (target.width, target.height);
let linear_fb = target.format == wgpu::TextureFormat::Rgba16Float;
let tone_map = std::mem::replace(&mut self.tone_map_pass, target.presents());
// Resolving needs the multisampled colour in the target's format, and
// the renderer's multisampled targets are in its own.
if target.samples() > 1 && target.format == self.color_format {
// three.js `samples`: drawn multisampled at the target's size,
// colour resolved into it and depth resolved (or, on WebGL2,
// redrawn) into its depth, which the glass and post-processing
// read as they would a single-sampled target's. The renderer's own
// MSAA setting is the canvas's and is left as it was.
let msaa = std::mem::replace(&mut self.msaa, MSAA_SAMPLES);
self.msaa_depth_out = Some(target.depth_texture.clone());
self.render_inner(
scene,
camera,
&target.color_view,
linear_fb,
None,
Some((&target.depth_texture, &target.color_texture)),
);
self.msaa_depth_out = None;
self.msaa = msaa;
} else {
// The target owns the live depth this pass — pass it as the copy
// source for the screen-space glass ray march.
self.render_inner(
scene,
camera,
&target.color_view,
linear_fb,
Some(&target.depth_texture),
Some((&target.depth_texture, &target.color_texture)),
);
}
self.tone_map_pass = tone_map;
self.depth_view = orig_depth;
self.depth_size = (orig_w, orig_h);
}
/// Draw into a [`RenderTarget`](super::RenderTarget) the surface-style way —
/// the path MSAA needs — while still handing the temporal pass the textures
/// it reads.
///
/// [`render`](Self::render) passes `None` for both, which silently turns TAA
/// off: it is gated on having a colour source, and that path has none to
/// give. Multisampling and temporal accumulation are complementary — one
/// resolves coverage, the other resolves shading — and a caller that asked
/// for both got only the first, with nothing said about it. Measured on a
/// phone's side rail, thirty-two accumulated samples took the banding from
/// 0.99 to 0.28 with MSAA off, and did exactly nothing with MSAA on.
///
/// The depth handed over is the target's, which the multisampled path does
/// not write. That is why this is separate from [`render_to`](Self::render_to)
/// rather than folded into it: the temporal pass binds depth but only reads
/// it when reprojecting, which [`set_taa_converge`](Self::set_taa_converge)
/// does not do, and the screen-space glass march — the other consumer of a
/// live depth — is deliberately not given it here.
pub fn render_to_multisampled(
&mut self,
scene: &mut crate::scene::Scene,
camera: &dyn Camera,
target: &super::RenderTarget,
linear_framebuffer: bool,
) {
let tone_map = std::mem::replace(&mut self.tone_map_pass, target.presents());
self.last_frame_msaa = false;
self.render_inner(
scene,
camera,
&target.color_view,
linear_framebuffer,
None,
Some((&target.depth_texture, &target.color_texture)),
);
self.tone_map_pass = tone_map;
// Antialiasing was asked for and the frame could not multisample
// (`Oit` or `Refract` glass in view): FXAA it rather than hand back
// hard edges. Temporal AA, when on, has already done the job.
if self.msaa > 1 && !self.last_frame_msaa && !self.taa_enabled {
self.fxaa_fallback(target);
}
}
/// FXAA over `target`, read from a copy of it.
///
/// On the stored bytes, as three.js runs FXAA over its 8-bit canvas: an
/// sRGB copy decodes as it is read, so the pass is told (`raw_srgb` bit 2)
/// and re-encodes, and the sRGB target encodes the result back to the
/// same bytes. A flat area comes back byte for byte.
fn fxaa_fallback(&mut self, target: &super::RenderTarget) {
let tex = &target.color_texture;
let (w, h, format) = (tex.width(), tex.height(), tex.format());
if format == wgpu::TextureFormat::Rgba16Float {
// A linear target is a stage on the way somewhere else; whatever
// presents it can antialias the result.
return;
}
let stale = self
.fxaa_scratch
.as_ref()
.is_none_or(|(t, _)| t.width() != w || t.height() != h || t.format() != format);
if stale {
let t = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers fxaa fallback source"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let v = t.create_view(&wgpu::TextureViewDescriptor::default());
self.fxaa_scratch = Some((t, v));
}
let (scratch, view) = self.fxaa_scratch.as_ref().unwrap();
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers fxaa fallback copy"),
});
encoder.copy_texture_to_texture(
tex.as_image_copy(),
scratch.as_image_copy(),
wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
);
self.queue.submit(Some(encoder.finish()));
let view = view.clone();
let normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let hw_depth = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
let raw_input = if format.is_srgb() { 2 } else { 0 };
self.apply_postfx_views(
&view,
&target.color_view,
&view,
&normal,
&hw_depth,
1,
0.0,
[1.0 / w as f32, 1.0 / h as f32, 0.0, 0.0],
[0.0; 4],
w,
h,
false,
PostFxCamera::default(),
false,
format,
raw_input,
);
}
/// Draw `scene` from `camera` into `target_view`.
/// `linear_framebuffer`: when true, skip sRGB encode (HalfFloat / postfx RT).
pub fn render(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
target_view: &wgpu::TextureView,
linear_framebuffer: bool,
) {
self.render_inner(scene, camera, target_view, linear_framebuffer, None, None);
}
/// Body of [`render`]. `depth_src` is the depth texture backing the current
/// depth attachment (the external target's, via `render_to`) — the copy
/// source for the screen-space glass `ss_depth`; `None` uses the renderer's
/// own depth (the direct-`render`/surface path).
fn render_inner(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
target_view: &wgpu::TextureView,
linear_framebuffer: bool,
depth_src: Option<&wgpu::Texture>,
// `(depth, colour)` for the temporal pass. Separate from `depth_src`,
// which is the *live* depth for the screen-space glass march — the
// multisampled path has one and not the other.
taa_src: Option<(&wgpu::Texture, &wgpu::Texture)>,
) {
scene.update_world();
if self.capturing_transmission.is_none() && !self.cube_pass {
self.capture_transmission(scene, camera);
}
// Viewport / scissor for this render. A cube face is always the whole
// face. `None` means the viewport or scissor misses the target and
// there is nothing to draw.
let vp_plan = if self.cube_pass {
super::viewport::ViewportPlan::full(self.depth_size.0, self.depth_size.1)
} else {
match self.viewport_state.settings.plan(self.depth_size.0, self.depth_size.1) {
Some(p) => p,
None => return,
}
};
// Whether the shader writes linear light and lets something else encode
// it. Two different reasons to: the target stores linear (a float
// framebuffer, which is what `linear_framebuffer` says), or the target's
// format is sRGB and the hardware encodes on write.
//
// This is *not* the same question as `linear_framebuffer`, which every
// other use of that flag below is really asking — "is this a float
// target, so pick the f16 pipeline". Conflating the two is what made an
// sRGB target double-encode. Picking the format off `self.color_format`
// rather than the target view is sound because every non-float target
// the renderer draws into is the one its pipelines were built against.
let shader_outputs_linear =
linear_framebuffer || !super::shader_applies_transfer(self.color_format);
// TAA active only when we have a sampleable color+depth target.
// NOT during a probe. A cube face is 48 pixels and is not the picture:
// running temporal AA over it reprojects the frame's history through
// the probe's camera and writes the result back, so the next real frame
// blends against six tiny views of the scene. On screen that reads as
// the whole vehicle going half transparent — which is what it looked
// like, and why the cause was not obvious from the symptom.
let taa_active =
self.taa_enabled && !self.cube_pass && taa_src.is_some() && vp_plan.legacy;
let view_m = camera.view_matrix();
let mut proj_m = camera.projection_matrix();
if let Some(fix) = &vp_plan.projection_fix {
proj_m = fix.multiply(&proj_m);
}
// Un-jittered view-projection is kept for TAA reprojection.
let unjittered = proj_m.multiply(&view_m);
if taa_active || self.jitter_override.is_some() {
// Sub-pixel Halton jitter, half a pixel either way.
//
// Deliberately a box over the pixel and not a weighted
// reconstruction: a pixel *is* a box, so weighting the samples by
// a tent and widening the jitter to match was tried and measures
// worse — the synthetic edge went from 0.0216 px of deviation to
// 0.0318, because spreading the same samples over four times the
// area undersamples it faster than the filter narrows it.
let (ox, oy) = self.jitter_override.unwrap_or((
halton(self.taa_frame + 1, 2) - 0.5,
halton(self.taa_frame + 1, 3) - 0.5,
));
// Per viewport pixel — the whole target unless a viewport is set.
let jx = ox * 2.0 / vp_plan.viewport.width as f32;
let jy = oy * 2.0 / vp_plan.viewport.height as f32;
// Which element carries the offset depends on the projection, and
// getting it wrong is not subtle. A perspective matrix divides by
// `-z`, so a shift in the *z* column arrives in NDC as a constant:
// `x_clip += jx·z` over `w = -z` is `-jx` at every depth. An
// orthographic matrix does not divide — `w` is 1 — so that same
// shift lands as `jx·z`, which is a shear that grows with distance
// from the camera, not a sub-pixel offset. With the camera ten
// units back it spread a hard edge over nine pixels. Orthographic
// wants the translation column, where the offset is already in NDC.
//
// `elements[11]` is `-1` for perspective and `0` for orthographic,
// which is the projection asked about rather than the camera type
// guessed at.
if proj_m.elements[11].abs() > 0.5 {
proj_m.elements[8] += jx;
proj_m.elements[9] += jy;
} else {
// Negated so the jitter means the same direction either way.
proj_m.elements[12] -= jx;
proj_m.elements[13] -= jy;
}
}
// Reversed depth flips only what rasterises: TAA, motion blur and
// culling keep the standard matrices, and every reader of the depth
// buffer converts it back (`1 - d`) before using them.
let reversed = self.state_pipelines.reversed();
if reversed {
proj_m = reverse_depth(&proj_m);
}
let view_proj = proj_m.multiply(&view_m).elements;
let taa_inv_vp = unjittered.invert().elements;
let taa_unjittered_vp = unjittered.elements;
// tone_mapping_exposure[2] is the "IBL on" flag — the PBR shader's
// env-map branch is gated on it. Enable whenever the scene has any
// environment source (CPU cube texture or cube render target).
let has_env = scene.environment.is_some() || scene.environment_cube_rt.is_some();
let (cam_near, cam_far) = camera.near_far();
// Remembered for the post passes. Depth linearisation needs these and
// they are a property of the frame, not of the effect — making every
// caller pass them again is an invitation to pass the wrong ones, and
// the failure is silent: the occlusion or the blur is simply computed
// at the wrong distances and still looks like an effect.
self.last_camera_planes = (cam_near, cam_far);
// The lens, from the projection itself: for a perspective matrix
// `m[5]` is `1 / tan(fov/2)` and `m[0]` is that over the aspect.
let proj = camera.projection_matrix();
let (m0, m5) = (proj.elements[0], proj.elements[5]);
if m5.abs() > 1e-9 && m0.abs() > 1e-9 {
self.last_camera_lens = (1.0 / m5, m5 / m0);
}
let mut frame_u = FrameUniforms {
view: view_m.elements,
projection: proj_m.elements,
view_proj,
// w: 1 with reversed depth — the sky pin and the screen-space
// marches read it.
camera_position: [
camera.position().x,
camera.position().y,
camera.position().z,
if reversed { 1.0 } else { 0.0 },
],
fog_color: [scene.fog.color.r, scene.fog.color.g, scene.fog.color.b, 1.0],
fog_params: [
scene.fog.near,
scene.fog.far,
scene.fog.density,
scene.fog.mode as f32,
],
tone_mapping_exposure: [
if self.tone_map_pass && !self.cube_pass {
self.tone_mapping.shader_mode()
} else {
0.0
},
self.exposure,
if has_env { 1.0 } else { 0.0 },
// 2: linear because the target is sRGB and encodes on write,
// which the shader's data outputs (`framebuffer_data`) undo.
if !shader_outputs_linear {
0.0
} else if !linear_framebuffer && self.color_format.is_srgb() {
2.0
} else {
1.0
},
],
viewport_size: [
self.depth_size.0 as f32,
self.depth_size.1 as f32,
cam_near,
cam_far,
],
..FrameUniforms::default()
};
let mut ambient = [0.0_f32; 3];
let mut n_dir = 0usize;
let mut n_point = 0usize;
let mut n_spot = 0usize;
let mut n_hemi = 0usize;
let mut n_rect = 0usize;
let oit_available = self.pipeline_oit.is_some();
// Every shadow-casting light, by kind: its index in the kind's light
// array, and what its shadow pass needs.
// Every shadow-casting light, in the order its record takes. A light
// names its record in its own `color[3]`.
let mut casters: Vec<Caster> = Vec::new();
#[derive(Clone, Copy, PartialEq, Eq)]
enum Topology {
Triangle,
TriangleAlpha,
TriangleWire,
TriangleNoCull,
Sky,
Line,
/// three.js `Points`: one instance per point, each a quad
/// (`vs_points`).
Point,
/// `Point` with a transparent material: blended and sorted with
/// the other transparent draws.
PointAlpha,
Sprite,
Instanced,
/// `Instanced` with a `wireframe: true` material: line list.
InstancedWire,
/// `Instanced` with a transparent material: alpha-blended, sorted
/// with the other transparent draws, as three.js renders a
/// transparent `InstancedMesh`.
InstancedAlpha,
Skinned,
/// `Skinned` with a `wireframe: true` material: line list.
SkinnedWire,
/// `Skinned` with a transparent material.
SkinnedAlpha,
/// Single-layer glass depth prepass (writes depth, no color).
GlassDepth,
/// The tint half of the glass colour pass, drawn just before
/// `GlassColor`: what is behind times the glass's transmittance.
GlassTint,
/// Single-layer glass color pass (LessEqual, no depth write): the
/// light half, added over the tint.
GlassColor,
/// Weighted-blended OIT surface (drawn into accum+revealage MRT).
Oit,
/// Screen-space refraction glass (drawn in a dedicated pass that
/// samples the captured opaque color + depth).
Refract,
/// Custom-shader material:
/// (fragment-source hash, is-transparent, wants-screen-space).
/// The last flag moves the draw into the screen-space pass, where the
/// captured opaque colour and depth are bound at `@group(3)`.
/// (shader hash, transparent, screen-space, side) — exactly the
/// custom pipeline cache key minus the framebuffer format, so
/// every lookup site can build the key from the topology alone.
Custom(u64, bool, bool, u32),
}
impl Topology {
/// Drawn from the mesh's wire (line-list) index buffer.
fn is_wire(self) -> bool {
matches!(
self,
Topology::TriangleWire | Topology::InstancedWire | Topology::SkinnedWire
)
}
/// Reads per-instance matrices from vertex slot 1.
fn is_instanced(self) -> bool {
matches!(
self,
Topology::Instanced | Topology::InstancedWire | Topology::InstancedAlpha
)
}
/// Binds the combined mesh+skin group and joint attributes.
fn is_skinned(self) -> bool {
matches!(self, Topology::Skinned | Topology::SkinnedWire | Topology::SkinnedAlpha)
}
/// Drawn as faces, so three.js's `side` culls them (`side_cull`).
fn is_faces(self) -> bool {
matches!(
self,
Topology::Triangle
| Topology::TriangleNoCull
| Topology::TriangleAlpha
| Topology::Instanced
| Topology::InstancedAlpha
| Topology::Skinned
| Topology::SkinnedAlpha
)
}
/// One instance per point, a quad each, read from the geometry's
/// own vertex buffer.
fn is_points(self) -> bool {
matches!(self, Topology::Point | Topology::PointAlpha)
}
/// Blends with what is behind it — and so, on an sRGB target,
/// draws in the encoded-blend pass (see `encoded_pass`). Glass
/// included, prepass and all: it sorts with the transparent draws
/// by `renderOrder`, so it has to be drawn in the same pass as
/// them or a glass shell ordered after them still went first.
fn encodes(self) -> bool {
matches!(
self,
Topology::GlassDepth
| Topology::GlassTint
| Topology::GlassColor
| Topology::TriangleAlpha
| Topology::PointAlpha
| Topology::Sprite
| Topology::InstancedAlpha
| Topology::SkinnedAlpha
| Topology::Custom(_, true, false, ..)
)
}
}
#[derive(Clone)]
struct DrawMesh {
key: *const BufferGeometry,
topology: Topology,
/// Z in view space, used to back-to-front sort transparent draws.
view_z: f32,
render_order: i32,
/// False when the camera frustum cannot see this. It still has to
/// be drawn into the shadow maps — a caster behind the camera can
/// throw a shadow across the whole view — so culled draws stay in
/// this list and only the colour passes skip them.
in_frustum: bool,
/// three.js's transmissive material (`Material::transmissive`).
transmissive: bool,
/// Any transmissive physical material: cast with the cut-out shadow
/// pipelines, which drop texels for the light it lets through.
shadow_transmits: bool,
cast_shadow: bool,
refract_capture: bool,
alpha_test: f32,
/// The material's three.js `side` (0 front, 1 back, 2 double): the
/// shadow passes cull by it, as three.js's `shadowSide` does.
side: u32,
/// The `side` the shadow passes use: the material's, even when the
/// colour passes draw a blended DoubleSide mesh as its back and
/// front halves (see the two-pass split before the sort).
shadow_side: u32,
model: [f32; 16],
normal_matrix: [f32; 16],
color: [f32; 4],
emissive: [f32; 4],
specular: [f32; 4],
shininess_or_near: f32,
opacity_or_far: f32,
roughness: f32,
metalness: f32,
ao_intensity: f32,
normal_scale: [f32; 2],
physical: [f32; 4],
physical2: [f32; 4],
physical3: [f32; 4],
physical4: [f32; 4],
physical5: [f32; 4],
displacement: [f32; 4],
uv_transform: [f32; 4],
atmos: [f32; 4],
twilight: [f32; 4],
eclipse: [f32; 4],
scatter: [f32; 4],
aurora: [f32; 4],
shader_flags: u32,
kind: MaterialKind,
slots: MaterialTextureSlots,
/// The material shader variant this draw needs, if its maps do not
/// fit the legacy layout (see `material_maps`).
map_variant: Option<super::material_maps::MapVariant>,
/// `Material::map_uniforms`, a variant's uniform block.
map_uniforms: [[f32; 4]; 6],
/// A Standard/Physical material's own environment
/// (`material_env_groups`), in place of the scene's.
env_group: Option<MaterialEnvKey>,
/// Index into `instance_buffers` for Topology::Instanced.
instance_buf_idx: usize,
/// The instance data's content stamp (`InstanceBuffer::stamp`),
/// for the shadow fingerprint; 0 for a plain mesh.
instance_stamp: u64,
instance_count: u32,
/// Index into `skin_data` for Topology::Skinned.
skin_idx: usize,
/// Index into `shader_data` for Topology::Custom.
shader_idx: usize,
/// The part of the index (vertices, unindexed) this draw covers —
/// a group and/or the draw range, three.js's `renderBufferDirect`
/// clipping. `None` is the whole geometry.
range: Option<(u32, u32)>,
/// Morph uniforms (count 0: no morphing) and the texture to bind.
morph: [f32; 4],
morph_weights: [f32; crate::core::MAX_MORPH_TARGETS],
morph_tex: (usize, u32),
/// three.js `polygonOffset`: (factor bits, units), drawn with a
/// depth-biased pipeline (see `Renderer::biased_pipelines`).
polygon_offset: Option<(u32, i32)>,
/// three.js `depthTest` / `depthWrite` / `depthFunc` /
/// `colorWrite`, applied over whichever pipeline the draw picks
/// (see `pipeline_state`). Always the default for the glass,
/// order-independent and refraction modes, which own theirs.
state: crate::materials::RenderState,
/// `Object3D::clip_plane`, packed for `MeshUniforms`.
clip_plane: [f32; 4],
}
let mut draws: Vec<DrawMesh> = Vec::new();
// The triangle topologies a three.js `polygonOffset` applies to, as
// the code `build_biased_pipeline` builds them from: plain (back-face
// culled), alpha-blended, double-sided.
let biased_topology = |t: Topology| -> Option<u8> {
match t {
Topology::Triangle => Some(0),
Topology::TriangleAlpha => Some(1),
Topology::TriangleNoCull => Some(2),
_ => None,
}
};
// Per-custom-shader-material draw data (parallel to Topology::Custom).
struct ShaderDrawData {
fragment: String,
vertex: Option<String>,
data: [[f32; 4]; 16],
storage: [Vec<f32>; 3],
textures: Vec<std::sync::Arc<wgpu::TextureView>>,
volumes: Vec<std::sync::Arc<wgpu::TextureView>>,
/// Drawn from an `InstancedMesh`: the instanced pipeline layout,
/// with the instance buffer at `instance_buf_idx` in slot 1 and
/// the custom columns at `custom_buf` in slot 2.
instanced: bool,
custom_buf: usize,
/// three.js `alphaToCoverage`.
alpha_to_coverage: bool,
}
let mut shader_data: Vec<ShaderDrawData> = Vec::new();
let mut instance_buffers: Vec<wgpu::Buffer> = Vec::new();
struct SkinData {
bone_buf: wgpu::Buffer,
bg: Option<wgpu::BindGroup>,
/// The bone matrices, hashed, for the shadow fingerprint.
bone_hash: u64,
}
let mut skin_data: Vec<SkinData> = Vec::new();
// Helper: build a DrawMesh from a geometry+material pair under a given topology.
let make_draw = |geom: &std::sync::Arc<BufferGeometry>,
mat: &Material,
obj: &crate::core::Object3D,
topology: Topology|
-> DrawMesh {
let key = geom_cache_key(geom);
let nm3 = Matrix3::normal_matrix(&obj.matrix_world);
// Mirror materials repurpose the normal_matrix slot for the
// projective texture matrix supplied per-frame from JS.
let normal_matrix = match mat {
Material::Mirror(m) => m.texture_matrix,
_ => mat3_to_mat4_array(&nm3),
};
// Promote Triangle to TriangleAlpha / TriangleWire based on material
// flags. Pre-set view_z for later sort.
let world_pos = obj.world_position();
let view_z = view_m.elements[2] * world_pos.x
+ view_m.elements[6] * world_pos.y
+ view_m.elements[10] * world_pos.z
+ view_m.elements[14];
let topology = if topology == Topology::Instanced && mat.wireframe() {
Topology::InstancedWire
} else if topology == Topology::Instanced && mat.transparent() {
Topology::InstancedAlpha
} else if topology == Topology::Skinned && mat.wireframe() {
Topology::SkinnedWire
} else if topology == Topology::Skinned && mat.transparent() {
Topology::SkinnedAlpha
} else if topology == Topology::Triangle {
if matches!(mat, Material::Sky(_)) {
Topology::Sky
} else if mat.wireframe() {
Topology::TriangleWire
} else if mat.transparent() {
Topology::TriangleAlpha
} else if mat.side() != 0 {
Topology::TriangleNoCull
} else {
Topology::Triangle
}
} else {
topology
};
let c = mat.color();
let e = mat.emissive();
// For MeshDistanceMaterial, pack the reference position into the
// specular channel (unused by that path) so the shader can read it.
// For SkyMaterial, pack the sun position into specular.
let s = match mat {
Material::Distance(m) => crate::math::Color::new(
m.reference_position.x,
m.reference_position.y,
m.reference_position.z,
),
Material::Sky(m) => {
crate::math::Color::new(m.sun_position.x, m.sun_position.y, m.sun_position.z)
}
_ => mat.specular(),
};
// For SkyMaterial, pack atmospheric tuning into params.x/y (replacing
// shininess/opacity which it doesn't use).
let (shin_or_near, opacity_or_far) = match mat {
Material::Depth(m) => (m.near, m.far),
Material::Distance(m) => (m.near_distance, m.far_distance),
Material::Sky(m) => (m.turbidity, m.rayleigh),
_ => (mat.shininess(), mat.opacity()),
};
let physical = match mat {
Material::Physical(m) => {
[m.clearcoat, m.clearcoat_roughness, m.ior, m.transmission]
}
Material::Line(m) => [m.dash_scale, m.dash_size, m.gap_size, 0.0],
// The atmosphere shader intersects the view ray with both
// spheres, so it needs their radii rather than a surface
// description.
Material::Atmosphere(m) => {
[m.planet_radius, m.atmosphere_radius, m.intensity, m.falloff]
}
_ => [0.0; 4],
};
let physical2 = match mat {
Material::Physical(m) => [
m.thickness,
m.dispersion,
m.vertex_emissive,
m.anisotropy_rotation,
],
Material::Atmosphere(m) => [
m.sunset_color.r,
m.sunset_color.g,
m.sunset_color.b,
m.airglow,
],
_ => [0.0; 4],
};
let physical3 = match mat {
Material::Physical(m) => [
m.iridescence,
m.iridescence_ior,
m.iridescence_thickness_range[1],
m.sheen,
],
Material::Atmosphere(m) => {
[m.airglow_color.r, m.airglow_color.g, m.airglow_color.b, 0.0]
}
_ => [0.0; 4],
};
let physical4 = match mat {
Material::Physical(m) => [
m.sheen_color.r,
m.sheen_color.g,
m.sheen_color.b,
m.sheen_roughness,
],
_ => [0.0; 4],
};
let physical5 = match mat {
Material::Physical(m) => {
// attenuation_distance defaults to INFINITY. Feeding that to
// the GPU makes the Beer-Lambert coefficient -log(c)/inf,
// which is 0 for c>0 but NaN for a fully-black channel — and
// one NaN poisons the whole fragment. Collapse any
// non-finite/non-positive distance to 0, the shader's
// "absorption disabled" sentinel.
let dist = if m.attenuation_distance.is_finite() && m.attenuation_distance > 0.0
{
m.attenuation_distance
} else {
0.0
};
[
m.attenuation_color.r,
m.attenuation_color.g,
m.attenuation_color.b,
dist,
]
}
_ => [0.0; 4],
};
let displacement = {
let (scale, bias) = mat.displacement();
let night = mat.emissive_night_side();
[scale, bias, night, 0.0]
};
// three.js gives every map its own matrix. The legacy layout
// holds one scale and translation, applied in the vertex stage to
// every map; a material whose maps need more gets a shader variant
// that transforms each map itself (`material_maps::needs_variant`).
let uv_transform = super::material_maps::legacy_uv_transform(&mat.texture_slots());
let atmos = mat.atmosphere_params();
let (eclipse, sun_angle) = mat.eclipse();
let twilight = {
let c = mat.twilight_color();
[c.r, c.g, c.b, sun_angle]
};
let scatter = mat.scatter_params();
let aurora = mat.aurora_params();
let mut shader_flags = match mat {
Material::Line(m) if m.dash_size > 0.0 || m.gap_size > 0.0 => FLAG_DASHED,
Material::Basic(m) if m.shadow_only => FLAG_SHADOW_MAT,
_ => 0,
};
if obj.receive_shadow {
shader_flags |= FLAG_RECEIVE_SHADOW;
}
if !mat.tone_mapped() {
shader_flags |= FLAG_NO_TONE_MAP;
}
let shadow_transmits = matches!(mat, Material::Physical(m)
if m.transmission > 0.0
&& (m.thickness <= 0.0 || m.transparency == crate::materials::TransparencyMode::Glass));
if shadow_transmits {
shader_flags |= FLAG_SHADOW_TRANSMITS;
}
if let Material::Physical(m) = mat {
if m.transmission > 0.0
&& matches!(
m.transparency,
crate::materials::TransparencyMode::Glass | crate::materials::TransparencyMode::Oit
)
{
shader_flags |= FLAG_BLENDED_GLASS;
}
}
DrawMesh {
key,
topology,
view_z,
render_order: obj.render_order,
clip_plane: clip_plane_of(obj),
in_frustum: true,
transmissive: mat.transmissive(),
shadow_transmits,
cast_shadow: obj.cast_shadow,
refract_capture: obj.refract_capture,
alpha_test: mat.alpha_test(),
side: mat.side(),
shadow_side: mat.side(),
model: obj.matrix_world.elements,
normal_matrix,
color: [c.r, c.g, c.b, mat.opacity()],
// emissive.w carries the physical-material anisotropy strength
// (0 = isotropic); the shader stretches the specular lobe along
// the surface tangent by this amount. Non-physical mats leave 0.
emissive: [
e.r,
e.g,
e.b,
match mat {
Material::Physical(m) => m.anisotropy,
_ => 0.0,
},
],
// Phong's specular colour; Physical's `specularColor` and, in
// w, `specularIntensity`.
specular: match mat {
Material::Physical(m) => {
let c = m.specular_color;
[c.r, c.g, c.b, m.specular_intensity]
}
_ => [s.r, s.g, s.b, 0.0],
},
shininess_or_near: shin_or_near,
opacity_or_far,
// For SkyMaterial, repurpose roughness/metalness as
// params.z/w (mieCoefficient/mieDirectionalG).
roughness: match mat {
Material::Sky(m) => m.mie_coefficient,
_ => mat.roughness(),
},
metalness: match mat {
Material::Sky(m) => m.mie_directional_g,
_ => mat.metalness(),
},
ao_intensity: mat.ao_intensity(),
normal_scale: [mat.normal_scale().x, mat.normal_scale().y],
physical,
physical2,
physical3,
physical4,
physical5,
displacement,
uv_transform,
atmos,
twilight,
eclipse,
scatter,
aurora,
shader_flags,
kind: mat.kind(),
slots: mat.texture_slots(),
map_variant: None,
map_uniforms: mat.map_uniforms(),
env_group: mat.pbr_env().map(material_env_key),
instance_buf_idx: usize::MAX,
instance_stamp: 0,
instance_count: 1,
skin_idx: usize::MAX,
shader_idx: usize::MAX,
range: None,
morph: [0.0; 4],
morph_weights: [0.0; crate::core::MAX_MORPH_TARGETS],
morph_tex: (0, 0),
polygon_offset: mat.polygon_offset().map(|o| (o.factor.to_bits(), o.units.round() as i32)),
state: mat.render_state(),
}
};
let cam_layers = camera.layers();
let root = scene.root;
self.instance_frame += 1;
// Meshes not drawn for a while (removed, hidden, culled away) give
// their buffers back. Generous, as a frame of several panes renders
// more than once.
let now = self.instance_frame;
self.instance_cache.retain(|_, c| now - c.frame < 64);
scene.arena.traverse_visible(root, &mut |obj_id, obj| {
if !cam_layers.test(&obj.layers) {
return;
}
match &obj.kind {
ObjectKind::Light(light) => match light {
Light::Ambient(l) => {
ambient[0] += l.color.r * l.intensity;
ambient[1] += l.color.g * l.intensity;
ambient[2] += l.color.b * l.intensity;
}
Light::Directional(l) => {
if n_dir >= MAX_DIR_LIGHTS {
return;
}
// three.js: direction = normalize(target - position); default target (0,0,0).
let pos = obj.world_position();
let dir = {
let d = Vector3::new(-pos.x, -pos.y, -pos.z);
if d.length_sq() > 1e-8 {
d.normalize()
} else {
transform_direction(&obj.matrix_world, l.direction).normalize()
}
};
let c = l.color;
frame_u.dir_lights[n_dir] = DirLightGpu {
direction: [dir.x, dir.y, dir.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
};
if l.cast_shadow && casters.len() < MAX_SHADOW_RECORDS {
casters.push(Caster::Dir { dir, settings: l.shadow });
frame_u.dir_lights[n_dir].color[3] = casters.len() as f32;
}
n_dir += 1;
}
Light::Point(l) => {
if n_point >= MAX_POINT_LIGHTS {
return;
}
let p = obj.world_position();
let c = l.color;
frame_u.point_lights[n_point] = PointLightGpu {
position: [p.x, p.y, p.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
params: [l.distance, l.decay, 0.0, 0.0],
};
if l.cast_shadow {
// three.js `PointLightShadow`: `light.distance ||
// camera.far`.
let radius = if l.distance > 0.0 { l.distance } else { l.shadow.camera_far };
if casters.len() < MAX_SHADOW_RECORDS {
casters.push(Caster::Point { pos: p, radius, settings: l.shadow });
frame_u.point_lights[n_point].color[3] = casters.len() as f32;
}
}
n_point += 1;
}
Light::Spot(l) => {
if n_spot >= MAX_SPOT_LIGHTS {
return;
}
let p = obj.world_position();
let dir = transform_direction(&obj.matrix_world, l.direction).normalize();
let c = l.color;
let cos_outer = l.angle.cos();
let cos_inner = (l.angle * (1.0 - l.penumbra)).cos();
frame_u.spot_lights[n_spot] = SpotLightGpu {
position: [p.x, p.y, p.z, 0.0],
direction: [dir.x, dir.y, dir.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
params: [l.distance, l.decay, cos_outer, cos_inner],
};
if l.cast_shadow && casters.len() < MAX_SHADOW_RECORDS {
casters.push(Caster::Spot { pos: p, dir, angle: l.angle, settings: l.shadow });
frame_u.spot_lights[n_spot].color[3] = casters.len() as f32;
}
n_spot += 1;
}
Light::Hemisphere(l) => {
if n_hemi >= MAX_HEMI_LIGHTS {
return;
}
let up = transform_direction(&obj.matrix_world, Vector3::UP).normalize();
frame_u.hemi_lights[n_hemi] = HemiLightGpu {
sky_color: [
l.sky_color.r * l.intensity,
l.sky_color.g * l.intensity,
l.sky_color.b * l.intensity,
0.0,
],
ground_color: [
l.ground_color.r * l.intensity,
l.ground_color.g * l.intensity,
l.ground_color.b * l.intensity,
0.0,
],
direction: [up.x, up.y, up.z, 0.0],
};
n_hemi += 1;
}
Light::RectArea(l) => {
if n_rect >= MAX_RECT_LIGHTS {
return;
}
// three.js orients a RectAreaLight by its matrixWorld:
// width runs along local +X, height along local +Y, and
// the emitting face looks down local -Z. Store half
// extents so the shader can form corners by ± directly.
// Through the world matrix's rotation alone, as
// three.js's `extractRotation`: a scaled light keeps
// its `width` and `height`.
let pos = obj.world_position();
let unit = |v: Vector3| {
let d = transform_direction(&obj.matrix_world, v);
let len = (d.x * d.x + d.y * d.y + d.z * d.z).sqrt().max(1e-12);
Vector3::new(d.x / len, d.y / len, d.z / len)
};
let (ax, ay) = (unit(Vector3::new(1.0, 0.0, 0.0)), unit(Vector3::new(0.0, 1.0, 0.0)));
let right = Vector3::new(ax.x * l.width * 0.5, ax.y * l.width * 0.5, ax.z * l.width * 0.5);
let up = Vector3::new(ay.x * l.height * 0.5, ay.y * l.height * 0.5, ay.z * l.height * 0.5);
let c = l.color;
frame_u.rect_lights[n_rect] = RectLightGpu {
position: [pos.x, pos.y, pos.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
right: [right.x, right.y, right.z, 0.0],
up: [up.x, up.y, up.z, 0.0],
};
n_rect += 1;
}
},
ObjectKind::Mesh(mesh) => {
self.ensure_geometry(&mesh.geometry);
// Morph targets: the per-draw uniforms and the geometry's
// morph texture, shared by every group of the mesh.
let morph = crate::core::morph_uniforms(&mesh.geometry, &mesh.morph_influences)
.and_then(|u| Some((u, self.ensure_morph(&mesh.geometry)?)));
let full = mesh.geometry.draw_count() as u32;
// One draw per three.js render item: the whole draw range
// with one material, or each group with its own — opaque
// and transparent sorted per group, as three.js's render
// lists are.
for item in mesh.draws() {
let material = item.material;
let range = (item.start != 0 || item.end != full).then_some((item.start, item.end));
if material.wireframe() {
match range {
None => self.ensure_wire_indices(&mesh.geometry),
Some((a, b)) => self.ensure_wire_span(&mesh.geometry, a, b),
}
}
let with_span = |mut d: DrawMesh| -> DrawMesh {
d.range = range;
if let Some(((header, weights), tex)) = morph {
d.morph = header;
d.morph_weights = weights;
d.morph_tex = tex;
}
d
};
let mut d = with_span(make_draw(&mesh.geometry, material, obj, Topology::Triangle));
// Custom-shader material: route to a per-source pipeline and
// stash its user data for the @group(4) bind group.
if let Material::Shader(sm) = &**material {
// Morph targets reach a shader material as three.js's
// `#include <morphtarget_vertex>` does: the default
// vertex stage (`standard_vertex_morphed`) applies
// them, and a custom one calls `morph_position` /
// `morph_normal` / `morph_color` itself. Its group 2
// then carries the geometry's morph texture.
let hash = custom_shader_hash(&sm.fragment, sm.vertex.as_deref())
^ if sm.alpha_to_coverage { COVERAGE_CUSTOM_SALT } else { 0 };
let transparent = sm.transparent || sm.opacity < 1.0;
d.topology = Topology::Custom(
hash,
transparent,
sm.screen_space,
sm.side,
);
d.shader_idx = shader_data.len();
let pad = |s: &Vec<f32>| {
if s.is_empty() {
vec![0.0f32]
} else {
s.clone()
}
};
shader_data.push(ShaderDrawData {
fragment: sm.fragment.clone(),
vertex: sm.vertex.clone(),
data: sm.data_slots(),
storage: [pad(&sm.storage0), pad(&sm.storage1), pad(&sm.storage2)],
textures: sm.textures.clone(),
volumes: sm.volumes.clone(),
instanced: false,
custom_buf: 0,
alpha_to_coverage: sm.alpha_to_coverage,
});
}
// Route transparent PhysicalMaterials to single-layer glass
// (depth prepass + color) or weighted-blended OIT.
if d.topology == Topology::TriangleAlpha {
// Where OIT cannot run (WebGL2 blends every attachment
// alike), its glass draws as `Glass` does — tinted,
// lit and shadowed, one layer deep — rather than not
// at all.
let mode = match material.transparency_mode() {
crate::materials::TransparencyMode::Oit if !oit_available => {
crate::materials::TransparencyMode::Glass
}
m => m,
};
match mode {
crate::materials::TransparencyMode::Glass => {
let mut prepass = with_span(make_draw(
&mesh.geometry,
material,
obj,
Topology::GlassDepth,
));
prepass.state = crate::materials::RenderState::DEFAULT;
draws.push(prepass);
// The tint half, then (as `d`) the light half.
let mut tint = d.clone();
tint.topology = Topology::GlassTint;
tint.state = crate::materials::RenderState::DEFAULT;
tint.cast_shadow = false;
draws.push(tint);
d.topology = Topology::GlassColor;
}
crate::materials::TransparencyMode::Oit => d.topology = Topology::Oit,
crate::materials::TransparencyMode::Refract => {
d.topology = Topology::Refract
}
crate::materials::TransparencyMode::Blend => {}
}
// These modes own their depth state (a prepass, an
// accumulation target); the material's does not apply.
if d.topology != Topology::TriangleAlpha {
d.state = crate::materials::RenderState::DEFAULT;
}
}
draws.push(d);
}
}
ObjectKind::LineSegments(ls) => {
self.ensure_geometry(&ls.geometry);
// three.js applies the draw range to lines too.
let full = ls.geometry.draw_count() as u32;
let Some((start, end)) = ls.geometry.draw_span(None) else {
return;
};
let mut d = make_draw(&ls.geometry, &ls.material, obj, Topology::Line);
d.range = (start != 0 || end != full).then_some((start, end));
draws.push(d);
}
ObjectKind::Points(p) => {
// three.js `Points`: one draw, one instance per point,
// each expanded to a `size`-pixel quad by `vs_points`
// (WebGPU has no point size). `params.x` carries the size
// in device pixels (× the pixel ratio, as three.js's
// `size` uniform), `params.w` whether it attenuates.
self.ensure_geometry(&p.geometry);
let full = p.geometry.draw_count() as u32;
let Some((start, end)) = p.geometry.draw_span(None) else {
return;
};
let topology = if p.material.transparent() {
Topology::PointAlpha
} else {
Topology::Point
};
let mut d = make_draw(&p.geometry, &p.material, obj, topology);
d.range = (start != 0 || end != full).then_some((start, end));
d.shininess_or_near = p.material.point_size() * self.pixel_ratio();
d.metalness = p.material.point_size_attenuation() as u32 as f32;
d.cast_shadow = false;
draws.push(d);
}
ObjectKind::Sprite(sprite) => {
// Inline construction — the sprite quad is built-in, so we
// can't reuse make_draw (which keys off an Arc<BufferGeometry>).
let mat = &*sprite.material;
// three.js `sprite_vert` uniforms, in slots the sprite
// shader has to itself (see `vs_sprite`): the centre as
// an offset from the middle, so that zero — what point
// draws leave there — is three.js's default (0.5, 0.5),
// and the rotation; `params13.x` set means size
// attenuation off.
let (rotation, size_attenuation) = match mat {
Material::Sprite(m) => (m.rotation, m.size_attenuation),
_ => (0.0, true),
};
let sprite_params =
[sprite.center.x - 0.5, sprite.center.y - 0.5, 0.0, rotation];
let nm3 = Matrix3::normal_matrix(&obj.matrix_world);
let c = mat.color();
let sp = obj.world_position();
let svz = view_m.elements[2] * sp.x
+ view_m.elements[6] * sp.y
+ view_m.elements[10] * sp.z
+ view_m.elements[14];
draws.push(DrawMesh {
key: std::ptr::null::<BufferGeometry>(),
topology: Topology::Sprite,
view_z: svz,
render_order: obj.render_order,
clip_plane: clip_plane_of(obj),
in_frustum: true,
transmissive: false,
shadow_transmits: false,
cast_shadow: false,
refract_capture: true,
alpha_test: mat.alpha_test(),
side: mat.side(),
shadow_side: mat.side(),
model: obj.matrix_world.elements,
normal_matrix: mat3_to_mat4_array(&nm3),
color: [c.r, c.g, c.b, mat.opacity()],
emissive: [0.0; 4],
specular: [0.0; 4],
shininess_or_near: 0.0,
opacity_or_far: mat.opacity(),
roughness: 1.0,
metalness: 0.0,
ao_intensity: 1.0,
normal_scale: [1.0, 1.0],
physical: [0.0; 4],
physical2: [0.0; 4],
physical3: [0.0; 4],
physical4: [0.0; 4],
physical5: [0.0; 4],
displacement: sprite_params,
uv_transform: [0.0, 0.0, 1.0, 1.0],
atmos: [0.0; 4],
twilight: [0.0; 4],
eclipse: [0.0; 4],
scatter: [if size_attenuation { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0],
aurora: [0.0; 4],
shader_flags: (if mat.tone_mapped() { 0 } else { FLAG_NO_TONE_MAP })
| if mat.transparent() { 0 } else { FLAG_OPAQUE_OUT },
kind: mat.kind(),
slots: mat.texture_slots(),
map_variant: None,
map_uniforms: mat.map_uniforms(),
env_group: mat.pbr_env().map(material_env_key),
instance_buf_idx: usize::MAX,
instance_stamp: 0,
instance_count: 1,
skin_idx: usize::MAX,
shader_idx: usize::MAX,
range: None,
morph: [0.0; 4],
morph_weights: [0.0; crate::core::MAX_MORPH_TARGETS],
morph_tex: (0, 0),
polygon_offset: None,
state: mat.render_state(),
});
}
ObjectKind::InstancedMesh(im) => {
self.ensure_geometry(&im.geometry);
if im.transforms.is_empty() {
return;
}
// Its draws: the draw range with one material, or every
// group with its own from the material array — each one
// instanced, as three.js's render list holds an
// InstancedMesh with a material array.
let items: Vec<DrawItem<std::sync::Arc<Material>>> = {
let full = im.geometry.draw_count() as u32;
im.draws()
.into_iter()
.map(|i| {
(
i.material.clone(),
(i.start != 0 || i.end != full).then_some((i.start, i.end)),
)
})
.collect()
};
if items.is_empty() {
return;
}
for (material, range) in &items {
if material.wireframe() {
match range {
None => self.ensure_wire_indices(&im.geometry),
Some((a, b)) => self.ensure_wire_span(&im.geometry, *a, *b),
}
}
}
// Morph targets: one row per instance when the mesh has a
// morph texture (`set_morph_at`), else the shared
// influences as for a mesh.
let row_len = im.morph_row_len();
let per_instance = !im.morph_texture.is_empty()
&& im.morph_texture.len() == row_len * im.transforms.len();
let morph = if per_instance {
crate::core::morph_header(&im.geometry).and_then(|mut h| {
h[3] = (h[3] as u32 | 16) as f32;
let tex = self.ensure_instance_morph(
im as *const crate::core::InstancedMesh as usize,
&im.geometry,
&im.morph_texture,
im.transforms.len() as u32,
row_len as u32,
)?;
Some(((h, [0.0; crate::core::MAX_MORPH_TARGETS]), tex))
})
} else {
crate::core::morph_uniforms(&im.geometry, &im.morph_influences)
.and_then(|u| Some((u, self.ensure_morph(&im.geometry)?)))
};
// Twenty floats an instance: the matrix, then the tint.
// Instances past the end of `colors` are white, so a caller
// that never sets one pays four floats and nothing else.
// A mesh with an `instance_version` that has not moved
// keeps last frame's buffer without being read at all.
let version = im.instance_version.map(|v| (v, im.transforms.len()));
let buf = match self.cached_instances(obj_id, 0, version) {
Some(b) => b,
None => {
let mut matrices: Vec<f32> = Vec::with_capacity(im.transforms.len() * 20);
for (i, t) in im.transforms.iter().enumerate() {
matrices.extend_from_slice(&t.elements);
let c = im.colors.get(i).copied().unwrap_or(crate::math::Color::WHITE);
matrices.extend_from_slice(&[c.r, c.g, c.b, 1.0]);
}
self.instance_buffer(obj_id, 0, matrices, version)
}
};
let idx = instance_buffers.len();
instance_buffers.push(buf);
// A `ShaderMaterial` reads the two custom columns too:
// eight floats an instance, zero-padded, in slot 2.
let custom_idx = items
.iter()
.any(|(m, _)| matches!(&**m, Material::Shader(_)))
.then(|| {
let b = match self.cached_instances(obj_id, 1, version) {
Some(b) => b,
None => {
let mut data: Vec<f32> = Vec::with_capacity(im.transforms.len() * 8);
for i in 0..im.transforms.len() {
data.extend_from_slice(&im.custom_row(0, i));
data.extend_from_slice(&im.custom_row(1, i));
}
self.instance_buffer(obj_id, 1, data, version)
}
};
instance_buffers.push(b);
instance_buffers.len() - 1
});
for (material, range) in &items {
let mut d = make_draw(&im.geometry, material, obj, Topology::Instanced);
d.range = *range;
d.instance_buf_idx = idx;
d.instance_stamp =
self.instance_stamp(obj_id, 0) ^ self.instance_stamp(obj_id, 1).rotate_left(32);
d.instance_count = im.transforms.len() as u32;
if let Some(((header, weights), tex)) = morph {
d.morph = header;
d.morph_weights = weights;
d.morph_tex = tex;
}
// Custom-shader material: its own pipeline, on the
// instanced layout — salted so it never shares a cache
// entry with the same material on a plain mesh.
if let (Material::Shader(sm), Some(custom_buf)) = (&**material, custom_idx) {
let hash = custom_shader_hash(&sm.fragment, sm.vertex.as_deref())
^ INSTANCED_CUSTOM_SALT
^ if sm.alpha_to_coverage { COVERAGE_CUSTOM_SALT } else { 0 };
let transparent = sm.transparent || sm.opacity < 1.0;
d.topology = Topology::Custom(hash, transparent, sm.screen_space, sm.side);
d.shader_idx = shader_data.len();
let pad = |s: &Vec<f32>| if s.is_empty() { vec![0.0f32] } else { s.clone() };
shader_data.push(ShaderDrawData {
fragment: sm.fragment.clone(),
vertex: sm.vertex.clone(),
data: sm.data_slots(),
storage: [pad(&sm.storage0), pad(&sm.storage1), pad(&sm.storage2)],
textures: sm.textures.clone(),
volumes: sm.volumes.clone(),
instanced: true,
custom_buf,
alpha_to_coverage: sm.alpha_to_coverage,
});
}
draws.push(d);
}
}
ObjectKind::SkinnedMesh(sm) => {
self.ensure_geometry(&sm.geometry);
let morph = crate::core::morph_uniforms(&sm.geometry, &sm.morph_influences)
.and_then(|u| Some((u, self.ensure_morph(&sm.geometry)?)));
let full = sm.geometry.draw_count() as u32;
let items: Vec<DrawItem<&std::sync::Arc<Material>>> = sm
.draws()
.into_iter()
.map(|i| (i.material, (i.start != 0 || i.end != full).then_some((i.start, i.end))))
.collect();
for &(material, range) in &items {
if material.wireframe() {
match range {
None => self.ensure_wire_indices(&sm.geometry),
Some((a, b)) => self.ensure_wire_span(&sm.geometry, a, b),
}
}
}
let with_span = |mut d: DrawMesh, range: Option<(u32, u32)>| -> DrawMesh {
d.range = range;
if let Some(((header, weights), tex)) = morph {
d.morph = header;
d.morph_weights = weights;
d.morph_tex = tex;
}
d
};
let key = geom_cache_key(&sm.geometry);
// Upload joints+weights to slot-1 vertex buffer (cached per-geometry).
if !self.skin_attr_cache.contains_key(&key) {
let joints = sm.geometry.get_attribute("joint");
let weights = sm.geometry.get_attribute("weight");
let (Some(j), Some(w)) = (joints, weights) else {
// Geometry isn't skin-equipped; draw at rest
// (morphed).
for &(material, range) in &items {
draws.push(with_span(
make_draw(&sm.geometry, material, obj, Topology::Triangle),
range,
));
}
return;
};
let count = j.count();
let mut interleaved: Vec<f32> = Vec::with_capacity(count * 8);
for i in 0..count {
interleaved.extend_from_slice(&j.array[i * 4..i * 4 + 4]);
interleaved.extend_from_slice(&w.array[i * 4..i * 4 + 4]);
}
let buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers skin attrs"),
contents: bytemuck::cast_slice(&interleaved),
usage: wgpu::BufferUsages::VERTEX,
},
);
self.skin_attr_cache.insert(key, buf);
}
// Upload bone matrices (per-frame, per-skinned-mesh).
//
// Always exactly `MAX_BONES` of them, padded with
// identities: the shader's array is fixed because WebGL2
// cannot do a runtime-sized one, and a uniform binding has
// to match the size the layout declares.
const MAX_BONES: usize = 128;
let mut bone_data: Vec<f32> = Vec::with_capacity(MAX_BONES * 16);
for m in sm.skeleton.bone_matrices.iter().take(MAX_BONES) {
bone_data.extend_from_slice(&m.elements);
}
let identity = crate::math::Matrix4::identity();
while bone_data.len() < MAX_BONES * 16 {
bone_data.extend_from_slice(&identity.elements);
}
let bone_buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers bone matrices"),
contents: bytemuck::cast_slice(&bone_data),
usage: wgpu::BufferUsages::UNIFORM,
},
);
// Defer creating the combined mesh+skin bind group until
// after per_mesh is populated below — we need the per-mesh
// uniform buffer at binding 0. One per draw: each group
// has its own mesh uniform, and the bones are shared.
let bone_hash = hash_words(bone_data.iter().map(|v| v.to_bits() as u64));
for &(material, range) in &items {
let idx = skin_data.len();
skin_data.push(SkinData {
bone_buf: bone_buf.clone(),
bg: None,
bone_hash,
});
let mut d = with_span(
make_draw(&sm.geometry, material, obj, Topology::Skinned),
range,
);
d.skin_idx = idx;
draws.push(d);
}
}
ObjectKind::Group => {}
}
});
// Sort: opaque first (stable order), then transparents back-to-front so
// alpha blending composites correctly. Sprites are already alpha-blended
// and we treat them as transparent for ordering purposes.
// Draw order class: opaque(0) → glass depth prepass(1) → glass color(2) →
// ordinary alpha & OIT(3). Glass must run after opaque (so its prepass
// sees opaque depth) and before ordinary alpha (which blends over it).
fn ord_class(t: Topology) -> u8 {
match t {
Topology::GlassDepth => 1,
Topology::GlassTint | Topology::GlassColor => 2,
Topology::TriangleAlpha
| Topology::PointAlpha
| Topology::Sprite
| Topology::Oit
| Topology::Refract
| Topology::InstancedAlpha
| Topology::SkinnedAlpha => 3,
Topology::Custom(_, transparent, ..) if transparent => 3,
_ => 0,
}
}
// three.js renders the transmissive list between the opaque and the
// transparent ones, so it can read the opaque scene behind it.
let class = |d: &DrawMesh| -> u8 {
match ord_class(d.topology) {
0 if d.transmissive => 1,
0 => 0,
c => c + 1,
}
};
// three.js draws a blended DoubleSide mesh twice — its back faces,
// then its front faces (`WebGLRenderer.renderObject`, with the default
// `forceSinglePass: false`) — so a translucent surface's far side always
// lies under its near side. In one unculled pass the triangles blend
// in index order instead, and a closed translucent shell shows its own
// back faces over its front ones as triangle-shaped shards. The sort
// below is stable and the pair shares every key, so it stays adjacent
// and in this order. The back half casts no shadow: the front half's
// record already covers a double-sided caster. Meshes, instanced and
// skinned alike; a custom shader's pipeline is built apart from the cull
// variants and still draws in one pass.
let mut two_pass = Vec::with_capacity(draws.len());
for d in draws.drain(..) {
let blended_faces = matches!(
d.topology,
Topology::TriangleAlpha | Topology::InstancedAlpha | Topology::SkinnedAlpha
);
if blended_faces && d.side == 2 && !d.transmissive {
let mut back = d.clone();
back.side = 1;
back.cast_shadow = false;
let mut front = d;
front.side = 0;
two_pass.push(back);
two_pass.push(front);
} else {
two_pass.push(d);
}
}
draws = two_pass;
// Opaque, then transmissive, then the translucent family (glass
// prepass, glass colour, ordinary alpha). Within the family
// `renderOrder` comes first, as it does in three.js's transparent list,
// and only then the family's own order — so with equal render orders
// every glass prepass still precedes every glass colour pass and both
// precede ordinary alpha, while a glass shell given a higher order is
// drawn after the translucent things inside it, whose colour it then
// blends over instead of hiding them behind its prepass depth.
let tier = |d: &DrawMesh| -> u8 { class(d).min(2) };
draws.sort_by(|a, b| {
tier(a)
.cmp(&tier(b))
.then(a.render_order.cmp(&b.render_order))
.then(class(a).cmp(&class(b)))
.then_with(|| {
// For ordinary transparents we want farther-from-camera first.
// view_z is negative in front of the camera; smaller = farther.
if ord_class(a.topology) == 3 && ord_class(b.topology) == 3 {
a.view_z
.partial_cmp(&b.view_z)
.unwrap_or(std::cmp::Ordering::Equal)
} else {
std::cmp::Ordering::Equal
}
})
});
// --- Frustum culling.
//
// Nothing here used to test whether a draw was on screen: every mesh in
// the scene went through the vertex shader and got rasterised every
// frame, however far outside the view it was. `Frustum` has been in
// `src/math` the whole time, correct for this crate's 0..1 clip depth
// and exposed to wasm, and the renderer simply never called it.
//
// Culled draws stay in `draws`. The shadow passes walk the same list
// and a caster behind the camera can still throw a shadow right across
// the view, so only the colour passes read this flag. The indices also
// key `per_mesh` and the bind-group caches, and removing entries would
// shift all of them.
//
// The jitter-free view-projection is deliberate: culling off the
// jittered matrix would let an object on the boundary flicker in and
// out from frame to frame.
if self.frustum_culling {
let frustum = Frustum::from_projection_matrix(&unjittered);
for d in draws.iter_mut() {
// Only geometry whose object-space bounds really do bound what
// gets rasterised. A skinned mesh moves outside its bind pose,
// an instanced draw covers ground the source geometry does not,
// a custom vertex shader may put the vertices anywhere, and the
// sky is deliberately pinned to the far plane.
let plain = matches!(
d.topology,
Topology::Triangle
| Topology::TriangleAlpha
| Topology::TriangleNoCull
| Topology::TriangleWire
| Topology::Line
| Topology::GlassDepth
| Topology::GlassTint
| Topology::GlassColor
| Topology::Oit
| Topology::Refract
) && d.instance_count == 1
&& d.skin_idx == usize::MAX
&& d.shader_idx == usize::MAX
// A morphed mesh can leave its rest-pose bounds.
&& d.morph[0] == 0.0;
if !plain {
continue;
}
let Some(sphere) = self.geom_cache.get(&d.key).and_then(|g| g.sphere) else {
continue;
};
let world = sphere.apply_matrix4(&Matrix4 { elements: d.model });
d.in_frustum = frustum.intersects_sphere(&world);
}
}
// The transmission capture passes (`capture_transmission`): the first
// draws everything but the transmissive objects, the second only the
// back faces of the double-sided ones, as three.js's
// `renderTransmissionPass` does. Through `in_frustum`, so the shadow
// passes still see every caster.
if let Some(back) = self.capturing_transmission {
for d in draws.iter_mut() {
let keep = if back { d.transmissive && d.side == 2 } else { !d.transmissive };
if !keep {
d.in_frustum = false;
} else if back {
d.side = 1;
}
}
}
self.cull_stats = (
draws.iter().filter(|d| d.in_frustum).count(),
draws.iter().filter(|d| !d.in_frustum).count(),
);
frame_u.ambient = [ambient[0], ambient[1], ambient[2], 0.0];
frame_u.light_counts = [n_dir as u32, n_point as u32, n_spot as u32, n_hemi as u32];
// w: the bound capture's mip count — the stand-in's one while a capture
// pass draws, the capture's after it.
let capture_levels = match (self.capturing_transmission, &self.transmission) {
(Some(false), _) | (None, None) => 1,
(Some(true), Some(c)) | (None, Some(c)) => c.levels,
(Some(true), None) => 1,
};
frame_u.light_counts2 = [
n_rect as u32,
self.specular_antialiasing as u32,
self.reflective_transparency as u32,
capture_levels,
];
// Each shadow-casting light's record — layers, matrices, biases and
// filter — and the passes that draw its maps. A directional light's
// single map fits a fixed cube on the world origin
// (`ShadowSettings::camera_size`), so it depends on lights and
// casters, never on the camera; cascades follow the camera.
//
// The maps are allocated before any light exists to ask for a size,
// so the first frame that names one reallocates. `map_size` used to be
// read and discarded, which is a worse failure than not offering it:
// the caller sets 4096, sees no error, and gets 1024.
let layers_of = |kind: u8| -> usize {
casters
.iter()
.filter(|c| matches!((kind, c), (0, Caster::Dir { .. }) | (1, Caster::Spot { .. }) | (2, Caster::Point { .. })))
.map(Caster::layers)
.sum()
};
let (dir_layers, spot_layers, point_layers) = (layers_of(0), layers_of(1), layers_of(2));
self.ensure_shadow_arrays(
casters
.iter()
.filter_map(|c| match c {
Caster::Dir { settings, .. } => Some(settings.map_size),
_ => None,
})
.max()
.unwrap_or(0),
dir_layers,
spot_layers,
point_layers / 6,
);
let mut shadow_passes: Vec<ShadowPass> = Vec::new();
let mut next_layer = [0usize; 3];
for (r, caster) in casters.iter().enumerate() {
let settings = caster.settings();
let filter = settings.filter.unwrap_or(self.shadow_type).code();
let bias = settings.bias.max(0.0);
let normal_bias = settings.normal_bias.max(0.0);
let mut rec = ShadowRecordGpu::zeroed();
match *caster {
Caster::Dir { dir, settings } => {
let size = self.dir_shadows.size;
let texel = 1.0 / size as f32;
let layer = next_layer[0];
let cascades = caster.layers();
next_layer[0] += cascades;
// The light's size as a penumbra per unit of normalised
// depth, in map uv: an angle times the depth range over
// the map's width. Cascades keep that ratio fixed (see
// `cascade_frusta`), so one number serves them all.
let angle = if settings.light_size > 0.0 { settings.light_size } else { 0.02 };
let (depth_range, width) = if cascades > 1 {
(12.0, 2.0)
} else {
(settings.camera_far - settings.camera_near, 2.0 * settings.camera_size)
};
let scale = angle * depth_range / width.max(1e-6);
rec.info = [0, layer as u32, cascades as u32, filter];
rec.params = [bias, normal_bias, settings.radius.max(0.0) * texel, texel];
rec.pcss = [(scale * 0.25).clamp(2.0 * texel, 0.1), 0.0, 0.0, scale];
if cascades > 1 {
for (c, (vp, far)) in cascade_frusta(&view_m, &camera.projection_matrix(), dir, &settings, size).into_iter().enumerate() {
rec.vp[c] = vp;
rec.extra[c] = far;
shadow_passes.push(ShadowPass { kind: ShadowKind::Dir, layer: (layer + c) as u32, vp, pos: [0.0; 4] });
}
} else {
let s = settings.camera_size;
let light_eye = -dir.normalize() * (s * 1.5);
let light_view = Matrix4::look_at(light_eye, Vector3::ZERO, Vector3::UP);
let light_proj =
Matrix4::orthographic(-s, s, s, -s, settings.camera_near, settings.camera_far);
let vp = light_proj.multiply(&light_view).elements;
rec.vp[0] = vp;
rec.extra = [f32::MAX; 4];
shadow_passes.push(ShadowPass { kind: ShadowKind::Dir, layer: layer as u32, vp, pos: [0.0; 4] });
}
}
Caster::Spot { pos, dir, angle, settings } => {
let texel = 1.0 / self.spot_shadows.size as f32;
let layer = next_layer[1];
next_layer[1] += 1;
let target = pos + dir.normalize();
let light_view = Matrix4::look_at(pos, target, Vector3::UP);
// Perspective frustum: fov = 2 * outer_angle to cover the cone.
let fov = (angle * 2.0).clamp(0.05, std::f32::consts::PI - 0.05);
let light_proj =
Matrix4::perspective(fov, 1.0, settings.camera_near, settings.camera_far);
let vp = light_proj.multiply(&light_view).elements;
// The light's width over the frustum's width at unit
// distance: the penumbra in uv per unit of (receiver −
// blocker) / (blocker · receiver).
let size = if settings.light_size > 0.0 { settings.light_size } else { 0.5 };
let scale = size / (2.0 * (fov * 0.5).tan());
rec.info = [1, layer as u32, 1, filter];
rec.params = [bias, normal_bias, settings.radius.max(0.0) * texel, texel];
rec.pcss = [(scale * 0.05).clamp(2.0 * texel, 0.1), settings.camera_near, settings.camera_far, scale];
rec.vp[0] = vp;
shadow_passes.push(ShadowPass { kind: ShadowKind::Spot, layer: layer as u32, vp, pos: [0.0; 4] });
}
Caster::Point { pos, radius, settings } => {
// The filter disc lies across the direction to the light,
// a face texel (`2 / size` of a unit cube face) per unit
// of radius.
let texel = 2.0 / POINT_SHADOW_SIZE as f32;
let layer = next_layer[2];
next_layer[2] += 6;
let at = [pos.x, pos.y, pos.z, radius];
let size = if settings.light_size > 0.0 { settings.light_size } else { 0.5 };
rec.info = [2, layer as u32, 1, filter];
rec.params = [bias, normal_bias, settings.radius.max(0.0) * texel, texel];
rec.extra = at;
rec.pcss = [(size * 0.05).clamp(2.0 * texel, 0.2), 0.0, 0.0, size];
for face in 0..6 {
shadow_passes.push(ShadowPass {
kind: ShadowKind::Point,
layer: (layer + face) as u32,
vp: point_face_vp(pos, radius, face),
pos: at,
});
}
}
}
frame_u.shadows[r] = rec;
}
frame_u.shadow_info = [casters.len() as u32, 0, 0, 0];
// Sync environment cubemap. Upload on first sight, rebuild bind group on change.
// A cube texture is prefiltered first, as three.js's `WebGLCubeUVMaps`
// does for every Standard/Physical environment.
let scene_env_cube = scene.environment.as_ref().map(|e| self.prefiltered(e));
let env_key = scene_env_cube.as_ref().map(cube_cache_key);
let env_rt_id = scene.environment_cube_rt;
if self.env_dirty || env_key != self.env_cached_key || env_rt_id != self.env_cached_rt_id {
let mut env_map_params = [0.0_f32; 4];
if let Some(env) = &scene_env_cube {
let k = cube_cache_key(env);
if !self.cube_cache.contains_key(&k) {
let gc = GpuCubeTexture::upload(&self.device, &self.queue, env);
self.cube_cache.insert(k, gc);
}
if let Some(atlas) = &env.cube_uv_atlas {
env_map_params = [
atlas.texel_width,
atlas.texel_height,
atlas.lod_max as f32,
1.0,
];
}
}
frame_u.env_map_params = env_map_params;
let cube_uv_view: &wgpu::TextureView = if let Some(env) = &scene_env_cube {
self.cube_cache
.get(&cube_cache_key(env))
.and_then(|gc| gc.cube_uv_view.as_ref())
.unwrap_or(&self.default_cube_uv_view)
} else {
&self.default_cube_uv_view
};
let view: &wgpu::TextureView = if let Some(rt_id) = scene.environment_cube_rt {
self.cube_rt_view_cache
.get(&rt_id)
.unwrap_or(&self.default_env_cube.view)
} else if let Some(env) = &scene_env_cube {
&self.cube_cache[&cube_cache_key(env)].view
} else {
&self.default_env_cube.view
};
// Whatever `view` just became, record how many mips the shader may
// sample from it. A cube render target's view is built with
// `mip_level_count: Some(1)` and the placeholder cube is 1x1, so
// both expose a single level; only an uploaded environment has a
// chain worth walking.
self.env_max_mip = if scene.environment_cube_rt.is_some() {
0.0
} else if let Some(env) = &scene_env_cube {
let levels = self.cube_cache[&cube_cache_key(env)]
.texture
.mip_level_count();
levels.saturating_sub(1) as f32
} else {
0.0
};
self.env_bind_group = env_bind_group!(
self.device,
&self.env_bgl,
"threers env bg",
view,
&self.env_sampler,
&self.dir_shadows.view,
&self.shadow_sampler,
&self.spot_shadows.view,
&self.spot_shadow_sampler,
&self.point_shadows.view,
&self.point_shadow_sampler,
cube_uv_view,
&self.env_uniform,
&self.ltc.1,
);
self.env_dirty = false;
// Theirs share the shadow-map views just rebound.
self.material_env_groups.clear();
self.env_cached_key = env_key;
self.env_cached_rt_id = env_rt_id;
}
// The plain-cube path reads its chain length from here as well, so this
// has to be set on every frame: the bind-group block above only runs
// when the environment changes, and `frame_u` starts from `Default`.
frame_u.env_map_params[2] = self.env_max_mip;
if let Some(env) = &scene_env_cube {
if let Some(atlas) = &env.cube_uv_atlas {
frame_u.env_map_params = [
atlas.texel_width,
atlas.texel_height,
atlas.lod_max as f32,
1.0,
];
}
}
// The scene's environment as group 3 reads it: three.js's
// `scene.environmentIntensity` and `environmentRotation`.
let scene_env = EnvUniforms {
params: frame_u.env_map_params,
info: [has_env as u32 as f32, scene.environment_intensity, 0.0, 0.0],
rot: crate::materials::environment_lookup_rows(
scene.environment_rotation,
scene.environment_cube_rt.is_none()
&& scene_env_cube.as_ref().is_some_and(|e| e.cube_uv_atlas.is_none()),
),
};
self.queue.write_buffer(&self.env_uniform, 0, bytemuck::bytes_of(&scene_env));
// -- Ensure every texture referenced in this frame is uploaded. --
// Every role's map — the list `material_maps` binds from, so a new
// role cannot be bound without being uploaded.
for d in &draws {
for (_, t) in super::material_maps::role_textures(&d.slots) {
self.ensure_slot_uploaded(&t.cloned());
}
// A Standard/Physical material's own `envMap` prefiltered, as the
// scene's is; a Basic/Lambert/Phong one sampled as it is.
let pbr = d.slots.pbr_env_map.as_ref().map(|c| self.prefiltered(c));
for cube in [d.slots.env_map.as_ref(), pbr.as_ref()].into_iter().flatten() {
let k = cube_cache_key(cube);
if !self.cube_cache.contains_key(&k) {
let gc = GpuCubeTexture::upload(&self.device, &self.queue, cube);
self.cube_cache.insert(k, gc);
}
}
}
// Group 3 for each Standard/Physical material's own `envMap`.
for d in &draws {
let (Some(key), Some(source)) = (d.env_group, d.slots.pbr_env_map.as_ref()) else {
continue;
};
if self.material_env_groups.contains_key(&key) {
continue;
}
let cube = &self.prefiltered(source);
let gc = &self.cube_cache[&cube_cache_key(cube)];
let u = EnvUniforms::of(cube, gc, f32::from_bits(key.1), crate::math::Euler {
x: f32::from_bits(key.2[0]),
y: f32::from_bits(key.2[1]),
z: f32::from_bits(key.2[2]),
order: crate::math::EulerOrder::ALL[key.2[3] as usize],
});
let buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers material env uniforms"),
contents: bytemuck::bytes_of(&u),
usage: wgpu::BufferUsages::UNIFORM,
},
);
let bg = env_bind_group!(
self.device,
&self.env_bgl,
"threers material env bg",
&gc.view,
&self.env_sampler,
&self.dir_shadows.view,
&self.shadow_sampler,
&self.spot_shadows.view,
&self.spot_shadow_sampler,
&self.point_shadows.view,
&self.point_shadow_sampler,
gc.cube_uv_view.as_ref().unwrap_or(&self.default_cube_uv_view),
&buf,
&self.ltc.1,
);
self.material_env_groups.insert(key, (buf, bg));
}
// -- Ensure pool capacity: the uniform arena, and a mesh bind group
// over each draw's slice of it. Grown by half again, so a scene
// gaining meshes one at a time does not rebuild it every frame. --
let stride = self.mesh_stride;
let mesh_size = wgpu::BufferSize::new(std::mem::size_of::<MeshUniforms>() as u64);
let capacity = self.mesh_arena.as_ref().map_or(0, |b| (b.size() / stride) as usize);
if capacity < draws.len() {
let capacity = (draws.len() + draws.len() / 2).max(64);
let arena = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers mesh uniforms"),
size: capacity as u64 * stride,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = |i: usize| {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers mesh bg"),
layout: &self.mesh_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &arena,
offset: i as u64 * stride,
size: mesh_size,
}),
}],
})
};
let rebuilt: Vec<wgpu::BindGroup> = (0..capacity).map(bind).collect();
for (i, mesh_bg) in rebuilt.into_iter().enumerate() {
if let Some(entry) = self.per_mesh.get_mut(i) {
entry.0 = i as u64 * stride;
entry.1 = mesh_bg;
} else {
// Texture bind group is rebuilt per-frame per-mesh below,
// but the pool entry needs a placeholder until then.
let tex_bg = std::sync::Arc::new(self.make_default_tex_bg());
self.per_mesh.push((i as u64 * stride, mesh_bg, tex_bg));
}
}
self.mesh_arena = Some(arena);
}
let mut mesh_bytes = std::mem::take(&mut self.mesh_bytes);
mesh_bytes.clear();
mesh_bytes.resize(draws.len() * stride as usize, 0);
// -- Build combined mesh+skin bind groups now that per_mesh is grown. --
for (i, d) in draws.iter().enumerate() {
if d.topology.is_skinned() && d.skin_idx < skin_data.len() {
let sd = &mut skin_data[d.skin_idx];
let arena = self.mesh_arena.as_ref().expect("grown above");
sd.bg = Some(self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers mesh skinned bg"),
layout: &self.mesh_skinned_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: arena,
offset: self.per_mesh[i].0,
size: mesh_size,
}),
},
wgpu::BindGroupEntry {
binding: 1,
resource: sd.bone_buf.as_entire_binding(),
},
],
}));
}
}
// The topologies the multisampled pipelines exist for.
let msaa_drawable = |t: Topology| {
matches!(
t,
Topology::Triangle
| Topology::TriangleAlpha
| Topology::TriangleNoCull
| Topology::Sky
| Topology::TriangleWire
| Topology::Line
| Topology::Point
| Topology::GlassDepth
| Topology::GlassTint
| Topology::GlassColor
| Topology::Skinned
| Topology::Instanced
// An opaque shader material (see `custom_msaa_pipelines`).
| Topology::Custom(_, false, false, _)
)
};
// Multisampling in a pane with a partial clear: the pane is drawn into
// a target of its own, the size of the clear rectangle, and
// composited into this one — see `viewport::PanePlan`. Its viewport is
// relative to that target, so the projection is redone for it here,
// before the frame uniforms go up.
let pane_msaa = vp_plan.pane.filter(|_| {
self.msaa > 1
&& !self.cube_pass
&& depth_src.is_none()
&& !linear_framebuffer
&& self.jitter_override.is_none()
&& draws.iter().all(|d| msaa_drawable(d.topology))
});
if let Some(p) = &pane_msaa {
let mut proj = camera.projection_matrix();
if let Some(fix) = &p.projection_fix {
proj = fix.multiply(&proj);
}
if self.state_pipelines.reversed() {
proj = reverse_depth(&proj);
}
frame_u.projection = proj.elements;
frame_u.view_proj = proj.multiply(&view_m).elements;
}
// Alpha blending as three.js's default renderer does it — on the
// sRGB-encoded bytes of its 8-bit canvas, not in linear light. A plain
// `Unorm` target already works that way (the shader encodes). An sRGB
// one blends in linear in hardware, so its blended mesh draws go in a
// pass of their own, after the rest, through a `Unorm` view of the same
// texture with the shader encoding — the hardware then mixes encoded
// values exactly as WebGL does, while the opaque pass, its multisample
// resolve and everything downstream stay in linear light. Needs the
// target texture (the `render_to` paths hand it over) and view-format
// reinterpretation (not on WebGL2); elsewhere the blend stays linear.
//
// Every blended kind goes there (`Topology::encodes`): meshes,
// sprites, transparent instanced and skinned meshes and transparent
// custom shaders. In a pane drawn through its own multisampled target
// the pass draws into that target's `Unorm` view; in a frame with
// screen-space refraction, into the opaque capture's, which is then
// blitted to the target as before.
let encoded_target: Option<&wgpu::Texture> = taa_src
.map(|(_, c)| c)
.filter(|t| t.format().is_srgb() && t.format() == self.color_format)
.filter(|t| t.sample_count() == 1 && t.mip_level_count() == 1);
//
// Without view reinterpretation (WebGL2) the pass draws into a `Unorm`
// scratch copy of the target instead, copied back after
// (`ensure_encoded_scratch`) — for a single-sampled frame without a
// pane target or screen-space refraction, which is what a WebGL2
// canvas drawn through its back buffer is.
let reinterpret = super::caps::supports_view_formats(&self.device);
let scratch_ok = !reinterpret
&& self.msaa <= 1
&& pane_msaa.is_none()
&& !draws.iter().any(|d| {
d.topology == Topology::Refract
|| matches!(d.topology, Topology::Custom(_, _, true, ..))
})
&& encoded_target.is_some_and(|t| t.usage().contains(wgpu::TextureUsages::TEXTURE_BINDING));
let encoded_pass = encoded_target.is_some()
&& !linear_framebuffer
&& !self.cube_pass
&& self.encoded_blend_pipelines.is_some()
&& (reinterpret || scratch_ok)
&& draws.iter().any(|d| d.topology.encodes());
let encoded_scratch = encoded_pass && !reinterpret;
if let (true, Some(t)) = (encoded_scratch, encoded_target) {
self.ensure_encoded_scratch(t.width(), t.height());
}
// Material shader variants: a draw whose maps the legacy layout cannot
// hold (or whose maps disagree on filtering or transform) gets one,
// built here, before any pass needs its pipelines. Custom shader
// materials compile against the legacy layout and keep it.
for d in draws.iter_mut() {
d.map_variant = (!matches!(d.topology, Topology::Custom(..))
&& super::material_maps::needs_variant(&d.slots))
.then(|| super::material_maps::MapVariant::of(&d.slots));
}
let wanted: std::collections::HashSet<super::material_maps::MapVariant> =
draws.iter().filter_map(|d| d.map_variant).collect();
for v in wanted {
self.ensure_map_variant(v);
}
// -- Upload uniforms + rebuild per-mesh tex bind groups. --
self.queue
.write_buffer(&self.frame_buffer, 0, bytemuck::bytes_of(&frame_u));
for (i, d) in draws.iter().enumerate() {
let mut flags: u32 = 0;
if d.slots.map.is_some() {
flags |= FLAG_MAP;
}
if d.slots.normal_map.is_some() {
flags |= FLAG_NORMAL_MAP;
}
if d.slots.roughness_map.is_some() {
flags |= FLAG_ROUGHNESS_MAP;
}
if d.slots.metalness_map.is_some() {
flags |= FLAG_METALNESS_MAP;
}
if d.slots.ao_map.is_some() {
flags |= FLAG_AO_MAP;
}
if d.slots.emissive_map.is_some() {
flags |= FLAG_EMISSIVE_MAP;
}
if d.slots.matcap_map.is_some() {
flags |= FLAG_MATCAP_MAP;
}
if d.slots.cloud_shadow_map.is_some() && d.atmos[1] > 0.0 {
flags |= FLAG_CLOUD_SHADOW;
}
let u = MeshUniforms {
model: d.model,
normal_matrix: d.normal_matrix,
color: d.color,
emissive: d.emissive,
specular: d.specular,
params: [
d.shininess_or_near,
d.opacity_or_far,
d.roughness,
d.metalness,
],
params2: [
d.ao_intensity,
d.normal_scale[0],
d.normal_scale[1],
0.0,
],
params3: d.physical,
params4: d.physical2,
params5: d.physical3,
params6: d.physical4,
params7: d.physical5,
params8: d.displacement,
// A variant transforms each map's uv itself; its vertex stage
// passes the raw uv through.
params9: if d.map_variant.is_some() { [0.0, 0.0, 1.0, 1.0] } else { d.uv_transform },
params10: d.atmos,
params11: d.twilight,
params12: d.eclipse,
params13: d.scatter,
params14: d.aurora,
flags: [
d.kind as u32,
flags,
d.shader_flags
| if encoded_pass && d.topology.encodes() {
FLAG_ENCODED_OUT
} else {
0
},
d.alpha_test.to_bits(),
],
// `morph.w` bit 32: the geometry has extra uv sets.
morph: {
let mut m = d.morph;
if self.uv_cache.contains_key(&d.key) {
m[3] = (m[3] as u32 | 32) as f32;
}
m
},
morph_weights: bytemuck::cast(d.morph_weights),
clip_plane: d.clip_plane,
};
let o = self.per_mesh[i].0 as usize;
mesh_bytes[o..o + std::mem::size_of::<MeshUniforms>()].copy_from_slice(bytemuck::bytes_of(&u));
}
if let (Some(arena), false) = (&self.mesh_arena, mesh_bytes.is_empty()) {
self.queue.write_buffer(arena, 0, &mesh_bytes);
}
self.mesh_bytes = mesh_bytes;
// Texture bind groups, from the cache. Keys are computed up front so
// the miss path can borrow `self` immutably to build and then mutably
// to insert, one draw at a time.
let tex_keys: Vec<TexBgKey> = draws
.iter()
.map(|d| {
let (maps, _, sampler, _) = tex_bg_key(&d.slots);
(maps, d.morph_tex, sampler, self.uv_key(d.key))
})
.collect();
// The set of distinct texture combinations in a scene is small and
// static; this bound is a runaway guard, not a working limit.
if self.tex_bg_cache.len() > 4096 {
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
}
for (i, d) in draws.iter().enumerate() {
if !self.tex_bg_cache.contains_key(&tex_keys[i]) {
let morph = self
.morph_cache
.get(&(d.morph_tex.0 as *const BufferGeometry))
.filter(|_| d.morph_tex.0 != 0)
.map(|m| &m.view);
let uv = self.uv_cache.get(&d.key).map(|u| &u.view);
let bg = std::sync::Arc::new(self.build_tex_bg(&d.slots, morph, uv));
self.tex_bg_cache.insert(tex_keys[i], bg);
}
}
for (i, k) in tex_keys.iter().enumerate() {
self.per_mesh[i].2 = self.tex_bg_cache[k].clone();
}
// Variant draws: their own group 2.
if self.variant_bg_cache.len() > 4096 {
self.variant_bg_cache.clear();
}
for (i, d) in draws.iter().enumerate() {
let Some(v) = d.map_variant else { continue };
let key = (variant_bg_key(&d.slots, v, d.morph_tex, d.map_uniforms), self.uv_key(d.key));
if !self.variant_bg_cache.contains_key(&key) {
let morph = self
.morph_cache
.get(&(d.morph_tex.0 as *const BufferGeometry))
.filter(|_| d.morph_tex.0 != 0)
.map(|m| &m.view);
let uv = self.uv_cache.get(&d.key).map(|u| &u.view);
let bg = std::sync::Arc::new(self.build_variant_tex_bg(&d.slots, morph, uv, v, d.map_uniforms));
self.variant_bg_cache.insert(key.clone(), bg);
}
self.per_mesh[i].2 = self.variant_bg_cache[&key].clone();
}
// A shader material's group 2 when its geometry is morphed or has
// extra uv sets: the shared custom one with the geometry's morph
// texture and uv sets in place of the empty defaults. (Its `morph.w`
// bit 32 is set whenever the uv sets exist, so the shared group's
// empty texture would be read as zeros.)
let custom_morph_bgs: Vec<Option<wgpu::BindGroup>> = draws
.iter()
.map(|d| {
let uv = self.uv_cache.get(&d.key).map(|u| &u.view);
if !matches!(d.topology, Topology::Custom(..)) || (d.morph_tex.0 == 0 && uv.is_none()) {
return None;
}
let view = if d.morph_tex.0 == 0 {
&self.default_morph.1
} else {
&self.morph_cache.get(&(d.morph_tex.0 as *const BufferGeometry))?.view
};
let uv = uv.unwrap_or(&self.default_uv_sets.1);
Some(self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers custom morph tex bg"),
layout: &self.custom_tex_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(uv),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler(&self.sampler_linear_repeat),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(view),
},
],
}))
})
.collect();
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers encoder"),
});
// Whether this render redraws the shadow maps: always, unless
// `shadow_map.auto_update` is off — then only when asked, or when the
// maps were last drawn for other casters or another size. They
// depend on lights and casters, never on the camera (the directional
// map is a fixed cube on the origin), so a skipped update samples the
// same maps a redraw would have produced.
//
// With `auto_update` on (the default), a render whose casters and
// lights are the same as last time keeps the maps it has: a still
// scene under a moving camera stops redrawing every caster into every
// map each frame.
let mut pass_hashes: Vec<Option<u64>> = Vec::new();
let mut pass_changed: Vec<bool> = Vec::new();
let update_shadows = !shadow_passes.is_empty() && {
let sig: ShadowSig = (dir_layers, spot_layers, point_layers, self.dir_shadows.size, self.spot_shadows.size);
let valid = self.shadow_sig == Some(sig);
let content = {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut mix = |x: u64| h = mix_word(h, x);
let mut known = true;
for d in draws.iter().filter(|d| d.cast_shadow) {
// Skinned: the pose. Instanced: the instance data, through
// its content stamp.
if d.topology.is_skinned() {
mix(skin_data.get(d.skin_idx).map_or(0, |s| s.bone_hash));
}
mix(d.instance_stamp);
mix(d.instance_count as u64);
// A custom shader is a function of its inputs — there is
// no clock in the frame uniforms — so its data, storage and
// source stand for its output. Not its textures: a texture
// can be drawn into without anything here changing.
if let Topology::Custom(..) = d.topology {
match shader_data.get(d.shader_idx) {
Some(sd) if sd.textures.is_empty() && sd.volumes.is_empty() => {
sd.data.iter().flatten().for_each(|v| mix(v.to_bits() as u64));
sd.storage.iter().for_each(|st| {
mix(st.len() as u64);
st.iter().for_each(|v| mix(v.to_bits() as u64));
});
mix(hash_words(sd.fragment.bytes().map(u64::from)));
mix(sd.vertex.as_deref().map_or(0, |v| hash_words(v.bytes().map(u64::from))));
}
_ => {
known = false;
break;
}
}
}
mix(d.key as usize as u64);
mix(self.geom_cache.get(&d.key).map_or(0, |e| e.version) as u64);
d.model.iter().for_each(|v| mix(v.to_bits() as u64));
mix(d.shadow_side as u64);
mix(d.alpha_test.to_bits() as u64);
mix(d.slots.map.as_ref().map_or(0, |t| std::sync::Arc::as_ptr(t) as usize as u64));
mix(d.slots.alpha_map.as_ref().map_or(0, |t| std::sync::Arc::as_ptr(t) as usize as u64));
mix(d.shader_flags as u64);
d.color.iter().chain(&d.physical).chain(&d.morph).for_each(|v| mix(v.to_bits() as u64));
d.morph_weights.iter().for_each(|v| mix(v.to_bits() as u64));
mix(d.range.map_or(u64::MAX, |(a, b)| ((a as u64) << 32) | b as u64));
}
known.then_some(h)
};
// Each pass's own: the casters and its light's matrix. A pass is
// redrawn when its own changed — a cascade following the camera
// does not take a still point light's six faces with it.
pass_hashes = shadow_passes
.iter()
.map(|p| {
content.map(|c| {
let mut h = mix_word(c, p.layer as u64 | ((p.kind as u64) << 32));
for v in p.vp.iter().chain(&p.pos) {
h = mix_word(h, v.to_bits() as u64);
}
h
})
})
.collect();
pass_changed = pass_hashes
.iter()
.enumerate()
.map(|(k, h)| !valid || h.is_none() || self.shadow_pass_hashes.get(k) != Some(h))
.collect();
let unchanged = !pass_changed.iter().any(|&c| c);
self.shadow_sig = Some(sig);
self.shadow_map.take_update(valid, unchanged)
};
// A forced update (`needs_update` with `auto_update` off) redraws
// every pass; an automatic one, the passes that changed.
let draw_pass: Vec<bool> = (0..shadow_passes.len())
.map(|k| update_shadows && (!self.shadow_map.auto_update || pass_changed.get(k).copied().unwrap_or(true)))
.collect();
if update_shadows {
self.shadow_pass_hashes = std::mem::take(&mut pass_hashes);
}
let update_shadows = draw_pass.iter().any(|&d| d);
if update_shadows {
self.shadow_updates += 1;
// Every pass's matrix, at its own aligned offset in one buffer,
// written once.
self.ensure_shadow_pass_buffer(shadow_passes.len());
let stride = self.shadow_pass_stride as usize;
let mut bytes = vec![0u8; stride * shadow_passes.len()];
for (k, p) in shadow_passes.iter().enumerate() {
let g = ShadowPassGpu { vp: p.vp, light: p.pos };
bytes[k * stride..k * stride + std::mem::size_of::<ShadowPassGpu>()]
.copy_from_slice(bytemuck::bytes_of(&g));
}
if let Some((buffer, _)) = &self.shadow_pass_buffer {
self.queue.write_buffer(buffer, 0, &bytes);
}
}
// The shadow depth passes: every caster from each light, one layer
// each (six for a point light). The timer brackets the first pass's
// start and the last one's end.
// Each caster's world bounding sphere, where its geometry's bounds
// really bound what it draws (as the main pass culls): a pass skips
// casters outside its light's frustum.
let caster_spheres: Vec<Option<crate::math::Sphere>> = draws
.iter()
.map(|d| {
let plain = d.cast_shadow
&& matches!(d.topology, Topology::Triangle | Topology::TriangleNoCull | Topology::TriangleAlpha)
&& d.instance_count == 1
&& d.skin_idx == usize::MAX
&& d.shader_idx == usize::MAX
&& d.morph[0] == 0.0;
if !plain {
return None;
}
let sphere = self.geom_cache.get(&d.key).and_then(|g| g.sphere)?;
Some(sphere.apply_matrix4(&Matrix4 { elements: d.model }))
})
.collect();
let drawn: Vec<usize> = (0..shadow_passes.len()).filter(|&k| draw_pass[k]).collect();
self.shadow_stats.0 += drawn.len() as u64;
for (n, &k) in drawn.iter().enumerate() {
let p = &shadow_passes[k];
let pass_frustum = Frustum::from_projection_matrix(&Matrix4 { elements: p.vp });
let view = match p.kind {
ShadowKind::Dir => self.dir_shadows.layer_view(p.layer),
ShadowKind::Spot => self.spot_shadows.layer_view(p.layer),
ShadowKind::Point => self.point_shadows.layer_view(p.layer),
};
let timestamp_writes = self.shadow_timer.as_ref().and_then(|t| match (n == 0, n + 1 == drawn.len()) {
(true, true) => Some(t.mark_both(0, 1)),
(true, false) => Some(t.mark(0)),
(false, true) => Some(t.mark_end(1)),
_ => None,
});
let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(match p.kind {
ShadowKind::Dir => "threers shadow pass",
ShadowKind::Spot => "threers spot shadow pass",
ShadowKind::Point => "threers point shadow face pass",
}),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes,
occlusion_query_set: None,
multiview_mask: None,
});
let Some((_, pass_bg)) = &self.shadow_pass_buffer else { break };
spass.set_bind_group(0, pass_bg, &[(k as u64 * self.shadow_pass_stride) as u32]);
for (i, d) in draws.iter().enumerate() {
// three.js draws only `castShadow` objects into a shadow map.
if !d.cast_shadow {
continue;
}
if caster_spheres[i].as_ref().is_some_and(|s| !pass_frustum.intersects_sphere(s)) {
continue;
}
self.shadow_stats.1 += 1;
let skinned = matches!(d.topology, Topology::Skinned | Topology::SkinnedAlpha);
let instanced = matches!(d.topology, Topology::Instanced | Topology::InstancedAlpha);
// A transparent caster casts too: three.js's shadow map ignores
// blending (only `alphaTest` cuts a shadow).
if d.topology != Topology::Triangle
&& d.topology != Topology::TriangleNoCull
&& d.topology != Topology::TriangleAlpha
&& !skinned
&& !instanced
{
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
let mut instances = 0..1;
// three.js's shadow depth material takes `map` and `alphaTest`;
// the point passes have no cut-out variant.
let cut = p.kind != ShadowKind::Point
&& (d.shadow_transmits
|| (d.alpha_test > 0.0 && (d.slots.map.is_some() || d.slots.alpha_map.is_some())));
let c = &self.shadow_cut;
let base = match (p.kind, skinned, instanced, cut) {
(ShadowKind::Dir, true, _, false) => &self.pipeline_shadow_skinned,
(ShadowKind::Dir, true, _, true) => &c.dir_skinned,
(ShadowKind::Dir, false, true, false) => &self.pipeline_shadow_instanced,
(ShadowKind::Dir, false, true, true) => &c.dir_instanced,
(ShadowKind::Dir, false, false, false) => &self.pipeline_shadow,
(ShadowKind::Dir, false, false, true) => &c.dir,
(ShadowKind::Spot, true, _, false) => &self.pipeline_shadow_spot_skinned,
(ShadowKind::Spot, true, _, true) => &c.spot_skinned,
(ShadowKind::Spot, false, true, false) => &self.pipeline_shadow_spot_instanced,
(ShadowKind::Spot, false, true, true) => &c.spot_instanced,
(ShadowKind::Spot, false, false, false) => &self.pipeline_shadow_spot,
(ShadowKind::Spot, false, false, true) => &c.spot,
(ShadowKind::Point, true, _, _) => &self.pipeline_shadow_point_skinned,
(ShadowKind::Point, false, true, _) => &self.pipeline_shadow_point_instanced,
(ShadowKind::Point, false, false, _) => &self.pipeline_shadow_point,
};
let cull = if p.kind == ShadowKind::Point {
shadow_cull_point(d.shadow_side)
} else {
shadow_cull(d.shadow_side)
};
if skinned {
// The pose, not the bind pose: the skinned pipeline with
// the bones and the joint/weight buffer.
let (Some(bg), Some(attrs)) = (
skin_data.get(d.skin_idx).and_then(|s| s.bg.as_ref()),
self.skin_attr_cache.get(&d.key),
) else {
continue;
};
let base = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, base, d.map_variant);
spass.set_pipeline(&self.state_pipelines.cull_variant(&self.device, &base, cull));
spass.set_bind_group(1, bg, &[]);
spass.set_vertex_buffer(1, attrs.slice(..));
} else {
let base = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, base, d.map_variant);
spass.set_pipeline(&self.state_pipelines.cull_variant(&self.device, &base, cull));
spass.set_bind_group(1, &self.per_mesh[i].1, &[]);
if instanced {
// Every instance, at its matrix and with its morph row.
spass.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
instances = 0..d.instance_count;
}
}
spass.set_bind_group(2, &*self.per_mesh[i].2, &[]);
spass.set_bind_group(3, &self.shadow_env_bind_group, &[]);
spass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
spass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
spass.draw_indexed(draw_span(d.range, gm.index_count), 0, instances);
} else {
spass.draw(draw_span(d.range, gm.vertex_count), instances);
}
}
}
// Screen-space refraction glass: when any Refract surface is present, the
// opaque scene is rendered into the mipped ss-color capture (instead of
// straight to the frame target); the glass pass below then refracts and
// reflects that capture. Otherwise the main pass targets the frame view
// directly, exactly as before.
// A custom shader that asked for the opaque-scene capture needs the same
// machinery the refraction glass does, so it turns it on too.
// SUPPRESSED while rendering an environment cube. The glass path
// copies the frame's depth into a screen-sized scratch texture, and a
// cube face's depth is 48 pixels, not 7680 — wgpu refuses the copy
// outright ("the entire texture must be copied when copying from depth
// texture") and the whole render dies. A reflection probe has no use
// for screen-space refraction anyway: it exists to light other
// surfaces, and what it would refract is not in it.
let wants_screen_space = draws.iter().any(|d| {
d.topology == Topology::Refract
|| matches!(d.topology, Topology::Custom(_, _, true, ..))
});
// Screen-space refraction captures and marches the *whole* frame, so
// it has no per-pane meaning: with a viewport or a partial clear those
// draws are skipped (the main pass already leaves them out) rather
// than drawn against the wrong pixels.
if wants_screen_space
&& !vp_plan.legacy
&& !self.cube_pass
&& !self.viewport_state.warned_screen_space
{
self.viewport_state.warned_screen_space = true;
log::warn!(
"screen-space refraction / screen-space shader materials are not drawn \
with a viewport or scissor set"
);
}
let refract_present = !self.cube_pass && vp_plan.legacy && wants_screen_space;
let ss_format = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
if refract_present {
let (w, h) = self.depth_size;
self.ensure_ss_targets(w, h, ss_format);
}
// Compile any not-yet-seen custom-shader pipelines and build their
// @group(1) user bind groups (buffers kept alive until submit). Hoisted
// above the passes because a screen-space custom material draws in the
// glass pass rather than the opaque one, and both need these.
let mut user_bgs: Vec<Option<wgpu::BindGroup>> = Vec::new();
user_bgs.resize_with(draws.len(), || None);
let mut _custom_keep_alive: Vec<wgpu::Buffer> = Vec::new();
let mut _custom_keep_alive_tex: Vec<wgpu::Texture> = Vec::new();
for (i, d) in draws.iter().enumerate() {
if let Topology::Custom(hash, transparent, screen_space, side) = d.topology {
let sd = &shader_data[d.shader_idx];
let key = (hash, linear_framebuffer, transparent, screen_space, side);
let layout = if screen_space {
self.custom_ss_pipeline_layout.as_ref()
} else {
self.custom_pipeline_layout.as_ref()
};
let Some(custom_layout) = layout else {
// No layout on this device — skip the object rather than
// submit a draw that cannot validate.
continue;
};
if self.custom_failed.contains(&key) {
continue;
}
if !self.custom_pipelines.contains_key(&key) {
let fmt = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
let pipeline = build_custom_pipeline(
&self.device,
custom_layout,
&sd.fragment,
sd.vertex.as_deref(),
fmt,
transparent,
screen_space,
side,
sd.instanced,
1,
sd.alpha_to_coverage,
&mut self.state_pipelines,
);
match pipeline {
Ok(p) => {
self.custom_pipelines.insert(key, p);
}
Err(e) => {
// One material is skipped; the rest of the frame
// draws. Previously this was a panic from inside
// wgpu, which took the program with it.
log::error!("shader material failed to compile:\n{e}");
self.custom_failed.insert(key);
continue;
}
}
}
// The encoded-blend pass's variant, into the `Unorm` view.
let ekey = (hash, transparent, screen_space, side);
if encoded_pass
&& d.topology.encodes()
&& !self.custom_encoded_pipelines.contains_key(&ekey)
{
match build_custom_pipeline(
&self.device,
custom_layout,
&sd.fragment,
sd.vertex.as_deref(),
self.color_format.remove_srgb_suffix(),
transparent,
screen_space,
side,
sd.instanced,
1,
sd.alpha_to_coverage,
&mut self.state_pipelines,
) {
Ok(p) => {
self.custom_encoded_pipelines.insert(ekey, p);
}
Err(e) => log::error!("shader material failed to compile:\n{e}"),
}
}
// The multisampled variant, for a frame drawn under MSAA: an
// opaque material only (the blended passes draw single-sampled).
let mkey = (hash, transparent, screen_space, side);
if self.msaa > 1
&& !transparent
&& !screen_space
&& !linear_framebuffer
&& !self.custom_msaa_pipelines.contains_key(&mkey)
{
match build_custom_pipeline(
&self.device,
custom_layout,
&sd.fragment,
sd.vertex.as_deref(),
self.color_format,
transparent,
screen_space,
side,
sd.instanced,
MSAA_SAMPLES,
sd.alpha_to_coverage,
&mut self.state_pipelines,
) {
Ok(p) => {
self.custom_msaa_pipelines.insert(mkey, p);
}
Err(e) => log::error!("shader material failed to compile:\n{e}"),
}
}
let (bg, bufs, texs) = build_user_bind_group(
&self.device,
&self.queue,
&self.custom_mesh_bgl,
wgpu::BufferBinding {
buffer: self.mesh_arena.as_ref().expect("grown above"),
offset: self.per_mesh[i].0,
size: wgpu::BufferSize::new(std::mem::size_of::<MeshUniforms>() as u64),
},
&sd.data,
&sd.storage,
&sd.textures,
&self.default_white_linear.view,
&self.default_data_tex_view,
&self.sampler_linear_repeat,
&sd.volumes,
&self.default_volume_view,
&self.sampler_volume,
);
_custom_keep_alive.extend(bufs);
_custom_keep_alive_tex.extend(texs);
user_bgs[i] = Some(bg);
}
}
{
let main_format = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
// `scene.background` is linear; the shared rule encodes it only
// where the shader encodes too (a plain `Unorm` target), so a hex
// background lands as that hex — see `super::clear_value`.
let clear =
super::clear_value(main_format, scene.background, scene.background_alpha);
// Hardware MSAA on the direct-to-surface opaque pass. Falls back to
// single-sample for render-to-texture, linear/postfx targets, and any
// scene using glass/OIT/refraction/instanced/skinned/custom draws.
// Not straight into the target when the colour is loaded (a partial
// clear, or none): the resolve rewrites the whole target and would
// erase the other panes. A partial clear goes through a pane-sized
// target instead (`pane_msaa`); with no clear at all there is
// nothing to start the pane target from, so that stays
// single-sampled.
let pane_key = pane_msaa
.as_ref()
.map(|p| (p.region.width, p.region.height, main_format, self.msaa));
// OIT and refraction glass multisample on the whole target (not
// in a pane), with a capture the colour can resolve into.
let oit_msaa = self.pipeline_oit_msaa.is_some() && !linear_framebuffer;
// Under MSAA the glass reads a single-sampled opaque depth: the
// multisampled one resolved where a shader can read it, the
// opaque scene's depth redrawn where it cannot (WebGL2).
let refract_msaa = !linear_framebuffer && ss_format == self.color_format;
let use_msaa = pane_msaa.is_some()
|| (self.msaa > 1
&& vp_plan.clear == super::viewport::ClearMode::Full
&& depth_src.is_none()
&& (!linear_framebuffer || taa_src.is_some())
&& (!refract_present || refract_msaa)
&& draws.iter().all(|d| {
msaa_drawable(d.topology)
|| (d.topology == Topology::Oit && oit_msaa)
|| (d.topology == Topology::Refract && refract_msaa)
}));
// Not over refraction glass: it is drawn single-sampled into the
// frame, and resolving the multisampled colour again would erase it.
self.overlay_msaa = use_msaa && pane_msaa.is_none() && !refract_present;
self.last_frame_msaa = use_msaa;
// three.js `polygonOffset`: the depth-biased pipelines this frame's
// draws need, built once per (topology, target, offset).
let bias_variant: u8 = if use_msaa {
2
} else if linear_framebuffer {
1
} else {
0
};
// The encoded-blend pass's variant: the target's `Unorm` view,
// single- or multisampled.
let enc_variant: u8 = if use_msaa { 4 } else { 3 };
if encoded_pass && use_msaa {
self.ensure_msaa_targets(self.depth_size.0, self.depth_size.1);
}
for d in &draws {
let in_encoded_pass = encoded_pass && d.topology == Topology::TriangleAlpha;
let (factor, units) = match d.polygon_offset {
Some(o) => o,
None if in_encoded_pass => (0f32.to_bits(), 0),
None => continue,
};
let Some(code) = biased_topology(d.topology) else {
continue;
};
let variant = if in_encoded_pass { enc_variant } else { bias_variant };
let key = (code, variant, factor, units);
if !self.biased_pipelines.contains_key(&key) {
let (format, samples) = match variant {
4 => (self.color_format.remove_srgb_suffix(), MSAA_SAMPLES),
3 => (self.color_format.remove_srgb_suffix(), 1),
2 => (self.color_format, MSAA_SAMPLES),
1 => (wgpu::TextureFormat::Rgba16Float, 1),
_ => (self.color_format, 1),
};
let p = build_biased_pipeline(
&self.device,
&self.mesh_shader,
&self.mesh_pipeline_layout,
format,
samples,
code,
f32::from_bits(factor),
units,
&mut self.state_pipelines,
);
self.biased_pipelines.insert(key, p);
}
}
if let Some(key) = pane_key {
self.viewport_state
.ensure_pane_target(&self.device, key, DEPTH_FORMAT);
} else if use_msaa {
self.ensure_msaa_targets(self.depth_size.0, self.depth_size.1);
}
// The pane's own plan when drawing into a pane target.
let main_plan = pane_msaa.as_ref().map(|p| p.local()).unwrap_or(vp_plan);
if let super::viewport::ClearMode::Rect(_) = vp_plan.clear {
self.viewport_state
.ensure_clear_pipeline(&self.device, main_format, Some(DEPTH_FORMAT));
}
// Screen-space glass redirects the opaque pass into the ss-color capture
// (mip 0); MSAA renders into the multisampled color and resolves into the
// frame view; otherwise it targets the frame view directly.
let (main_color_view, msaa_resolve, depth_pass_view): (
&wgpu::TextureView,
Option<&wgpu::TextureView>,
&wgpu::TextureView,
) = if let Some(pane) = pane_key
.as_ref()
.and_then(|k| self.viewport_state.pane_target(k))
{
(&pane.msaa_color, Some(&pane.resolve), &pane.msaa_depth)
} else if use_msaa {
let (_, _, cv, dv) = self.msaa_targets.as_ref().unwrap();
// Under refraction glass the opaque scene resolves into the
// capture the glass refracts, as it is drawn there unsampled.
let resolve = if refract_present {
&self.ss_color.as_ref().unwrap().mip_render_views[0]
} else {
target_view
};
(cv, Some(resolve), dv)
} else if refract_present {
(
&self.ss_color.as_ref().unwrap().mip_render_views[0],
None,
&self.depth_view,
)
} else {
(target_view, None, &self.depth_view)
};
// Timestamps go on the main pass alone. It is where the scene's
// geometry is actually shaded — shadows, post-fx and the glass
// passes are separate costs and averaging them together would hide
// exactly the change anyone is trying to measure.
let main_timestamps = self.timer.as_ref().map(|t| t.writes());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers main pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: main_color_view,
depth_slice: None,
resolve_target: msaa_resolve,
ops: wgpu::Operations {
load: if main_plan.clear == super::viewport::ClearMode::Full {
wgpu::LoadOp::Clear(clear)
} else {
wgpu::LoadOp::Load
},
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_pass_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(self.depth_clear()),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: main_timestamps,
occlusion_query_set: None,
multiview_mask: None,
});
// The partial clear first: the clear colour over the scissor
// rectangle, as `gl.clear` does with the scissor test on.
if let super::viewport::ClearMode::Rect(r) = main_plan.clear {
self.viewport_state.fill_rect(&mut pass, main_format, true, r, clear);
}
main_plan.apply(&mut pass);
// Alpha-to-coverage pipelines store the blend constant as their
// alpha: opaque. (The partial clear above sets its own.)
pass.set_blend_constant(wgpu::Color::WHITE);
pass.set_bind_group(0, &self.frame_bind_group, &[]);
pass.set_bind_group(3, &self.env_bind_group, &[]);
let mut last_topology: Option<Topology> = None;
let mut last_bias: Option<(u32, i32)> = None;
let mut last_state = crate::materials::RenderState::DEFAULT;
let mut last_variant: Option<super::material_maps::MapVariant> = None;
let mut last_side: u32 = u32::MAX;
// Group 3 is the scene's environment unless a material has its own.
let mut env_bound: Option<MaterialEnvKey> = None;
for (i, d) in draws.iter().enumerate() {
if d.env_group != env_bound {
pass.set_bind_group(
3,
d.env_group
.and_then(|k| self.material_env_groups.get(&k))
.map_or(&self.env_bind_group, |(_, g)| g),
&[],
);
env_bound = d.env_group;
}
// Off-screen. The shadow passes above deliberately did draw it:
// a caster the camera cannot see still casts into the view.
if !d.in_frustum {
continue;
}
// Writes neither colour nor depth: nothing to see here (a
// shadow-only caster — fur's and hair's). Skipped rather than
// drawn for nothing; and on WebGL2 a colour-masked draw left
// the whole frame black.
if !d.state.color_write && d.state.depth_write == Some(false) {
continue;
}
// OIT + screen-space-refraction surfaces are drawn in dedicated
// later passes, not here.
if d.topology == Topology::Oit
|| d.topology == Topology::Refract
|| matches!(d.topology, Topology::Custom(_, _, true, ..))
{
continue;
}
// Objects opted out of glass capture draw *over* the glass (a
// later overlay pass), so they're not refracted — skip here.
if refract_present && !d.refract_capture {
continue;
}
// Blended draws on an sRGB target: the encoded-blend pass.
if encoded_pass && d.topology.encodes() {
continue;
}
if last_topology != Some(d.topology)
|| last_bias != d.polygon_offset
|| last_state != d.state
|| last_variant != d.map_variant
|| last_side != d.side
{
let biased = d.polygon_offset.and_then(|(factor, units)| {
let code = biased_topology(d.topology)?;
self.biased_pipelines.get(&(code, bias_variant, factor, units))
});
let pipe = if let Some(p) = biased {
p
} else if use_msaa {
match d.topology {
Topology::Triangle => &self.pipeline_tri_msaa,
Topology::TriangleAlpha => &self.pipeline_tri_alpha_msaa,
Topology::TriangleNoCull => &self.pipeline_tri_nocull_msaa,
Topology::Sky => &self.pipeline_tri_sky_msaa,
Topology::TriangleWire => &self.pipeline_tri_wire_msaa,
Topology::Line => &self.pipeline_line_msaa,
Topology::Point => &self.pipeline_point_msaa,
Topology::GlassDepth => &self.pipeline_glass_depth_msaa,
Topology::GlassColor => &self.pipeline_glass_color_msaa,
Topology::GlassTint => &self.pipeline_glass_tint_msaa,
Topology::Skinned => &self.pipeline_skinned_msaa,
Topology::Instanced => &self.pipeline_instanced_msaa,
Topology::Custom(h, tr, ss, sd) => {
match self.custom_msaa_pipelines.get(&(h, tr, ss, sd)) {
Some(p) => p,
None => continue,
}
}
// gated by `use_msaa`; other topologies never occur here
_ => &self.pipeline_tri_msaa,
}
} else if linear_framebuffer {
match d.topology {
Topology::Triangle => &self.pipeline_tri_f16,
Topology::TriangleAlpha => &self.pipeline_tri_alpha_f16,
Topology::TriangleNoCull => &self.pipeline_tri_nocull_f16,
Topology::GlassDepth => &self.pipeline_glass_depth_f16,
Topology::GlassColor => &self.pipeline_glass_color_f16,
Topology::GlassTint => &self.pipeline_glass_tint_f16,
Topology::Sky => &self.pipeline_tri_sky_f16,
Topology::TriangleWire => &self.pipeline_tri_wire_f16,
Topology::Line => &self.pipeline_line_f16,
Topology::Point => &self.pipeline_point_f16,
Topology::PointAlpha => &self.pipeline_point_alpha_f16,
Topology::Sprite => &self.pipeline_sprite_f16,
Topology::Instanced => &self.pipeline_instanced_f16,
Topology::InstancedWire => &self.pipeline_instanced_wire_f16,
Topology::InstancedAlpha => &self.pipeline_instanced_alpha_f16,
Topology::Skinned => &self.pipeline_skinned_f16,
Topology::SkinnedWire => &self.pipeline_skinned_wire_f16,
Topology::SkinnedAlpha => &self.pipeline_skinned_alpha_f16,
Topology::Oit | Topology::Refract => continue,
// A shader that would not compile has no
// pipeline. Skipping the draw costs one object;
// indexing the map costs the process.
Topology::Custom(h, tr, ss, sd) => {
match self.custom_pipelines.get(&(h, true, tr, ss, sd)) {
Some(p) => p,
None => continue,
}
}
}
} else {
match d.topology {
Topology::Triangle => &self.pipeline_tri,
Topology::TriangleAlpha => &self.pipeline_tri_alpha,
Topology::TriangleNoCull => &self.pipeline_tri_nocull,
Topology::GlassDepth => &self.pipeline_glass_depth,
Topology::GlassColor => &self.pipeline_glass_color,
Topology::GlassTint => &self.pipeline_glass_tint,
Topology::Sky => &self.pipeline_tri_sky,
Topology::TriangleWire => &self.pipeline_tri_wire,
Topology::Line => &self.pipeline_line,
Topology::Point => &self.pipeline_point,
Topology::PointAlpha => &self.pipeline_point_alpha,
Topology::Sprite => &self.pipeline_sprite,
Topology::Instanced => &self.pipeline_instanced,
Topology::InstancedWire => &self.pipeline_instanced_wire,
Topology::InstancedAlpha => &self.pipeline_instanced_alpha,
Topology::Skinned => &self.pipeline_skinned,
Topology::SkinnedWire => &self.pipeline_skinned_wire,
Topology::SkinnedAlpha => &self.pipeline_skinned_alpha,
Topology::Oit | Topology::Refract => continue,
// A shader that would not compile has no
// pipeline. Skipping the draw costs one object;
// indexing the map costs the process.
Topology::Custom(h, tr, ss, sd) => {
match self.custom_pipelines.get(&(h, false, tr, ss, sd)) {
Some(p) => p,
None => continue,
}
}
}
};
let pipe = variant_pipeline(
&mut self.state_pipelines,
&self.map_variants,
&self.device,
&self.main_shader,
pipe,
d.map_variant,
);
let pipe = self.state_pipelines.variant(&self.device, &pipe, &d.state);
let pipe = match side_cull(d.topology.is_faces(), d.side) {
Some(cull) => self.state_pipelines.cull_variant(&self.device, &pipe, cull),
None => pipe,
};
pass.set_pipeline(&pipe);
last_side = d.side;
last_topology = Some(d.topology);
last_bias = d.polygon_offset;
last_state = d.state;
last_variant = d.map_variant;
}
let gm = if d.topology == Topology::Sprite {
&self.sprite_quad
} else {
&self.geom_cache[&d.key].mesh
};
if d.topology.is_skinned() {
// Skinned pipeline uses the combined mesh+skin BGL at group(1).
if let Some(bg) = skin_data.get(d.skin_idx).and_then(|s| s.bg.as_ref()) {
pass.set_bind_group(1, bg, &[]);
}
pass.set_bind_group(2, &*self.per_mesh[i].2, &[]);
if let Some(skin_attrs) = self.skin_attr_cache.get(&d.key) {
pass.set_vertex_buffer(1, skin_attrs.slice(..));
}
} else if let Topology::Custom(..) = d.topology {
// Custom-shader draws use the combined mesh+user bind group
// at @group(1) (mesh uniform + user data/storage), and a
// group 2 holding only what the shared vertex entry needs —
// a `ShaderMaterial` has no standard maps, and declaring the
// eight it cannot use is what put this layout over WebGPU's
// per-stage texture limit.
if let Some(bg) = &user_bgs[i] {
pass.set_bind_group(1, bg, &[]);
}
pass.set_bind_group(
2,
custom_morph_bgs[i].as_ref().unwrap_or(&self.custom_tex_bind_group),
&[],
);
} else {
pass.set_bind_group(1, &self.per_mesh[i].1, &[]);
pass.set_bind_group(2, &*self.per_mesh[i].2, &[]);
}
pass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
// Points: a quad's six corners for each point in the range.
if d.topology.is_points() {
pass.draw(0..6, draw_span(d.range, gm.vertex_count));
continue;
}
// A `ShaderMaterial` on an `InstancedMesh` reads the instance
// buffer too, and its custom columns from slot 2.
let custom_instanced = matches!(d.topology, Topology::Custom(..))
&& shader_data[d.shader_idx].instanced;
let instance_count = if d.topology.is_instanced() || custom_instanced {
pass.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
if custom_instanced {
let custom = &instance_buffers[shader_data[d.shader_idx].custom_buf];
pass.set_vertex_buffer(2, custom.slice(..));
}
d.instance_count
} else {
1
};
// Wire topologies draw the line-list index buffer: polygon
// outlines, or three.js's a,b,b,c,c,a per triangle without a
// polygon table (`BufferGeometry::wireframe_indices`).
// A partial span (a group, a draw range) has a line list of
// its own (`BufferGeometry::wireframe_indices_in`).
let (ib_opt, idx_range) = if d.topology.is_wire() {
match d.range {
Some((a, b)) => {
let version = self.geom_cache.get(&d.key).map(|e| e.version);
match version.and_then(|v| self.wire_span_cache.get(&(d.key, v, a, b))) {
Some((buf, n)) => (Some(buf), 0..*n),
None => (None, 0..0),
}
}
None => (gm.wire_index_buffer.as_ref(), 0..gm.wire_index_count),
}
} else {
(gm.index_buffer.as_ref(), draw_span(d.range, gm.index_count))
};
if let Some(ib) = ib_opt {
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(idx_range, 0, 0..instance_count);
} else if d.topology.is_wire() && d.range.is_some() {
// Nothing to outline in this span.
} else {
pass.draw(draw_span(d.range, gm.vertex_count), 0..instance_count);
}
}
drop(pass);
// The encoded-blend pass (see `encoded_pass`): the blended meshes,
// back to front, into a `Unorm` view of the target (or of the
// multisampled colour) with the shader encoding, so the hardware
// blend mixes sRGB-encoded values as three.js's canvas does.
if let (true, Some(tex)) = (encoded_pass, encoded_target) {
let unorm = tex.format().remove_srgb_suffix();
// (Not on the scratch path: there the device cannot take it.)
let target_unorm = (!encoded_scratch).then(|| {
tex.create_view(&wgpu::TextureViewDescriptor {
format: Some(unorm),
..Default::default()
})
});
// Where the main pass drew: a pane's own multisampled target,
// the shared multisampled colour, the refraction capture, or
// the target itself.
let pane = pane_key
.as_ref()
.and_then(|k| self.viewport_state.pane_target(k));
let color_view = if encoded_scratch {
self.encoded_scratch.as_ref().map(|(_, _, v)| v)
} else if let Some(pane) = pane {
pane.msaa_color_unorm.as_ref()
} else if use_msaa {
self.msaa_color_unorm.as_ref()
} else if refract_present {
self.ss_color.as_ref().and_then(|c| c.mip0_unorm.as_ref())
} else {
target_unorm.as_ref()
};
let target_srgb = encoded_scratch.then(|| tex.create_view(&Default::default()));
if let (Some(color_view), Some(enc)) = (color_view, self.encoded_blend_pipelines.as_ref()) {
if let Some(t) = &target_srgb {
self.encoded_copy_pass(&mut encoder, false, t, color_view);
}
let mut ep = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers encoded blend pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_pass_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
main_plan.apply(&mut ep);
ep.set_bind_group(0, &self.frame_bind_group, &[]);
ep.set_bind_group(3, &self.env_bind_group, &[]);
// Group 3 is the scene's environment unless a material has its own.
let mut env_bound: Option<MaterialEnvKey> = None;
for (i, d) in draws.iter().enumerate() {
if d.env_group != env_bound {
ep.set_bind_group(
3,
d.env_group
.and_then(|k| self.material_env_groups.get(&k))
.map_or(&self.env_bind_group, |(_, g)| g),
&[],
);
env_bound = d.env_group;
}
if !d.in_frustum || !d.topology.encodes() {
continue;
}
// Opted out of the refraction capture: the overlay
// pass draws it, over the glass.
if refract_present && !d.refract_capture {
continue;
}
let pipe = match d.topology {
Topology::TriangleAlpha => {
let (factor, units) = d.polygon_offset.unwrap_or((0f32.to_bits(), 0));
self.biased_pipelines.get(&(1, enc_variant, factor, units))
}
Topology::Sprite => Some(&enc[0]),
Topology::PointAlpha => Some(&enc[3]),
Topology::InstancedAlpha => Some(&enc[1]),
Topology::SkinnedAlpha => Some(&enc[2]),
Topology::GlassDepth => Some(match (&self.encoded_glass_msaa, use_msaa) {
(Some(m), true) => &m[0],
_ => &enc[4],
}),
Topology::GlassColor => Some(match (&self.encoded_glass_msaa, use_msaa) {
(Some(m), true) => &m[1],
_ => &enc[5],
}),
Topology::GlassTint => Some(match (&self.encoded_glass_msaa, use_msaa) {
(Some(m), true) => &m[2],
_ => &enc[6],
}),
Topology::Custom(h, tr, ss, sd) => {
self.custom_encoded_pipelines.get(&(h, tr, ss, sd))
}
_ => None,
};
let Some(pipe) = pipe else { continue };
let pipe = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, pipe, d.map_variant);
let pipe = self.state_pipelines.variant(&self.device, &pipe, &d.state);
let pipe = match side_cull(d.topology.is_faces(), d.side) {
Some(cull) => self.state_pipelines.cull_variant(&self.device, &pipe, cull),
None => pipe,
};
ep.set_pipeline(&pipe);
let gm = if d.topology == Topology::Sprite {
&self.sprite_quad
} else {
&self.geom_cache[&d.key].mesh
};
if d.topology.is_skinned() {
let Some(bg) = skin_data.get(d.skin_idx).and_then(|s| s.bg.as_ref()) else {
continue;
};
let Some(skin_attrs) = self.skin_attr_cache.get(&d.key) else {
continue;
};
ep.set_bind_group(1, bg, &[]);
ep.set_bind_group(2, &*self.per_mesh[i].2, &[]);
ep.set_vertex_buffer(1, skin_attrs.slice(..));
} else if let Topology::Custom(..) = d.topology {
let Some(bg) = &user_bgs[i] else { continue };
ep.set_bind_group(1, bg, &[]);
ep.set_bind_group(
2,
custom_morph_bgs[i].as_ref().unwrap_or(&self.custom_tex_bind_group),
&[],
);
} else {
ep.set_bind_group(1, &self.per_mesh[i].1, &[]);
ep.set_bind_group(2, &*self.per_mesh[i].2, &[]);
}
ep.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if d.topology.is_points() {
ep.draw(0..6, draw_span(d.range, gm.vertex_count));
continue;
}
let custom_instanced = matches!(d.topology, Topology::Custom(..))
&& shader_data[d.shader_idx].instanced;
let instances = if d.topology.is_instanced() || custom_instanced {
ep.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
if custom_instanced {
let custom = &instance_buffers[shader_data[d.shader_idx].custom_buf];
ep.set_vertex_buffer(2, custom.slice(..));
}
d.instance_count
} else {
1
};
if let Some(ib) = &gm.index_buffer {
ep.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
ep.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..instances);
} else {
ep.draw(draw_span(d.range, gm.vertex_count), 0..instances);
}
}
drop(ep);
if let Some(t) = &target_srgb {
self.encoded_copy_pass(&mut encoder, true, color_view, t);
}
// Multisampled: resolve again, in linear light, now that
// the samples hold the blended surfaces too.
if use_msaa {
let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers encoded blend resolve"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: main_color_view,
depth_slice: None,
resolve_target: msaa_resolve,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
}
}
}
// A pane drawn into its own multisampled target: copy its resolved
// picture into the clear rectangle, and only there.
if let Some(p) = &pane_msaa {
let key = (p.region.width, p.region.height, self.color_format, self.msaa);
self.viewport_state.composite_pane(
&mut encoder,
target_view,
self.color_format,
&key,
p.region,
);
}
// Which OIT draws composite where. Without refraction, all of them
// over the frame. With it, each where the refraction glass would see
// it: into the capture just before the first group of glass that
// lies wholly in front of it (so that glass refracts it), or, nearer
// than every group, over the finished glass.
let (refract_groups, refract_group) = {
let mut order: Vec<usize> = (0..draws.len())
.filter(|&i| refract_present && draws[i].in_frustum && draws[i].topology == Topology::Refract)
.collect();
order.sort_by(|&a, &b| draws[a].view_z.partial_cmp(&draws[b].view_z).unwrap_or(std::cmp::Ordering::Equal));
let groups = self.refraction_layers.clamp(1, order.len().max(1));
let mut group = vec![usize::MAX; draws.len()];
for (k, &i) in order.iter().enumerate() {
group[i] = k * groups / order.len();
}
(groups, group)
};
let oit_phase: Vec<usize> = {
// Each group's farthest object, as a view depth (more negative is
// farther).
let mut farthest = vec![f32::INFINITY; refract_groups];
for (i, &g) in refract_group.iter().enumerate() {
if g != usize::MAX {
farthest[g] = farthest[g].min(draws[i].view_z);
}
}
draws
.iter()
.map(|d| {
if d.topology != Topology::Oit {
usize::MAX
} else if !refract_present {
0
} else {
(0..refract_groups).find(|&g| d.view_z <= farthest[g]).unwrap_or(refract_groups)
}
})
.collect()
};
// One OIT phase: accumulate its draws against the depth so far, then
// composite them into `$target` — the frame, or the refraction
// capture — multisampled when `$allow_msaa` and the frame is.
macro_rules! oit_phase {
($phase:expr, $target:expr, $allow_msaa:expr) => {{
// --- Weighted-blended OIT: accumulate the OIT surfaces, then resolve
// (composite) over the opaque image already in `target_view`. ---
// Not during a probe, and this one bites hard. The order-independent
// transparency targets are sized from `depth_size`, which a cube pass
// has set to the face's 48 pixels — so a probe RESIZES them, and the
// next real frame resolves a 48-pixel transparency buffer stretched
// across the whole picture. It reads as the entire vehicle going
// translucent, which looks like an alpha bug in the materials and is
// nothing of the kind.
if !self.cube_pass
&& self.pipeline_oit.is_some()
&& draws.iter().enumerate().any(|(i, d)| d.topology == Topology::Oit && oit_phase[i] == $phase)
{
let (tw, th) = self.depth_size;
self.ensure_oit_targets(tw, th);
// Multisampled when the opaque pass was: against its depth, into
// samples resolved at the end of the pass.
let msaa = $allow_msaa && self.last_frame_msaa && pane_msaa.is_none() && self.pipeline_oit_msaa.is_some();
if msaa {
self.ensure_oit_msaa_targets(tw, th);
}
let msaa_views = msaa
.then(|| Some((self.oit_msaa_targets.as_ref()?, self.msaa_targets.as_ref()?)))
.flatten();
if let Some((_, _, _, accum_view, _, reveal_view, resolve_bg)) =
self.oit_targets.as_ref()
{
// 1) Accumulation pass (accum cleared to 0, revealage cleared to 1).
{
let mut opass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers oit accum pass"),
color_attachments: &[
Some(wgpu::RenderPassColorAttachment {
view: msaa_views.map_or(accum_view, |((_, _, a, _), _)| a),
depth_slice: None,
resolve_target: msaa_views.map(|_| accum_view),
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
}),
Some(wgpu::RenderPassColorAttachment {
view: msaa_views.map_or(reveal_view, |((_, _, _, r), _)| r),
depth_slice: None,
resolve_target: msaa_views.map(|_| reveal_view),
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
}),
],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: msaa_views.map_or(&self.depth_view, |(_, (_, _, _, dv))| dv),
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
let pipe = if msaa_views.is_some() { &self.pipeline_oit_msaa } else { &self.pipeline_oit };
let Some(oit_pipe) = pipe.as_ref() else {
unreachable!("oit pass entered without a pipeline")
};
vp_plan.apply(&mut opass);
opass.set_pipeline(oit_pipe);
opass.set_bind_group(0, &self.frame_bind_group, &[]);
opass.set_bind_group(3, &self.env_bind_group, &[]);
// Group 3 is the scene's environment unless a material has its own.
let mut env_bound: Option<MaterialEnvKey> = None;
for (i, d) in draws.iter().enumerate() {
if d.env_group != env_bound {
opass.set_bind_group(
3,
d.env_group
.and_then(|k| self.material_env_groups.get(&k))
.map_or(&self.env_bind_group, |(_, g)| g),
&[],
);
env_bound = d.env_group;
}
if !d.in_frustum {
continue;
}
if d.topology != Topology::Oit || oit_phase[i] != $phase {
continue;
}
// The draw's group 2 is its material variant's, so
// the pipeline has to be too.
let pipe = variant_pipeline(
&mut self.state_pipelines,
&self.map_variants,
&self.device,
&self.main_shader,
oit_pipe,
d.map_variant,
);
let pipe = self.state_pipelines.variant(
&self.device,
&pipe,
&crate::materials::RenderState::DEFAULT,
);
opass.set_pipeline(&pipe);
let gm = &self.geom_cache[&d.key].mesh;
opass.set_bind_group(1, &self.per_mesh[i].1, &[]);
opass.set_bind_group(2, &*self.per_mesh[i].2, &[]);
opass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
opass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
opass.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..1);
} else {
opass.draw(draw_span(d.range, gm.vertex_count), 0..1);
}
}
}
// 2) Resolve over the opaque image: what is behind times the
// layers' transmittance, then plus their light.
{
let resolve_pipe = if msaa_views.is_some() {
&self.pipeline_oit_resolve_msaa
} else if linear_framebuffer {
&self.pipeline_oit_resolve_f16
} else {
&self.pipeline_oit_resolve
};
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers oit resolve pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: msaa_views.map_or($target, |(_, (_, _, cv, _))| cv),
depth_slice: None,
resolve_target: msaa_views.map(|_| $target),
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
if !vp_plan.legacy {
// Full-screen composite: confine it to this pane.
let sc = vp_plan.scissor;
rpass.set_scissor_rect(sc.x, sc.y, sc.width, sc.height);
}
rpass.set_bind_group(0, resolve_bg, &[]);
for pipe in resolve_pipe {
rpass.set_pipeline(pipe);
rpass.draw(0..3, 0..1);
}
}
}
}
}};
}
if !refract_present {
oit_phase!(0, target_view, true);
}
// A multisampled opaque pass left its depth multisampled: resolve it
// into the single-sampled one — the renderer's own, which refraction
// glass tests against and its march copies, or a multisampled render
// target's, which post-processing reads (`RenderTarget::samples`).
let depth_out = self.last_frame_msaa && pane_msaa.is_none() && (refract_present || self.msaa_depth_out.is_some());
if depth_out && (self.depth_resolve.is_none() || self.force_depth_replay) {
// The camera's view-projection as the replay's pass uniform.
if self.depth_replay_pass.is_none() {
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers depth replay uniform"),
size: std::mem::size_of::<ShadowPassGpu>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers depth replay bg"),
layout: &self.shadow_pass_bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: self.frame_buffer.as_entire_binding() },
wgpu::BindGroupEntry { binding: 3, resource: buffer.as_entire_binding() },
],
});
self.depth_replay_pass = Some((buffer, bg));
}
let (replay_buffer, replay_bg) = self.depth_replay_pass.as_ref().unwrap();
let replay_u = ShadowPassGpu { vp: frame_u.view_proj, light: [0.0; 4] };
self.queue.write_buffer(replay_buffer, 0, bytemuck::bytes_of(&replay_u));
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers depth replay pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(self.depth_clear()),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rp.set_bind_group(0, replay_bg, &[0]);
rp.set_bind_group(3, &self.shadow_env_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.in_frustum {
continue;
}
// What the opaque pass wrote depth for. Lines, points,
// sprites and custom shaders are left out: they rarely
// stand behind glass, and have no depth-only pipeline.
let skinned = d.topology == Topology::Skinned;
let instanced = d.topology == Topology::Instanced;
if !(matches!(d.topology, Topology::Triangle | Topology::TriangleNoCull) || skinned || instanced) {
continue;
}
let cut = d.alpha_test > 0.0 && (d.slots.map.is_some() || d.slots.alpha_map.is_some());
let base = &self.depth_replay[usize::from(cut) * 3 + if skinned { 1 } else if instanced { 2 } else { 0 }];
let gm = &self.geom_cache[&d.key].mesh;
let mut instances = 0..1;
if skinned {
let (Some(bg), Some(attrs)) = (
skin_data.get(d.skin_idx).and_then(|s| s.bg.as_ref()),
self.skin_attr_cache.get(&d.key),
) else {
continue;
};
rp.set_bind_group(1, bg, &[]);
rp.set_vertex_buffer(1, attrs.slice(..));
} else {
rp.set_bind_group(1, &self.per_mesh[i].1, &[]);
if instanced {
rp.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
instances = 0..d.instance_count;
}
}
let pipe = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, base, d.map_variant);
// The material's depth state, and with reversed depth the
// flipped compare, as the opaque pass drew it.
let pipe = self.state_pipelines.variant(&self.device, &pipe, &d.state);
let pipe = match side_cull(true, d.side) {
Some(cull) => self.state_pipelines.cull_variant(&self.device, &pipe, cull),
None => pipe,
};
rp.set_pipeline(&pipe);
rp.set_bind_group(2, &*self.per_mesh[i].2, &[]);
rp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
rp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
rp.draw_indexed(draw_span(d.range, gm.index_count), 0, instances);
} else {
rp.draw(draw_span(d.range, gm.vertex_count), instances);
}
}
} else if depth_out {
if let (Some((bgl, pipe)), Some((_, _, _, msaa_depth))) = (&self.depth_resolve, &self.msaa_targets) {
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers depth resolve bg"),
layout: bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(msaa_depth),
}],
});
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers depth resolve pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(self.depth_clear()),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rp.set_pipeline(pipe);
rp.set_bind_group(0, &bg, &[]);
rp.draw(0..3, 0..1);
}
}
// --- Screen-space refraction glass: build the ss-color mip chain from
// the opaque capture, blit the sharp capture to the frame target, then
// draw the glass surface sampling it for refraction + reflection. ---
//
if refract_present {
// The refracting objects back to front, in `refract_groups` groups
// (worked out above, with the OIT phases).
if refract_groups > 1 {
self.ensure_ss_layer();
}
// Overlapping glass, in layers (`set_refraction_layers`): the
// refracting objects back to front in up to that many groups,
// each refracting a capture of everything drawn before it — the
// opaque scene for the farthest, that and the farther glass for
// the next. Every group but the last draws into a scratch target
// copied back into the capture; the last draws into the frame.
for group in 0..refract_groups {
let last_group = group + 1 == refract_groups;
if group > 0 {
// What the previous group drew is the next one's capture.
let (ssc, (_, _, layer_tex, _)) = (self.ss_color.as_ref().unwrap(), self.ss_layer.as_ref().unwrap());
encoder.copy_texture_to_texture(
layer_tex.as_image_copy(),
ssc.texture.as_image_copy(),
wgpu::Extent3d { width: ssc.width, height: ssc.height, depth_or_array_layers: 1 },
);
}
// OIT surfaces behind this group's glass, into its capture.
oit_phase!(group, &self.ss_color.as_ref().unwrap().mip_render_views[0], false);
let layer_target: &wgpu::TextureView = if last_group {
target_view
} else {
&self.ss_layer.as_ref().unwrap().3
};
let ssc = self.ss_color.as_ref().unwrap();
// Copy the opaque depth into the sampleable ss_depth so the glass
// shader can ray-march it for refraction/reflection.
if let Some((_, _, ss_dtex, _)) = &self.ss_depth {
let src = depth_src.or(self.msaa_depth_out.as_ref()).unwrap_or(&self.depth_texture);
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: src,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::DepthOnly,
},
wgpu::TexelCopyTextureInfo {
texture: ss_dtex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::DepthOnly,
},
wgpu::Extent3d {
width: ssc.width,
height: ssc.height,
depth_or_array_layers: 1,
},
);
}
let ss_depth_view = &self.ss_depth.as_ref().unwrap().3;
let ss_back_depth_view = &self.ss_back_depth.as_ref().unwrap().3;
// Two-surface: render glass back faces (cull front) into ss_back_depth
// so the shader can derive per-pixel glass thickness.
{
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss back-depth pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: ss_back_depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(self.depth_clear()),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(&self.pipeline_ss_back_depth);
bp.set_bind_group(0, &self.frame_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.in_frustum {
continue;
}
if d.topology != Topology::Refract || refract_group[i] != group {
continue;
}
let pipe = variant_pipeline(
&mut self.state_pipelines,
&self.map_variants,
&self.device,
&self.main_shader,
&self.pipeline_ss_back_depth,
d.map_variant,
);
let pipe = self.state_pipelines.variant(
&self.device,
&pipe,
&crate::materials::RenderState::DEFAULT,
);
bp.set_pipeline(&pipe);
let gm = &self.geom_cache[&d.key].mesh;
bp.set_bind_group(1, &self.per_mesh[i].1, &[]);
bp.set_bind_group(2, &*self.per_mesh[i].2, &[]);
bp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
bp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
bp.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..1);
} else {
bp.draw(draw_span(d.range, gm.vertex_count), 0..1);
}
}
}
let blit_pipe = if linear_framebuffer {
&self.pipeline_ss_blit_f16
} else {
&self.pipeline_ss_blit
};
// 1) Downsample chain: build mip m by box-filtering mip m-1.
for m in 1..ssc.mips as usize {
let src_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers ss mip src"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(
&ssc.mip_sample_views[m - 1],
),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
});
let mut mp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss mip gen"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &ssc.mip_render_views[m],
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
mp.set_pipeline(blit_pipe);
mp.set_bind_group(0, &src_bg, &[]);
mp.draw(0..3, 0..1);
}
// 2) Blit the sharp capture (mip 0) to the frame target so non-glass
// pixels show through; the glass draws over it next.
{
let blit_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers ss blit src"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&ssc.mip_sample_views[0]),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
});
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss blit"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: layer_target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(blit_pipe);
bp.set_bind_group(0, &blit_bg, &[]);
bp.draw(0..3, 0..1);
}
// 3) group(3) bind group with the real ss-color at binding 9 (env cube
// + shadows mirror the frame's env bind group).
// The scene environment as the frame's group reads it: prefiltered
// (earlier this frame).
let scene_env_cube = scene.environment.as_ref().map(|e| self.prefiltered_cached(e));
let cube_uv_view: &wgpu::TextureView = if let Some(env) = &scene_env_cube {
self.cube_cache
.get(&cube_cache_key(env))
.and_then(|gc| gc.cube_uv_view.as_ref())
.unwrap_or(&self.default_cube_uv_view)
} else {
&self.default_cube_uv_view
};
let env_cube_view: &wgpu::TextureView = if let Some(rt_id) = scene.environment_cube_rt {
self.cube_rt_view_cache
.get(&rt_id)
.unwrap_or(&self.default_env_cube.view)
} else if let Some(env) = &scene_env_cube {
&self.cube_cache[&cube_cache_key(env)].view
} else {
&self.default_env_cube.view
};
// 4a) Each light's shadow on the glass, for the pass below, which
// has no room for the maps (`fs_glass_shadow`). It also lays
// down the glass depth that pass tests `LessEqual` against.
let glass_shadow_view = &self.ss_glass_shadow.as_ref().unwrap().1;
{
let mut sp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers glass shadow pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: glass_shadow_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
sp.set_bind_group(0, &self.frame_bind_group, &[]);
sp.set_bind_group(3, &self.env_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.in_frustum || d.topology != Topology::Refract || refract_group[i] != group {
continue;
}
let pipe = variant_pipeline(
&mut self.state_pipelines,
&self.map_variants,
&self.device,
&self.main_shader,
&self.pipeline_glass_shadow,
d.map_variant,
);
let pipe = self.state_pipelines.variant(
&self.device,
&pipe,
&crate::materials::RenderState::DEFAULT,
);
sp.set_pipeline(&pipe);
let gm = &self.geom_cache[&d.key].mesh;
sp.set_bind_group(1, &self.per_mesh[i].1, &[]);
sp.set_bind_group(2, &*self.per_mesh[i].2, &[]);
sp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
sp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
sp.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..1);
} else {
sp.draw(draw_span(d.range, gm.vertex_count), 0..1);
}
}
}
// Built by hand rather than through `env_bind_group!`: this group
// has the capture where the macro puts the shadow maps, and the
// shadow maps are exactly what was dropped to make room for it.
let glass_env_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers glass env bg"),
layout: &self.env_bgl_glass,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(env_cube_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.env_sampler),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(cube_uv_view),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::TextureView(&ssc.all_mips_view),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
wgpu::BindGroupEntry {
binding: 11,
resource: wgpu::BindingResource::TextureView(ss_depth_view),
},
wgpu::BindGroupEntry {
binding: 12,
resource: wgpu::BindingResource::TextureView(ss_back_depth_view),
},
wgpu::BindGroupEntry {
binding: 13,
resource: self.env_uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 15,
resource: wgpu::BindingResource::TextureView(glass_shadow_view),
},
],
});
// 4) Glass surface pass (Less + depth-write, opaque composite).
let glass_pipe = if linear_framebuffer {
&self.pipeline_ss_glass_f16
} else {
&self.pipeline_ss_glass
};
let mut gp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss glass pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: layer_target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
gp.set_pipeline(glass_pipe);
gp.set_bind_group(0, &self.frame_bind_group, &[]);
gp.set_bind_group(3, &glass_env_bg, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.in_frustum {
continue;
}
if d.topology != Topology::Refract || refract_group[i] != group {
continue;
}
let pipe = variant_pipeline(
&mut self.state_pipelines,
&self.map_variants,
&self.device,
&self.main_shader,
glass_pipe,
d.map_variant,
);
let pipe = self.state_pipelines.variant(
&self.device,
&pipe,
&crate::materials::RenderState::DEFAULT,
);
gp.set_pipeline(&pipe);
let gm = &self.geom_cache[&d.key].mesh;
gp.set_bind_group(1, &self.per_mesh[i].1, &[]);
gp.set_bind_group(2, &*self.per_mesh[i].2, &[]);
gp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
gp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
gp.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..1);
} else {
gp.draw(draw_span(d.range, gm.vertex_count), 0..1);
}
}
// Custom shaders that asked for the capture draw here too, with the
// real ss-colour/ss-depth at group(3) — the whole point of the flag.
for (i, d) in draws.iter().enumerate() {
let Topology::Custom(h, tr, true, sd) = d.topology else {
continue;
};
if !last_group {
continue;
}
let Some(bg) = &user_bgs[i] else { continue };
let Some(pipe) =
self.custom_pipelines
.get(&(h, linear_framebuffer, tr, true, sd))
else {
continue;
};
let pipe = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, pipe, d.map_variant);
let pipe = self.state_pipelines.variant(&self.device, &pipe, &d.state);
gp.set_pipeline(&pipe);
gp.set_bind_group(1, bg, &[]);
gp.set_bind_group(
2,
custom_morph_bgs[i].as_ref().unwrap_or(&self.custom_tex_bind_group),
&[],
);
let gm = &self.geom_cache[&d.key].mesh;
gp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
let sdd = &shader_data[d.shader_idx];
let instances = if sdd.instanced {
gp.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
gp.set_vertex_buffer(2, instance_buffers[sdd.custom_buf].slice(..));
0..d.instance_count
} else {
0..1
};
if let Some(ib) = &gm.index_buffer {
gp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
gp.draw_indexed(draw_span(d.range, gm.index_count), 0, instances);
} else {
gp.draw(draw_span(d.range, gm.vertex_count), instances);
}
}
drop(gp); // end glass pass before the overlay pass reuses the encoder
}
// OIT surfaces in front of all the glass, over it.
oit_phase!(refract_groups, target_view, false);
// Overlay pass: objects opted out of glass capture draw here, over the
// glass, depth-tested against it (so they stay crisp and un-refracted).
if draws.iter().any(|d| !d.refract_capture) {
let mut op = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers glass overlay pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
op.set_bind_group(0, &self.frame_bind_group, &[]);
op.set_bind_group(3, &self.env_bind_group, &[]);
let mut last: Option<(
Topology,
crate::materials::RenderState,
Option<super::material_maps::MapVariant>,
u32,
)> = None;
// Group 3 is the scene's environment unless a material has its own.
let mut env_bound: Option<MaterialEnvKey> = None;
for (i, d) in draws.iter().enumerate() {
if d.env_group != env_bound {
op.set_bind_group(
3,
d.env_group
.and_then(|k| self.material_env_groups.get(&k))
.map_or(&self.env_bind_group, |(_, g)| g),
&[],
);
env_bound = d.env_group;
}
if !d.in_frustum {
continue;
}
if d.refract_capture {
continue;
}
let pipe = match (linear_framebuffer, d.topology) {
(false, Topology::Triangle) => &self.pipeline_tri,
(false, Topology::TriangleAlpha) => &self.pipeline_tri_alpha,
(false, Topology::TriangleNoCull) => &self.pipeline_tri_nocull,
(false, Topology::Line) => &self.pipeline_line,
(false, Topology::Sprite) => &self.pipeline_sprite,
(false, Topology::Point) => &self.pipeline_point,
(false, Topology::PointAlpha) => &self.pipeline_point_alpha,
(false, Topology::Instanced) => &self.pipeline_instanced,
(false, Topology::InstancedAlpha) => &self.pipeline_instanced_alpha,
(true, Topology::Triangle) => &self.pipeline_tri_f16,
(true, Topology::TriangleAlpha) => &self.pipeline_tri_alpha_f16,
(true, Topology::TriangleNoCull) => &self.pipeline_tri_nocull_f16,
(true, Topology::Line) => &self.pipeline_line_f16,
(true, Topology::Sprite) => &self.pipeline_sprite_f16,
(true, Topology::Point) => &self.pipeline_point_f16,
(true, Topology::PointAlpha) => &self.pipeline_point_alpha_f16,
(true, Topology::Instanced) => &self.pipeline_instanced_f16,
(true, Topology::InstancedAlpha) => &self.pipeline_instanced_alpha_f16,
_ => continue, // skinned/custom/etc not supported as overlay
};
if last != Some((d.topology, d.state, d.map_variant, d.side)) {
let pipe = variant_pipeline(&mut self.state_pipelines, &self.map_variants, &self.device, &self.main_shader, pipe, d.map_variant);
let pipe = self.state_pipelines.variant(&self.device, &pipe, &d.state);
let pipe = match side_cull(d.topology.is_faces(), d.side) {
Some(cull) => self.state_pipelines.cull_variant(&self.device, &pipe, cull),
None => pipe,
};
op.set_pipeline(&pipe);
last = Some((d.topology, d.state, d.map_variant, d.side));
}
let gm = if d.topology == Topology::Sprite {
&self.sprite_quad
} else {
&self.geom_cache[&d.key].mesh
};
op.set_bind_group(1, &self.per_mesh[i].1, &[]);
op.set_bind_group(2, &*self.per_mesh[i].2, &[]);
op.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if d.topology.is_points() {
op.draw(0..6, draw_span(d.range, gm.vertex_count));
continue;
}
let inst = if d.topology.is_instanced() {
op.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
d.instance_count
} else {
1
};
if let Some(ib) = &gm.index_buffer {
op.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
op.draw_indexed(draw_span(d.range, gm.index_count), 0, 0..inst);
} else {
op.draw(draw_span(d.range, gm.vertex_count), 0..inst);
}
}
}
}
// --- Temporal anti-aliasing: reproject + blend the rendered frame with
// the accumulated history, then blit the result back to the target. ---
if taa_active {
let (depth_tex, color_tex) = taa_src.unwrap();
let (w, h) = self.depth_size;
// ACCUMULATE IN FLOAT, NOT IN THE FRAMEBUFFER'S FORMAT.
//
// A running mean folds each new sample in at `1/(n+1)`, and in an
// eight-bit history that is below the quantum long before the mean
// has settled: by the thirty-second sample the increment is a
// 255th of the difference, which rounds to nothing, and every
// sample after it is discarded. The mean stops improving while the
// caller keeps paying for samples. Sixteen float bits cost one more
// byte a pixel at output size and make every sample count.
//
// Only when converging. Ordinary TAA blends at a fixed 0.9 and
// never gets near the quantum, and it is the interactive path,
// where the bandwidth is worth more than the precision.
let hist_format = if self.taa_converge {
wgpu::TextureFormat::Rgba16Float
} else {
ss_format
};
self.ensure_taa_targets(w, h, hist_format);
let first = self.taa_frame == 0;
// Camera movement, carried for a caller that can distinguish its
// own pinned geometry. This pass cannot: see TAA_SHADER.
let cam = camera.position();
let d = [
cam.x - self.taa_prev_cam[0],
cam.y - self.taa_prev_cam[1],
cam.z - self.taa_prev_cam[2],
];
let taa_u = TaaUniforms {
inv_view_proj: taa_inv_vp,
prev_view_proj: self.taa_prev_view_proj,
// Converging: `n/(n+1)` makes the history the mean of every
// sample so far. Otherwise the usual fixed feedback.
params: [
w as f32,
h as f32,
if self.taa_converge {
self.taa_frame as f32 / (self.taa_frame as f32 + 1.0)
} else {
0.9
},
if first { 1.0 } else { 0.0 },
],
// w: 0 feedback, 1 converging over sRGB-encoded bytes, 2
// converging over linear light. The converge branch needs to
// know which, because a running mean of encoded bytes is a mean
// over a curve: see TAA_SHADER.
cam_delta: [
d[0],
d[1],
d[2],
match (self.taa_converge, shader_outputs_linear) {
(false, _) => 0.0,
(true, false) => 1.0,
(true, true) => 2.0,
},
],
flags: [if self.state_pipelines.reversed() { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0],
};
self.queue
.write_buffer(&self.taa_uniform, 0, bytemuck::bytes_of(&taa_u));
let cur_view = color_tex.create_view(&wgpu::TextureViewDescriptor::default());
let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
// frame N reads what N-1 wrote, writes the other buffer.
let even = self.taa_frame.is_multiple_of(2);
if self.taa_bind_cache.is_none() {
let (_, _, _, a_view, _, b_view) = self.taa_history.as_ref().unwrap();
let mk_resolve = |read: &wgpu::TextureView| {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers taa bg"),
layout: &self.taa_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&cur_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(read),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&depth_view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.taa_sampler),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.taa_uniform.as_entire_binding(),
},
],
})
};
let mk_blit = |write: &wgpu::TextureView| {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers taa blit bg"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(write),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
})
};
// Index by `taa_frame % 2`: even frames read b and write a.
self.taa_bind_cache = Some(TaaBindCache {
resolve: [mk_resolve(b_view), mk_resolve(a_view)],
blit: [mk_blit(a_view), mk_blit(b_view)],
});
}
let parity = usize::from(!even);
let (a_view, b_view) = {
let (_, _, _, av, _, bv) = self.taa_history.as_ref().unwrap();
(av, bv)
};
let write_view = if even { a_view } else { b_view };
let resolve_bg = &self.taa_bind_cache.as_ref().unwrap().resolve[parity];
// The resolve draws into the history, so its target format is the
// history's — float whenever converging, whatever the framebuffer.
let taa_pipe = if linear_framebuffer || self.taa_converge {
&self.pipeline_taa_f16
} else {
&self.pipeline_taa
};
{
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers taa resolve"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: write_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rp.set_pipeline(taa_pipe);
rp.set_bind_group(0, resolve_bg, &[]);
rp.draw(0..3, 0..1);
}
// Blit the resolved history back to the frame target — unless this
// is an intermediate sample of an accumulation run, in which case
// the mean is in the history buffer and nothing will read the
// target before the next sample overwrites it anyway.
if self.taa_blit {
let blit_bg = &self.taa_bind_cache.as_ref().unwrap().blit[parity];
let blit_pipe = if linear_framebuffer {
&self.pipeline_ss_blit_f16
} else {
&self.pipeline_ss_blit
};
{
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers taa blit"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(blit_pipe);
bp.set_bind_group(0, blit_bg, &[]);
bp.draw(0..3, 0..1);
}
}
}
// Roll the motion-blur matrices on every frame -- but a PROBE IS NOT A
// FRAME. An environment cube is six renders from a camera that is not
// the picture's, and rolling on those leaves `mb_last_vp` holding a
// 90-degree view from somewhere else. The next real frame then blurs
// along the difference between the two, which is enormous: the vehicle
// smears into a translucent double of itself and streaks run across the
// whole image. It reads exactly like a transparency bug, and was chased
// as one for a long time -- through the OIT buffers, the cube format,
// the PMREM prefilter and the probe's brightness -- none of which it
// ever was.
if !self.cube_pass {
self.mb_inv_vp = taa_inv_vp;
self.mb_prev_vp = self.mb_last_vp;
self.mb_last_vp = taa_unjittered_vp;
}
if taa_active && !self.cube_pass {
// (separate block so the history-view borrows above have ended)
self.taa_prev_view_proj = taa_unjittered_vp;
{
let c = camera.position();
self.taa_prev_cam = [c.x, c.y, c.z];
}
self.taa_frame += 1;
}
if let Some(t) = &self.timer {
t.resolve(&mut encoder);
}
if update_shadows {
if let Some(t) = &self.shadow_timer {
t.resolve(&mut encoder);
}
}
self.queue.submit(Some(encoder.finish()));
// After submit, so the map is queued behind this frame's work. Never
// blocks — see `gpu_timer`.
if let Some(t) = &mut self.timer {
let device = self.device.clone();
t.poll(&device);
}
if let Some(t) = &mut self.shadow_timer {
let device = self.device.clone();
t.poll(&device);
}
let _ = (&self.frame_bgl,);
}
/// GPU milliseconds in the main pass, from the most recently completed
/// readback — a few frames old, and 0.0 when the adapter has no timestamp
/// support or none has landed yet.
///
/// This is the number to trust when comparing renderer changes. Wall-clock
/// time round `render` measures CPU submission and whatever else the
/// machine is doing; three identical frames timed that way here came back
/// at 18, 31 and 35 ms.
pub fn gpu_frame_ms(&self) -> f32 {
self.timer.as_ref().map(|t| t.last_ms()).unwrap_or(0.0)
}
/// GPU milliseconds from the start of the first shadow pass to the end of
/// the last, from the most recent completed readback of a render that drew
/// them — like [`gpu_frame_ms`](Self::gpu_frame_ms), a few renders old,
/// and 0.0 without timestamp support.
pub fn gpu_shadow_ms(&self) -> f32 {
self.shadow_timer.as_ref().map(|t| t.last_ms()).unwrap_or(0.0)
}
/// three.js `renderer.shadowMap`: `auto_update` (default on) redraws the
/// shadow maps whenever a caster or a light changed since they were last
/// drawn — a still scene under a moving camera keeps them; turn it off
/// and set `needs_update` to have the next render redraw them once. See
/// [`ShadowMap`](super::ShadowMap).
pub fn shadow_map(&self) -> &super::viewport::ShadowMap {
&self.shadow_map
}
pub fn shadow_map_mut(&mut self) -> &mut super::viewport::ShadowMap {
&mut self.shadow_map
}
/// How many renders so far drew the shadow maps.
pub fn shadow_map_updates(&self) -> u64 {
self.shadow_updates
}
fn ensure_slot_uploaded(&mut self, slot: &Option<Arc<Texture>>) {
let Some(t) = slot else {
return;
};
// Skip upload for render-target-backed textures — the view lives in
// the RenderTarget itself.
if t.external_rt_id.is_some() {
return;
}
let key = tex_cache_key(t);
// No liveness check any more: the key is the texture's own id, which
// does not depend on where — or whether — its bytes are. That is what
// lets a data-less `Texture::handle` resolve to the upload its full
// twin made, and it closes the recycled-address hole the weak handle
// was guarding, since an id is never handed out twice.
if !self.tex_cache.contains_key(&key) {
// Drop stale GPU copies for this logical texture (older upload_seq).
self.tex_cache.retain(|k, _| k.0 != t.id);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
if t.is_handle() {
// A handle carries no pixels: it can only ever resolve to an
// upload its full twin already made. Reaching here means that
// upload is missing, and what gets created instead is a texture
// of the right size with nothing in it -- which samples black
// and raises no error anywhere.
log::warn!(
"uploading a data-less handle: id {} {}x{} {:?} -- this samples black",
t.id,
t.width,
t.height,
t.format
);
if std::env::var("TEXWARN").is_ok() {
eprintln!(
" WARN data-less handle uploaded: id {} {}x{} {:?}",
t.id, t.width, t.height, t.format
);
}
}
// Downsampling is a texture read and a write, so let the GPU do it
// rather than computing the whole chain serially on this thread and
// uploading it level by level.
let mipgen = self
.mipgen
.get_or_insert_with(|| MipGenerator::new(&self.device));
let gt = GpuTexture::upload_with_mipgen(&self.device, &self.queue, t, mipgen);
self.tex_cache.insert(key, gt);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
}
}
fn view_for<'a>(
&'a self,
slot: &Option<Arc<Texture>>,
default: &'a GpuTexture,
) -> &'a wgpu::TextureView {
match slot {
Some(t) => {
// If this Texture is RT-backed, sample from the RT's color view.
if let Some(rt_id) = t.external_rt_id {
if let Some(view) = self.rt_view_cache.get(&rt_id) {
return view;
}
}
&self.tex_cache[&tex_cache_key(t)].view
}
None => &default.view,
}
}
/// Borrow an RT's sample-side view by id. Caller must have previously
/// `register_render_target`'d this id. Used by post-fx to bind the input.
pub fn rt_view_cache_get(&self, rt_id: u32) -> &wgpu::TextureView {
self.rt_view_cache
.get(&rt_id)
.expect("rt id not registered")
}
/// Register a CubeRenderTarget so scene.environment_cube_rt can sample
/// from its 6-face cube view as an env map.
pub fn register_cube_render_target(&mut self, rt_id: u32, rt: &Arc<super::CubeRenderTarget>) {
let sample_format = rt.format.add_srgb_suffix();
let view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers cube rt sample view"),
format: Some(sample_format),
dimension: Some(wgpu::TextureViewDimension::Cube),
base_array_layer: 0,
array_layer_count: Some(6),
base_mip_level: 0,
mip_level_count: Some(1),
aspect: wgpu::TextureAspect::All,
usage: None,
});
self.cube_rt_view_cache.insert(rt_id, view);
}
/// Register a RenderTarget so RT-backed Textures can sample from its color view.
/// Creates a sample-side view using the sRGB-variant of the storage format
/// (when applicable) so the hardware does sRGB→linear decode on read,
/// matching three.js's WebGL behavior where RT textures auto-decode.
pub fn register_render_target(&mut self, rt_id: u32, rt: &Arc<super::RenderTarget>) {
let sample_format = rt_sample_format(rt.format);
let view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt sample view"),
format: Some(sample_format),
..Default::default()
});
self.rt_view_cache.insert(rt_id, view);
self.tex_bg_cache.clear();
self.variant_bg_cache.clear();
let linear_view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt linear sample view"),
format: Some(rt.format),
..Default::default()
});
self.rt_linear_view_cache.insert(rt_id, linear_view);
let depth_view = rt.depth_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt depth sample view"),
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.rt_depth_view_cache.insert(rt_id, depth_view);
self.rt_registry.insert(rt_id, Arc::clone(rt));
}
fn build_tex_bg(
&self,
slots: &MaterialTextureSlots,
morph: Option<&wgpu::TextureView>,
uv_sets: Option<&wgpu::TextureView>,
) -> wgpu::BindGroup {
let morph = morph.unwrap_or(&self.default_morph.1);
let uv_sets = uv_sets.unwrap_or(&self.default_uv_sets.1);
let albedo = self.view_for(&slots.map, &self.default_white_srgb);
let normal = self.view_for(&slots.normal_map, &self.default_normal);
let roughness = self.view_for(&slots.roughness_map, &self.default_white_linear);
let metalness = self.view_for(&slots.metalness_map, &self.default_white_linear);
let ao = self.view_for(&slots.ao_map, &self.default_white_linear);
let emissive = self.view_for(&slots.emissive_map, &self.default_white_srgb);
// Matcap and cloud cover share a binding. WebGPU guarantees only 16
// sampled textures per fragment stage and we are at that ceiling, so a
// seventeenth is not available — but the two can never both be set: a
// matcap belongs to `MatcapMaterial`, a cloud deck to a Standard or
// Physical surface.
let matcap = match &slots.cloud_shadow_map {
Some(_) => self.view_for(&slots.cloud_shadow_map, &self.default_transparent),
None => self.view_for(&slots.matcap_map, &self.default_white_srgb),
};
// One sampler for every map of the material, from the colour map's
// filter and wrap (or the first map present) — see
// `MaterialTextureSlots::sampler_source`.
let chosen = slots.sampler_source();
let sampler = match chosen {
Some(t) => self.pick_sampler(t),
None => &self.samplers[SAMPLER_DEFAULT],
};
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers tex bg"),
layout: &self.tex_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(albedo),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(normal),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(roughness),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(metalness),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(ao),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(emissive),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(matcap),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler(sampler),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(morph),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(uv_sets),
},
],
})
}
/// Select one of the 4 pre-built samplers based on a Texture's filter/wrap
/// fields. Mirrors three.js: NearestFilter→nearest, LinearFilter→linear;
/// RepeatWrapping→repeat, ClampToEdgeWrapping→clamp.
/// Build material shader variant `v` — its module and group-2 layout — if
/// it is not built yet.
fn ensure_map_variant(&mut self, v: super::material_maps::MapVariant) {
use super::material_maps as mm;
if self.map_variants.contains_key(&v) {
return;
}
let source = super::shader::shader_source_with_maps(&mm::prelude(v));
let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers material variant shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let b = mm::bindings(v);
let mut entries = vec![uv_sets_entry(), wgpu::BindGroupLayoutEntry {
binding: 10,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
}];
for (role, t, smp) in &b.maps {
let visibility = if role.vertex() {
wgpu::ShaderStages::VERTEX
} else {
wgpu::ShaderStages::FRAGMENT
};
entries.push(wgpu::BindGroupLayoutEntry {
binding: *t,
visibility,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
});
entries.push(wgpu::BindGroupLayoutEntry {
binding: *smp,
visibility,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
});
}
if let Some((t, smp)) = b.env {
entries.push(wgpu::BindGroupLayoutEntry {
binding: t,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::Cube,
multisampled: false,
},
count: None,
});
entries.push(wgpu::BindGroupLayoutEntry {
binding: smp,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
});
}
entries.push(wgpu::BindGroupLayoutEntry {
binding: b.xforms,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
});
let bgl = self.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers material variant bgl"),
entries: &entries,
});
self.map_variants.insert(v, (module, bgl));
}
/// Group 2 for a draw on material variant `v`: each map with its own
/// sampler, and the block of their uv transforms.
fn build_variant_tex_bg(
&self,
slots: &MaterialTextureSlots,
morph: Option<&wgpu::TextureView>,
uv_sets: Option<&wgpu::TextureView>,
v: super::material_maps::MapVariant,
uniforms: [[f32; 4]; 6],
) -> wgpu::BindGroup {
use super::material_maps as mm;
let b = mm::bindings(v);
let textures: Vec<&std::sync::Arc<Texture>> = mm::role_textures(slots)
.into_iter()
.filter(|(r, _)| v.contains(*r))
.filter_map(|(_, t)| t)
.collect();
let mut rows: Vec<[f32; 4]> = Vec::with_capacity(6 + 2 * textures.len().max(1));
rows.extend(uniforms);
// Row 0's w: the uv set the map reads (three.js `Texture.channel`).
for t in &textures {
let [r0, r1] = t.uv_transform_rows();
rows.push([r0[0], r0[1], r0[2], t.channel.min(3) as f32]);
rows.push([r1[0], r1[1], r1[2], 0.0]);
}
if textures.is_empty() {
rows.extend([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]);
}
let xforms = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers material map transforms"),
contents: bytemuck::cast_slice(&rows),
usage: wgpu::BufferUsages::UNIFORM,
},
);
let morph = morph.unwrap_or(&self.default_morph.1);
let mut entries = vec![
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(morph),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(uv_sets.unwrap_or(&self.default_uv_sets.1)),
},
];
for ((_, t, smp), tex) in b.maps.iter().zip(&textures) {
let slot = Some((*tex).clone());
entries.push(wgpu::BindGroupEntry {
binding: *t,
resource: wgpu::BindingResource::TextureView(self.view_for(&slot, &self.default_white_linear)),
});
entries.push(wgpu::BindGroupEntry {
binding: *smp,
resource: wgpu::BindingResource::Sampler(self.pick_sampler(tex)),
});
}
if let (Some((t, smp)), Some(cube)) = (b.env, slots.env_map.as_ref()) {
entries.push(wgpu::BindGroupEntry {
binding: t,
resource: wgpu::BindingResource::TextureView(&self.cube_cache[&cube_cache_key(cube)].view),
});
entries.push(wgpu::BindGroupEntry {
binding: smp,
resource: wgpu::BindingResource::Sampler(&self.samplers[cube_sampler_index(cube)]),
});
}
entries.push(wgpu::BindGroupEntry {
binding: b.xforms,
resource: xforms.as_entire_binding(),
});
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers material variant bg"),
layout: &self.map_variants[&v].1,
entries: &entries,
})
}
/// three.js `WebGLCubeUVMaps`: a cube texture lighting a Standard or
/// Physical material is read through its PMREM — prefiltered here once,
/// and kept — unless it already carries one (`PMREMGenerator` output).
fn prefiltered(&mut self, cube: &std::sync::Arc<CubeTexture>) -> std::sync::Arc<CubeTexture> {
if cube.cube_uv_atlas.is_some() {
return cube.clone();
}
self.pmrem_cache
.entry(cube_cache_key(cube))
.or_insert_with(|| crate::PmremGenerator::from_cube(cube.clone()))
.clone()
}
/// [`prefiltered`](Self::prefiltered) once it has run for `cube`.
fn prefiltered_cached(&self, cube: &std::sync::Arc<CubeTexture>) -> std::sync::Arc<CubeTexture> {
self.pmrem_cache.get(&cube_cache_key(cube)).cloned().unwrap_or_else(|| cube.clone())
}
fn pick_sampler<'a>(&'a self, t: &Texture) -> &'a wgpu::Sampler {
&self.samplers[sampler_index(t)]
}
fn make_default_tex_bg(&self) -> wgpu::BindGroup {
self.build_tex_bg(&MaterialTextureSlots::default(), None, None)
}
}
/// `n` sub-pixel jitter offsets in `[-0.5, 0.5)`, each axis exactly stratified.
///
/// [`halton`] is the right sequence when the sample count is not known ahead of
/// time, which is the streaming TAA case: it is spread at every prefix length.
/// When the count *is* known — an offline frame asking for exactly `n` samples —
/// it is the wrong one, because its one-dimensional marginals are only uniform
/// in the limit and at any particular `n` the two bases disagree about how
/// uniform they are. At sixteen samples base 2 lands on the exact sixteenths and
/// base 3 does not, so x and y converge at different rates. Measured as how
/// precisely a straight edge is placed as it slides across a pixel:
///
/// ```text
/// vertical edge horizontal edge
/// Halton 0.0017 px 0.0253 px
/// stratified 0.0017 px 0.0017 px
/// ```
///
/// A renderer whose horizontal edges are fifteen times less precisely placed
/// than its vertical ones is not one anyone would ask for, and nothing about
/// the picture says which axis to distrust.
///
/// The arrangement here is N-rooks: both axes get the same ladder of `n` evenly
/// spaced positions, so both marginals are exact and both are zero-mean —
/// Halton's are not, and a jitter set whose mean is not zero translates the
/// whole frame by that much. The pairing between the two ladders is Halton's
/// own, taken by *ranking* its values rather than using them, which keeps the
/// two-dimensional spread and keeps the progressive property with it: any
/// prefix of the result is still well distributed, because ranking does not
/// reorder.
///
/// ```
/// # use threers::stratified_jitter;
/// let j = stratified_jitter(16);
/// let mean_x: f32 = j.iter().map(|o| o.0).sum::<f32>() / 16.0;
/// assert!(mean_x.abs() < 1e-6);
/// ```
pub fn stratified_jitter(n: u32) -> Vec<(f32, f32)> {
let n = n.max(1);
let ladder = |base: u32| -> Vec<f32> {
let vals: Vec<f32> = (0..n).map(|k| halton(k + 1, base)).collect();
let mut order: Vec<u32> = (0..n).collect();
order.sort_by(|&a, &b| vals[a as usize].total_cmp(&vals[b as usize]));
let mut out = vec![0.0; n as usize];
for (rung, &k) in order.iter().enumerate() {
out[k as usize] = (rung as f32 + 0.5) / n as f32 - 0.5;
}
out
};
ladder(2).into_iter().zip(ladder(3)).collect()
}
/// Halton low-discrepancy sequence — the standard source of TAA sub-pixel jitter.
///
/// `index` is one-based; `base` should be a prime, and bases 2 and 3 are the
/// conventional pair for the two screen axes. Public because
/// [`Renderer::set_jitter_override`] hands the jitter to the caller, and a
/// caller driving it wants the same sequence the renderer would have used:
///
/// ```
/// # use threers::halton;
/// let offset = (halton(4, 2) - 0.5, halton(4, 3) - 0.5); // sample 4, in [-0.5, 0.5)
/// # let _ = offset;
/// ```
pub fn halton(mut index: u32, base: u32) -> f32 {
let (mut f, mut r) = (1.0f32, 0.0f32);
while index > 0 {
f /= base as f32;
r += f * (index % base) as f32;
index /= base;
}
r
}
/// `PrimitiveState` with the fields that never vary across our pipelines filled
/// in (Ccw front, fill, clipped, non-conservative) — only topology + cull differ.
fn primitive(topology: wgpu::PrimitiveTopology, cull: Option<wgpu::Face>) -> wgpu::PrimitiveState {
wgpu::PrimitiveState {
topology,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: cull,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
}
}
/// The mesh triangle pipeline (`code`: 0 culled, 1 alpha-blended, 2 double-sided) with
/// three.js's `polygonOffset` as a depth bias.
///
/// `glPolygonOffset(factor, units)` offsets depth by `factor · m + units · r`
/// (`m` the largest window-space depth slope, `r` the smallest resolvable
/// step), and WebGPU's `DepthBiasState` is defined by the same formula with
/// `slope_scale` and `constant` — so the values carry over unchanged. Depth
/// here is not reversed (cleared to 1, `LessEqual`), so a negative offset
/// pulls toward the camera exactly as in WebGL.
#[allow(clippy::too_many_arguments)]
fn build_biased_pipeline(
device: &wgpu::Device,
module: &wgpu::ShaderModule,
layout: &wgpu::PipelineLayout,
format: wgpu::TextureFormat,
samples: u32,
code: u8,
factor: f32,
units: i32,
pipes: &mut super::pipeline_state::StatePipelines,
) -> wgpu::RenderPipeline {
let alpha = code == 1;
let vertex_buffers = [Some(wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x3 },
wgpu::VertexAttribute { offset: 12, shader_location: 1, format: wgpu::VertexFormat::Float32x3 },
wgpu::VertexAttribute { offset: 24, shader_location: 2, format: wgpu::VertexFormat::Float32x2 },
wgpu::VertexAttribute { offset: 32, shader_location: 3, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 48, shader_location: 8, format: wgpu::VertexFormat::Float32x4 },
],
})];
let mut ds = depth_stencil(!alpha, wgpu::CompareFunction::LessEqual);
ds.bias = wgpu::DepthBiasState {
constant: units,
slope_scale: factor,
clamp: 0.0,
};
pipes.create(device, &wgpu::RenderPipelineDescriptor {
label: Some("threers polygon-offset pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
if code == 2 { None } else { Some(wgpu::Face::Back) },
),
depth_stencil: Some(ds),
multisample: wgpu::MultisampleState {
count: samples,
..Default::default()
},
multiview_mask: None,
cache: None,
})
}
/// `DepthStencilState` at [`DEPTH_FORMAT`] with default stencil/bias — only the
/// write flag and compare function differ across our pipelines.
fn depth_stencil(write: bool, compare: wgpu::CompareFunction) -> wgpu::DepthStencilState {
wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(write),
depth_compare: Some(compare),
stencil: Default::default(),
bias: Default::default(),
}
}
fn create_depth_view(
device: &wgpu::Device,
width: u32,
height: u32,
) -> (wgpu::Texture, wgpu::TextureView) {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers depth"),
size: wgpu::Extent3d {
width: width.max(1),
height: height.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
// COPY_SRC so the opaque depth can be copied into the sampleable ss_depth
// for the screen-space glass ray march.
// TEXTURE_BINDING as well: passes that run after the frame — ambient
// occlusion, and anything else reconstructing geometry from depth —
// have to sample this, and a depth buffer that can only be rendered
// into and copied out of is no use to them.
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
}
/// three.js's `RectAreaLight` lookup tables — `RectAreaLightUniformsLib`'s
/// `LTC_MAT_1` and `LTC_MAT_2` (Heitz et al.'s fitted linearly transformed
/// cosines), extracted from three.js r165 — as the two layers of one 64×64
/// half-float texture: half floats filter on every backend (three.js falls
/// back to the same `LTC_HALF` tables), and two layers keep the bilinear
/// filter from reading across from one table into the other.
///
/// Built with `--cfg threers_no_rect_area_light` the tables are not embedded
/// (they are 128 KB of floats that barely compress — a fifth of a small wasm)
/// and the texture is zero-filled instead: same shape, same bindings, and a
/// RectAreaLight simply contributes nothing. For consumers that never use one.
fn upload_ltc(device: &wgpu::Device, queue: &wgpu::Queue) -> (wgpu::Texture, wgpu::TextureView) {
#[cfg(not(threers_no_rect_area_light))]
let half: Vec<u16> = {
const LTC_1: &[u8] = include_bytes!("ltc/ltc_float_1.bin");
const LTC_2: &[u8] = include_bytes!("ltc/ltc_float_2.bin");
[LTC_1, LTC_2]
.iter()
.flat_map(|b| b.chunks_exact(4))
.map(|c| super::gpu_texture::f32_to_f16_bits(f32::from_le_bytes([c[0], c[1], c[2], c[3]])))
.collect()
};
#[cfg(threers_no_rect_area_light)]
let half: Vec<u16> = vec![0; 64 * 64 * 4 * 2];
let size = wgpu::Extent3d { width: 64, height: 64, depth_or_array_layers: 2 };
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers RectAreaLight LTC tables"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&half),
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(64 * 8), rows_per_image: Some(64) },
size,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
(texture, view)
}
/// A frame bind group: the frame uniforms and a transmission capture view.
fn frame_bg(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
buffer: &wgpu::Buffer,
capture: &wgpu::TextureView,
sampler: &wgpu::Sampler,
label: &str,
) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(label),
layout,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(capture) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) },
],
})
}
fn transform_direction(m: &Matrix4, v: Vector3) -> Vector3 {
let e = &m.elements;
Vector3::new(
e[0] * v.x + e[4] * v.y + e[8] * v.z,
e[1] * v.x + e[5] * v.y + e[9] * v.z,
e[2] * v.x + e[6] * v.y + e[10] * v.z,
)
}
fn mat3_to_mat4_array(m: &Matrix3) -> [f32; 16] {
let e = &m.elements;
[
e[0], e[1], e[2], 0.0, e[3], e[4], e[5], 0.0, e[6], e[7], e[8], 0.0, 0.0, 0.0, 0.0, 1.0,
]
}
#[cfg(test)]
mod tests {
use super::*;
/// The preamble a `ShaderMaterial` is compiled against is "everything in
/// `SHADER_SOURCE` above the first `@fragment`", and the documented
/// contract is that every built-in helper is in it. Those two facts are
/// only compatible while no other fragment entry point is declared ahead of
/// `fs_main` — and when one was, the preamble silently lost 900 lines and
/// every shader material that called `framebuffer_encode` stopped
/// compiling, including the one in `examples/shader_material.rs`.
///
/// Nothing about that failure looks like an ordering problem: the error is
/// `no definition in scope for identifier`, at pipeline-creation time, in
/// the user's own shader.
#[test]
fn the_custom_preamble_carries_the_documented_helpers() {
let module = custom_shader_module_source("@fragment\nfn fs_main() {}\n", None, true, false, 1);
let preamble = module.split("struct ThreersUserData").next().unwrap();
for name in [
"fn framebuffer_encode",
"fn linear_to_srgb",
"fn aces_tonemap",
"fn sample_env_cube",
"fn pbr_brdf",
"fn apply_fog",
"struct VsOut",
"fn vs_main",
] {
assert!(
preamble.contains(name),
"`{name}` is missing from the custom-shader preamble — something \
declared an entry point above it in SHADER_SOURCE"
);
}
}
/// The same invariant stated directly, so a violation names the cause
/// rather than the symptom.
#[test]
fn no_fragment_entry_point_precedes_fs_main() {
let source = crate::renderer::shader::legacy_shader_source();
let first = source
.find("@fragment")
.expect("SHADER_SOURCE has a fragment entry point");
let after = &source[first..];
let name = after
.split("fn ")
.nth(1)
.and_then(|s| s.split(|c: char| !c.is_alphanumeric() && c != '_').next())
.unwrap_or("");
assert_eq!(
name, "fs_main",
"the first `@fragment` in SHADER_SOURCE is `{name}`, not `fs_main`; \
move it below `fs_main` or it truncates the shader-material preamble"
);
}
}