summaryrefslogtreecommitdiffstats
path: root/tools/gfx/d3d12/render-d3d12.cpp
blob: b8ff47ad362b94c89629a00fcfeaefd8b79ce40a (plain)
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
// render-d3d12.cpp
#define _CRT_SECURE_NO_WARNINGS

#include "render-d3d12.h"

//WORKING:#include "options.h"
#include "../renderer-shared.h"
#include "../transient-resource-heap-base.h"
#include "../simple-render-pass-layout.h"
#include "../d3d/d3d-swapchain.h"
#include "core/slang-blob.h"
#include "core/slang-basic.h"

// In order to use the Slang API, we need to include its header

//WORKING:#include <slang.h>

// We will be rendering with Direct3D 12, so we need to include
// the Windows and D3D12 headers

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX

#include <dxgi1_4.h>
#include <d3d12.h>
//#include <d3dcompiler.h>

#ifndef __ID3D12GraphicsCommandList1_FWD_DEFINED__
// If can't find a definition of CommandList1, just use an empty definition
struct ID3D12GraphicsCommandList1 {};
#endif

#ifdef GFX_NVAPI
#   include "../nvapi/nvapi-include.h"
#endif

#include "slang-com-ptr.h"
#include "../flag-combiner.h"

#include "resource-d3d12.h"
#include "descriptor-heap-d3d12.h"

#include "../d3d/d3d-util.h"

#include "../nvapi/nvapi-util.h"

// We will use the C standard library just for printing error messages.
#include <stdio.h>

#ifdef _MSC_VER
#include <stddef.h>
#if (_MSC_VER < 1900)
#define snprintf sprintf_s
#endif
#endif
//

#define ENABLE_DEBUG_LAYER 1

namespace gfx {
using namespace Slang;

static D3D12_RESOURCE_STATES _calcResourceState(IResource::Usage usage);

class D3D12Device : public RendererBase
{
public:
    // Renderer    implementation
    virtual SLANG_NO_THROW SlangResult SLANG_MCALL initialize(const Desc& desc) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL
        createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createTransientResourceHeap(
        const ITransientResourceHeap::Desc& desc,
        ITransientResourceHeap** outHeap) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createSwapchain(
        const ISwapchain::Desc& desc,
        WindowHandle window,
        ISwapchain** outSwapchain) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL createTextureResource(
        IResource::Usage initialUsage,
        const ITextureResource::Desc& desc,
        const ITextureResource::SubresourceData* initData,
        ITextureResource** outResource) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createBufferResource(
        IResource::Usage initialUsage,
        const IBufferResource::Desc& desc,
        const void* initData,
        IBufferResource** outResource) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL
        createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
        ITextureResource* texture,
        IResourceView::Desc const& desc,
        IResourceView** outView) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createBufferView(
        IBufferResource* buffer, IResourceView::Desc const& desc, IResourceView** outView) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL
        createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFrameBuffer) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL
        createFramebufferLayout(IFramebufferLayout::Desc const& desc, IFramebufferLayout** outLayout) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL createRenderPassLayout(
        const IRenderPassLayout::Desc& desc,
        IRenderPassLayout** outRenderPassLayout) override;

    virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
        const InputElementDesc* inputElements,
        UInt inputElementCount,
        IInputLayout** outLayout) override;

    virtual Result createShaderObjectLayout(
        slang::TypeLayoutReflection* typeLayout,
        ShaderObjectLayoutBase** outLayout) override;
    virtual Result createShaderObject(ShaderObjectLayoutBase* layout, IShaderObject** outObject)
        override;

    virtual SLANG_NO_THROW Result SLANG_MCALL
        createProgram(const IShaderProgram::Desc& desc, IShaderProgram** outProgram) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
        const GraphicsPipelineStateDesc& desc, IPipelineState** outState) override;
    virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
        const ComputePipelineStateDesc& desc, IPipelineState** outState) override;

    virtual SLANG_NO_THROW SlangResult SLANG_MCALL readTextureResource(
        ITextureResource* resource,
        ResourceState state,
        ISlangBlob** outBlob,
        size_t* outRowPitch,
        size_t* outPixelSize) override;

    virtual SLANG_NO_THROW SlangResult SLANG_MCALL readBufferResource(
        IBufferResource* resource,
        size_t offset,
        size_t size,
        ISlangBlob** outBlob) override;

    virtual SLANG_NO_THROW const DeviceInfo& SLANG_MCALL getDeviceInfo() const override
    {
        return m_info;
    }

    ~D3D12Device();

public:
    
    static const Int kMaxNumRenderFrames = 4;
    static const Int kMaxNumRenderTargets = 3;

    static const Int kMaxRTVCount = 8;
    static const Int kMaxDescriptorSetCount = 16;

    struct DeviceInfo
    {
        void clear()
        {
            m_dxgiFactory.setNull();
            m_device.setNull();
            m_adapter.setNull();
            m_desc = {}; 
            m_desc1 = {};
            m_isWarp = false;
        }

        bool m_isWarp;
        ComPtr<IDXGIFactory> m_dxgiFactory;
        ComPtr<ID3D12Device> m_device;
        ComPtr<IDXGIAdapter> m_adapter;
        DXGI_ADAPTER_DESC m_desc;
        DXGI_ADAPTER_DESC1 m_desc1;
    };

    struct Submitter
    {
        virtual void setRootConstantBufferView(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) = 0;
        virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0;
        virtual void setRootSignature(ID3D12RootSignature* rootSignature) = 0;
        virtual void setRootConstants(Index rootParamIndex, Index dstOffsetIn32BitValues, Index countOf32BitValues, void const* srcData) = 0;
    };

    class BufferResourceImpl: public gfx::BufferResource
    {
    public:
        typedef BufferResource Parent;

        BufferResourceImpl(IResource::Usage initialUsage, const Desc& desc):
            Parent(desc), m_initialUsage(initialUsage)
            , m_defaultState(_calcResourceState(initialUsage))
        {
        }

        D3D12Resource m_resource;           ///< The resource typically in gpu memory
        D3D12Resource m_uploadResource;     ///< If the resource can be written to, and is in gpu memory (ie not Memory backed), will have upload resource

        Usage m_initialUsage;
        D3D12_RESOURCE_STATES m_defaultState;
    };

    class TextureResourceImpl: public TextureResource
    {
    public:
        typedef TextureResource Parent;

        TextureResourceImpl(const Desc& desc):
            Parent(desc)
        {
            m_defaultState = _calcResourceState(desc.initialUsage);
        }

        D3D12Resource m_resource;
        D3D12_RESOURCE_STATES m_defaultState;
    };

    class SamplerStateImpl : public ISamplerState, public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        ISamplerState* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_ISamplerState)
                return static_cast<ISamplerState*>(this);
            return nullptr;
        }
    public:
        D3D12Descriptor m_descriptor;
        D3D12Device* m_renderer;
        ~SamplerStateImpl()
        {
            m_renderer->m_cpuSamplerHeap.free(m_descriptor);
        }
    };

    class ResourceViewImpl : public IResourceView, public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        IResourceView* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResourceView)
                return static_cast<IResourceView*>(this);
            return nullptr;
        }
    public:
        RefPtr<Resource>            m_resource;
        D3D12Descriptor  m_descriptor;
        D3D12GeneralDescriptorHeap* m_allocator;
        ~ResourceViewImpl()
        {
            m_allocator->free(m_descriptor);
        }
    };

    class FramebufferLayoutImpl
        : public IFramebufferLayout
        , public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        IFramebufferLayout* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IFramebufferLayout)
                return static_cast<IFramebufferLayout*>(this);
            return nullptr;
        }

    public:
        ShortList<IFramebufferLayout::AttachmentLayout> m_renderTargets;
        bool m_hasDepthStencil = false;
        IFramebufferLayout::AttachmentLayout m_depthStencil;
    };

    class FramebufferImpl
        : public IFramebuffer
        , public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        IFramebuffer* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IFramebuffer)
                return static_cast<IFramebuffer*>(this);
            return nullptr;
        }

    public:
        ShortList<ComPtr<IResourceView>> renderTargetViews;
        ComPtr<IResourceView> depthStencilView;
        ShortList<D3D12_CPU_DESCRIPTOR_HANDLE> renderTargetDescriptors;
        struct Color4f
        {
            float values[4];
        };
        ShortList<Color4f> renderTargetClearValues;
        D3D12_CPU_DESCRIPTOR_HANDLE depthStencilDescriptor;
        DepthStencilClearValue depthStencilClearValue;
    };

    class RenderPassLayoutImpl : public SimpleRenderPassLayout
    {
    public:
        RefPtr<FramebufferLayoutImpl> m_framebufferLayout;
        void init(const IRenderPassLayout::Desc& desc)
        {
            SimpleRenderPassLayout::init(desc);
            m_framebufferLayout = static_cast<FramebufferLayoutImpl*>(desc.framebufferLayout);
        }
    };

    class InputLayoutImpl: public IInputLayout, public RefObject
	{
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        IInputLayout* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IInputLayout)
                return static_cast<IInputLayout*>(this);
            return nullptr;
        }
    public:
        List<D3D12_INPUT_ELEMENT_DESC> m_elements;
        List<char> m_text;                              ///< Holds all strings to keep in scope
    };

    class PipelineStateImpl : public PipelineStateBase
    {
    public:
        ComPtr<ID3D12PipelineState> m_pipelineState;
        void init(const GraphicsPipelineStateDesc& inDesc)
        {
            PipelineStateDesc pipelineDesc;
            pipelineDesc.type = PipelineType::Graphics;
            pipelineDesc.graphics = inDesc;
            initializeBase(pipelineDesc);
        }
        void init(const ComputePipelineStateDesc& inDesc)
        {
            PipelineStateDesc pipelineDesc;
            pipelineDesc.type = PipelineType::Compute;
            pipelineDesc.compute = inDesc;
            initializeBase(pipelineDesc);
        }
    };

    struct BoundVertexBuffer
    {
        RefPtr<BufferResourceImpl> m_buffer;
        int m_stride;
        int m_offset;
    };

    struct GraphicsSubmitter : public Submitter
    {
        virtual void setRootConstantBufferView(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override
        {
            m_commandList->SetGraphicsRootConstantBufferView(index, gpuBufferLocation);
        }
        virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor) override
        {
            m_commandList->SetGraphicsRootDescriptorTable(index, baseDescriptor);
        }
        void setRootSignature(ID3D12RootSignature* rootSignature)
        {
            m_commandList->SetGraphicsRootSignature(rootSignature);
        }
        void setRootConstants(
            Index rootParamIndex,
            Index dstOffsetIn32BitValues,
            Index countOf32BitValues,
            void const* srcData) override
        {
            m_commandList->SetGraphicsRoot32BitConstants(UINT(rootParamIndex), UINT(countOf32BitValues), srcData, UINT(dstOffsetIn32BitValues));
        }

        GraphicsSubmitter(ID3D12GraphicsCommandList* commandList):
            m_commandList(commandList)
        {
        }

        ID3D12GraphicsCommandList* m_commandList;
    };

    struct ComputeSubmitter : public Submitter
    {
        virtual void setRootConstantBufferView(int index, D3D12_GPU_VIRTUAL_ADDRESS gpuBufferLocation) override
        {
            m_commandList->SetComputeRootConstantBufferView(index, gpuBufferLocation);
        }
        virtual void setRootDescriptorTable(int index, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor) override
        {
            m_commandList->SetComputeRootDescriptorTable(index, baseDescriptor);
        }
        void setRootSignature(ID3D12RootSignature* rootSignature)
        {
            m_commandList->SetComputeRootSignature(rootSignature);
        }
        void setRootConstants(
            Index rootParamIndex,
            Index dstOffsetIn32BitValues,
            Index countOf32BitValues,
            void const* srcData) override
        {
            m_commandList->SetComputeRoot32BitConstants(UINT(rootParamIndex), UINT(countOf32BitValues), srcData, UINT(dstOffsetIn32BitValues));
        }

        ComputeSubmitter(ID3D12GraphicsCommandList* commandList) :
            m_commandList(commandList)
        {
        }

        ID3D12GraphicsCommandList* m_commandList;
    };

    static void _initBufferResourceDesc(size_t bufferSize, D3D12_RESOURCE_DESC& out)
    {
        out = {};

        out.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
        out.Alignment = 0;
        out.Width = bufferSize;
        out.Height = 1;
        out.DepthOrArraySize = 1;
        out.MipLevels = 1;
        out.Format = DXGI_FORMAT_UNKNOWN;
        out.SampleDesc.Count = 1;
        out.SampleDesc.Quality = 0;
        out.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
        out.Flags = D3D12_RESOURCE_FLAG_NONE;
    }

    static Result _uploadBufferData(
        ID3D12GraphicsCommandList* cmdList,
        BufferResourceImpl* buffer,
        size_t offset,
        size_t size,
        void* data)
    {
        D3D12_RANGE readRange = {};
        readRange.Begin = offset;
        readRange.End = offset + size;

        void* uploadData;
        SLANG_RETURN_ON_FAIL(buffer->m_uploadResource.getResource()->Map(
            0, &readRange, reinterpret_cast<void**>(&uploadData)));
        memcpy((uint8_t*)uploadData + offset, data, size);
        buffer->m_uploadResource.getResource()->Unmap(0, &readRange);
        {
            D3D12BarrierSubmitter submitter(cmdList);
            submitter.transition(
                buffer->m_resource, buffer->m_defaultState, D3D12_RESOURCE_STATE_COPY_DEST);
        }
        cmdList->CopyBufferRegion(
            buffer->m_resource.getResource(),
            offset,
            buffer->m_uploadResource.getResource(),
            offset,
            size);
        {
            D3D12BarrierSubmitter submitter(cmdList);
            submitter.transition(
                buffer->m_resource, D3D12_RESOURCE_STATE_COPY_DEST, buffer->m_defaultState);
        }
        return SLANG_OK;
    }
    
    class TransientResourceHeapImpl
        : public TransientResourceHeapBase<D3D12Device, BufferResourceImpl>
    {
    private:
        typedef TransientResourceHeapBase<D3D12Device, BufferResourceImpl> Super;
    public:
        ComPtr<ID3D12CommandAllocator> m_commandAllocator;
        List<ComPtr<ID3D12GraphicsCommandList>> m_d3dCommandListPool;
        List<ComPtr<ICommandBuffer>> m_commandBufferPool;
        uint32_t m_commandListAllocId = 0;
        // Wait values for each command queue.
        struct QueueWaitInfo
        {
            uint64_t waitValue;
            HANDLE fenceEvent;
        };
        ShortList<QueueWaitInfo, 4> m_waitInfos;

        QueueWaitInfo& getQueueWaitInfo(uint32_t queueIndex)
        {
            if (queueIndex < (uint32_t)m_waitInfos.getCount())
            {
                return m_waitInfos[queueIndex];
            }
            auto oldCount = m_waitInfos.getCount();
            m_waitInfos.setCount(queueIndex + 1);
            for (auto i = oldCount; i < m_waitInfos.getCount(); i++)
            {
                m_waitInfos[i].waitValue = 0;
                m_waitInfos[i].fenceEvent = CreateEventEx(
                    nullptr,
                    false,
                    CREATE_EVENT_INITIAL_SET | CREATE_EVENT_MANUAL_RESET,
                    EVENT_ALL_ACCESS);
            }
            return m_waitInfos[queueIndex];
        }
        // During command submission, we need all the descriptor tables that get
        // used to come from a single heap (for each descriptor heap type).
        //
        // We will thus keep a single heap of each type that we hope will hold
        // all the descriptors that actually get needed in a frame.
        D3D12DescriptorHeap m_viewHeap; // Cbv, Srv, Uav
        D3D12DescriptorHeap m_samplerHeap; // Heap for samplers

        ~TransientResourceHeapImpl()
        {
            synchronizeAndReset();
            for (auto& waitInfo : m_waitInfos)
                CloseHandle(waitInfo.fenceEvent);
        }

        Result init(
            const ITransientResourceHeap::Desc& desc,
            D3D12Device* device,
            uint32_t viewHeapSize,
            uint32_t samplerHeapSize)
        {
            Super::init(desc, device);
            auto d3dDevice = device->m_device;
            SLANG_RETURN_ON_FAIL(d3dDevice->CreateCommandAllocator(
                D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(m_commandAllocator.writeRef())));
            
            SLANG_RETURN_ON_FAIL(m_viewHeap.init(
                d3dDevice,
                viewHeapSize,
                D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
                D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE));
            SLANG_RETURN_ON_FAIL(m_samplerHeap.init(
                d3dDevice,
                samplerHeapSize,
                D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
                D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE));

            if (desc.constantBufferSize != 0)
            {
                ComPtr<IBufferResource> bufferResourcePtr;
                IBufferResource::Desc bufferDesc;
                bufferDesc.init(desc.constantBufferSize);
                bufferDesc.cpuAccessFlags |= IResource::AccessFlag::Write;
                SLANG_RETURN_ON_FAIL(device->createBufferResource(
                    IResource::Usage::ConstantBuffer,
                    bufferDesc,
                    nullptr,
                    bufferResourcePtr.writeRef()));
                m_constantBuffers.add(static_cast<BufferResourceImpl*>(bufferResourcePtr.get()));
            }
            return SLANG_OK;
        }

        virtual SLANG_NO_THROW Result SLANG_MCALL
            createCommandBuffer(ICommandBuffer** outCommandBuffer) override;

        virtual SLANG_NO_THROW Result SLANG_MCALL synchronizeAndReset() override;
    };

    class CommandBufferImpl;

    class PipelineCommandEncoder
    {
    public:
        bool m_isOpen = false;
        bool m_bindingDirty = true;
        CommandBufferImpl* m_commandBuffer;
        TransientResourceHeapImpl* m_transientHeap;
        D3D12Device* m_renderer;
        ID3D12Device* m_device;
        ID3D12GraphicsCommandList* m_d3dCmdList;
        ID3D12GraphicsCommandList* m_preCmdList = nullptr;

        RefPtr<PipelineStateImpl> m_currentPipeline;

        static int getBindPointIndex(PipelineType type)
        {
            switch (type)
            {
            case PipelineType::Graphics:
                return 0;
            case PipelineType::Compute:
                return 1;
            case PipelineType::RayTracing:
                return 2;
            default:
                assert(!"unknown pipeline type.");
                return -1;
            }
        }

        void init(CommandBufferImpl* commandBuffer)
        {
            m_commandBuffer = commandBuffer;
            m_d3dCmdList = m_commandBuffer->m_cmdList;
            m_renderer = commandBuffer->m_renderer;
            m_transientHeap = commandBuffer->m_transientHeap;
        }

        void endEncodingImpl() { m_isOpen = false; }

        Result bindPipelineImpl(IPipelineState* pipelineState, IShaderObject** outRootObject)
        {
            m_currentPipeline = static_cast<PipelineStateImpl*>(pipelineState);
            auto rootObject = &m_commandBuffer->m_rootShaderObject;
            SLANG_RETURN_ON_FAIL(rootObject->reset(
                m_renderer,
                m_currentPipeline->getProgram<ShaderProgramImpl>()->m_rootObjectLayout,
                m_commandBuffer->m_transientHeap));
            *outRootObject = rootObject;
            m_bindingDirty = true;
            return SLANG_OK;
        }

        Result _bindRenderState(Submitter* submitter);
    };

    struct DescriptorTable
    {
        DescriptorHeapReference heap;
        uint32_t table;
    };

    struct BindingOffset
    {
        int32_t resource;
        int32_t sampler;
    };

    struct RootBindingState
    {
        TransientResourceHeapImpl* transientHeap;
        D3D12Device* device;
        ArrayView<DescriptorTable> descriptorTables;
        BindingOffset offset;
        uint32_t rootParamIndex; // The root parameter index of this object.
        uint32_t futureRootParamOffset; // The starting offset of additional sub-object descriptor tables.
    };

    struct DescriptorSetInfo
    {
        uint32_t resourceDescriptorCount = 0;
        uint32_t samplerDescriptorCount = 0;
    };

    struct BindingLocation
    {
        int32_t index;
        BindingOffset offsetInDescriptorTable;
    };

    // Provides information on how binding ranges are stored in descriptor tables for
    // a shader object.
    // We allocate one CPU descriptor table for each descriptor heap type for the shader
    // object. In `ShaderObjectLayoutImpl`, we store the offset into the descriptor tables
    // for each binding, so we know where to write the descriptor when the user sets
    // a resource or sampler binding.
    class ShaderObjectLayoutImpl : public ShaderObjectLayoutBase
    {
    public:
        struct BindingRangeInfo
        {
            slang::BindingType bindingType;
            uint32_t count;
            uint32_t spaceIndex;
            uint32_t flatResourceOffset; // Offset in flattend array of resource binding slots.
            BindingLocation binding;

            // Returns true if this binding range consumes a specialization argument slot.
            bool isSpecializationArg() const
            {
                return bindingType == slang::BindingType::ExistentialValue;
            }
        };
        struct SubObjectRangeInfo
        {
            RefPtr<ShaderObjectLayoutImpl> layout;
            Index bindingRangeIndex;
            slang::BindingType bindingType;

            // The offset for the constant buffer descriptor if this
            // sub-object is referenced as a `ConstantBuffer<T>`.
            // For a `ParameterBlock` binding range, this is always 0 since
            // parameter blocks start in a fresh descriptor table.
            BindingOffset descriptorOffset;
        };

        struct Builder
        {
        public:
            Builder(RendererBase* renderer)
                : m_renderer(renderer)
            {}

            RendererBase* m_renderer;
            slang::TypeLayoutReflection* m_elementTypeLayout;
            List<BindingRangeInfo> m_bindingRanges;
            List<SubObjectRangeInfo> m_subObjectRanges;
            DescriptorSetInfo m_descriptorSetInfo;
            uint32_t m_subObjectCount = 0;
            uint32_t m_flatResourceCount = 0;

            void addBindingRangesOfType(slang::TypeLayoutReflection* typeLayout)
            {
                SlangInt bindingRangeCount = typeLayout->getBindingRangeCount();

                // Reserve CBV slot for the implicit constant buffer if the type contains
                // ordinary uniform data fields.
                if (typeLayout->getSize(slang::ParameterCategory::Uniform) != 0)
                {
                    m_descriptorSetInfo.resourceDescriptorCount = 1;
                }

                for (SlangInt r = 0; r < bindingRangeCount; ++r)
                {
                    slang::BindingType slangBindingType = typeLayout->getBindingRangeType(r);
                    uint32_t count = (uint32_t)typeLayout->getBindingRangeBindingCount(r);
                    slang::TypeLayoutReflection* slangLeafTypeLayout =
                        typeLayout->getBindingRangeLeafTypeLayout(r);
                    BindingRangeInfo bindingRangeInfo = {};
                    bindingRangeInfo.bindingType = slangBindingType;
                    bindingRangeInfo.count = count;
                    bindingRangeInfo.flatResourceOffset = m_flatResourceCount;
                    bindingRangeInfo.spaceIndex =
                        (uint32_t)typeLayout->getBindingRangeDescriptorSetIndex(r);

                    switch (slangBindingType)
                    {
                    case slang::BindingType::ConstantBuffer:
                    case slang::BindingType::ParameterBlock:
                    case slang::BindingType::ExistentialValue:
                        bindingRangeInfo.binding.index = m_subObjectCount;
                        m_subObjectCount += count;
                        break;

                    case slang::BindingType::Sampler:
                        bindingRangeInfo.binding.offsetInDescriptorTable.sampler =
                            m_descriptorSetInfo.samplerDescriptorCount;
                        m_descriptorSetInfo.samplerDescriptorCount += count;
                        break;

                    case slang::BindingType::CombinedTextureSampler:
                        bindingRangeInfo.binding.offsetInDescriptorTable.sampler =
                            m_descriptorSetInfo.samplerDescriptorCount;
                        bindingRangeInfo.binding.offsetInDescriptorTable.resource =
                            m_descriptorSetInfo.resourceDescriptorCount;
                        m_descriptorSetInfo.samplerDescriptorCount += count;
                        m_descriptorSetInfo.resourceDescriptorCount += count;
                        m_flatResourceCount += count;
                        break;

                    case slang::BindingType::MutableRawBuffer:
                    case slang::BindingType::MutableTexture:
                    case slang::BindingType::MutableTypedBuffer:
                        bindingRangeInfo.binding.offsetInDescriptorTable.resource =
                            m_descriptorSetInfo.resourceDescriptorCount;
                        m_descriptorSetInfo.resourceDescriptorCount += count;
                        m_flatResourceCount += count;
                        break;

                    case slang::BindingType::VaryingInput:
                    case slang::BindingType::VaryingOutput:
                        break;

                    default:
                        bindingRangeInfo.binding.offsetInDescriptorTable.resource =
                            m_descriptorSetInfo.resourceDescriptorCount;
                        m_descriptorSetInfo.resourceDescriptorCount += count;
                        m_flatResourceCount += count;
                        break;
                    }
                    m_bindingRanges.add(bindingRangeInfo);
                }
            }

            Result setElementTypeLayout(slang::TypeLayoutReflection* typeLayout)
            {
                typeLayout = _unwrapParameterGroups(typeLayout);

                m_elementTypeLayout = typeLayout;

                // Compute the binding ranges that are used to store
                // the logical contents of the object in memory.

                addBindingRangesOfType(typeLayout);

                SlangInt subObjectRangeCount = typeLayout->getSubObjectRangeCount();
                for (SlangInt r = 0; r < subObjectRangeCount; ++r)
                {
                    SlangInt bindingRangeIndex = typeLayout->getSubObjectRangeBindingRangeIndex(r);
                    auto slangBindingType = typeLayout->getBindingRangeType(bindingRangeIndex);
                    slang::TypeLayoutReflection* slangLeafTypeLayout =
                        typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex);

                    // A sub-object range can either represent a sub-object of a known
                    // type, like a `ConstantBuffer<Foo>` or `ParameterBlock<Foo>`
                    // (in which case we can pre-compute a layout to use, based on
                    // the type `Foo`) *or* it can represent a sub-object of some
                    // existential type (e.g., `IBar`) in which case we cannot
                    // know the appropraite type/layout of sub-object to allocate.
                    //
                    RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
                    if (slangBindingType != slang::BindingType::ExistentialValue)
                    {
                        createForElementType(
                            m_renderer,
                            slangLeafTypeLayout->getElementTypeLayout(),
                            subObjectLayout.writeRef());
                    }

                    SubObjectRangeInfo subObjectRange;
                    subObjectRange.bindingRangeIndex = bindingRangeIndex;
                    subObjectRange.layout = subObjectLayout;
                    subObjectRange.bindingType = slangBindingType;
                    subObjectRange.descriptorOffset.resource =
                        m_descriptorSetInfo.resourceDescriptorCount;
                    subObjectRange.descriptorOffset.sampler =
                        m_descriptorSetInfo.samplerDescriptorCount;
                    m_subObjectRanges.add(subObjectRange);
                }

                return SLANG_OK;
            }

            SlangResult build(ShaderObjectLayoutImpl** outLayout)
            {
                auto layout = RefPtr<ShaderObjectLayoutImpl>(new ShaderObjectLayoutImpl());
                SLANG_RETURN_ON_FAIL(layout->_init(this));

                *outLayout = layout.detach();
                return SLANG_OK;
            }
        };

        static Result createForElementType(
            RendererBase* renderer,
            slang::TypeLayoutReflection* elementType,
            ShaderObjectLayoutImpl** outLayout)
        {
            Builder builder(renderer);
            builder.setElementTypeLayout(elementType);
            return builder.build(outLayout);
        }

        List<BindingRangeInfo> const& getBindingRanges() { return m_bindingRanges; }

        Index getBindingRangeCount() { return m_bindingRanges.getCount(); }

        BindingRangeInfo const& getBindingRange(Index index) { return m_bindingRanges[index]; }

        DescriptorSetInfo getDescriptorSetInfo() { return m_descriptorSetInfo; }

        slang::TypeLayoutReflection* getElementTypeLayout() { return m_elementTypeLayout; }

        uint32_t getResourceCount() { return m_resourceSlotCount; }

        Index getSubObjectCount() { return m_subObjectCount; }

        SubObjectRangeInfo const& getSubObjectRange(Index index)
        {
            return m_subObjectRanges[index];
        }
        List<SubObjectRangeInfo> const& getSubObjectRanges() { return m_subObjectRanges; }

        RendererBase* getRenderer() { return m_renderer; }

        slang::TypeReflection* getType() { return m_elementTypeLayout->getType(); }

    protected:
        Result _init(Builder* builder)
        {
            auto renderer = builder->m_renderer;

            initBase(renderer, builder->m_elementTypeLayout);

            m_descriptorSetInfo = builder->m_descriptorSetInfo;
            m_bindingRanges = _Move(builder->m_bindingRanges);
            m_subObjectCount = builder->m_subObjectCount;
            m_subObjectRanges = builder->m_subObjectRanges;
            m_resourceSlotCount = builder->m_flatResourceCount;
            return SLANG_OK;
        }

        List<BindingRangeInfo> m_bindingRanges;
        DescriptorSetInfo m_descriptorSetInfo;
        Index m_subObjectCount = 0;
        List<SubObjectRangeInfo> m_subObjectRanges;
        uint32_t m_resourceSlotCount;
    };

    class RootShaderObjectLayoutImpl : public ShaderObjectLayoutImpl
    {
        typedef ShaderObjectLayoutImpl Super;

    public:
        struct EntryPointInfo
        {
            RefPtr<ShaderObjectLayoutImpl> layout;
        };

        struct Builder : Super::Builder
        {
            Builder(
                RendererBase* renderer,
                slang::IComponentType* program,
                slang::ProgramLayout* programLayout)
                : Super::Builder(renderer)
                , m_program(program)
                , m_programLayout(programLayout)
            {}

            Result build(RootShaderObjectLayoutImpl** outLayout)
            {
                RefPtr<RootShaderObjectLayoutImpl> layout = new RootShaderObjectLayoutImpl();
                SLANG_RETURN_ON_FAIL(layout->_init(this));

                *outLayout = layout.detach();
                return SLANG_OK;
            }

            void addGlobalParams(slang::VariableLayoutReflection* globalsLayout)
            {
                setElementTypeLayout(globalsLayout->getTypeLayout());
            }

            void addEntryPoint(SlangStage stage, ShaderObjectLayoutImpl* entryPointLayout)
            {
                EntryPointInfo info;
                info.layout = entryPointLayout;
                m_entryPoints.add(info);
            }

            slang::IComponentType* m_program;
            slang::ProgramLayout* m_programLayout;
            List<EntryPointInfo> m_entryPoints;
        };

        EntryPointInfo& getEntryPoint(Index index) { return m_entryPoints[index]; }

        List<EntryPointInfo>& getEntryPoints() { return m_entryPoints; }

        struct DescriptorSetLayout
        {
            List<D3D12_DESCRIPTOR_RANGE> m_resourceRanges;
            List<D3D12_DESCRIPTOR_RANGE> m_samplerRanges;
            uint32_t m_resourceCount = 0;
            uint32_t m_samplerCount = 0;
        };

        struct RootSignatureDescBuilder
        {
            // We will use one descriptor set for the global scope and one additional
            // descriptor set for each `ParameterBlock` binding range in the shader object
            // hierarchy, regardless of the shader's `space` indices.
            List<DescriptorSetLayout> m_descriptorSets;
            List<D3D12_ROOT_PARAMETER> m_rootParameters;
            D3D12_ROOT_SIGNATURE_DESC m_rootSignatureDesc = {};

            static Result translateDescriptorRangeType(
                slang::BindingType c,
                D3D12_DESCRIPTOR_RANGE_TYPE* outType)
            {
                switch (c)
                {
                case slang::BindingType::ConstantBuffer:
                    *outType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
                    return SLANG_OK;
                case slang::BindingType::RawBuffer:
                case slang::BindingType::Texture:
                case slang::BindingType::TypedBuffer:
                    *outType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
                    return SLANG_OK;
                case slang::BindingType::MutableRawBuffer:
                case slang::BindingType::MutableTexture:
                case slang::BindingType::MutableTypedBuffer:
                    *outType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
                    return SLANG_OK;
                case slang::BindingType::Sampler:
                    *outType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
                    return SLANG_OK;
                default:
                    return SLANG_FAIL;
                }
            }

                /// Stores offset information to apply to the reflected register/space for a descriptor range.
                ///
            struct BindingRegisterOffset
            {
                uint32_t spaceOffset = 0; // The `space` index as specified in shader.

                    /// An offset to apply for each D3D12 register class, as given
                    /// by a `D3D12_DESCRIPTOR_RANGE_TYPE`.
                    ///
                    /// Note that the `D3D12_DESCRIPTOR_RANGE_TYPE` enumeration has
                    /// values between 0 and 3, inclusive.
                    ///
                uint32_t offsetForRangeType[4] = {0, 0, 0, 0};

                uint32_t& operator[](D3D12_DESCRIPTOR_RANGE_TYPE type)
                {
                    return offsetForRangeType[int(type)];
                }

                uint32_t operator[](D3D12_DESCRIPTOR_RANGE_TYPE type) const
                {
                    return offsetForRangeType[int(type)];
                }
            };

                /// Add a new descriptor set to the layout being computed.
                ///
                /// Note that a "descriptor set" in the layout may amount to
                /// zero, one, or two different descriptor *tables* in the
                /// final D3D12 root signature. Each descriptor set may
                /// contain zero or more view ranges (CBV/SRV/UAV) and zero
                /// or more sampler ranges. It maps to a view descriptor table
                /// if the number of view ranges is non-zero and to a sampler
                /// descriptor table if the number of sampler ranges is non-zero.
                ///
            uint32_t addDescriptorSet()
            {
                auto result = (uint32_t) m_descriptorSets.getCount();
                m_descriptorSets.add(DescriptorSetLayout{});
                return result;
            }

                /// Add one descriptor range as specified in Slang reflection information to the layout.
                ///
                /// The layout information is taken from `typeLayout` for the descriptor
                /// range with the given `descriptorRangeIndex` within the logical
                /// descriptor set (reflected by Slang) with the given `logicalDescriptorSetIndex`.
                ///
                /// The `physicalDescriptorSetIndex` is the index in the `m_descriptorSets` array of
                /// the descriptor set that the range should be added to.
                ///
                /// The `offset` encodes information about space and/or register offsets that
                /// should be applied to descrptor ranges.
                ///
                /// This operation can fail if the given descriptor range encodes a range that
                /// doesn't map to anything directly supported by D3D12. Higher-level routines
                /// will often want to ignore such failures.
                ///
            Result addDescriptorRange(
                slang::TypeLayoutReflection*    typeLayout,
                Index                           physicalDescriptorSetIndex,
                BindingRegisterOffset const&    offset,
                Index                           logicalDescriptorSetIndex,
                Index                           descriptorRangeIndex)
            {
                auto& descriptorSet = m_descriptorSets[physicalDescriptorSetIndex];

                auto bindingType = typeLayout->getDescriptorSetDescriptorRangeType(logicalDescriptorSetIndex, descriptorRangeIndex);
                auto count = typeLayout->getDescriptorSetDescriptorRangeDescriptorCount(logicalDescriptorSetIndex, descriptorRangeIndex);
                auto index = typeLayout->getDescriptorSetDescriptorRangeIndexOffset(logicalDescriptorSetIndex, descriptorRangeIndex);
                auto space = typeLayout->getDescriptorSetSpaceOffset(logicalDescriptorSetIndex);

                D3D12_DESCRIPTOR_RANGE_TYPE rangeType;
                SLANG_RETURN_ON_FAIL(translateDescriptorRangeType(bindingType, &rangeType));

                D3D12_DESCRIPTOR_RANGE range = {};
                range.RangeType = rangeType;
                range.NumDescriptors = (UINT) count;
                range.BaseShaderRegister = (UINT) index + offset[rangeType];
                range.RegisterSpace = (UINT) space;
                range.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;

                if (range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER)
                {
                    descriptorSet.m_samplerRanges.add(range);
                    descriptorSet.m_samplerCount += range.NumDescriptors;
                }
                else
                {
                    descriptorSet.m_resourceRanges.add(range);
                    descriptorSet.m_resourceCount += range.NumDescriptors;
                }

                return SLANG_OK;
            }

                /// Add one binding range to the computed layout.
                ///
                /// The layout information is taken from `typeLayout` for the binding
                /// range with the given `bindingRangeIndex`.
                ///
                /// The `physicalDescriptorSetIndex` is the index in the `m_descriptorSets` array of
                /// the descriptor set that the range should be added to.
                ///
                /// The `offset` encodes information about space and/or register offsets that
                /// should be applied to descrptor ranges.
                ///
                /// Note that a single binding range may encompass zero or more descriptor ranges.
                ///
            void addBindingRange(
                slang::TypeLayoutReflection*    typeLayout,
                Index                           physicalDescriptorSetIndex,
                BindingRegisterOffset const&    offset,
                Index                           bindingRangeIndex)
            {
                auto logicalDescriptorSetIndex  = typeLayout->getBindingRangeDescriptorSetIndex(bindingRangeIndex);
                auto firstDescriptorRangeIndex  = typeLayout->getBindingRangeFirstDescriptorRangeIndex(bindingRangeIndex);
                Index descriptorRangeCount      = typeLayout->getBindingRangeDescriptorRangeCount(bindingRangeIndex);
                for( Index i = 0; i < descriptorRangeCount; ++i )
                {
                    auto descriptorRangeIndex = firstDescriptorRangeIndex + i;

                    // Note: we ignore the `Result` returned by `addDescriptorRange()` because we
                    // want to silently skip any ranges that represent kinds of bindings that
                    // don't actually exist in D3D12.
                    //
                    addDescriptorRange(typeLayout, physicalDescriptorSetIndex, offset, logicalDescriptorSetIndex, descriptorRangeIndex);
                }
            }

                /// Add binding ranges and parameter blocks to the root signature.
                ///
                /// The layout information is taken from `varLayout` which should
                /// be a layout for either a program or an entry point.
                ///
                /// The `physicalDescriptorSetIndex` is the index in the `m_descriptorSets` array of
                /// the descriptor set that binding ranges not belonging to nested
                /// parameter blocks should be added to.
                ///
                /// This routine will use absolute offset information computed from `varLayout`
                /// to apply appropriate space/register offsets to the bindings and parameter
                ///  blocks inside the layout.
                ///
            void addBindingRangesAndParameterBlocks(
                slang::VariableLayoutReflection*    varLayout,
                Index                               physicalDescriptorSetIndex)
            {
                BindingRegisterOffset offset;
                offset.spaceOffset                          = (UINT) varLayout->getOffset(SLANG_PARAMETER_CATEGORY_REGISTER_SPACE);
                offset[D3D12_DESCRIPTOR_RANGE_TYPE_CBV]     = (UINT) varLayout->getOffset(SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER);
                offset[D3D12_DESCRIPTOR_RANGE_TYPE_SRV]     = (UINT) varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE);
                offset[D3D12_DESCRIPTOR_RANGE_TYPE_UAV]     = (UINT) varLayout->getOffset(SLANG_PARAMETER_CATEGORY_UNORDERED_ACCESS);
                offset[D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER] = (UINT) varLayout->getOffset(SLANG_PARAMETER_CATEGORY_SAMPLER_STATE);

                addBindingRangesAndParameterBlocks(varLayout->getTypeLayout(), physicalDescriptorSetIndex, offset);
            }

                /// Add binding ranges and parameter blocks to the root signature.
                ///
                /// The layout information is taken from `typeLayout` which should
                /// be a layout for either a program or an entry point.
                ///
                /// The `physicalDescriptorSetIndex` is the index in the `m_descriptorSets` array of
                /// the descriptor set that binding ranges not belonging to nested
                /// parameter blocks should be added to.
                ///
                /// The `offset` encodes information about space and/or register offsets that
                /// should be applied to descrptor ranges.
                ///
            void addBindingRangesAndParameterBlocks(
                slang::TypeLayoutReflection*        typeLayout,
                Index                               physicalDescriptorSetIndex,
                BindingRegisterOffset const&        offset)
            {
                // Our first task is to add the binding ranges for stuff that is
                // directly contained in `typeLayout` rather than via sub-objects.
                //
                // Our goal is to have the descriptors for directly-contained views/samplers
                // always be contiguous in CPU and GPU memory, so that we can write
                // to them easily with a single operaiton.
                //
                Index bindingRangeCount = typeLayout->getBindingRangeCount();
                for (Index bindingRangeIndex = 0; bindingRangeIndex < bindingRangeCount; bindingRangeIndex++)
                {
                    // We will look at the type of each binding range and intentionally
                    // skip those that represent sub-objects.
                    //
                    auto bindingType = typeLayout->getBindingRangeType(bindingRangeIndex);
                    switch(bindingType)
                    {
                    case slang::BindingType::ConstantBuffer:
                    case slang::BindingType::ParameterBlock:
                    case slang::BindingType::ExistentialValue:
                        continue;

                    default:
                        break;
                    }

                    // For binding ranges that don't represent sub-objects, we will add
                    // all of the descriptor ranges they encompass to the root signature.
                    //
                    addBindingRange(typeLayout, physicalDescriptorSetIndex, offset, bindingRangeIndex);
                }

                // Next we need to recurse on the various sub-objects that the type might contain.
                // 
                Index subObjectCount = typeLayout->getSubObjectRangeCount();
                for (Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectCount; subObjectRangeIndex++)
                {
                    // There are a few different concerns being tackled at once here, which depend on
                    // the type of each sub-object range.
                    //
                    auto bindingRangeIndex = typeLayout->getSubObjectRangeBindingRangeIndex(subObjectRangeIndex);
                    auto bindingType = typeLayout->getBindingRangeType(bindingRangeIndex);
                    switch (bindingType)
                    {
                    case slang::BindingType::ConstantBuffer:
                        {
                            // Constant buffer ranges (for `ConstantBuffer<ConcreteType>`) will "leak" their
                            // binding ranges into the surrounding type, so we can add them here like any other
                            // binding range.
                            //
                            // Note: It would be valid to allow `slang::BindingType::ConstantBuffer` to be handled
                            // in the earlier loop, but that would mean that descriptor ranges coming directly
                            // from the fields of `typeLayout` could be broken up with ranges coming from constant-buffer
                            // sub-objects. By moving the handling of constant buffers to this later loop, we
                            // guarantee that the descritpors used by non-sub-object binding ranges are all
                            // contiguous.
                            //
                            addBindingRange(typeLayout, physicalDescriptorSetIndex, offset, bindingRangeIndex);
                        }
                        break;

                    case slang::BindingType::ParameterBlock:
                        {
                            // A parameter block (`ParameterBlock<ConcreteType>`) will always map to a distinct
                            // descriptor set, and its contained view/sampler binding ranges will be bound
                            // through that set.
                            //
                            auto blockPhysicalDescriptorSetIndex = addDescriptorSet();

                            // We will need to recursively add the binding ranges implied by the type of
                            // the parameter block.
                            //
                            auto blockTypeLayout = typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex);

                            // One important detail is that the `blockTypeLayout` does not know the base register
                            // space that the contents of the block should use. All descriptor ranges stored in
                            // that layout will by default use a space offset of zero.
                            //
                            // We need to compute the space offset to apply when recursing into that block type
                            // based on the binding range we are processing here.
                            //
                            auto blockLogicalDescriptorSetIndex = typeLayout->getBindingRangeDescriptorSetIndex(bindingRangeIndex);
                            auto blockSpaceOffset = typeLayout->getDescriptorSetSpaceOffset(blockLogicalDescriptorSetIndex);

                            // The space offset for this binding range should be added to any additional space
                            // offset that was being passed down from above this layer.
                            //
                            // Any other offset information (register offsets) should be ignored at this point,
                            // because `register` offsets from outside of the block don't affect layout within
                            // the block.
                            //
                            BindingRegisterOffset blockOffset;
                            blockOffset.spaceOffset = offset.spaceOffset + (uint32_t) blockSpaceOffset;

                            // Once we have all the details worked out, we can write the binding ranges for the
                            // block's type into the newly-allocated descriptor set.
                            //
                            // Note: there is an important subtlety going on here. We are passing in the type
                            // `blockTypeLayout` which corresponds to `ParameterBlock<ConcreteType>` and *not* to
                            // `ConcreteType` alone. Because of that detail, the binding/descriptor ranges will
                            // include any "default constant buffer" range that needed to be allocated based
                            // on `ConcreteType`.
                            //
                            // TODO: validate that this logic is right.
                            //
                            addBindingRangesAndParameterBlocks(blockTypeLayout, blockPhysicalDescriptorSetIndex, blockOffset);
                        }
                        break;

                    case slang::BindingType::ExistentialValue:
                        // TODO: Need to handle this case here.
                        break;

                    default:
                        break;
                    }
                }
            }

            D3D12_ROOT_SIGNATURE_DESC& build(
                List<D3D12Device::DescriptorSetInfo>& outRootDescriptorSetInfos)
            {
                for (Index i = 0; i < m_descriptorSets.getCount(); i++)
                {
                    auto& descriptorSet = m_descriptorSets[i];
                    D3D12Device::DescriptorSetInfo setInfo;
                    setInfo.resourceDescriptorCount = descriptorSet.m_resourceCount;
                    setInfo.samplerDescriptorCount = descriptorSet.m_samplerCount;
                    outRootDescriptorSetInfos.add(setInfo);
                    if (descriptorSet.m_resourceRanges.getCount())
                    {
                        D3D12_ROOT_PARAMETER rootParam = {};
                        rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
                        rootParam.DescriptorTable.NumDescriptorRanges =
                            (UINT)descriptorSet.m_resourceRanges.getCount();
                        rootParam.DescriptorTable.pDescriptorRanges =
                            descriptorSet.m_resourceRanges.getBuffer();
                        m_rootParameters.add(rootParam);
                    }
                    if (descriptorSet.m_samplerRanges.getCount())
                    {
                        D3D12_ROOT_PARAMETER rootParam = {};
                        rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
                        rootParam.DescriptorTable.NumDescriptorRanges =
                            (UINT)descriptorSet.m_samplerRanges.getCount();
                        rootParam.DescriptorTable.pDescriptorRanges =
                            descriptorSet.m_samplerRanges.getBuffer();
                        m_rootParameters.add(rootParam);
                    }
                }

                m_rootSignatureDesc.NumParameters = UINT(m_rootParameters.getCount());
                m_rootSignatureDesc.pParameters = m_rootParameters.getBuffer();

                // TODO: static samplers should be reasonably easy to support...
                m_rootSignatureDesc.NumStaticSamplers = 0;
                m_rootSignatureDesc.pStaticSamplers = nullptr;

                // TODO: only set this flag if needed (requires creating root
                // signature at same time as pipeline state...).
                //
                m_rootSignatureDesc.Flags =
                    D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;

                return m_rootSignatureDesc;
            }
        };

        static Result createRootSignatureFromSlang(
            D3D12Device* device,
            slang::IComponentType* program,
            ID3D12RootSignature** outRootSignature,
            List<DescriptorSetInfo>& outRootDescriptorSetInfos)
        {
            // We are going to build up the root signature by adding
            // binding/descritpor ranges and nested parameter blocks
            // based on the computed layout information for `program`.
            //
            RootSignatureDescBuilder builder;
            auto layout = program->getLayout();

            // The layout information computed by Slang breaks up shader
            // parameters into what we can think of as "logical" descriptor
            // sets based on whether or not parameters have the same `space`.
            //
            // We want to basically ignore that decomposition and generate a
            // single descriptor set to hold all top-level parameters, and only
            // generate distinct descriptor sets when the shader has opted in
            // via explicit parameter blocks.
            //
            // To achieve this goal, we will manually allocate a default descriptor
            // set for root parameters in our signature, and then recursively
            // add all the binding/descriptor ranges implied by the global-scope
            // parameters.
            //
            auto rootDescriptorSetIndex = builder.addDescriptorSet();
            builder.addBindingRangesAndParameterBlocks(layout->getGlobalParamsVarLayout(), rootDescriptorSetIndex);

            for (SlangUInt i = 0; i < layout->getEntryPointCount(); i++)
            {
                // Entry-point parameters should also be added to the default root
                // descriptor set.
                //
                // We add the parameters using the "variable layout" for the entry point
                // and not just its type layout, to ensure that any offset information is
                // applied correctly to the `register` and `space` information for entry-point
                // parameters.
                //
                // Note: When we start to support DXR we will need to handle entry-point parameters
                // differently because they will need to map to local root signatures rather than
                // being included in the global root signature as is being done here.
                //
                auto entryPoint = layout->getEntryPointByIndex(i);
                builder.addBindingRangesAndParameterBlocks(entryPoint->getVarLayout(), rootDescriptorSetIndex);
            }

            auto& rootSignatureDesc = builder.build(outRootDescriptorSetInfos);

            ComPtr<ID3DBlob> signature;
            ComPtr<ID3DBlob> error;
            if (SLANG_FAILED(device->m_D3D12SerializeRootSignature(
                    &rootSignatureDesc,
                    D3D_ROOT_SIGNATURE_VERSION_1,
                    signature.writeRef(),
                    error.writeRef())))
            {
                fprintf(stderr, "error: D3D12SerializeRootSignature failed");
                if (error)
                {
                    fprintf(stderr, ": %s\n", (const char*)error->GetBufferPointer());
                }
                return SLANG_FAIL;
            }

            SLANG_RETURN_ON_FAIL(device->m_device->CreateRootSignature(
                0,
                signature->GetBufferPointer(),
                signature->GetBufferSize(),
                IID_PPV_ARGS(outRootSignature)));
            return SLANG_OK;
        }

        static Result create(
            D3D12Device* device,
            slang::IComponentType* program,
            slang::ProgramLayout* programLayout,
            RootShaderObjectLayoutImpl** outLayout)
        {
            RootShaderObjectLayoutImpl::Builder builder(device, program, programLayout);
            builder.addGlobalParams(programLayout->getGlobalParamsVarLayout());

            SlangInt entryPointCount = programLayout->getEntryPointCount();
            for (SlangInt e = 0; e < entryPointCount; ++e)
            {
                auto slangEntryPoint = programLayout->getEntryPointByIndex(e);
                RefPtr<ShaderObjectLayoutImpl> entryPointLayout;
                SLANG_RETURN_ON_FAIL(ShaderObjectLayoutImpl::createForElementType(
                    device, slangEntryPoint->getTypeLayout(), entryPointLayout.writeRef()));
                builder.addEntryPoint(slangEntryPoint->getStage(), entryPointLayout);
            }

            SLANG_RETURN_ON_FAIL(builder.build(outLayout));

            if (program->getSpecializationParamCount() == 0)
            {
                // For root object, we would like know the union of all binding slots
                // including all sub-objects in the shader-object hierarchy, so at
                // parameter binding time we can easily know how many GPU descriptor tables
                // to create without walking through the shader-object hierarchy again.
                // We build out this array along with root signature construction and store
                // it in `m_gpuDescriptorSetInfos`.
                SLANG_RETURN_ON_FAIL(createRootSignatureFromSlang(
                    device,
                    program,
                    (*outLayout)->m_rootSignature.writeRef(),
                    (*outLayout)->m_gpuDescriptorSetInfos));
            }
            return SLANG_OK;
        }

        slang::IComponentType* getSlangProgram() const { return m_program; }
        slang::ProgramLayout* getSlangProgramLayout() const { return m_programLayout; }

    protected:
        Result _init(Builder* builder)
        {
            auto renderer = builder->m_renderer;

            SLANG_RETURN_ON_FAIL(Super::_init(builder));

            m_program = builder->m_program;
            m_programLayout = builder->m_programLayout;
            m_entryPoints = builder->m_entryPoints;
            return SLANG_OK;
        }

        ComPtr<slang::IComponentType> m_program;
        slang::ProgramLayout* m_programLayout = nullptr;

        List<EntryPointInfo> m_entryPoints;

    public:
        ComPtr<ID3D12RootSignature> m_rootSignature;
        List<DescriptorSetInfo> m_gpuDescriptorSetInfos;
    };

    class ShaderProgramImpl : public ShaderProgramBase
    {
    public:
        PipelineType m_pipelineType;
        List<uint8_t> m_vertexShader;
        List<uint8_t> m_pixelShader;
        List<uint8_t> m_computeShader;
        RefPtr<RootShaderObjectLayoutImpl> m_rootObjectLayout;
    };

    class ShaderObjectImpl : public ShaderObjectBase
    {
    public:
        static Result create(
            D3D12Device* device,
            ShaderObjectLayoutImpl* layout,
            ShaderObjectImpl** outShaderObject)
        {
            auto object = ComPtr<ShaderObjectImpl>(new ShaderObjectImpl());
            SLANG_RETURN_ON_FAIL(
                object->init(device, layout, &device->m_cpuViewHeap, &device->m_cpuSamplerHeap));

            *outShaderObject = object.detach();
            return SLANG_OK;
        }

        ~ShaderObjectImpl()
        {
            auto layoutImpl = static_cast<ShaderObjectLayoutImpl*>(m_layout.Ptr());
            if (m_descriptorSet.m_resourceCount)
            {
                m_resourceHeap.freeIfSupported(
                    m_descriptorSet.m_resourceTable, m_descriptorSet.m_resourceCount);
            }
            if (m_descriptorSet.m_samplerCount)
            {
                m_samplerHeap.freeIfSupported(
                    m_descriptorSet.m_samplerTable, m_descriptorSet.m_samplerCount);
            }
        }

        RendererBase* getDevice() { return m_layout->getDevice(); }

        SLANG_NO_THROW UInt SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return 0; }

        SLANG_NO_THROW Result SLANG_MCALL getEntryPoint(UInt index, IShaderObject** outEntryPoint)
            SLANG_OVERRIDE
        {
            *outEntryPoint = nullptr;
            return SLANG_OK;
        }

        ShaderObjectLayoutImpl* getLayout()
        {
            return static_cast<ShaderObjectLayoutImpl*>(m_layout.Ptr());
        }

        SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL getElementTypeLayout()
            SLANG_OVERRIDE
        {
            return m_layout->getElementTypeLayout();
        }

        SLANG_NO_THROW Result SLANG_MCALL
            setData(ShaderOffset const& inOffset, void const* data, size_t inSize) SLANG_OVERRIDE
        {
            Index offset = inOffset.uniformOffset;
            Index size = inSize;

            char* dest = m_ordinaryData.getBuffer();
            Index availableSize = m_ordinaryData.getCount();

            // TODO: We really should bounds-check access rather than silently ignoring sets
            // that are too large, but we have several test cases that set more data than
            // an object actually stores on several targets...
            //
            if (offset < 0)
            {
                size += offset;
                offset = 0;
            }
            if ((offset + size) >= availableSize)
            {
                size = availableSize - offset;
            }

            memcpy(dest + offset, data, size);

            return SLANG_OK;
        }

        virtual SLANG_NO_THROW Result SLANG_MCALL
            setObject(ShaderOffset const& offset, IShaderObject* object) SLANG_OVERRIDE
        {
            if (offset.bindingRangeIndex < 0)
                return SLANG_E_INVALID_ARG;
            auto layout = getLayout();
            if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
                return SLANG_E_INVALID_ARG;

            auto subObject = static_cast<ShaderObjectImpl*>(object);

            auto bindingRangeIndex = offset.bindingRangeIndex;
            auto& bindingRange = layout->getBindingRange(bindingRangeIndex);

            m_objects[bindingRange.binding.index + offset.bindingArrayIndex] = subObject;

            // If the range being assigned into represents an interface/existential-type leaf field,
            // then we need to consider how the `object` being assigned here affects specialization.
            // We may also need to assign some data from the sub-object into the ordinary data
            // buffer for the parent object.
            //
            if (bindingRange.bindingType == slang::BindingType::ExistentialValue)
            {
                // A leaf field of interface type is laid out inside of the parent object
                // as a tuple of `(RTTI, WitnessTable, Payload)`. The layout of these fields
                // is a contract between the compiler and any runtime system, so we will
                // need to rely on details of the binary layout.

                // We start by querying the layout/type of the concrete value that the application
                // is trying to store into the field, and also the layout/type of the leaf
                // existential-type field itself.
                //
                auto concreteTypeLayout = subObject->getElementTypeLayout();
                auto concreteType = concreteTypeLayout->getType();
                //
                auto existentialTypeLayout =
                    layout->getElementTypeLayout()->getBindingRangeLeafTypeLayout(
                        bindingRangeIndex);
                auto existentialType = existentialTypeLayout->getType();

                // The first field of the tuple (offset zero) is the run-time type information
                // (RTTI) ID for the concrete type being stored into the field.
                //
                // TODO: We need to be able to gather the RTTI type ID from `object` and then
                // use `setData(offset, &TypeID, sizeof(TypeID))`.

                // The second field of the tuple (offset 8) is the ID of the "witness" for the
                // conformance of the concrete type to the interface used by this field.
                //
                auto witnessTableOffset = offset;
                witnessTableOffset.uniformOffset += 8;
                //
                // Conformances of a type to an interface are computed and then stored by the
                // Slang runtime, so we can look up the ID for this particular conformance (which
                // will create it on demand).
                //
                ComPtr<slang::ISession> slangSession;
                SLANG_RETURN_ON_FAIL(getRenderer()->getSlangSession(slangSession.writeRef()));
                //
                // Note: If the type doesn't actually conform to the required interface for
                // this sub-object range, then this is the point where we will detect that
                // fact and error out.
                //
                uint32_t conformanceID = 0xFFFFFFFF;
                SLANG_RETURN_ON_FAIL(slangSession->getTypeConformanceWitnessSequentialID(
                    concreteType, existentialType, &conformanceID));
                //
                // Once we have the conformance ID, then we can write it into the object
                // at the required offset.
                //
                SLANG_RETURN_ON_FAIL(
                    setData(witnessTableOffset, &conformanceID, sizeof(conformanceID)));

                // The third field of the tuple (offset 16) is the "payload" that is supposed to
                // hold the data for a value of the given concrete type.
                //
                auto payloadOffset = offset;
                payloadOffset.uniformOffset += 16;

                // There are two cases we need to consider here for how the payload might be used:
                //
                // * If the concrete type of the value being bound is one that can "fit" into the
                //   available payload space,  then it should be stored in the payload.
                //
                // * If the concrete type of the value cannot fit in the payload space, then it
                //   will need to be stored somewhere else.
                //
                if (_doesValueFitInExistentialPayload(concreteTypeLayout, existentialTypeLayout))
                {
                    // If the value can fit in the payload area, then we will go ahead and copy
                    // its bytes into that area.
                    //
                    setData(
                        payloadOffset,
                        subObject->m_ordinaryData.getBuffer(),
                        subObject->m_ordinaryData.getCount());
                }
                else
                {
                    // If the value does *not *fit in the payload area, then there is nothing
                    // we can do at this point (beyond saving a reference to the sub-object, which
                    // was handled above).
                    //
                    // Once all the sub-objects have been set into the parent object, we can
                    // compute a specialized layout for it, and that specialized layout can tell
                    // us where the data for these sub-objects has been laid out.
                    return SLANG_E_NOT_IMPLEMENTED;
                }
            }
            return SLANG_OK;
        }

        virtual SLANG_NO_THROW Result SLANG_MCALL
            getObject(ShaderOffset const& offset, IShaderObject** outObject) SLANG_OVERRIDE
        {
            SLANG_ASSERT(outObject);
            if (offset.bindingRangeIndex < 0)
                return SLANG_E_INVALID_ARG;
            auto layout = getLayout();
            if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
                return SLANG_E_INVALID_ARG;
            auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);

            auto object = m_objects[bindingRange.binding.index + offset.bindingArrayIndex].Ptr();
            object->addRef();
            *outObject = object;
            return SLANG_OK;
        }

        SLANG_NO_THROW Result SLANG_MCALL
            setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE
        {
            if (offset.bindingRangeIndex < 0)
                return SLANG_E_INVALID_ARG;
            auto layout = getLayout();
            if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
                return SLANG_E_INVALID_ARG;

            auto resourceViewImpl = static_cast<ResourceViewImpl*>(resourceView);

            auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
            auto descriptorSlotIndex = bindingRange.binding.offsetInDescriptorTable.resource +
                                       (int32_t)offset.bindingArrayIndex;
            // Hold a reference to the resource to prevent its destruction.
            m_boundResources[bindingRange.flatResourceOffset + offset.bindingArrayIndex] =
                resourceViewImpl->m_resource;
            ID3D12Device* d3dDevice = static_cast<D3D12Device*>(getDevice())->m_device;
            d3dDevice->CopyDescriptorsSimple(
                1,
                m_resourceHeap.getCpuHandle(
                    m_descriptorSet.m_resourceTable +
                    bindingRange.binding.offsetInDescriptorTable.resource +
                    (int32_t)offset.bindingArrayIndex),
                resourceViewImpl->m_descriptor.cpuHandle,
                D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
            return SLANG_OK;
        }

        SLANG_NO_THROW Result SLANG_MCALL
            setSampler(ShaderOffset const& offset, ISamplerState* sampler) SLANG_OVERRIDE
        {
            if (offset.bindingRangeIndex < 0)
                return SLANG_E_INVALID_ARG;
            auto layout = getLayout();
            if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
                return SLANG_E_INVALID_ARG;
            auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
            auto samplerImpl = static_cast<SamplerStateImpl*>(sampler);
            ID3D12Device* d3dDevice = static_cast<D3D12Device*>(getDevice())->m_device;
            d3dDevice->CopyDescriptorsSimple(
                1,
                m_samplerHeap.getCpuHandle(
                    m_descriptorSet.m_samplerTable +
                    bindingRange.binding.offsetInDescriptorTable.sampler +
                    (int32_t)offset.bindingArrayIndex),
                samplerImpl->m_descriptor.cpuHandle,
                D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
            return SLANG_OK;
        }

        SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
            ShaderOffset const& offset,
            IResourceView* textureView,
            ISamplerState* sampler) SLANG_OVERRIDE
        {
            if (offset.bindingRangeIndex < 0)
                return SLANG_E_INVALID_ARG;
            auto layout = getLayout();
            if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
                return SLANG_E_INVALID_ARG;
            auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
            auto resourceViewImpl = static_cast<ResourceViewImpl*>(textureView);
            ID3D12Device* d3dDevice = static_cast<D3D12Device*>(getDevice())->m_device;
            d3dDevice->CopyDescriptorsSimple(
                1,
                m_resourceHeap.getCpuHandle(
                    m_descriptorSet.m_resourceTable +
                    bindingRange.binding.offsetInDescriptorTable.resource +
                    (int32_t)offset.bindingArrayIndex),
                resourceViewImpl->m_descriptor.cpuHandle,
                D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
            auto samplerImpl = static_cast<SamplerStateImpl*>(sampler);
            d3dDevice->CopyDescriptorsSimple(
                1,
                m_samplerHeap.getCpuHandle(
                    m_descriptorSet.m_samplerTable +
                    bindingRange.binding.offsetInDescriptorTable.sampler +
                    (int32_t)offset.bindingArrayIndex),
                samplerImpl->m_descriptor.cpuHandle,
                D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
            return SLANG_OK;
        }

    public:
        // Appends all types that are used to specialize the element type of this shader object in
        // `args` list.
        virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
        {
            auto& subObjectRanges = getLayout()->getSubObjectRanges();
            // The following logic is built on the assumption that all fields that involve
            // existential types (and therefore require specialization) will results in a sub-object
            // range in the type layout. This allows us to simply scan the sub-object ranges to find
            // out all specialization arguments.
            Index subObjectRangeCount = subObjectRanges.getCount();
            for (Index subObjectRangeIndex = 0; subObjectRangeIndex < subObjectRangeCount;
                 subObjectRangeIndex++)
            {
                auto const& subObjectRange = subObjectRanges[subObjectRangeIndex];
                auto const& bindingRange =
                    getLayout()->getBindingRange(subObjectRange.bindingRangeIndex);

                Index count = bindingRange.count;
                SLANG_ASSERT(count == 1);

                Index subObjectIndexInRange = 0;
                auto subObject = m_objects[bindingRange.binding.index + subObjectIndexInRange];

                switch (bindingRange.bindingType)
                {
                case slang::BindingType::ExistentialValue:
                    {
                        // A binding type of `ExistentialValue` means the sub-object represents a
                        // interface-typed field. In this case the specialization argument for this
                        // field is the actual specialized type of the bound shader object. If the
                        // shader object's type is an ordinary type without existential fields, then
                        // the type argument will simply be the ordinary type. But if the sub
                        // object's type is itself a specialized type, we need to make sure to use
                        // that type as the specialization argument.

                        ExtendedShaderObjectType specializedSubObjType;
                        SLANG_RETURN_ON_FAIL(
                            subObject->getSpecializedShaderObjectType(&specializedSubObjType));
                        args.add(specializedSubObjType);
                        break;
                    }
                case slang::BindingType::ParameterBlock:
                case slang::BindingType::ConstantBuffer:
                    // Currently we only handle the case where the field's type is
                    // `ParameterBlock<SomeStruct>` or `ConstantBuffer<SomeStruct>`, where
                    // `SomeStruct` is a struct type (not directly an interface type). In this case,
                    // we just recursively collect the specialization arguments from the bound sub
                    // object.
                    SLANG_RETURN_ON_FAIL(subObject->collectSpecializationArgs(args));
                    // TODO: we need to handle the case where the field is of the form
                    // `ParameterBlock<IFoo>`. We should treat this case the same way as the
                    // `ExistentialValue` case here, but currently we lack a mechanism to
                    // distinguish the two scenarios.
                    break;
                }
                // TODO: need to handle another case where specialization happens on resources
                // fields e.g. `StructuredBuffer<IFoo>`.
            }
            return SLANG_OK;
        }

    protected:
        Result init(
            D3D12Device* device,
            ShaderObjectLayoutImpl* layout,
            DescriptorHeapReference viewHeap,
            DescriptorHeapReference samplerHeap)
        {
            m_layout = layout;

            m_upToDateConstantBufferHeapVersion = 0;

            // If the layout tells us that there is any uniform data,
            // then we will allocate a CPU memory buffer to hold that data
            // while it is being set from the host.
            //
            // Once the user is done setting the parameters/fields of this
            // shader object, we will produce a GPU-memory version of the
            // uniform data (which includes values from this object and
            // any existential-type sub-objects).
            //
            size_t uniformSize = layout->getElementTypeLayout()->getSize();
            if (uniformSize)
            {
                m_ordinaryData.setCount(uniformSize);
                memset(m_ordinaryData.getBuffer(), 0, uniformSize);
            }

            // Allocate descriptor tables for this shader object.
            m_resourceHeap = viewHeap;
            m_samplerHeap = samplerHeap;
            auto descSetInfo = layout->getDescriptorSetInfo();
            m_descriptorSet.m_resourceCount = descSetInfo.resourceDescriptorCount;
            if (descSetInfo.resourceDescriptorCount)
            {
                m_descriptorSet.m_resourceTable =
                    viewHeap.allocate(descSetInfo.resourceDescriptorCount);
            }
            m_descriptorSet.m_samplerCount = descSetInfo.samplerDescriptorCount;
            if (descSetInfo.samplerDescriptorCount)
            {
                m_descriptorSet.m_samplerTable =
                    samplerHeap.allocate(descSetInfo.samplerDescriptorCount);
            }

            m_boundResources.setCount(layout->getResourceCount());

            // If the layout specifies that we have any sub-objects, then
            // we need to size the array to account for them.
            //
            Index subObjectCount = layout->getSubObjectCount();
            m_objects.setCount(subObjectCount);

            for (auto subObjectRangeInfo : layout->getSubObjectRanges())
            {
                auto subObjectLayout = subObjectRangeInfo.layout;

                // In the case where the sub-object range represents an
                // existential-type leaf field (e.g., an `IBar`), we
                // cannot pre-allocate the object(s) to go into that
                // range, since we can't possibly know what to allocate
                // at this point.
                //
                if (!subObjectLayout)
                    continue;
                //
                // Otherwise, we will allocate a sub-object to fill
                // in each entry in this range, based on the layout
                // information we already have.

                auto& bindingRangeInfo =
                    layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
                for (uint32_t i = 0; i < bindingRangeInfo.count; ++i)
                {
                    RefPtr<ShaderObjectImpl> subObject;
                    SLANG_RETURN_ON_FAIL(
                        ShaderObjectImpl::create(device, subObjectLayout, subObject.writeRef()));
                    m_objects[bindingRangeInfo.binding.index + i] = subObject;
                }
            }

            return SLANG_OK;
        }

        /// Write the uniform/ordinary data of this object into the given `dest` buffer at the given
        /// `offset`
        Result _writeOrdinaryData(
            PipelineCommandEncoder* encoder,
            BufferResourceImpl* buffer,
            size_t offset,
            size_t destSize,
            ShaderObjectLayoutImpl* specializedLayout)
        {
            auto src = m_ordinaryData.getBuffer();
            auto srcSize = size_t(m_ordinaryData.getCount());

            SLANG_ASSERT(srcSize <= destSize);

            _uploadBufferData(encoder->m_d3dCmdList, buffer, offset, srcSize, src);

            // In the case where this object has any sub-objects of
            // existential/interface type, we need to recurse on those objects
            // that need to write their state into an appropriate "pending" allocation.
            //
            // Note: Any values that could fit into the "payload" included
            // in the existential-type field itself will have already been
            // written as part of `setObject()`. This loop only needs to handle
            // those sub-objects that do not "fit."
            //
            // An implementers looking at this code might wonder if things could be changed
            // so that *all* writes related to sub-objects for interface-type fields could
            // be handled in this one location, rather than having some in `setObject()` and
            // others handled here.
            //
            Index subObjectRangeCounter = 0;
            for (auto const& subObjectRangeInfo : specializedLayout->getSubObjectRanges())
            {
                Index subObjectRangeIndex = subObjectRangeCounter++;
                auto const& bindingRangeInfo =
                    specializedLayout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);

                // We only need to handle sub-object ranges for interface/existential-type fields,
                // because fields of constant-buffer or parameter-block type are responsible for
                // the ordinary/uniform data of their own existential/interface-type sub-objects.
                //
                if (bindingRangeInfo.bindingType != slang::BindingType::ExistentialValue)
                    continue;

                // Each sub-object range represents a single "leaf" field, but might be nested
                // under zero or more outer arrays, such that the number of existential values
                // in the same range can be one or more.
                //
                auto count = bindingRangeInfo.count;

                // We are not concerned with the case where the existential value(s) in the range
                // git into the payload part of the leaf field.
                //
                // In the case where the value didn't fit, the Slang layout strategy would have
                // considered the requirements of the value as a "pending" allocation, and would
                // allocate storage for the ordinary/uniform part of that pending allocation inside
                // of the parent object's type layout.
                //
                // Here we assume that the Slang reflection API can provide us with a single byte
                // offset and stride for the location of the pending data allocation in the
                // specialized type layout, which will store the values for this sub-object range.
                //
                // TODO: The reflection API functions we are assuming here haven't been implemented
                // yet, so the functions being called here are stubs.
                //
                // TODO: It might not be that a single sub-object range can reliably map to a single
                // contiguous array with a single stride; we need to carefully consider what the
                // layout logic does for complex cases with multiple layers of nested arrays and
                // structures.
                //
                size_t subObjectRangePendingDataOffset =
                    _getSubObjectRangePendingDataOffset(specializedLayout, subObjectRangeIndex);
                size_t subObjectRangePendingDataStride =
                    _getSubObjectRangePendingDataStride(specializedLayout, subObjectRangeIndex);

                // If the range doesn't actually need/use the "pending" allocation at all, then
                // we need to detect that case and skip such ranges.
                //
                // TODO: This should probably be handled on a per-object basis by caching a "does it
                // fit?" bit as part of the information for bound sub-objects, given that we already
                // compute the "does it fit?" status as part of `setObject()`.
                //
                if (subObjectRangePendingDataOffset == 0)
                    continue;

                for (uint32_t i = 0; i < count; ++i)
                {
                    auto subObject = m_objects[bindingRangeInfo.binding.index + i];

                    RefPtr<ShaderObjectLayoutImpl> subObjectLayout;
                    SLANG_RETURN_ON_FAIL(
                        subObject->getSpecializedLayout(subObjectLayout.writeRef()));

                    auto subObjectOffset =
                        subObjectRangePendingDataOffset + i * subObjectRangePendingDataStride;

                    subObject->_writeOrdinaryData(
                        encoder,
                        buffer,
                        offset + subObjectOffset,
                        destSize - subObjectOffset,
                        subObjectLayout);
                }
            }

            return SLANG_OK;
        }

        // As discussed in `_writeOrdinaryData()`, these methods are just stubs waiting for
        // the "flat" Slang refelction information to provide access to the relevant data.
        //
        size_t _getSubObjectRangePendingDataOffset(
            ShaderObjectLayoutImpl* specializedLayout,
            Index subObjectRangeIndex)
        {
            return 0;
        }
        size_t _getSubObjectRangePendingDataStride(
            ShaderObjectLayoutImpl* specializedLayout,
            Index subObjectRangeIndex)
        {
            return 0;
        }

        /// Ensure that the `m_ordinaryDataBuffer` has been created, if it is needed
        Result _ensureOrdinaryDataBufferCreatedIfNeeded(PipelineCommandEncoder* encoder)
        {
            // If we have already created a buffer to hold ordinary data, then we should
            // simply re-use that buffer rather than re-create it.
            //
            // TODO: Simply re-using the buffer without any kind of validation checks
            // means that we are assuming that users cannot or will not perform any `set`
            // operations on a shader object once an operation has requested this buffer
            // be created. We need to enforce that rule if we want to rely on it.
            //
            if (m_upToDateConstantBufferHeapVersion ==
                encoder->m_commandBuffer->m_transientHeap->getVersion())
            {
                return SLANG_OK;
            }

            // Computing the size of the ordinary data buffer is *not* just as simple
            // as using the size of the `m_ordinayData` array that we store. The reason
            // for the added complexity is that interface-type fields may lead to the
            // storage being specialized such that it needs extra appended data to
            // store the concrete values that logically belong in those interface-type
            // fields but wouldn't fit in the fixed-size allocation we gave them.
            //
            // TODO: We need to actually implement that logic by using reflection
            // data computed for the specialized type of this shader object.
            // For now we just make the simple assumption described above despite
            // knowing that it is false.
            //
            RefPtr<ShaderObjectLayoutImpl> specializedLayout;
            SLANG_RETURN_ON_FAIL(getSpecializedLayout(specializedLayout.writeRef()));

            m_constantBufferSize = specializedLayout->getElementTypeLayout()->getSize();
            if (m_constantBufferSize == 0)
            {
                m_upToDateConstantBufferHeapVersion =
                    encoder->m_commandBuffer->m_transientHeap->getVersion();
                return SLANG_OK;
            }

            // Once we have computed how large the buffer should be, we can allocate
            // it from the transient resource heap.
            //
            auto alignedConstantBufferSize = D3DUtil::calcAligned(m_constantBufferSize, 256);
            SLANG_RETURN_ON_FAIL(encoder->m_commandBuffer->m_transientHeap->allocateConstantBuffer(
                alignedConstantBufferSize, m_constantBufferWeakPtr, m_constantBufferOffset));

            // Once the buffer is allocated, we can use `_writeOrdinaryData` to fill it in.
            //
            // Note that `_writeOrdinaryData` is potentially recursive in the case
            // where this object contains interface/existential-type fields, so we
            // don't need or want to inline it into this call site.
            //
            SLANG_RETURN_ON_FAIL(_writeOrdinaryData(
                encoder,
                static_cast<BufferResourceImpl*>(m_constantBufferWeakPtr),
                m_constantBufferOffset,
                m_constantBufferSize,
                specializedLayout));

            // Update version tracker so that we don't redundantly alloc and fill in
            // constant buffers for the same transient heap.
            m_upToDateConstantBufferHeapVersion =
                encoder->m_commandBuffer->m_transientHeap->getVersion();

            {
                // We also create and store a descriptor for our root constant buffer
                // into the descriptor table allocation that was reserved for them.
                //
                // We always know that the ordinary data buffer will be the first descriptor
                // in the table of resource views.
                //
                auto descriptorTable = m_descriptorSet.m_resourceTable;
                D3D12_CONSTANT_BUFFER_VIEW_DESC viewDesc = {};
                viewDesc.BufferLocation = static_cast<BufferResourceImpl*>(m_constantBufferWeakPtr)
                                              ->m_resource.getResource()
                                              ->GetGPUVirtualAddress() +
                                          m_constantBufferOffset;
                viewDesc.SizeInBytes = (UINT)alignedConstantBufferSize;
                encoder->m_device->CreateConstantBufferView(
                    &viewDesc, m_resourceHeap.getCpuHandle(descriptorTable));
            }

            return SLANG_OK;
        }

    public:
        Result bindObject(PipelineCommandEncoder* encoder, RootBindingState* bindingState)
        {
            ShaderObjectLayoutImpl* layout = getLayout();
            SLANG_RETURN_ON_FAIL(_ensureOrdinaryDataBufferCreatedIfNeeded(encoder));
            uint32_t descTableIndex = bindingState->rootParamIndex;
            auto& descSet = m_descriptorSet;
            if (descSet.m_resourceCount)
            {
                auto gpuDescriptorTable = bindingState->descriptorTables[descTableIndex];
                auto& gpuHeap = gpuDescriptorTable.heap;
                auto& cpuHeap = m_resourceHeap;
                auto cpuDescriptorTable = descSet.m_resourceTable;

                bindingState->device->m_device->CopyDescriptorsSimple(
                    UINT(descSet.m_resourceCount),
                    gpuHeap.getCpuHandle(
                        gpuDescriptorTable.table + bindingState->offset.resource),
                    cpuHeap.getCpuHandle(cpuDescriptorTable),
                    D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
                bindingState->offset.resource += descSet.m_resourceCount;
                descTableIndex++;
            }
            if (descSet.m_samplerCount)
            {
                auto gpuDescriptorTable = bindingState->descriptorTables[descTableIndex];
                auto& gpuHeap = gpuDescriptorTable.heap;
                auto& cpuHeap = m_samplerHeap;
                auto cpuDescriptorTable = (int)descSet.m_samplerTable;

                bindingState->device->m_device->CopyDescriptorsSimple(
                    UINT(descSet.m_samplerCount),
                    gpuHeap.getCpuHandle(
                        gpuDescriptorTable.table + bindingState->offset.sampler),
                    cpuHeap.getCpuHandle(cpuDescriptorTable),
                    D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
                bindingState->offset.sampler += descSet.m_samplerCount;
                descTableIndex++;
            }
            bindingState->futureRootParamOffset =
                Math::Max(descTableIndex, bindingState->futureRootParamOffset);
            auto& subObjectRanges = layout->getSubObjectRanges();
            for (Index i = 0; i < subObjectRanges.getCount(); i++)
            {
                auto bindingRange =
                    layout->getBindingRange(layout->getSubObjectRange(i).bindingRangeIndex);
                switch (layout->getSubObjectRange(i).bindingType)
                {
                case slang::BindingType::ParameterBlock:
                    {
                        auto baseIndex = bindingRange.binding.index;
                        for (uint32_t j = 0; j < bindingRange.count; j++)
                        {
                            auto newBindingState = *bindingState;
                            newBindingState.offset.resource = 0;
                            newBindingState.offset.sampler = 0;
                            newBindingState.rootParamIndex = bindingState->futureRootParamOffset;
                            newBindingState.futureRootParamOffset = newBindingState.rootParamIndex;
                            m_objects[baseIndex + j]->bindObject(encoder, &newBindingState);
                            bindingState->futureRootParamOffset =
                                newBindingState.futureRootParamOffset;
                        }
                    }
                    break;
                case slang::BindingType::ConstantBuffer:
                    {
                        auto baseIndex = bindingRange.binding.index;
                        for (uint32_t j = 0; j < bindingRange.count; j++)
                        {
                            m_objects[baseIndex + j]->bindObject(encoder, bindingState);
                        }
                    }
                    break;
                case slang::BindingType::ExistentialValue:
                    // If the existential object contains only ordinary data fields,
                    // the data is already written into m_ordinaryDataBuffer during `setObject`,
                    // so we don't need to do anything here.
                    // If the existential object has resource fields, this is the time to set
                    // those fields as in the "pendingLayout" section.
                    // TODO: implement resource fields binding for inline existential values.
                default:
                    break;
                }
            }
            return SLANG_OK;
        }

        /// Any "ordinary" / uniform data for this object
        List<char> m_ordinaryData;

        List<RefPtr<ShaderObjectImpl>> m_objects;

        // The resource and sampler heaps used to allocate the descriptor tables.
        DescriptorHeapReference m_resourceHeap;
        DescriptorHeapReference m_samplerHeap;

        struct DescriptorSet
        {
            int32_t m_resourceTable = 0;
            int32_t m_samplerTable = 0;
            uint32_t m_resourceCount = 0;
            uint32_t m_samplerCount = 0;
        };
        DescriptorSet m_descriptorSet;

        ShortList<RefPtr<Resource>, 8> m_boundResources;

        /// A constant buffer used to stored ordinary data for this object
        /// and existential-type sub-objects.
        ///
        /// Allocated from transient heap on demand with `_createOrdinaryDataBufferIfNeeded()`
        IBufferResource* m_constantBufferWeakPtr = nullptr;
        size_t m_constantBufferOffset = 0;
        size_t m_constantBufferSize = 0;

        /// The version number of the transient resource heap that contains up-to-date
        /// constant buffer content for this shader object. If this is equal to the version number
        /// of currently active transient heap, then the current set-up of constant buffer contents
        /// as defined by the above `m_constantBuffer*` fields is valid and up-to-date so we can
        /// use them directly.
        uint64_t m_upToDateConstantBufferHeapVersion;

        /// Get the layout of this shader object with specialization arguments considered
        ///
        /// This operation should only be called after the shader object has been
        /// fully filled in and finalized.
        ///
        Result getSpecializedLayout(ShaderObjectLayoutImpl** outLayout)
        {
            if (!m_specializedLayout)
            {
                SLANG_RETURN_ON_FAIL(_createSpecializedLayout(m_specializedLayout.writeRef()));
            }
            *outLayout = RefPtr<ShaderObjectLayoutImpl>(m_specializedLayout).detach();
            return SLANG_OK;
        }

        /// Create the layout for this shader object with specialization arguments considered
        ///
        /// This operation is virtual so that it can be customized by `RootShaderObject`.
        ///
        virtual Result _createSpecializedLayout(ShaderObjectLayoutImpl** outLayout)
        {
            ExtendedShaderObjectType extendedType;
            SLANG_RETURN_ON_FAIL(getSpecializedShaderObjectType(&extendedType));

            auto renderer = getRenderer();
            RefPtr<ShaderObjectLayoutBase> layout;
            SLANG_RETURN_ON_FAIL(
                renderer->getShaderObjectLayout(extendedType.slangType, layout.writeRef()));

            *outLayout = static_cast<ShaderObjectLayoutImpl*>(layout.detach());
            return SLANG_OK;
        }

        RefPtr<ShaderObjectLayoutImpl> m_specializedLayout;
    };

    class RootShaderObjectImpl : public ShaderObjectImpl
    {
        typedef ShaderObjectImpl Super;

    public:
        // Override default reference counting behavior to disable lifetime management.
        // Root objects are managed by command buffer and does not need to be freed by the user.
        SLANG_NO_THROW uint32_t SLANG_MCALL addRef() override { return 1; }
        SLANG_NO_THROW uint32_t SLANG_MCALL release() override { return 1; }
    public:
        RootShaderObjectLayoutImpl* getLayout()
        {
            return static_cast<RootShaderObjectLayoutImpl*>(m_layout.Ptr());
        }

        UInt SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE
        {
            return (UInt)m_entryPoints.getCount();
        }
        SlangResult SLANG_MCALL getEntryPoint(UInt index, IShaderObject** outEntryPoint)
            SLANG_OVERRIDE
        {
            *outEntryPoint = m_entryPoints[index];
            m_entryPoints[index]->addRef();
            return SLANG_OK;
        }

        virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
        {
            SLANG_RETURN_ON_FAIL(ShaderObjectImpl::collectSpecializationArgs(args));
            for (auto& entryPoint : m_entryPoints)
            {
                SLANG_RETURN_ON_FAIL(entryPoint->collectSpecializationArgs(args));
            }
            return SLANG_OK;
        }

    public:
        Result bindObject(PipelineCommandEncoder* encoder, RootBindingState* bindingState)
        {
            SLANG_RETURN_ON_FAIL(Super::bindObject(encoder, bindingState));

            auto entryPointCount = m_entryPoints.getCount();
            for (Index i = 0; i < entryPointCount; ++i)
            {
                auto entryPoint = m_entryPoints[i];
                SLANG_RETURN_ON_FAIL(entryPoint->bindObject(encoder, bindingState));
            }

            return SLANG_OK;
        }

    public:

        Result init(D3D12Device* device)
        {
            SLANG_RETURN_ON_FAIL(m_cpuViewHeap.init(
                device->m_device,
                64,
                D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
                D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
            SLANG_RETURN_ON_FAIL(m_cpuSamplerHeap.init(
                device->m_device,
                8,
                D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
                D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
            return SLANG_OK;
        }

        Result reset(
            D3D12Device* device,
            RootShaderObjectLayoutImpl* layout,
            TransientResourceHeapImpl* heap)
        {
            m_cpuViewHeap.deallocateAll();
            m_cpuSamplerHeap.deallocateAll();
            SLANG_RETURN_ON_FAIL(Super::init(device, layout, &m_cpuViewHeap, &m_cpuSamplerHeap));
            m_specializedLayout = nullptr;
            m_entryPoints.clear();
            for (auto entryPointInfo : layout->getEntryPoints())
            {
                RefPtr<ShaderObjectImpl> entryPoint;
                SLANG_RETURN_ON_FAIL(
                    ShaderObjectImpl::create(device, entryPointInfo.layout, entryPoint.writeRef()));
                m_entryPoints.add(entryPoint);
            }
            return SLANG_OK;
        }

    protected:
        Result _createSpecializedLayout(ShaderObjectLayoutImpl** outLayout) SLANG_OVERRIDE
        {
            ExtendedShaderObjectTypeList specializationArgs;
            SLANG_RETURN_ON_FAIL(collectSpecializationArgs(specializationArgs));

            // Note: There is an important policy decision being made here that we need
            // to approach carefully.
            //
            // We are doing two different things that affect the layout of a program:
            //
            // 1. We are *composing* one or more pieces of code (notably the shared global/module
            //    stuff and the per-entry-point stuff).
            //
            // 2. We are *specializing* code that includes generic/existential parameters
            //    to concrete types/values.
            //
            // We need to decide the relative *order* of these two steps, because of how it impacts
            // layout. The layout for `specialize(compose(A,B), X, Y)` is potentially different
            // form that of `compose(specialize(A,X), speciealize(B,Y))`, even when both are
            // semantically equivalent programs.
            //
            // Right now we are using the first option: we are first generating a full composition
            // of all the code we plan to use (global scope plus all entry points), and then
            // specializing it to the concatenated specialization argumenst for all of that.
            //
            // In some cases, though, this model isn't appropriate. For example, when dealing with
            // ray-tracing shaders and local root signatures, we really want the parameters of each
            // entry point (actually, each entry-point *group*) to be allocated distinct storage,
            // which really means we want to compute something like:
            //
            //      SpecializedGlobals = specialize(compose(ModuleA, ModuleB, ...), X, Y, ...)
            //
            //      SpecializedEP1 = compose(SpecializedGlobals, specialize(EntryPoint1, T, U, ...))
            //      SpecializedEP2 = compose(SpecializedGlobals, specialize(EntryPoint2, A, B, ...))
            //
            // Note how in this case all entry points agree on the layout for the shared/common
            // parmaeters, but their layouts are also independent of one another.
            //
            // Furthermore, in this example, loading another entry point into the system would not
            // rquire re-computing the layouts (or generated kernel code) for any of the entry
            // points that had already been loaded (in contrast to a compose-then-specialize
            // approach).
            //
            ComPtr<slang::IComponentType> specializedComponentType;
            ComPtr<slang::IBlob> diagnosticBlob;
            auto result = getLayout()->getSlangProgram()->specialize(
                specializationArgs.components.getArrayView().getBuffer(),
                specializationArgs.getCount(),
                specializedComponentType.writeRef(),
                diagnosticBlob.writeRef());

            // TODO: print diagnostic message via debug output interface.

            if (result != SLANG_OK)
                return result;

            auto slangSpecializedLayout = specializedComponentType->getLayout();
            RefPtr<RootShaderObjectLayoutImpl> specializedLayout;
            RootShaderObjectLayoutImpl::create(
                static_cast<D3D12Device*>(getRenderer()),
                specializedComponentType,
                slangSpecializedLayout,
                specializedLayout.writeRef());

            // Note: Computing the layout for the specialized program will have also computed
            // the layouts for the entry points, and we really need to attach that information
            // to them so that they don't go and try to compute their own specializations.
            //
            // TODO: Well, if we move to the specialization model described above then maybe
            // we *will* want entry points to do their own specialization work...
            //
            auto entryPointCount = m_entryPoints.getCount();
            for (Index i = 0; i < entryPointCount; ++i)
            {
                auto entryPointInfo = specializedLayout->getEntryPoint(i);
                auto entryPointVars = m_entryPoints[i];

                entryPointVars->m_specializedLayout = entryPointInfo.layout;
            }

            *outLayout = specializedLayout.detach();
            return SLANG_OK;
        }

        List<RefPtr<ShaderObjectImpl>> m_entryPoints;

    public:
        // Descriptor heaps for the root object. Resets with the life cycle of each root shader
        // object use.
        D3D12DescriptorHeap m_cpuViewHeap;
        D3D12DescriptorHeap m_cpuSamplerHeap;
    };

    class CommandBufferImpl
        : public ICommandBuffer
        , public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        ICommandBuffer* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_ICommandBuffer)
                return static_cast<ICommandBuffer*>(this);
            return nullptr;
        }
    public:
        ComPtr<ID3D12GraphicsCommandList> m_cmdList;
        TransientResourceHeapImpl* m_transientHeap;
        D3D12Device* m_renderer;
        RootShaderObjectImpl m_rootShaderObject;

        void init(
            D3D12Device* renderer,
            ID3D12GraphicsCommandList* d3dCommandList,
            TransientResourceHeapImpl* transientHeap)
        {
            m_transientHeap = transientHeap;
            m_renderer = renderer;
            m_cmdList = d3dCommandList;

            ID3D12DescriptorHeap* heaps[] = {
                m_transientHeap->m_viewHeap.getHeap(),
                m_transientHeap->m_samplerHeap.getHeap(),
            };
            m_cmdList->SetDescriptorHeaps(SLANG_COUNT_OF(heaps), heaps);
            m_rootShaderObject.init(renderer);
        }

        class RenderCommandEncoderImpl
            : public IRenderCommandEncoder
            , public PipelineCommandEncoder
        {
        public:
            virtual SLANG_NO_THROW SlangResult SLANG_MCALL
                queryInterface(SlangUUID const& uuid, void** outObject) override
            {
                if (uuid == GfxGUID::IID_ISlangUnknown ||
                    uuid == GfxGUID::IID_IRenderCommandEncoder)
                {
                    *outObject = static_cast<IRenderCommandEncoder*>(this);
                    return SLANG_OK;
                }
                *outObject = nullptr;
                return SLANG_E_NO_INTERFACE;
            }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() { return 1; }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() { return 1; }
        public:
            RefPtr<RenderPassLayoutImpl> m_renderPass;
            RefPtr<FramebufferImpl> m_framebuffer;

            List<BoundVertexBuffer> m_boundVertexBuffers;

            RefPtr<BufferResourceImpl> m_boundIndexBuffer;

            D3D12_VIEWPORT m_viewports[kMaxRTVCount];
            D3D12_RECT m_scissorRects[kMaxRTVCount];

            DXGI_FORMAT m_boundIndexFormat;
            UINT m_boundIndexOffset;

            D3D12_PRIMITIVE_TOPOLOGY_TYPE m_primitiveTopologyType;
            D3D12_PRIMITIVE_TOPOLOGY m_primitiveTopology;

            void init(
                D3D12Device* renderer,
                TransientResourceHeapImpl* transientHeap,
                CommandBufferImpl* cmdBuffer,
                RenderPassLayoutImpl* renderPass,
                FramebufferImpl* framebuffer)
            {
                PipelineCommandEncoder::init(cmdBuffer);
                m_preCmdList = nullptr;
                m_device = renderer->m_device;
                m_renderPass = renderPass;
                m_framebuffer = framebuffer;
                m_transientHeap = transientHeap;
                m_boundVertexBuffers.clear();
                m_boundIndexBuffer = nullptr;
                m_primitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
                m_primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
                m_boundIndexFormat = DXGI_FORMAT_UNKNOWN;
                m_boundIndexOffset = 0;
                m_currentPipeline = nullptr;

                // Set render target states.
                m_d3dCmdList->OMSetRenderTargets(
                    (UINT)framebuffer->renderTargetViews.getCount(),
                    framebuffer->renderTargetDescriptors.getArrayView().getBuffer(),
                    FALSE,
                    framebuffer->depthStencilView ? &framebuffer->depthStencilDescriptor : nullptr);

                // Issue clear commands based on render pass set up.
                for (Index i = 0; i < renderPass->m_renderTargetAccesses.getCount(); i++)
                {
                    auto& access = renderPass->m_renderTargetAccesses[i];

                    // Transit resource states.
                    {
                        D3D12BarrierSubmitter submitter(m_d3dCmdList);
                        auto resourceViewImpl =
                            static_cast<ResourceViewImpl*>(framebuffer->renderTargetViews[i].get());
                        auto textureResource =
                            static_cast<TextureResourceImpl*>(resourceViewImpl->m_resource.Ptr());
                        D3D12_RESOURCE_STATES initialState;
                        if (access.initialState == ResourceState::Undefined)
                        {
                            initialState = textureResource->m_defaultState;
                        }
                        else
                        {
                            initialState = D3DUtil::translateResourceState(access.initialState);
                        }
                        textureResource->m_resource.transition(
                            initialState,
                            D3D12_RESOURCE_STATE_RENDER_TARGET,
                            submitter);
                    }
                    // Clear.
                    if (access.loadOp == IRenderPassLayout::AttachmentLoadOp::Clear)
                    {
                        m_d3dCmdList->ClearRenderTargetView(
                            framebuffer->renderTargetDescriptors[i],
                            framebuffer->renderTargetClearValues[i].values,
                            0,
                            nullptr);
                    }
                }

                if (renderPass->m_hasDepthStencil)
                {
                    // Transit resource states.
                    {
                        D3D12BarrierSubmitter submitter(m_d3dCmdList);
                        auto resourceViewImpl =
                            static_cast<ResourceViewImpl*>(framebuffer->depthStencilView.get());
                        auto textureResource =
                            static_cast<TextureResourceImpl*>(resourceViewImpl->m_resource.Ptr());
                        D3D12_RESOURCE_STATES initialState;
                        if (renderPass->m_depthStencilAccess.initialState ==
                            ResourceState::Undefined)
                        {
                            initialState = textureResource->m_defaultState;
                        }
                        else
                        {
                            initialState = D3DUtil::translateResourceState(
                                renderPass->m_depthStencilAccess.initialState);
                        }
                        textureResource->m_resource.transition(
                            initialState,
                            D3D12_RESOURCE_STATE_DEPTH_WRITE,
                            submitter);
                    }
                    // Clear.
                    uint32_t clearFlags = 0;
                    if (renderPass->m_depthStencilAccess.loadOp ==
                        IRenderPassLayout::AttachmentLoadOp::Clear)
                    {
                        clearFlags |= D3D12_CLEAR_FLAG_DEPTH;
                    }
                    if (renderPass->m_depthStencilAccess.stencilLoadOp ==
                        IRenderPassLayout::AttachmentLoadOp::Clear)
                    {
                        clearFlags |= D3D12_CLEAR_FLAG_STENCIL;
                    }
                    if (clearFlags)
                    {
                        m_d3dCmdList->ClearDepthStencilView(
                            framebuffer->depthStencilDescriptor,
                            (D3D12_CLEAR_FLAGS)clearFlags,
                            framebuffer->depthStencilClearValue.depth,
                            framebuffer->depthStencilClearValue.stencil,
                            0,
                            nullptr);
                    }
                }
            }

            virtual SLANG_NO_THROW Result SLANG_MCALL
                bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
            {
                return bindPipelineImpl(state, outRootObject);
            }

            virtual SLANG_NO_THROW void SLANG_MCALL
                setViewports(uint32_t count, const Viewport* viewports) override
            {
                static const int kMaxViewports =
                    D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
                assert(count <= kMaxViewports && count <= kMaxRTVCount);
                for (UInt ii = 0; ii < count; ++ii)
                {
                    auto& inViewport = viewports[ii];
                    auto& dxViewport = m_viewports[ii];

                    dxViewport.TopLeftX = inViewport.originX;
                    dxViewport.TopLeftY = inViewport.originY;
                    dxViewport.Width = inViewport.extentX;
                    dxViewport.Height = inViewport.extentY;
                    dxViewport.MinDepth = inViewport.minZ;
                    dxViewport.MaxDepth = inViewport.maxZ;
                }
                m_d3dCmdList->RSSetViewports(UINT(count), m_viewports);
            }

            virtual SLANG_NO_THROW void SLANG_MCALL
                setScissorRects(uint32_t count, const ScissorRect* rects) override
            {
                static const int kMaxScissorRects =
                    D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
                assert(count <= kMaxScissorRects && count <= kMaxRTVCount);

                for (UInt ii = 0; ii < count; ++ii)
                {
                    auto& inRect = rects[ii];
                    auto& dxRect = m_scissorRects[ii];

                    dxRect.left = LONG(inRect.minX);
                    dxRect.top = LONG(inRect.minY);
                    dxRect.right = LONG(inRect.maxX);
                    dxRect.bottom = LONG(inRect.maxY);
                }

                m_d3dCmdList->RSSetScissorRects(UINT(count), m_scissorRects);
            }

            virtual SLANG_NO_THROW void SLANG_MCALL
                setPrimitiveTopology(PrimitiveTopology topology) override
            {
                switch (topology)
                {
                case PrimitiveTopology::TriangleList:
                    {
                        m_primitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
                        m_primitiveTopology = D3DUtil::getPrimitiveTopology(topology);
                        break;
                    }
                default:
                    {
                        assert(!"Unhandled type");
                    }
                }
            }

            virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
                UInt startSlot,
                UInt slotCount,
                IBufferResource* const* buffers,
                const UInt* strides,
                const UInt* offsets) override
            {
                {
                    const Index num = startSlot + slotCount;
                    if (num > m_boundVertexBuffers.getCount())
                    {
                        m_boundVertexBuffers.setCount(num);
                    }
                }

                for (UInt i = 0; i < slotCount; i++)
                {
                    BufferResourceImpl* buffer = static_cast<BufferResourceImpl*>(buffers[i]);
                    if (buffer)
                    {
                        assert(buffer->m_initialUsage == IResource::Usage::VertexBuffer);
                    }

                    BoundVertexBuffer& boundBuffer = m_boundVertexBuffers[startSlot + i];
                    boundBuffer.m_buffer = buffer;
                    boundBuffer.m_stride = int(strides[i]);
                    boundBuffer.m_offset = int(offsets[i]);
                }
            }

            virtual SLANG_NO_THROW void SLANG_MCALL setIndexBuffer(
                IBufferResource* buffer,
                Format indexFormat,
                UInt offset = 0) override
            {
                m_boundIndexBuffer = (BufferResourceImpl*)buffer;
                m_boundIndexFormat = D3DUtil::getMapFormat(indexFormat);
                m_boundIndexOffset = UINT(offset);
            }

            void prepareDraw()
            {
                auto pipelineState = m_currentPipeline.Ptr();
                if (!pipelineState || (pipelineState->desc.type != PipelineType::Graphics))
                {
                    assert(!"No graphics pipeline state set");
                    return;
                }

                // Submit - setting for graphics
                {
                    GraphicsSubmitter submitter(m_d3dCmdList);
                    if(SLANG_FAILED(_bindRenderState(&submitter)))
                    {
                        assert(!"Failed to bind render state");
                    }
                }

                m_d3dCmdList->IASetPrimitiveTopology(m_primitiveTopology);

                // Set up vertex buffer views
                {
                    int numVertexViews = 0;
                    D3D12_VERTEX_BUFFER_VIEW vertexViews[16];
                    for (Index i = 0; i < m_boundVertexBuffers.getCount(); i++)
                    {
                        const BoundVertexBuffer& boundVertexBuffer = m_boundVertexBuffers[i];
                        BufferResourceImpl* buffer = boundVertexBuffer.m_buffer;
                        if (buffer)
                        {
                            D3D12_VERTEX_BUFFER_VIEW& vertexView = vertexViews[numVertexViews++];
                            vertexView.BufferLocation =
                                buffer->m_resource.getResource()->GetGPUVirtualAddress() +
                                boundVertexBuffer.m_offset;
                            vertexView.SizeInBytes =
                                UINT(buffer->getDesc()->sizeInBytes - boundVertexBuffer.m_offset);
                            vertexView.StrideInBytes = UINT(boundVertexBuffer.m_stride);
                        }
                    }
                    m_d3dCmdList->IASetVertexBuffers(0, numVertexViews, vertexViews);
                }
                // Set up index buffer
                if (m_boundIndexBuffer)
                {
                    D3D12_INDEX_BUFFER_VIEW indexBufferView;
                    indexBufferView.BufferLocation =
                        m_boundIndexBuffer->m_resource.getResource()->GetGPUVirtualAddress() +
                        m_boundIndexOffset;
                    indexBufferView.SizeInBytes =
                        UINT(m_boundIndexBuffer->getDesc()->sizeInBytes - m_boundIndexOffset);
                    indexBufferView.Format = m_boundIndexFormat;

                    m_d3dCmdList->IASetIndexBuffer(&indexBufferView);
                }
            }
            virtual SLANG_NO_THROW void SLANG_MCALL
                draw(UInt vertexCount, UInt startVertex = 0) override
            {
                prepareDraw();
                m_d3dCmdList->DrawInstanced(UINT(vertexCount), 1, UINT(startVertex), 0);
            }
            virtual SLANG_NO_THROW void SLANG_MCALL
                drawIndexed(UInt indexCount, UInt startIndex = 0, UInt baseVertex = 0) override
            {
                prepareDraw();
                m_d3dCmdList->DrawIndexedInstanced(
                    (UINT)indexCount, 1, (UINT)startIndex, (UINT)baseVertex, 0);
            }
            virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override
            {
                PipelineCommandEncoder::endEncodingImpl();
                // Issue clear commands based on render pass set up.
                for (Index i = 0; i < m_renderPass->m_renderTargetAccesses.getCount(); i++)
                {
                    auto& access = m_renderPass->m_renderTargetAccesses[i];

                    // Transit resource states.
                    {
                        D3D12BarrierSubmitter submitter(m_d3dCmdList);
                        auto resourceViewImpl = static_cast<ResourceViewImpl*>(
                            m_framebuffer->renderTargetViews[i].get());
                        auto textureResource =
                            static_cast<TextureResourceImpl*>(resourceViewImpl->m_resource.Ptr());
                        textureResource->m_resource.transition(
                            D3D12_RESOURCE_STATE_RENDER_TARGET,
                            D3DUtil::translateResourceState(access.finalState),
                            submitter);
                    }
                }

                if (m_renderPass->m_hasDepthStencil)
                {
                    // Transit resource states.
                    D3D12BarrierSubmitter submitter(m_d3dCmdList);
                    auto resourceViewImpl =
                        static_cast<ResourceViewImpl*>(m_framebuffer->depthStencilView.get());
                    auto textureResource =
                        static_cast<TextureResourceImpl*>(resourceViewImpl->m_resource.Ptr());
                    textureResource->m_resource.transition(
                        D3D12_RESOURCE_STATE_DEPTH_WRITE,
                        D3DUtil::translateResourceState(
                            m_renderPass->m_depthStencilAccess.finalState),
                        submitter);
                }
                m_framebuffer = nullptr;
            }

            virtual SLANG_NO_THROW void SLANG_MCALL
                setStencilReference(uint32_t referenceValue) override
            {
                m_d3dCmdList->OMSetStencilRef((UINT)referenceValue);
            }
        };

        RenderCommandEncoderImpl m_renderCommandEncoder;
        virtual SLANG_NO_THROW void SLANG_MCALL encodeRenderCommands(
            IRenderPassLayout* renderPass,
            IFramebuffer* framebuffer,
            IRenderCommandEncoder** outEncoder) override
        {
            m_renderCommandEncoder.init(
                m_renderer,
                m_transientHeap,
                this,
                static_cast<RenderPassLayoutImpl*>(renderPass),
                static_cast<FramebufferImpl*>(framebuffer));
            *outEncoder = &m_renderCommandEncoder;
        }

        class ComputeCommandEncoderImpl
            : public IComputeCommandEncoder
            , public PipelineCommandEncoder
        {
        public:
            virtual SLANG_NO_THROW SlangResult SLANG_MCALL
                queryInterface(SlangUUID const& uuid, void** outObject) override
            {
                if (uuid == GfxGUID::IID_ISlangUnknown ||
                    uuid == GfxGUID::IID_IComputeCommandEncoder)
                {
                    *outObject = static_cast<IComputeCommandEncoder*>(this);
                    return SLANG_OK;
                }
                *outObject = nullptr;
                return SLANG_E_NO_INTERFACE;
            }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() { return 1; }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() { return 1; }

        public:
            virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() override
            {
                PipelineCommandEncoder::endEncodingImpl();
            }
            void init(
                D3D12Device* renderer,
                TransientResourceHeapImpl* transientHeap,
                CommandBufferImpl* cmdBuffer)
            {
                PipelineCommandEncoder::init(cmdBuffer);
                m_preCmdList = nullptr;
                m_device = renderer->m_device;
                m_transientHeap = transientHeap;
                m_currentPipeline = nullptr;
            }

            virtual SLANG_NO_THROW Result SLANG_MCALL
                bindPipeline(IPipelineState* state, IShaderObject** outRootObject) override
            {
                return bindPipelineImpl(state, outRootObject);
            }

            virtual SLANG_NO_THROW void SLANG_MCALL dispatchCompute(int x, int y, int z) override
            {
                // Submit binding for compute
                {
                    ComputeSubmitter submitter(m_d3dCmdList);
                    if(SLANG_FAILED(_bindRenderState(&submitter)))
                    {
                        assert(!"Failed to bind render state");
                    }
                }
                m_d3dCmdList->Dispatch(x, y, z);
            }
        };

        ComputeCommandEncoderImpl m_computeCommandEncoder;
        virtual SLANG_NO_THROW void SLANG_MCALL
            encodeComputeCommands(IComputeCommandEncoder** outEncoder) override
        {
            m_computeCommandEncoder.init(m_renderer, m_transientHeap, this);
            *outEncoder = &m_computeCommandEncoder;
        }

        class ResourceCommandEncoderImpl : public IResourceCommandEncoder
        {
        public:
            virtual SLANG_NO_THROW SlangResult SLANG_MCALL
                queryInterface(SlangUUID const& uuid, void** outObject) override
            {
                if (uuid == GfxGUID::IID_ISlangUnknown ||
                    uuid == GfxGUID::IID_IResourceCommandEncoder)
                {
                    *outObject = static_cast<IResourceCommandEncoder*>(this);
                    return SLANG_OK;
                }
                *outObject = nullptr;
                return SLANG_E_NO_INTERFACE;
            }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() { return 1; }
            virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() { return 1; }

        public:
            CommandBufferImpl* m_commandBuffer;
            void init(D3D12Device* renderer, CommandBufferImpl* commandBuffer)
            {
                m_commandBuffer = commandBuffer;
            }
            virtual SLANG_NO_THROW void SLANG_MCALL copyBuffer(
                IBufferResource* dst,
                size_t dstOffset,
                IBufferResource* src,
                size_t srcOffset,
                size_t size) override
            {
                auto dstBuffer = static_cast<BufferResourceImpl*>(dst);
                auto srcBuffer = static_cast<BufferResourceImpl*>(src);

                m_commandBuffer->m_cmdList->CopyBufferRegion(
                    dstBuffer->m_resource.getResource(),
                    dstOffset,
                    srcBuffer->m_resource.getResource(),
                    srcOffset,
                    size);
            }
            virtual SLANG_NO_THROW void SLANG_MCALL uploadBufferData(
                IBufferResource* dst,
                size_t offset,
                size_t size,
                void* data) override
            {
                _uploadBufferData(
                    m_commandBuffer->m_cmdList,
                    static_cast<BufferResourceImpl*>(dst),
                    offset,
                    size,
                    data);
            }
            virtual SLANG_NO_THROW void SLANG_MCALL endEncoding() {}
        };

        ResourceCommandEncoderImpl m_resourceCommandEncoder;

        virtual SLANG_NO_THROW void SLANG_MCALL
            encodeResourceCommands(IResourceCommandEncoder** outEncoder) override
        {
            m_resourceCommandEncoder.init(m_renderer, this);
            *outEncoder = &m_resourceCommandEncoder;
        }

        virtual SLANG_NO_THROW void SLANG_MCALL close() override { m_cmdList->Close(); }
    };

    class CommandQueueImpl
        : public ICommandQueue
        , public RefObject
    {
    public:
        SLANG_REF_OBJECT_IUNKNOWN_ALL
        ICommandQueue* getInterface(const Guid& guid)
        {
            if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_ICommandQueue)
                return static_cast<ICommandQueue*>(this);
            return nullptr;
        }

    public:
        D3D12Device* m_renderer;
        ComPtr<ID3D12Device> m_device;
        ComPtr<ID3D12CommandQueue> m_d3dQueue;
        ComPtr<ID3D12Fence> m_fence;
        uint64_t m_fenceValue = 0;
        HANDLE globalWaitHandle;
        Desc m_desc;
        uint32_t m_queueIndex = 0;
        
        Result init(D3D12Device* device, uint32_t queueIndex)
        {
            m_queueIndex = queueIndex;
            m_renderer = device;
            m_device = device->m_device;
            D3D12_COMMAND_QUEUE_DESC queueDesc = {};
            queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
            SLANG_RETURN_ON_FAIL(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(m_d3dQueue.writeRef())));
            SLANG_RETURN_ON_FAIL(
                m_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(m_fence.writeRef())));
            globalWaitHandle = CreateEventEx(
                nullptr,
                nullptr,
                CREATE_EVENT_INITIAL_SET | CREATE_EVENT_MANUAL_RESET,
                EVENT_ALL_ACCESS);
            return SLANG_OK;
        }
        ~CommandQueueImpl()
        {
            wait();
            CloseHandle(globalWaitHandle);
            m_renderer->m_queueIndexAllocator.free((int)m_queueIndex, 1);
        }
        virtual SLANG_NO_THROW const Desc& SLANG_MCALL getDesc() override
        {
            return m_desc;
        }
        
        virtual SLANG_NO_THROW void SLANG_MCALL
            executeCommandBuffers(uint32_t count, ICommandBuffer* const* commandBuffers) override
        {
            ShortList<ID3D12CommandList*> commandLists;
            for (uint32_t i = 0; i < count; i++)
            {
                auto cmdImpl = static_cast<CommandBufferImpl*>(commandBuffers[i]);
                commandLists.add(cmdImpl->m_cmdList);
            }
            m_d3dQueue->ExecuteCommandLists((UINT)count, commandLists.getArrayView().getBuffer());

            m_fenceValue++;

            for (uint32_t i = 0; i < count; i++)
            {
                if (i > 0 && commandBuffers[i] == commandBuffers[i - 1])
                    continue;
                auto cmdImpl = static_cast<CommandBufferImpl*>(commandBuffers[i]);
                auto transientHeap = cmdImpl->m_transientHeap;
                auto& waitInfo = transientHeap->getQueueWaitInfo(m_queueIndex);
                waitInfo.waitValue = m_fenceValue;
                ResetEvent(waitInfo.fenceEvent);
                m_fence->SetEventOnCompletion(m_fenceValue, waitInfo.fenceEvent);
            }
            m_d3dQueue->Signal(m_fence, m_fenceValue);
            ResetEvent(globalWaitHandle);
        }

        virtual SLANG_NO_THROW void SLANG_MCALL wait() override
        {
            m_fenceValue++;
            m_d3dQueue->Signal(m_fence, m_fenceValue);
            ResetEvent(globalWaitHandle);
            m_fence->SetEventOnCompletion(m_fenceValue, globalWaitHandle);
            WaitForSingleObject(globalWaitHandle, INFINITE);
        }
    };

    class SwapchainImpl : public D3DSwapchainBase
    {
    public:
        ComPtr<ID3D12CommandQueue> m_queue;
        ComPtr<IDXGIFactory> m_dxgiFactory;
        ComPtr<IDXGISwapChain3> m_swapChain3;
        ComPtr<ID3D12Fence> m_fence;
        ShortList<HANDLE, kMaxNumRenderFrames> m_frameEvents;
        uint64_t fenceValue = 0;
        Result init(
            D3D12Device* renderer,
            const ISwapchain::Desc& swapchainDesc,
            WindowHandle window)
        {
            m_queue = static_cast<CommandQueueImpl*>(swapchainDesc.queue)->m_d3dQueue;
            m_dxgiFactory = renderer->m_deviceInfo.m_dxgiFactory;
            SLANG_RETURN_ON_FAIL(
                D3DSwapchainBase::init(swapchainDesc, window, DXGI_SWAP_EFFECT_FLIP_DISCARD));
            renderer->m_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(m_fence.writeRef()));

            SLANG_RETURN_ON_FAIL(m_swapChain->QueryInterface(m_swapChain3.writeRef()));
            for (uint32_t i = 0; i < swapchainDesc.imageCount; i++)
            {
                m_frameEvents.add(CreateEventEx(
                    nullptr,
                    false,
                    CREATE_EVENT_INITIAL_SET | CREATE_EVENT_MANUAL_RESET,
                    EVENT_ALL_ACCESS));
            }
            return SLANG_OK;
        }

        virtual void createSwapchainBufferImages() override
        {
            m_images.clear();
            
            for (uint32_t i = 0; i < m_desc.imageCount; i++)
            {
                ComPtr<ID3D12Resource> d3dResource;
                m_swapChain->GetBuffer(i, IID_PPV_ARGS(d3dResource.writeRef()));
                ITextureResource::Desc imageDesc = {};
                imageDesc.setDefaults(IResource::Usage::RenderTarget);
                imageDesc.init2D(
                    IResource::Type::Texture2D, m_desc.format, m_desc.width, m_desc.height, 0);
                RefPtr<TextureResourceImpl> image = new TextureResourceImpl(imageDesc);
                image->m_resource.setResource(d3dResource.get());
                image->m_defaultState = D3D12_RESOURCE_STATE_PRESENT;
                ComPtr<ITextureResource> imageResourcePtr;
                imageResourcePtr = image.Ptr();
                m_images.add(imageResourcePtr);
            }
            for (auto evt : m_frameEvents)
                SetEvent(evt);
        }
        virtual IDXGIFactory* getDXGIFactory() override { return m_dxgiFactory; }
        virtual IUnknown* getOwningDevice() override { return m_queue; }
        virtual SLANG_NO_THROW int SLANG_MCALL acquireNextImage() override
        {
            auto result = (int)m_swapChain3->GetCurrentBackBufferIndex();
            WaitForSingleObject(m_frameEvents[result], INFINITE);
            ResetEvent(m_frameEvents[result]);
            return result;
        }
        virtual SLANG_NO_THROW Result SLANG_MCALL present() override
        {
            SLANG_RETURN_ON_FAIL(D3DSwapchainBase::present());
            fenceValue++;
            m_fence->SetEventOnCompletion(fenceValue, m_frameEvents[m_swapChain3->GetCurrentBackBufferIndex()]);
            m_queue->Signal(m_fence, fenceValue);
            return SLANG_OK;
        }
    };

    static PROC loadProc(HMODULE module, char const* name);

    Result createCommandQueueImpl(CommandQueueImpl** outQueue);

    Result createTransientResourceHeapImpl(
        size_t constantBufferSize,
        uint32_t viewDescriptors,
        uint32_t samplerDescriptors,
        TransientResourceHeapImpl** outHeap);

    Result createBuffer(
        const D3D12_RESOURCE_DESC& resourceDesc,
        const void* srcData,
        size_t srcDataSize,
        D3D12Resource& uploadResource,
        D3D12_RESOURCE_STATES finalState,
        D3D12Resource& resourceOut);

    Result captureTextureToSurface(
        D3D12Resource& resource,
        ResourceState state,
        ISlangBlob** blob,
        size_t* outRowPitch,
        size_t* outPixelSize);

    Result _createDevice(
        DeviceCheckFlags deviceCheckFlags,
        const UnownedStringSlice& nameMatch,
        D3D_FEATURE_LEVEL featureLevel,
        DeviceInfo& outDeviceInfo);

    struct ResourceCommandRecordInfo
    {
        ComPtr<ICommandBuffer> commandBuffer;
        ID3D12GraphicsCommandList* d3dCommandList;
    };
    ResourceCommandRecordInfo encodeResourceCommands()
    {
        ResourceCommandRecordInfo info;
        m_resourceCommandTransientHeap->createCommandBuffer(info.commandBuffer.writeRef());
        info.d3dCommandList = static_cast<CommandBufferImpl*>(info.commandBuffer.get())->m_cmdList;
        return info;
    }
    void submitResourceCommandsAndWait(const ResourceCommandRecordInfo& info)
    {
        info.commandBuffer->close();
        m_resourceCommandQueue->executeCommandBuffer(info.commandBuffer);
        m_resourceCommandTransientHeap->synchronizeAndReset();
    }

    // D3D12Device members.

    Desc m_desc;

    gfx::DeviceInfo m_info;
    String m_adapterName;

    bool m_isInitialized = false;

    ComPtr<ID3D12Debug> m_dxDebug;

    DeviceInfo m_deviceInfo;
    ID3D12Device* m_device = nullptr;

    VirtualObjectPool m_queueIndexAllocator;

    RefPtr<CommandQueueImpl> m_resourceCommandQueue;
    RefPtr<TransientResourceHeapImpl> m_resourceCommandTransientHeap;

    D3D12GeneralDescriptorHeap m_rtvAllocator;
    D3D12GeneralDescriptorHeap m_dsvAllocator;
    // Space in the GPU-visible heaps is precious, so we will also keep
    // around CPU-visible heaps for storing descriptors in a format
    // that is ready for copying into the GPU-visible heaps as needed.
    //
    D3D12GeneralDescriptorHeap m_cpuViewHeap; ///< Cbv, Srv, Uav
    D3D12GeneralDescriptorHeap m_cpuSamplerHeap; ///< Heap for samplers

    // Dll entry points
    PFN_D3D12_GET_DEBUG_INTERFACE m_D3D12GetDebugInterface = nullptr;
    PFN_D3D12_CREATE_DEVICE m_D3D12CreateDevice = nullptr;
    PFN_D3D12_SERIALIZE_ROOT_SIGNATURE m_D3D12SerializeRootSignature = nullptr;

    bool m_nvapi = false;
};

SLANG_NO_THROW Result SLANG_MCALL D3D12Device::TransientResourceHeapImpl::synchronizeAndReset()
{
    Array<HANDLE, 16> waitHandles;
    for (auto& waitInfo : m_waitInfos)
    {
        if (waitInfo.waitValue != 0)
            waitHandles.add(waitInfo.fenceEvent);
    }
    WaitForMultipleObjects((DWORD)waitHandles.getCount(), waitHandles.getBuffer(), TRUE, INFINITE);
    m_viewHeap.deallocateAll();
    m_samplerHeap.deallocateAll();
    m_commandListAllocId = 0;
    SLANG_RETURN_ON_FAIL(m_commandAllocator->Reset());
    Super::reset();
    return SLANG_OK;
}

Result D3D12Device::TransientResourceHeapImpl::createCommandBuffer(ICommandBuffer** outCmdBuffer)
{
    if ((Index)m_commandListAllocId < m_commandBufferPool.getCount())
    {
        auto result = static_cast<D3D12Device::CommandBufferImpl*>(
            m_commandBufferPool[m_commandListAllocId].get());
        m_d3dCommandListPool[m_commandListAllocId]->Reset(m_commandAllocator, nullptr);
        result->init(m_device, m_d3dCommandListPool[m_commandListAllocId], this);
        ++m_commandListAllocId;
        result->addRef();
        *outCmdBuffer = result;
        return SLANG_OK;
    }
    ComPtr<ID3D12GraphicsCommandList> cmdList;
    m_device->m_device->CreateCommandList(
        0,
        D3D12_COMMAND_LIST_TYPE_DIRECT,
        m_commandAllocator,
        nullptr,
        IID_PPV_ARGS(cmdList.writeRef()));

    m_d3dCommandListPool.add(cmdList);
    RefPtr<CommandBufferImpl> cmdBuffer = new CommandBufferImpl();
    cmdBuffer->init(m_device, cmdList, this);
    ComPtr<ICommandBuffer> cmdBufferPtr;
    *cmdBufferPtr.writeRef() = cmdBuffer.detach();
    m_commandBufferPool.add(cmdBufferPtr);
    ++m_commandListAllocId;
    *outCmdBuffer = cmdBufferPtr.detach();
    return SLANG_OK;
}

Result D3D12Device::PipelineCommandEncoder::_bindRenderState(Submitter* submitter)
{
    RefPtr<PipelineStateBase> newPipeline;
    RootShaderObjectImpl* rootObjectImpl = &m_commandBuffer->m_rootShaderObject;
    m_renderer->maybeSpecializePipeline(m_currentPipeline, rootObjectImpl, newPipeline);
    PipelineStateImpl* newPipelineImpl = static_cast<PipelineStateImpl*>(newPipeline.Ptr());
    auto commandList = m_d3dCmdList;
    auto pipelineTypeIndex = (int)newPipelineImpl->desc.type;
    auto programImpl = static_cast<ShaderProgramImpl*>(newPipelineImpl->m_program.get());
    commandList->SetPipelineState(newPipelineImpl->m_pipelineState);
    submitter->setRootSignature(programImpl->m_rootObjectLayout->m_rootSignature);
    RefPtr<ShaderObjectLayoutImpl> specializedRootLayout;
    SLANG_RETURN_ON_FAIL(rootObjectImpl->getSpecializedLayout(specializedRootLayout.writeRef()));
    RootShaderObjectLayoutImpl* rootLayoutImpl =
        static_cast<RootShaderObjectLayoutImpl*>(specializedRootLayout.Ptr());

    ShortList<DescriptorTable> descriptorTables;       
    auto descSetInfo = rootLayoutImpl->getDescriptorSetInfo();
    auto heap = m_commandBuffer->m_transientHeap;
    for (auto& descSet : rootLayoutImpl->m_gpuDescriptorSetInfos)
    {
        if (descSet.resourceDescriptorCount)
        {
            DescriptorTable table;
            table.heap = &heap->m_viewHeap;
            table.table = heap->m_viewHeap.allocate((int)descSet.resourceDescriptorCount);
            descriptorTables.add(table);
        }
        if (descSet.samplerDescriptorCount)
        {
            DescriptorTable table;
            table.heap = &heap->m_samplerHeap;
            table.table = heap->m_samplerHeap.allocate((int)descSet.samplerDescriptorCount);
            descriptorTables.add(table);
        }
    }
    RootBindingState bindState = {};
    bindState.device = m_renderer;
    bindState.transientHeap = m_transientHeap;
    auto descTablesView = descriptorTables.getArrayView();
    bindState.descriptorTables = descTablesView.arrayView;
    SLANG_RETURN_ON_FAIL(rootObjectImpl->bindObject(this, &bindState));
    
    for (Index i = 0; i < descriptorTables.getCount(); i++)
    {
        submitter->setRootDescriptorTable(
            (int)i, descriptorTables[i].heap.getGpuHandle(descriptorTables[i].table));
    }
    return SLANG_OK;
}

Result D3D12Device::createTransientResourceHeapImpl(
    size_t constantBufferSize,
    uint32_t viewDescriptors,
    uint32_t samplerDescriptors,
    TransientResourceHeapImpl** outHeap)
{
    RefPtr<TransientResourceHeapImpl> result = new TransientResourceHeapImpl();
    ITransientResourceHeap::Desc desc = {};
    desc.constantBufferSize = constantBufferSize;
    SLANG_RETURN_ON_FAIL(result->init(desc, this, viewDescriptors, samplerDescriptors));
    *outHeap = result.detach();
    return SLANG_OK;
}

Result D3D12Device::createCommandQueueImpl(D3D12Device::CommandQueueImpl** outQueue)
{
    int queueIndex = m_queueIndexAllocator.alloc(1);
    // If we run out of queue index space, then the user is requesting too many queues.
    if (queueIndex == -1)
        return SLANG_FAIL;

    RefPtr<D3D12Device::CommandQueueImpl> queue = new D3D12Device::CommandQueueImpl();
    SLANG_RETURN_ON_FAIL(queue->init(this, (uint32_t)queueIndex));
    *outQueue = queue.detach();
    return SLANG_OK;
}

SlangResult SLANG_MCALL createD3D12Device(const IDevice::Desc* desc, IDevice** outDevice)
{
    RefPtr<D3D12Device> result = new D3D12Device();
    SLANG_RETURN_ON_FAIL(result->initialize(*desc));
    *outDevice = result.detach();
    return SLANG_OK;
}

/* static */PROC D3D12Device::loadProc(HMODULE module, char const* name)
{
    PROC proc = ::GetProcAddress(module, name);
    if (!proc)
    {
        fprintf(stderr, "error: failed load symbol '%s'\n", name);
        return nullptr;
    }
    return proc;
}

D3D12Device::~D3D12Device()
{
}

static void _initSrvDesc(IResource::Type resourceType, const ITextureResource::Desc& textureDesc, const D3D12_RESOURCE_DESC& desc, DXGI_FORMAT pixelFormat, D3D12_SHADER_RESOURCE_VIEW_DESC& descOut)
{
    // create SRV
    descOut = D3D12_SHADER_RESOURCE_VIEW_DESC();

    descOut.Format = (pixelFormat == DXGI_FORMAT_UNKNOWN) ? D3DUtil::calcFormat(D3DUtil::USAGE_SRV, desc.Format) : pixelFormat;
    descOut.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    if (desc.DepthOrArraySize == 1)
    {
        switch (desc.Dimension)
        {
            case D3D12_RESOURCE_DIMENSION_TEXTURE1D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; break;
            case D3D12_RESOURCE_DIMENSION_TEXTURE2D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; break;
            case D3D12_RESOURCE_DIMENSION_TEXTURE3D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; break;
            default: assert(!"Unknown dimension");
        }

        descOut.Texture2D.MipLevels = desc.MipLevels;
        descOut.Texture2D.MostDetailedMip = 0;
        descOut.Texture2D.PlaneSlice = 0;
        descOut.Texture2D.ResourceMinLODClamp = 0.0f;
    }
    else if (resourceType == IResource::Type::TextureCube)
    {
        if (textureDesc.arraySize > 1)
        {
            descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;

            descOut.TextureCubeArray.NumCubes = textureDesc.arraySize;
            descOut.TextureCubeArray.First2DArrayFace = 0;
            descOut.TextureCubeArray.MipLevels = desc.MipLevels;
            descOut.TextureCubeArray.MostDetailedMip = 0;
            descOut.TextureCubeArray.ResourceMinLODClamp = 0;
        }
        else
        {
            descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;

            descOut.TextureCube.MipLevels = desc.MipLevels;
            descOut.TextureCube.MostDetailedMip = 0;
            descOut.TextureCube.ResourceMinLODClamp = 0;
        }
    }
    else
    {
        assert(desc.DepthOrArraySize > 1);

        switch (desc.Dimension)
        {
            case D3D12_RESOURCE_DIMENSION_TEXTURE1D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; break;
            case D3D12_RESOURCE_DIMENSION_TEXTURE2D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; break;
            case D3D12_RESOURCE_DIMENSION_TEXTURE3D:  descOut.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; break;

            default: assert(!"Unknown dimension");
        }

        descOut.Texture2DArray.ArraySize = desc.DepthOrArraySize;
        descOut.Texture2DArray.MostDetailedMip = 0;
        descOut.Texture2DArray.MipLevels = desc.MipLevels;
        descOut.Texture2DArray.FirstArraySlice = 0;
        descOut.Texture2DArray.PlaneSlice = 0;
        descOut.Texture2DArray.ResourceMinLODClamp = 0;
    }
}

Result D3D12Device::createBuffer(const D3D12_RESOURCE_DESC& resourceDesc, const void* srcData, size_t srcDataSize, D3D12Resource& uploadResource, D3D12_RESOURCE_STATES finalState, D3D12Resource& resourceOut)
{
   const  size_t bufferSize = size_t(resourceDesc.Width);

    {
        D3D12_HEAP_PROPERTIES heapProps;
        heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
        heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
        heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
        heapProps.CreationNodeMask = 1;
        heapProps.VisibleNodeMask = 1;

        const D3D12_RESOURCE_STATES initialState = srcData ? D3D12_RESOURCE_STATE_COPY_DEST : finalState;

        SLANG_RETURN_ON_FAIL(resourceOut.initCommitted(m_device, heapProps, D3D12_HEAP_FLAG_NONE, resourceDesc, initialState, nullptr));
    }

    {
        D3D12_HEAP_PROPERTIES heapProps;
        heapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
        heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
        heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
        heapProps.CreationNodeMask = 1;
        heapProps.VisibleNodeMask = 1;

        D3D12_RESOURCE_DESC uploadResourceDesc(resourceDesc);
        uploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

        SLANG_RETURN_ON_FAIL(uploadResource.initCommitted(m_device, heapProps, D3D12_HEAP_FLAG_NONE, uploadResourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr));
    }

    if (srcData)
    {
        // Copy data to the intermediate upload heap and then schedule a copy
        // from the upload heap to the vertex buffer.
        UINT8* dstData;
        D3D12_RANGE readRange = {};         // We do not intend to read from this resource on the CPU.

        ID3D12Resource* dxUploadResource = uploadResource.getResource();

        SLANG_RETURN_ON_FAIL(dxUploadResource->Map(0, &readRange, reinterpret_cast<void**>(&dstData)));
        ::memcpy(dstData, srcData, srcDataSize);
        dxUploadResource->Unmap(0, nullptr);

        auto encodeInfo = encodeResourceCommands();
        encodeInfo.d3dCommandList->CopyBufferRegion(resourceOut, 0, uploadResource, 0, bufferSize);
        submitResourceCommandsAndWait(encodeInfo);
    }

    return SLANG_OK;
}

Result D3D12Device::captureTextureToSurface(
    D3D12Resource& resource,
    ResourceState state,
    ISlangBlob** outBlob,
    size_t* outRowPitch,
    size_t* outPixelSize)
{
    const D3D12_RESOURCE_STATES initialState = D3DUtil::translateResourceState(state);

    const D3D12_RESOURCE_DESC desc = resource.getResource()->GetDesc();

    // Don't bother supporting MSAA for right now
    if (desc.SampleDesc.Count > 1)
    {
        fprintf(stderr, "ERROR: cannot capture multi-sample texture\n");
        return SLANG_FAIL;
    }

    size_t bytesPerPixel = sizeof(uint32_t);
    size_t rowPitch = int(desc.Width) * bytesPerPixel;
    size_t bufferSize = rowPitch * int(desc.Height);
    if (outRowPitch)
        *outRowPitch = rowPitch;
    if (outPixelSize)
        *outPixelSize = bytesPerPixel;
 
    D3D12Resource stagingResource;
    {
        D3D12_RESOURCE_DESC stagingDesc;
        _initBufferResourceDesc(bufferSize, stagingDesc);

        D3D12_HEAP_PROPERTIES heapProps;
        heapProps.Type = D3D12_HEAP_TYPE_READBACK;
        heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
        heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
        heapProps.CreationNodeMask = 1;
        heapProps.VisibleNodeMask = 1;

        SLANG_RETURN_ON_FAIL(stagingResource.initCommitted(m_device, heapProps, D3D12_HEAP_FLAG_NONE, stagingDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr));
    }

    auto encodeInfo = encodeResourceCommands();
    auto currentState = D3DUtil::translateResourceState(state);

    {
        D3D12BarrierSubmitter submitter(encodeInfo.d3dCommandList);
        resource.transition(currentState, D3D12_RESOURCE_STATE_COPY_SOURCE, submitter);
    }

    // Do the copy
    {
        D3D12_TEXTURE_COPY_LOCATION srcLoc;
        srcLoc.pResource = resource;
        srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
        srcLoc.SubresourceIndex = 0;

        D3D12_TEXTURE_COPY_LOCATION dstLoc;
        dstLoc.pResource = stagingResource;
        dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
        dstLoc.PlacedFootprint.Offset = 0;
        dstLoc.PlacedFootprint.Footprint.Format = desc.Format;
        dstLoc.PlacedFootprint.Footprint.Width = UINT(desc.Width);
        dstLoc.PlacedFootprint.Footprint.Height = UINT(desc.Height);
        dstLoc.PlacedFootprint.Footprint.Depth = 1;
        dstLoc.PlacedFootprint.Footprint.RowPitch = UINT(rowPitch);

        encodeInfo.d3dCommandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, nullptr);
    }

    {
        D3D12BarrierSubmitter submitter(encodeInfo.d3dCommandList);
        resource.transition(D3D12_RESOURCE_STATE_COPY_SOURCE, currentState, submitter);
    }

    // Submit the copy, and wait for copy to complete
    submitResourceCommandsAndWait(encodeInfo);

    {
        ID3D12Resource* dxResource = stagingResource;

        UINT8* data;
        D3D12_RANGE readRange = {0, bufferSize};

        SLANG_RETURN_ON_FAIL(dxResource->Map(0, &readRange, reinterpret_cast<void**>(&data)));

        RefPtr<Slang::ListBlob> resultBlob = new Slang::ListBlob();
        resultBlob->m_data.setCount(bufferSize);
        memcpy(resultBlob->m_data.getBuffer(), data, bufferSize);
        dxResource->Unmap(0, nullptr);
        *outBlob = resultBlob.detach();
        return SLANG_OK;
    }
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!! Renderer interface !!!!!!!!!!!!!!!!!!!!!!!!!!

Result D3D12Device::_createDevice(DeviceCheckFlags deviceCheckFlags, const UnownedStringSlice& nameMatch, D3D_FEATURE_LEVEL featureLevel, DeviceInfo& outDeviceInfo)
{
    outDeviceInfo.clear();

    ComPtr<IDXGIFactory> dxgiFactory;
    SLANG_RETURN_ON_FAIL(D3DUtil::createFactory(deviceCheckFlags, dxgiFactory));

    List<ComPtr<IDXGIAdapter>> dxgiAdapters;
    SLANG_RETURN_ON_FAIL(D3DUtil::findAdapters(deviceCheckFlags, nameMatch, dxgiFactory, dxgiAdapters));

    ComPtr<ID3D12Device> device;
    ComPtr<IDXGIAdapter> adapter;

    for (Index i = 0; i < dxgiAdapters.getCount(); ++i)
    {
        IDXGIAdapter* dxgiAdapter = dxgiAdapters[i];
        if (SLANG_SUCCEEDED(m_D3D12CreateDevice(dxgiAdapter, featureLevel, IID_PPV_ARGS(device.writeRef()))))
        {
            adapter = dxgiAdapter;
            break;
        }
    }

    if (!device)
    {
        return SLANG_FAIL;
    }

    if (m_dxDebug && (deviceCheckFlags & DeviceCheckFlag::UseDebug))
    {
        m_dxDebug->EnableDebugLayer();

        ComPtr<ID3D12InfoQueue> infoQueue;
        if (SLANG_SUCCEEDED(device->QueryInterface(infoQueue.writeRef())))
        {
            // Make break 
            infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
            infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
            // infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true);

            // Apparently there is a problem with sm 6.3 with spurious errors, with debug layer enabled
            D3D12_FEATURE_DATA_SHADER_MODEL featureShaderModel;
            featureShaderModel.HighestShaderModel = D3D_SHADER_MODEL(0x63);
            SLANG_SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &featureShaderModel, sizeof(featureShaderModel)));

            if (featureShaderModel.HighestShaderModel >= D3D_SHADER_MODEL(0x63))
            {
                // Filter out any messages that cause issues
                // TODO: Remove this when the debug layers work properly
                D3D12_MESSAGE_ID messageIds[] =
                {
                    // When the debug layer is enabled this error is triggered sometimes after a CopyDescriptorsSimple
                    // call The failed check validates that the source and destination ranges of the copy do not
                    // overlap. The check assumes descriptor handles are pointers to memory, but this is not always the
                    // case and the check fails (even though everything is okay).
                    D3D12_MESSAGE_ID_COPY_DESCRIPTORS_INVALID_RANGES,
                };

                // We filter INFO messages because they are way too many
                D3D12_MESSAGE_SEVERITY severities[] = { D3D12_MESSAGE_SEVERITY_INFO };

                D3D12_INFO_QUEUE_FILTER infoQueueFilter = {};
                infoQueueFilter.DenyList.NumSeverities = SLANG_COUNT_OF(severities);
                infoQueueFilter.DenyList.pSeverityList = severities;
                infoQueueFilter.DenyList.NumIDs = SLANG_COUNT_OF(messageIds);
                infoQueueFilter.DenyList.pIDList = messageIds;

                infoQueue->PushStorageFilter(&infoQueueFilter);
            }
        }
    }

    // Get the descs
    {
        adapter->GetDesc(&outDeviceInfo.m_desc);

        // Look up GetDesc1 info
        ComPtr<IDXGIAdapter1> adapter1;
        if (SLANG_SUCCEEDED(adapter->QueryInterface(adapter1.writeRef())))
        {
            adapter1->GetDesc1(&outDeviceInfo.m_desc1);
        }
    }

    // Save other info
    outDeviceInfo.m_device = device;
    outDeviceInfo.m_dxgiFactory = dxgiFactory;
    outDeviceInfo.m_adapter = adapter;
    outDeviceInfo.m_isWarp = D3DUtil::isWarp(dxgiFactory, adapter);

    return SLANG_OK;
}

static bool _isSupportedNVAPIOp(ID3D12Device* dev, uint32_t op)
{
#ifdef GFX_NVAPI
    {
        bool isSupported;
        NvAPI_Status status = NvAPI_D3D12_IsNvShaderExtnOpCodeSupported(dev, NvU32(op), &isSupported);
        return status == NVAPI_OK && isSupported;
    }
#else
    return false;
#endif
}

Result D3D12Device::initialize(const Desc& desc)
{
    SLANG_RETURN_ON_FAIL(slangContext.initialize(desc.slang, SLANG_DXBC, "sm_5_1"));

    SLANG_RETURN_ON_FAIL(RendererBase::initialize(desc));

    // Initialize queue index allocator.
    // Support max 32 queues.
    m_queueIndexAllocator.initPool(32);

    // Initialize DeviceInfo
    {
        m_info.deviceType = DeviceType::DirectX12;
        m_info.bindingStyle = BindingStyle::DirectX;
        m_info.projectionStyle = ProjectionStyle::DirectX;
        m_info.apiName = "Direct3D 12";
        static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
        ::memcpy(m_info.identityProjectionMatrix, kIdentity, sizeof(kIdentity));
    }

    // Rather than statically link against D3D, we load it dynamically.

    HMODULE d3dModule = LoadLibraryA("d3d12.dll");
    if (!d3dModule)
    {
        fprintf(stderr, "error: failed load 'd3d12.dll'\n");
        return SLANG_FAIL;
    }

    // Get all the dll entry points
    m_D3D12SerializeRootSignature = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)loadProc(d3dModule, "D3D12SerializeRootSignature");
    if (!m_D3D12SerializeRootSignature)
    {
        return SLANG_FAIL;
    }

#if ENABLE_DEBUG_LAYER
    m_D3D12GetDebugInterface = (PFN_D3D12_GET_DEBUG_INTERFACE)loadProc(d3dModule, "D3D12GetDebugInterface");
    if (m_D3D12GetDebugInterface)
    {
        if (SLANG_SUCCEEDED(m_D3D12GetDebugInterface(IID_PPV_ARGS(m_dxDebug.writeRef()))))
        {
#if 0
            // Can enable for extra validation. NOTE! That d3d12 warns if you do.... 
            // D3D12 MESSAGE : Device Debug Layer Startup Options : GPU - Based Validation is enabled(disabled by default).
            // This results in new validation not possible during API calls on the CPU, by creating patched shaders that have validation
            // added directly to the shader. However, it can slow things down a lot, especially for applications with numerous
            // PSOs.Time to see the first render frame may take several minutes.
            // [INITIALIZATION MESSAGE #1016: CREATEDEVICE_DEBUG_LAYER_STARTUP_OPTIONS]

            ComPtr<ID3D12Debug1> debug1;
            if (SLANG_SUCCEEDED(m_dxDebug->QueryInterface(debug1.writeRef())))
            {
                debug1->SetEnableGPUBasedValidation(true);
            }
#endif

            m_dxDebug->EnableDebugLayer();
        }
    }
#endif

    m_D3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)loadProc(d3dModule, "D3D12CreateDevice");
    if (!m_D3D12CreateDevice)
    {
        return SLANG_FAIL;
    }

    FlagCombiner combiner;
    // TODO: we should probably provide a command-line option
    // to override UseDebug of default rather than leave it
    // up to each back-end to specify.
#if ENABLE_DEBUG_LAYER
    combiner.add(DeviceCheckFlag::UseDebug, ChangeType::OnOff);                 ///< First try debug then non debug
#else
    combiner.add(DeviceCheckFlag::UseDebug, ChangeType::Off);                   ///< Don't bother with debug
#endif
    combiner.add(DeviceCheckFlag::UseHardwareDevice, ChangeType::OnOff);        ///< First try hardware, then reference
    
    const D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;

    const int numCombinations = combiner.getNumCombinations();
    for (int i = 0; i < numCombinations; ++i)
    {
        if (SLANG_SUCCEEDED(_createDevice(combiner.getCombination(i), UnownedStringSlice(desc.adapter), featureLevel, m_deviceInfo)))
        {
            break;
        }
    }

    if (!m_deviceInfo.m_adapter)
    {
        // Couldn't find an adapter
        return SLANG_FAIL;
    }

    // Set the device
    m_device = m_deviceInfo.m_device;

    // NVAPI
    if (desc.nvapiExtnSlot >= 0)
    {
        if (SLANG_FAILED(NVAPIUtil::initialize()))
        {
            return SLANG_E_NOT_AVAILABLE;
        }

#ifdef GFX_NVAPI
        // From DOCS: Applications are expected to bind null UAV to this slot.
        // NOTE! We don't currently do this, but doesn't seem to be a problem.

        const NvAPI_Status status = NvAPI_D3D12_SetNvShaderExtnSlotSpace(m_device, NvU32(desc.nvapiExtnSlot), NvU32(0));
        
        if (status != NVAPI_OK)
        {
            return SLANG_E_NOT_AVAILABLE;
        }

        if (_isSupportedNVAPIOp(m_device, NV_EXTN_OP_UINT64_ATOMIC))
        {
            m_features.add("atomic-int64");
        }
        if (_isSupportedNVAPIOp(m_device, NV_EXTN_OP_FP32_ATOMIC))
        {
            m_features.add("atomic-float");
        }

        m_nvapi = true;
#endif

    }

    // Find what features are supported
    {
        // Check this is how this is laid out...
        SLANG_COMPILE_TIME_ASSERT(D3D_SHADER_MODEL_6_0 == 0x60);

        {
            D3D12_FEATURE_DATA_SHADER_MODEL featureShaderModel;
            featureShaderModel.HighestShaderModel = D3D_SHADER_MODEL(0x62);

            // TODO: Currently warp causes a crash when using half, so disable for now
            if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &featureShaderModel, sizeof(featureShaderModel))) &&
                m_deviceInfo.m_isWarp == false &&
                featureShaderModel.HighestShaderModel >= 0x62)
            {
                // With sm_6_2 we have half
                m_features.add("half");
            }
        }
        // Check what min precision support we have
        {
            D3D12_FEATURE_DATA_D3D12_OPTIONS options;
            if (SLANG_SUCCEEDED(m_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))))
            {
                auto minPrecisionSupport = options.MinPrecisionSupport;
            }
        }
    }

    m_desc = desc;

    // Create a command queue for internal resource transfer operations.
    SLANG_RETURN_ON_FAIL(createCommandQueueImpl(m_resourceCommandQueue.writeRef()));
    SLANG_RETURN_ON_FAIL(createTransientResourceHeapImpl(0, 8, 4, m_resourceCommandTransientHeap.writeRef()));

    SLANG_RETURN_ON_FAIL(m_cpuViewHeap.init(
        m_device, 8192, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
    SLANG_RETURN_ON_FAIL(m_cpuSamplerHeap.init(
        m_device, 1024, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));

    SLANG_RETURN_ON_FAIL(m_rtvAllocator.init(
        m_device, 16, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));
    SLANG_RETURN_ON_FAIL(m_dsvAllocator.init(
        m_device, 16, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE));

    ComPtr<IDXGIDevice> dxgiDevice;
    if (m_deviceInfo.m_adapter)
    {
        DXGI_ADAPTER_DESC adapterDesc;
        m_deviceInfo.m_adapter->GetDesc(&adapterDesc);
        m_adapterName = String::fromWString(adapterDesc.Description);
        m_info.adapterName = m_adapterName.begin();
    }

    m_isInitialized = true;
    return SLANG_OK;
}

Result D3D12Device::createTransientResourceHeap(
    const ITransientResourceHeap::Desc& desc,
    ITransientResourceHeap** outHeap)
{
    RefPtr<TransientResourceHeapImpl> heap;
    SLANG_RETURN_ON_FAIL(
        createTransientResourceHeapImpl(desc.constantBufferSize, 8192, 1024, heap.writeRef()));
    *outHeap = heap.detach();
    return SLANG_OK;
}

Result D3D12Device::createCommandQueue(const ICommandQueue::Desc& desc, ICommandQueue** outQueue)
{
    RefPtr<CommandQueueImpl> queue;
    SLANG_RETURN_ON_FAIL(createCommandQueueImpl(queue.writeRef()));
    *outQueue = queue.detach();
    return SLANG_OK;
}

SLANG_NO_THROW Result SLANG_MCALL D3D12Device::createSwapchain(
    const ISwapchain::Desc& desc, WindowHandle window, ISwapchain** outSwapchain)
{
    RefPtr<SwapchainImpl> swapchain = new SwapchainImpl();
    SLANG_RETURN_ON_FAIL(swapchain->init(this, desc, window));
    *outSwapchain = swapchain.detach();
    return SLANG_OK;
}

SlangResult D3D12Device::readTextureResource(
    ITextureResource* resource,
    ResourceState state,
    ISlangBlob** outBlob,
    size_t* outRowPitch,
    size_t* outPixelSize)
{
    return captureTextureToSurface(
        static_cast<TextureResourceImpl*>(resource)->m_resource,
        state,
        outBlob,
        outRowPitch,
        outPixelSize);
}

static D3D12_RESOURCE_STATES _calcResourceState(IResource::Usage usage)
{
    typedef IResource::Usage Usage;
    switch (usage)
    {
        case Usage::VertexBuffer:           return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
        case Usage::IndexBuffer:            return D3D12_RESOURCE_STATE_INDEX_BUFFER;
        case Usage::ConstantBuffer:         return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
        case Usage::StreamOutput:           return D3D12_RESOURCE_STATE_STREAM_OUT;
        case Usage::RenderTarget:           return D3D12_RESOURCE_STATE_RENDER_TARGET;
        case Usage::DepthWrite:             return D3D12_RESOURCE_STATE_DEPTH_WRITE;
        case Usage::DepthRead:              return D3D12_RESOURCE_STATE_DEPTH_READ;
        case Usage::UnorderedAccess:        return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
        case Usage::PixelShaderResource:    return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
        case Usage::NonPixelShaderResource: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
        case Usage::ShaderResource:         return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE |
                                                   D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
        case Usage::GenericRead:            return D3D12_RESOURCE_STATE_GENERIC_READ;
        case Usage::CopySource:             return D3D12_RESOURCE_STATE_COPY_SOURCE;
        case Usage::CopyDest:               return D3D12_RESOURCE_STATE_COPY_DEST;
        default: return D3D12_RESOURCE_STATES(0);
    }
}

static D3D12_RESOURCE_FLAGS _calcResourceFlag(IResource::BindFlag::Enum bindFlag)
{
    typedef IResource::BindFlag BindFlag;
    switch (bindFlag)
    {
        case BindFlag::RenderTarget:        return D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
        case BindFlag::DepthStencil:        return D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
        case BindFlag::UnorderedAccess:     return D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
        default:                            return D3D12_RESOURCE_FLAG_NONE;
    }
}

static D3D12_RESOURCE_FLAGS _calcResourceBindFlags(IResource::Usage initialUsage, int bindFlags)
{
    int dstFlags = 0;
    while (bindFlags)
    {
        int lsb = bindFlags & -bindFlags;

        dstFlags |= _calcResourceFlag(IResource::BindFlag::Enum(lsb));
        bindFlags &= ~lsb;
    }
    return D3D12_RESOURCE_FLAGS(dstFlags);
}

static D3D12_RESOURCE_DIMENSION _calcResourceDimension(IResource::Type type)
{
    switch (type)
    {
        case IResource::Type::Buffer:        return D3D12_RESOURCE_DIMENSION_BUFFER;
        case IResource::Type::Texture1D:     return D3D12_RESOURCE_DIMENSION_TEXTURE1D;
        case IResource::Type::TextureCube:
        case IResource::Type::Texture2D:
        {
            return D3D12_RESOURCE_DIMENSION_TEXTURE2D;
        }
        case IResource::Type::Texture3D:     return D3D12_RESOURCE_DIMENSION_TEXTURE3D;
        default:                            return D3D12_RESOURCE_DIMENSION_UNKNOWN;
    }
}

Result D3D12Device::createTextureResource(IResource::Usage initialUsage, const ITextureResource::Desc& descIn, const ITextureResource::SubresourceData* initData, ITextureResource** outResource)
{
    // Description of uploading on Dx12
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dn899215%28v=vs.85%29.aspx

    TextureResource::Desc srcDesc(descIn);
    srcDesc.setDefaults(initialUsage);

    const DXGI_FORMAT pixelFormat = D3DUtil::getMapFormat(srcDesc.format);
    if (pixelFormat == DXGI_FORMAT_UNKNOWN)
    {
        return SLANG_FAIL;
    }

    const int arraySize = srcDesc.calcEffectiveArraySize();

    const D3D12_RESOURCE_DIMENSION dimension = _calcResourceDimension(srcDesc.type);
    if (dimension == D3D12_RESOURCE_DIMENSION_UNKNOWN)
    {
        return SLANG_FAIL;
    }

    const int numMipMaps = srcDesc.numMipLevels;

    // Setup desc
    D3D12_RESOURCE_DESC resourceDesc;

    resourceDesc.Dimension = dimension;
    resourceDesc.Format = pixelFormat;
    resourceDesc.Width = srcDesc.size.width;
    resourceDesc.Height = srcDesc.size.height;
    resourceDesc.DepthOrArraySize = (srcDesc.size.depth > 1) ? srcDesc.size.depth : arraySize;

    resourceDesc.MipLevels = numMipMaps;
    resourceDesc.SampleDesc.Count = srcDesc.sampleDesc.numSamples;
    resourceDesc.SampleDesc.Quality = srcDesc.sampleDesc.quality;

    resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
    resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

    switch (initialUsage)
    {
    case IResource::Usage::RenderTarget:
        resourceDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
        break;
    case IResource::Usage::DepthWrite:
        resourceDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
        break;
    case IResource::Usage::UnorderedAccess:
        resourceDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
        break;
    default:
        break;
    }

    resourceDesc.Alignment = 0;

    RefPtr<TextureResourceImpl> texture(new TextureResourceImpl(srcDesc));

    // Create the target resource
    {
        D3D12_HEAP_PROPERTIES heapProps;

        heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
        heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
        heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
        heapProps.CreationNodeMask = 1;
        heapProps.VisibleNodeMask = 1;

        D3D12_CLEAR_VALUE clearValue;
        D3D12_CLEAR_VALUE* clearValuePtr = &clearValue;
        if ((resourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
                                   D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) == 0)
        {
            clearValuePtr = nullptr;
        }
        clearValue.Format = pixelFormat;
        memcpy(clearValue.Color, &descIn.optimalClearValue.color, sizeof(clearValue.Color));
        clearValue.DepthStencil.Depth = descIn.optimalClearValue.depthStencil.depth;
        clearValue.DepthStencil.Stencil = descIn.optimalClearValue.depthStencil.stencil;
        SLANG_RETURN_ON_FAIL(texture->m_resource.initCommitted(
            m_device,
            heapProps,
            D3D12_HEAP_FLAG_NONE,
            resourceDesc,
            D3D12_RESOURCE_STATE_COPY_DEST,
            clearValuePtr));

        texture->m_resource.setDebugName(L"Texture");
    }

    // Calculate the layout
    List<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> layouts;
    layouts.setCount(numMipMaps);
    List<UInt64> mipRowSizeInBytes;
    mipRowSizeInBytes.setCount(numMipMaps);
    List<UInt32> mipNumRows;
    mipNumRows.setCount(numMipMaps);

    // NOTE! This is just the size for one array upload -> not for the whole texture
    UInt64 requiredSize = 0;
    m_device->GetCopyableFootprints(&resourceDesc, 0, numMipMaps, 0, layouts.begin(), mipNumRows.begin(), mipRowSizeInBytes.begin(), &requiredSize);

    // Sub resource indexing
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dn705766(v=vs.85).aspx#subresource_indexing
    if (initData)
    {
        // Create the upload texture
        D3D12Resource uploadTexture;
       
        {
            D3D12_HEAP_PROPERTIES heapProps;

            heapProps.Type = D3D12_HEAP_TYPE_UPLOAD;
            heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
            heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
            heapProps.CreationNodeMask = 1;
            heapProps.VisibleNodeMask = 1;

            D3D12_RESOURCE_DESC uploadResourceDesc;

            uploadResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
            uploadResourceDesc.Format = DXGI_FORMAT_UNKNOWN;
            uploadResourceDesc.Width = requiredSize;
            uploadResourceDesc.Height = 1;
            uploadResourceDesc.DepthOrArraySize = 1;
            uploadResourceDesc.MipLevels = 1;
            uploadResourceDesc.SampleDesc.Count = 1;
            uploadResourceDesc.SampleDesc.Quality = 0;
            uploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
            uploadResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
            uploadResourceDesc.Alignment = 0;

            SLANG_RETURN_ON_FAIL(uploadTexture.initCommitted(m_device, heapProps, D3D12_HEAP_FLAG_NONE, uploadResourceDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr));

            uploadTexture.setDebugName(L"TextureUpload");
        }
        // Get the pointer to the upload resource
        ID3D12Resource* uploadResource = uploadTexture;

        int subResourceIndex = 0;
        for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
        {
            uint8_t* p;
            uploadResource->Map(0, nullptr, reinterpret_cast<void**>(&p));

            for (int j = 0; j < numMipMaps; ++j)
            {
                auto srcSubresource = initData[j];

                const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& layout = layouts[j];
                const D3D12_SUBRESOURCE_FOOTPRINT& footprint = layout.Footprint;

                const TextureResource::Size mipSize = srcDesc.size.calcMipSize(j);

                assert(footprint.Width == mipSize.width && footprint.Height == mipSize.height && footprint.Depth == mipSize.depth);

                auto mipRowSize = mipRowSizeInBytes[j];

                const ptrdiff_t dstMipRowPitch = ptrdiff_t(footprint.RowPitch);
                const ptrdiff_t srcMipRowPitch = ptrdiff_t(srcSubresource.strideY);

                const ptrdiff_t dstMipLayerPitch = ptrdiff_t(footprint.RowPitch*footprint.Height);
                const ptrdiff_t srcMipLayerPitch = ptrdiff_t(srcSubresource.strideZ);

                // Our outer loop will copy the depth layers one at a time.
                //
                const uint8_t* srcLayer = (const uint8_t*) srcSubresource.data;
                uint8_t* dstLayer = p + layouts[j].Offset;
                for (int l = 0; l < mipSize.depth; l++)
                {
                    // Our inner loop will copy the rows one at a time.
                    //
                    const uint8_t* srcRow = srcLayer;
                    uint8_t* dstRow = dstLayer;
                    for (int k = 0; k < mipSize.height; ++k)
                    {
                        ::memcpy(dstRow, srcRow, (size_t)mipRowSize);

                        srcRow += srcMipRowPitch;
                        dstRow += dstMipRowPitch;
                    }

                    srcLayer += srcMipLayerPitch;
                    dstLayer += dstMipLayerPitch;
                }

                //assert(srcRow == (const uint8_t*)(srcMip.getBuffer() + srcMip.getCount()));
            }
            uploadResource->Unmap(0, nullptr);

            auto encodeInfo = encodeResourceCommands();
            for (int mipIndex = 0; mipIndex < numMipMaps; ++mipIndex)
            {
                // https://msdn.microsoft.com/en-us/library/windows/desktop/dn903862(v=vs.85).aspx

                D3D12_TEXTURE_COPY_LOCATION src;
                src.pResource = uploadTexture;
                src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
                src.PlacedFootprint = layouts[mipIndex];

                D3D12_TEXTURE_COPY_LOCATION dst;
                dst.pResource = texture->m_resource;
                dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
                dst.SubresourceIndex = subResourceIndex;
                encodeInfo.d3dCommandList->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);

                subResourceIndex++;
            }

            // Block - waiting for copy to complete (so can drop upload texture)
            submitResourceCommandsAndWait(encodeInfo);
        }
    }
    {
        auto encodeInfo = encodeResourceCommands();
        const D3D12_RESOURCE_STATES finalState = _calcResourceState(initialUsage);
        {
            D3D12BarrierSubmitter submitter(encodeInfo.d3dCommandList);
            texture->m_resource.transition(D3D12_RESOURCE_STATE_COPY_DEST, finalState, submitter);
        }
        submitResourceCommandsAndWait(encodeInfo);
    }

    *outResource = texture.detach();
    return SLANG_OK;
}

Result D3D12Device::createBufferResource(IResource::Usage initialUsage, const IBufferResource::Desc& descIn, const void* initData, IBufferResource** outResource)
{
    BufferResource::Desc srcDesc(descIn);
    srcDesc.setDefaults(initialUsage);

    // Always align up to 256 bytes, since that is required for constant buffers.
    //
    // TODO: only do this for buffers that could potentially be bound as constant buffers...
    //
    const size_t alignedSizeInBytes = D3DUtil::calcAligned(srcDesc.sizeInBytes, 256);

    RefPtr<BufferResourceImpl> buffer(new BufferResourceImpl(initialUsage, srcDesc));

    D3D12_RESOURCE_DESC bufferDesc;
    _initBufferResourceDesc(alignedSizeInBytes, bufferDesc);

    bufferDesc.Flags = _calcResourceBindFlags(initialUsage, srcDesc.bindFlags);

    const D3D12_RESOURCE_STATES initialState = _calcResourceState(initialUsage);
    SLANG_RETURN_ON_FAIL(createBuffer(bufferDesc, initData, srcDesc.sizeInBytes, buffer->m_uploadResource, initialState, buffer->m_resource));

    *outResource = buffer.detach();
    return SLANG_OK;
}

D3D12_FILTER_TYPE translateFilterMode(TextureFilteringMode mode)
{
    switch (mode)
    {
    default:
        return D3D12_FILTER_TYPE(0);

#define CASE(SRC, DST) \
    case TextureFilteringMode::SRC: return D3D12_FILTER_TYPE_##DST

        CASE(Point, POINT);
        CASE(Linear, LINEAR);

#undef CASE
    }
}

D3D12_FILTER_REDUCTION_TYPE translateFilterReduction(TextureReductionOp op)
{
    switch (op)
    {
    default:
        return D3D12_FILTER_REDUCTION_TYPE(0);

#define CASE(SRC, DST) \
    case TextureReductionOp::SRC: return D3D12_FILTER_REDUCTION_TYPE_##DST

        CASE(Average, STANDARD);
        CASE(Comparison, COMPARISON);
        CASE(Minimum, MINIMUM);
        CASE(Maximum, MAXIMUM);

#undef CASE
    }
}

D3D12_TEXTURE_ADDRESS_MODE translateAddressingMode(TextureAddressingMode mode)
{
    switch (mode)
    {
    default:
        return D3D12_TEXTURE_ADDRESS_MODE(0);

#define CASE(SRC, DST) \
    case TextureAddressingMode::SRC: return D3D12_TEXTURE_ADDRESS_MODE_##DST

    CASE(Wrap,          WRAP);
    CASE(ClampToEdge,   CLAMP);
    CASE(ClampToBorder, BORDER);
    CASE(MirrorRepeat,  MIRROR);
    CASE(MirrorOnce,    MIRROR_ONCE);

#undef CASE
    }
}

static D3D12_COMPARISON_FUNC translateComparisonFunc(ComparisonFunc func)
{
    switch (func)
    {
    default:
        // TODO: need to report failures
        return D3D12_COMPARISON_FUNC_ALWAYS;

#define CASE(FROM, TO) \
    case ComparisonFunc::FROM: return D3D12_COMPARISON_FUNC_##TO

        CASE(Never, NEVER);
        CASE(Less, LESS);
        CASE(Equal, EQUAL);
        CASE(LessEqual, LESS_EQUAL);
        CASE(Greater, GREATER);
        CASE(NotEqual, NOT_EQUAL);
        CASE(GreaterEqual, GREATER_EQUAL);
        CASE(Always, ALWAYS);
#undef CASE
    }
}

Result D3D12Device::createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler)
{
    D3D12_FILTER_REDUCTION_TYPE dxReduction = translateFilterReduction(desc.reductionOp);
    D3D12_FILTER dxFilter;
    if (desc.maxAnisotropy > 1)
    {
        dxFilter = D3D12_ENCODE_ANISOTROPIC_FILTER(dxReduction);
    }
    else
    {
        D3D12_FILTER_TYPE dxMin = translateFilterMode(desc.minFilter);
        D3D12_FILTER_TYPE dxMag = translateFilterMode(desc.magFilter);
        D3D12_FILTER_TYPE dxMip = translateFilterMode(desc.mipFilter);

        dxFilter = D3D12_ENCODE_BASIC_FILTER(dxMin, dxMag, dxMip, dxReduction);
    }

    D3D12_SAMPLER_DESC dxDesc = {};
    dxDesc.Filter = dxFilter;
    dxDesc.AddressU = translateAddressingMode(desc.addressU);
    dxDesc.AddressV = translateAddressingMode(desc.addressV);
    dxDesc.AddressW = translateAddressingMode(desc.addressW);
    dxDesc.MipLODBias = desc.mipLODBias;
    dxDesc.MaxAnisotropy = desc.maxAnisotropy;
    dxDesc.ComparisonFunc = translateComparisonFunc(desc.comparisonFunc);
    for (int ii = 0; ii < 4; ++ii)
        dxDesc.BorderColor[ii] = desc.borderColor[ii];
    dxDesc.MinLOD = desc.minLOD;
    dxDesc.MaxLOD = desc.maxLOD;

    auto samplerHeap = &m_cpuSamplerHeap;

    D3D12Descriptor cpuDescriptor;
    samplerHeap->allocate(&cpuDescriptor);
    m_device->CreateSampler(&dxDesc, cpuDescriptor.cpuHandle);

    // TODO: We really ought to have a free-list of sampler-heap
    // entries that we check before we go to the heap, and then
    // when we are done with a sampler we simply add it to the free list.
    //
    RefPtr<SamplerStateImpl> samplerImpl = new SamplerStateImpl();
    samplerImpl->m_renderer = this;
    samplerImpl->m_descriptor = cpuDescriptor;
    *outSampler = samplerImpl.detach();
    return SLANG_OK;
}

Result D3D12Device::createTextureView(ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView)
{
    auto resourceImpl = (TextureResourceImpl*) texture;

    RefPtr<ResourceViewImpl> viewImpl = new ResourceViewImpl();
    viewImpl->m_resource = resourceImpl;

    switch (desc.type)
    {
    default:
        return SLANG_FAIL;

    case IResourceView::Type::RenderTarget:
        {
            SLANG_RETURN_ON_FAIL(m_rtvAllocator.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_rtvAllocator;
            D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
            rtvDesc.Format = D3DUtil::getMapFormat(desc.format);
            switch (desc.renderTarget.shape)
            {
            case IResource::Type::Texture1D:
                rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D;
                rtvDesc.Texture1D.MipSlice = desc.renderTarget.mipSlice;
                break;
            case IResource::Type::Texture2D:
                rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
                rtvDesc.Texture2D.MipSlice = desc.renderTarget.mipSlice;
                rtvDesc.Texture2D.PlaneSlice = desc.renderTarget.planeIndex;
                break;
            case IResource::Type::Texture3D:
                rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
                rtvDesc.Texture3D.MipSlice = desc.renderTarget.mipSlice;
                rtvDesc.Texture3D.FirstWSlice = desc.renderTarget.arrayIndex;
                rtvDesc.Texture3D.WSize = desc.renderTarget.arraySize;
                break;
            default:
                return SLANG_FAIL;
            }
            m_device->CreateRenderTargetView(
                resourceImpl->m_resource, &rtvDesc, viewImpl->m_descriptor.cpuHandle);
        }
        break;

    case IResourceView::Type::DepthStencil:
        {
            SLANG_RETURN_ON_FAIL(m_dsvAllocator.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_dsvAllocator;
            D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
            dsvDesc.Format = D3DUtil::getMapFormat(desc.format);
            switch (desc.renderTarget.shape)
            {
            case IResource::Type::Texture1D:
                dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D;
                dsvDesc.Texture1D.MipSlice = desc.renderTarget.mipSlice;
                break;
            case IResource::Type::Texture2D:
                dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
                dsvDesc.Texture2D.MipSlice = desc.renderTarget.mipSlice;
                break;
            default:
                return SLANG_FAIL;
            }
            m_device->CreateDepthStencilView(
                resourceImpl->m_resource, &dsvDesc, viewImpl->m_descriptor.cpuHandle);
        }
        break;

    case IResourceView::Type::UnorderedAccess:
        {
            // TODO: need to support the separate "counter resource" for the case
            // of append/consume buffers with attached counters.

            SLANG_RETURN_ON_FAIL(m_cpuViewHeap.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_cpuViewHeap;
            m_device->CreateUnorderedAccessView(resourceImpl->m_resource, nullptr, nullptr, viewImpl->m_descriptor.cpuHandle);
        }
        break;

    case IResourceView::Type::ShaderResource:
        {
            SLANG_RETURN_ON_FAIL(m_cpuViewHeap.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_cpuViewHeap;

            // Need to construct the D3D12_SHADER_RESOURCE_VIEW_DESC because otherwise TextureCube is not accessed
            // appropriately (rather than just passing nullptr to CreateShaderResourceView)
            const D3D12_RESOURCE_DESC resourceDesc = resourceImpl->m_resource.getResource()->GetDesc();
            const DXGI_FORMAT pixelFormat = resourceDesc.Format;

            D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
            _initSrvDesc(resourceImpl->getType(), *resourceImpl->getDesc(), resourceDesc, pixelFormat, srvDesc);

            m_device->CreateShaderResourceView(resourceImpl->m_resource, &srvDesc, viewImpl->m_descriptor.cpuHandle);
        }
        break;
    }

    *outView = viewImpl.detach();
    return SLANG_OK;
}

Result D3D12Device::createBufferView(IBufferResource* buffer, IResourceView::Desc const& desc, IResourceView** outView)
{
    auto resourceImpl = (BufferResourceImpl*) buffer;
    auto resourceDesc = *resourceImpl->getDesc();

    RefPtr<ResourceViewImpl> viewImpl = new ResourceViewImpl();
    viewImpl->m_resource = resourceImpl;

    switch (desc.type)
    {
    default:
        return SLANG_FAIL;

    case IResourceView::Type::UnorderedAccess:
        {
            D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
            uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
            uavDesc.Format = D3DUtil::getMapFormat(desc.format);
            uavDesc.Buffer.FirstElement = 0;

            if(resourceDesc.elementSize)
            {
                uavDesc.Buffer.StructureByteStride = resourceDesc.elementSize;
                uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
            }
            else if(desc.format == Format::Unknown)
            {
                uavDesc.Buffer.Flags |= D3D12_BUFFER_UAV_FLAG_RAW;
                uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
                uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / 4);
            }
            else
            {
                uavDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / gfxGetFormatSize(desc.format));
            }


            // TODO: need to support the separate "counter resource" for the case
            // of append/consume buffers with attached counters.

            SLANG_RETURN_ON_FAIL(m_cpuViewHeap.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_cpuViewHeap;
            m_device->CreateUnorderedAccessView(resourceImpl->m_resource, nullptr, &uavDesc, viewImpl->m_descriptor.cpuHandle);
        }
        break;

    case IResourceView::Type::ShaderResource:
        {
            D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
            srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
            srvDesc.Format = D3DUtil::getMapFormat(desc.format);
            srvDesc.Buffer.StructureByteStride = 0;
            srvDesc.Buffer.FirstElement = 0;
            srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
            if(resourceDesc.elementSize)
            {
                srvDesc.Buffer.StructureByteStride = resourceDesc.elementSize;
                srvDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / resourceDesc.elementSize);
            }
            else if(desc.format == Format::Unknown)
            {
                srvDesc.Buffer.Flags |= D3D12_BUFFER_SRV_FLAG_RAW;
                srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
                srvDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / 4);
            }
            else
            {
                srvDesc.Buffer.NumElements = UINT(resourceDesc.sizeInBytes / gfxGetFormatSize(desc.format));
            }

            SLANG_RETURN_ON_FAIL(m_cpuViewHeap.allocate(&viewImpl->m_descriptor));
            viewImpl->m_allocator = &m_cpuViewHeap;
            m_device->CreateShaderResourceView(resourceImpl->m_resource, &srvDesc, viewImpl->m_descriptor.cpuHandle);
        }
        break;
    }

    *outView = viewImpl.detach();
    return SLANG_OK;
}

Result D3D12Device::createFramebuffer(IFramebuffer::Desc const& desc, IFramebuffer** outFb)
{
    RefPtr<FramebufferImpl> framebuffer = new FramebufferImpl();
    framebuffer->renderTargetViews.setCount(desc.renderTargetCount);
    framebuffer->renderTargetDescriptors.setCount(desc.renderTargetCount);
    framebuffer->renderTargetClearValues.setCount(desc.renderTargetCount);
    for (uint32_t i = 0; i < desc.renderTargetCount; i++)
    {
        framebuffer->renderTargetViews[i] = desc.renderTargetViews[i];
        framebuffer->renderTargetDescriptors[i] =
            static_cast<ResourceViewImpl*>(desc.renderTargetViews[i])->m_descriptor.cpuHandle;
        auto clearValue =
            static_cast<TextureResourceImpl*>(
                static_cast<ResourceViewImpl*>(desc.renderTargetViews[i])->m_resource.Ptr())
                ->getDesc()
                ->optimalClearValue.color;
        memcpy(&framebuffer->renderTargetClearValues[i], &clearValue, sizeof(ColorClearValue));
    }
    framebuffer->depthStencilView = desc.depthStencilView;
    if (desc.depthStencilView)
    {
        framebuffer->depthStencilClearValue =
            static_cast<TextureResourceImpl*>(
                static_cast<ResourceViewImpl*>(desc.depthStencilView)->m_resource.Ptr())
                ->getDesc()
                ->optimalClearValue.depthStencil;
        framebuffer->depthStencilDescriptor =
            static_cast<ResourceViewImpl*>(desc.depthStencilView)->m_descriptor.cpuHandle;
    }
    else
    {
        framebuffer->depthStencilDescriptor.ptr = 0;
    }
    *outFb = framebuffer.detach();
    return SLANG_OK;
}

Result D3D12Device::createFramebufferLayout(
    IFramebufferLayout::Desc const& desc, IFramebufferLayout** outLayout)
{
    RefPtr<FramebufferLayoutImpl> layout = new FramebufferLayoutImpl();
    layout->m_renderTargets.setCount(desc.renderTargetCount);
    for (uint32_t i = 0; i < desc.renderTargetCount; i++)
    {
        layout->m_renderTargets[i] = desc.renderTargets[i];
    }
    
    if (desc.depthStencil)
    {
        layout->m_hasDepthStencil = true;
        layout->m_depthStencil = *desc.depthStencil;
    }
    else
    {
        layout->m_hasDepthStencil = false;
    }
    *outLayout = layout.detach();
    return SLANG_OK;
}

Result D3D12Device::createRenderPassLayout(
    const IRenderPassLayout::Desc& desc,
    IRenderPassLayout** outRenderPassLayout)
{
    RefPtr<RenderPassLayoutImpl> result = new RenderPassLayoutImpl();
    result->init(desc);
    *outRenderPassLayout = result.detach();
    return SLANG_OK;
}

Result D3D12Device::createInputLayout(const InputElementDesc* inputElements, UInt inputElementCount, IInputLayout** outLayout)
{
    RefPtr<InputLayoutImpl> layout(new InputLayoutImpl);

    // Work out a buffer size to hold all text
    size_t textSize = 0;
    for (int i = 0; i < Int(inputElementCount); ++i)
    {
        const char* text = inputElements[i].semanticName;
        textSize += text ? (::strlen(text) + 1) : 0;
    }
    layout->m_text.setCount(textSize);
    char* textPos = layout->m_text.getBuffer();

    //
    List<D3D12_INPUT_ELEMENT_DESC>& elements = layout->m_elements;
    elements.setCount(inputElementCount);


    for (UInt i = 0; i < inputElementCount; ++i)
    {
        const InputElementDesc& srcEle = inputElements[i];
        D3D12_INPUT_ELEMENT_DESC& dstEle = elements[i];

        // Add text to the buffer
        const char* semanticName = srcEle.semanticName;
        if (semanticName)
        {
            const int len = int(::strlen(semanticName));
            ::memcpy(textPos, semanticName, len + 1);
            semanticName = textPos;
            textPos += len + 1;
        }

        dstEle.SemanticName = semanticName;
        dstEle.SemanticIndex = (UINT)srcEle.semanticIndex;
        dstEle.Format = D3DUtil::getMapFormat(srcEle.format);
        dstEle.InputSlot = 0;
        dstEle.AlignedByteOffset = (UINT)srcEle.offset;
        dstEle.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
        dstEle.InstanceDataStepRate = 0;
    }

    *outLayout = layout.detach();
    return SLANG_OK;
}

Result D3D12Device::readBufferResource(
    IBufferResource* bufferIn,
    size_t offset,
    size_t size,
    ISlangBlob** outBlob)
{
    auto encodeInfo = encodeResourceCommands();

    BufferResourceImpl* buffer = static_cast<BufferResourceImpl*>(bufferIn);

    const size_t bufferSize = buffer->getDesc()->sizeInBytes;

    // This will be slow!!! - it blocks CPU on GPU completion
    D3D12Resource& resource = buffer->m_resource;

    // Readback heap
    D3D12_HEAP_PROPERTIES heapProps;
    heapProps.Type = D3D12_HEAP_TYPE_READBACK;
    heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
    heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
    heapProps.CreationNodeMask = 1;
    heapProps.VisibleNodeMask = 1;

    // Resource to readback to
    D3D12_RESOURCE_DESC stagingDesc;
    _initBufferResourceDesc(bufferSize, stagingDesc);

    D3D12Resource stageBuf;
    SLANG_RETURN_ON_FAIL(stageBuf.initCommitted(m_device, heapProps, D3D12_HEAP_FLAG_NONE, stagingDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr));

    // Do the copy
    encodeInfo.d3dCommandList->CopyBufferRegion(stageBuf, 0, resource, 0, bufferSize);

    // Wait until complete
    submitResourceCommandsAndWait(encodeInfo);

    // Map and copy
    RefPtr<ListBlob> blob = new ListBlob();
    {
        UINT8* data;
        D3D12_RANGE readRange = { 0, bufferSize };

        SLANG_RETURN_ON_FAIL(stageBuf.getResource()->Map(0, &readRange, reinterpret_cast<void**>(&data)));

        // Copy to memory buffer
        blob->m_data.setCount(bufferSize);
        ::memcpy(blob->m_data.getBuffer(), data, bufferSize);

        stageBuf.getResource()->Unmap(0, nullptr);
    }
    *outBlob = blob.detach();
    return SLANG_OK;
}

Result D3D12Device::createProgram(const IShaderProgram::Desc& desc, IShaderProgram** outProgram)
{
    RefPtr<ShaderProgramImpl> shaderProgram = new ShaderProgramImpl();
    shaderProgram->m_pipelineType = desc.pipelineType;
    shaderProgram->slangProgram = desc.slangProgram;
    RootShaderObjectLayoutImpl::create(
        this,
        desc.slangProgram,
        desc.slangProgram->getLayout(),
        shaderProgram->m_rootObjectLayout.writeRef());
    if (desc.slangProgram->getSpecializationParamCount() != 0)
    {
        // For a specializable program, we don't invoke any actual slang compilation yet.
        *outProgram = shaderProgram.detach();
        return SLANG_OK;
    }
    // For a fully specialized program, read and store its kernel code in `shaderProgram`.
    auto programReflection = desc.slangProgram->getLayout();
    for (SlangUInt i = 0; i < programReflection->getEntryPointCount(); i++)
    {
        auto entryPointInfo = programReflection->getEntryPointByIndex(i);
        auto stage = entryPointInfo->getStage();
        ComPtr<ISlangBlob> kernelCode;
        ComPtr<ISlangBlob> diagnostics;
        auto compileResult = desc.slangProgram->getEntryPointCode(
            (SlangInt)i, 0, kernelCode.writeRef(), diagnostics.writeRef());
        if (diagnostics)
        {
            // TODO: report compile error.
        }
        SLANG_RETURN_ON_FAIL(compileResult);
        List<uint8_t>* shaderCodeDestBuffer = nullptr;
        switch (stage)
        {
        case SLANG_STAGE_COMPUTE:
            shaderCodeDestBuffer = &shaderProgram->m_computeShader;
            break;
        case SLANG_STAGE_VERTEX:
            shaderCodeDestBuffer = &shaderProgram->m_vertexShader;
            break;
        case SLANG_STAGE_FRAGMENT:
            shaderCodeDestBuffer = &shaderProgram->m_pixelShader;
            break;
        default:
            SLANG_ASSERT(!"unsupported shader stage.");
            return SLANG_FAIL;
        }
        shaderCodeDestBuffer->addRange(
            reinterpret_cast<const uint8_t*>(kernelCode->getBufferPointer()),
            (Index)kernelCode->getBufferSize());
    }
    *outProgram = shaderProgram.detach();
    return SLANG_OK;
}

Result D3D12Device::createShaderObjectLayout(
    slang::TypeLayoutReflection* typeLayout,
    ShaderObjectLayoutBase** outLayout)
{
    RefPtr<ShaderObjectLayoutImpl> layout;
    SLANG_RETURN_ON_FAIL(
        ShaderObjectLayoutImpl::createForElementType(
        this, typeLayout, layout.writeRef()));
    *outLayout = layout.detach();
    return SLANG_OK;
}

Result D3D12Device::createShaderObject(
    ShaderObjectLayoutBase* layout,
    IShaderObject** outObject)
{
    RefPtr<ShaderObjectImpl> shaderObject;
    SLANG_RETURN_ON_FAIL(ShaderObjectImpl::create(
        this, reinterpret_cast<ShaderObjectLayoutImpl*>(layout),
        shaderObject.writeRef()));
    *outObject = shaderObject.detach();
    return SLANG_OK;
}

Result D3D12Device::createGraphicsPipelineState(const GraphicsPipelineStateDesc& inDesc, IPipelineState** outState)
{
    GraphicsPipelineStateDesc desc = inDesc;
    auto programImpl = (ShaderProgramImpl*) desc.program;

    if (!programImpl->m_rootObjectLayout->m_rootSignature)
    {
        RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
        pipelineStateImpl->init(desc);
        *outState = pipelineStateImpl.detach();
        return SLANG_OK;
    }

    // Only actually create a D3D12 pipeline state if the pipeline is fully specialized.
    auto inputLayoutImpl = (InputLayoutImpl*) desc.inputLayout;

    // Describe and create the graphics pipeline state object (PSO)
    D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};

    psoDesc.pRootSignature = programImpl->m_rootObjectLayout->m_rootSignature;

    psoDesc.VS = { programImpl->m_vertexShader.getBuffer(), SIZE_T(programImpl->m_vertexShader.getCount()) };
    psoDesc.PS = { programImpl->m_pixelShader .getBuffer(), SIZE_T(programImpl->m_pixelShader .getCount()) };

    psoDesc.InputLayout = { inputLayoutImpl->m_elements.getBuffer(), UINT(inputLayoutImpl->m_elements.getCount()) };
    psoDesc.PrimitiveTopologyType = D3DUtil::getPrimitiveType(desc.primitiveType);

    {
        auto framebufferLayout = static_cast<FramebufferLayoutImpl*>(desc.framebufferLayout);
        const int numRenderTargets = int(framebufferLayout->m_renderTargets.getCount());

        if (framebufferLayout->m_hasDepthStencil)
        {
            psoDesc.DSVFormat = D3DUtil::getMapFormat(framebufferLayout->m_depthStencil.format);
        }
        else
        {
            psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
        }
        psoDesc.NumRenderTargets = numRenderTargets;
        for (Int i = 0; i < numRenderTargets; i++)
        {
            psoDesc.RTVFormats[i] =
                D3DUtil::getMapFormat(framebufferLayout->m_renderTargets[i].format);
        }

        psoDesc.SampleDesc.Count = 1;
        psoDesc.SampleDesc.Quality = 0;

        psoDesc.SampleMask = UINT_MAX;
    }

    {
        auto& rs = psoDesc.RasterizerState;
        rs.FillMode = D3D12_FILL_MODE_SOLID;
        rs.CullMode = D3D12_CULL_MODE_NONE;
        rs.FrontCounterClockwise = FALSE;
        rs.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
        rs.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
        rs.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
        rs.DepthClipEnable = TRUE;
        rs.MultisampleEnable = FALSE;
        rs.AntialiasedLineEnable = FALSE;
        rs.ForcedSampleCount = 0;
        rs.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
    }

    {
        D3D12_BLEND_DESC& blend = psoDesc.BlendState;

        blend.AlphaToCoverageEnable = FALSE;
        blend.IndependentBlendEnable = FALSE;
        const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =
        {
            FALSE,FALSE,
            D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
            D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
            D3D12_LOGIC_OP_NOOP,
            D3D12_COLOR_WRITE_ENABLE_ALL,
        };
        for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
        {
            blend.RenderTarget[i] = defaultRenderTargetBlendDesc;
        }
    }

    {
        auto& ds = psoDesc.DepthStencilState;

        ds.DepthEnable = inDesc.depthStencil.depthTestEnable;
        ds.DepthWriteMask = inDesc.depthStencil.depthWriteEnable ? D3D12_DEPTH_WRITE_MASK_ALL
                                                                 : D3D12_DEPTH_WRITE_MASK_ZERO;
        ds.DepthFunc = D3DUtil::getComparisonFunc(inDesc.depthStencil.depthFunc);
        ds.StencilEnable = inDesc.depthStencil.stencilEnable;
        ds.StencilReadMask = (UINT8)inDesc.depthStencil.stencilReadMask;
        ds.StencilWriteMask = (UINT8)inDesc.depthStencil.stencilWriteMask;
        ds.FrontFace = D3DUtil::translateStencilOpDesc(inDesc.depthStencil.frontFace);
        ds.BackFace = D3DUtil::translateStencilOpDesc(inDesc.depthStencil.backFace);
    }

    psoDesc.PrimitiveTopologyType = D3DUtil::getPrimitiveType(desc.primitiveType);

    ComPtr<ID3D12PipelineState> pipelineState;
    SLANG_RETURN_ON_FAIL(m_device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(pipelineState.writeRef())));

    RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
    pipelineStateImpl->m_pipelineState = pipelineState;
    pipelineStateImpl->init(desc);
    *outState = pipelineStateImpl.detach();
    return SLANG_OK;
}

Result D3D12Device::createComputePipelineState(const ComputePipelineStateDesc& inDesc, IPipelineState** outState)
{
    ComputePipelineStateDesc desc = inDesc;

    auto programImpl = (ShaderProgramImpl*) desc.program;
    if (!programImpl->m_rootObjectLayout->m_rootSignature)
    {
        RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
        pipelineStateImpl->init(desc);
        *outState = pipelineStateImpl.detach();
        return SLANG_OK;
    }

    // Only actually create a D3D12 pipeline state if the pipeline is fully specialized.
    ComPtr<ID3D12PipelineState> pipelineState;
    if (!programImpl->slangProgram || programImpl->slangProgram->getSpecializationParamCount() == 0)
    {
        // Describe and create the compute pipeline state object
        D3D12_COMPUTE_PIPELINE_STATE_DESC computeDesc = {};
        computeDesc.pRootSignature = programImpl->m_rootObjectLayout->m_rootSignature;
        computeDesc.CS = {
            programImpl->m_computeShader.getBuffer(),
            SIZE_T(programImpl->m_computeShader.getCount())};

#ifdef GFX_NVAPI
        if (m_nvapi)
        {
            // Also fill the extension structure.
            // Use the same UAV slot index and register space that are declared in the shader.

            // For simplicities sake we just use u0
            NVAPI_D3D12_PSO_SET_SHADER_EXTENSION_SLOT_DESC extensionDesc;
            extensionDesc.baseVersion = NV_PSO_EXTENSION_DESC_VER;
            extensionDesc.version = NV_SET_SHADER_EXTENSION_SLOT_DESC_VER;
            extensionDesc.uavSlot = 0;
            extensionDesc.registerSpace = 0;

            // Put the pointer to the extension into an array - there can be multiple extensions
            // enabled at once.
            const NVAPI_D3D12_PSO_EXTENSION_DESC* extensions[] = {&extensionDesc};

            // Now create the PSO.
            const NvAPI_Status nvapiStatus = NvAPI_D3D12_CreateComputePipelineState(
                m_device,
                &computeDesc,
                SLANG_COUNT_OF(extensions),
                extensions,
                pipelineState.writeRef());

            if (nvapiStatus != NVAPI_OK)
            {
                return SLANG_FAIL;
            }
        }
        else
#endif
        {
            SLANG_RETURN_ON_FAIL(m_device->CreateComputePipelineState(
                &computeDesc, IID_PPV_ARGS(pipelineState.writeRef())));
        }
    }
    RefPtr<PipelineStateImpl> pipelineStateImpl = new PipelineStateImpl();
    pipelineStateImpl->m_pipelineState = pipelineState;
    pipelineStateImpl->init(desc);
    *outState = pipelineStateImpl.detach();
    return SLANG_OK;
}

} // renderer_test