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
|
#include "UnityPrefix.h"
#include "Runtime/GfxDevice/GfxDevice.h"
#include "Runtime/Shaders/GraphicsCaps.h"
#include "D3D11Context.h"
#include "D3D11VBO.h"
#include "External/shaderlab/Library/program.h"
#include "Runtime/GfxDevice/ChannelAssigns.h"
#include "Runtime/GfxDevice/GpuProgramParamsApply.h"
#include "External/shaderlab/Library/TextureBinding.h"
#include "External/shaderlab/Library/properties.h"
#include "D3D11Utils.h"
#include "GpuProgramsD3D11.h"
#include "ShaderPatchingD3D11.h"
#include "TimerQueryD3D11.h"
#include "PlatformDependent/Win/SmartComPointer.h"
#include "PlatformDependent/Win/WinUnicode.h"
#include "Runtime/Camera/CameraUtil.h"
#include "Runtime/Graphics/GraphicsHelper.h"
#include "Runtime/Graphics/Image.h"
#include "Runtime/Utilities/ArrayUtility.h"
#include "Runtime/Misc/Plugins.h"
#if UNITY_EDITOR
#include "D3D11Window.h"
#endif
#include "Runtime/GfxDevice/d3d11/StreamOutSkinnedMesh.h"
class GfxDeviceD3D11;
namespace ShaderLab {
TexEnv* GetTexEnvForBinding( const TextureBinding& binding, const PropertySheet* props ); // pass.cpp
}
#include "GfxDeviceD3D11.h"
extern const InputSignatureD3D11* g_CurrentVSInputD3D11;
extern ID3D11InputLayout* g_ActiveInputLayoutD3D11;
extern D3D11_PRIMITIVE_TOPOLOGY g_ActiveTopologyD3D11;
static ShaderLab::FastPropertyName kSLPropFogCB = ShaderLab::Property ("UnityFogPatchCB");
static const D3D11_COMPARISON_FUNC kCmpFuncD3D11[] = {
D3D11_COMPARISON_ALWAYS, D3D11_COMPARISON_NEVER, D3D11_COMPARISON_LESS, D3D11_COMPARISON_EQUAL, D3D11_COMPARISON_LESS_EQUAL, D3D11_COMPARISON_GREATER, D3D11_COMPARISON_NOT_EQUAL, D3D11_COMPARISON_GREATER_EQUAL, D3D11_COMPARISON_ALWAYS
};
static const D3D11_STENCIL_OP kStencilOpD3D11[] = {
D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_ZERO, D3D11_STENCIL_OP_REPLACE, D3D11_STENCIL_OP_INCR_SAT,
D3D11_STENCIL_OP_DECR_SAT, D3D11_STENCIL_OP_INVERT, D3D11_STENCIL_OP_INCR, D3D11_STENCIL_OP_DECR
};
// Graphics device requires access to reset render textures
bool RebindActiveRenderTargets (TexturesD3D11* textures);
DXGI_FORMAT GetRenderTextureFormat (RenderTextureFormat format, bool sRGB);
DXGI_FORMAT GetShaderResourceViewFormat (RenderTextureFormat format, bool sRGB);
extern DXGI_FORMAT kD3D11RenderResourceFormats[kRTFormatCount];
extern DXGI_FORMAT kD3D11RenderTextureFormatsNorm[kRTFormatCount];
bool SetTopologyD3D11 (GfxPrimitiveType topology, GfxDevice& device, ID3D11DeviceContext* ctx);
void SetInputLayoutD3D11 (ID3D11DeviceContext* ctx, ID3D11InputLayout* layout);
// --------------------------------------------------------------------------
ResolveTexturePool::ResolveTexturePool()
: m_UseCounter(0)
{
memset (m_Entries, 0, sizeof(m_Entries));
}
void ResolveTexturePool::Clear()
{
for (int i = 0; i < ARRAY_SIZE(m_Entries); ++i)
{
SAFE_RELEASE(m_Entries[i].texture);
SAFE_RELEASE(m_Entries[i].srv);
}
}
ResolveTexturePool::Entry* ResolveTexturePool::GetResolveTexture (int width, int height, RenderTextureFormat fmt, bool sRGB)
{
++m_UseCounter;
// check if we have a suitable temporary resolve texture already?
int newIndex = -1;
int lruIndex = 0;
int lruScore = 0;
for (int i = 0; i < ARRAY_SIZE(m_Entries); ++i)
{
Entry& e = m_Entries[i];
if (e.width == width && e.height == height && e.format == fmt && e.sRGB == sRGB)
{
Assert (e.texture);
Assert (e.srv);
e.lastUse = m_UseCounter;
return &e;
}
if (e.width == 0)
{
// unused slot
Assert (e.height == 0 && !e.texture && !e.srv);
if (newIndex == -1)
newIndex = i;
}
else
{
// used slot
if (m_UseCounter - e.lastUse > lruScore)
{
lruIndex = i;
lruScore = m_UseCounter - e.lastUse;
}
}
}
// if all slots are used; release least recently used
if (newIndex == -1)
{
Entry& e = m_Entries[lruIndex];
Assert (e.texture);
e.width = e.height = 0;
SAFE_RELEASE(e.texture);
SAFE_RELEASE(e.srv);
newIndex = lruIndex;
}
Entry& ee = m_Entries[newIndex];
// create texture & SRV in this slot
ID3D11Device* dev = GetD3D11Device();
D3D11_TEXTURE2D_DESC tDesc;
tDesc.Width = width;
tDesc.Height = height;
tDesc.MipLevels = 1;
tDesc.ArraySize = 1;
tDesc.Format = (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0 ? kD3D11RenderResourceFormats[fmt] : kD3D11RenderTextureFormatsNorm[fmt]);
tDesc.SampleDesc.Count = 1;
tDesc.SampleDesc.Quality = 0;
tDesc.Usage = D3D11_USAGE_DEFAULT;
tDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
// 9.x feature levels require the resolved texture to also have a render target flag, otherwise
// CopySubresourceRegion will silently corrupt runtime/driver state.
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level10_0)
tDesc.BindFlags |= D3D11_BIND_RENDER_TARGET;
tDesc.CPUAccessFlags = 0;
tDesc.MiscFlags = 0;
HRESULT hr = dev->CreateTexture2D (&tDesc, NULL, &ee.texture);
if (FAILED(hr))
return NULL;
SetDebugNameD3D11 (ee.texture, Format("ResolveTexture2D-%dx%d", width, height));
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = GetShaderResourceViewFormat (fmt, (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0) ? sRGB : false);
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
hr = dev->CreateShaderResourceView (ee.texture, &srvDesc, &ee.srv);
if (FAILED(hr))
return NULL;
SetDebugNameD3D11 (ee.srv, Format("ResolveTexture2D-SRV-%dx%d", width, height));
ee.width = width;
ee.height = height;
ee.format = fmt;
ee.sRGB = sRGB;
ee.lastUse = m_UseCounter;
return ⅇ
}
// --------------------------------------------------------------------------
static FixedFunctionProgramD3D11* GetFixedFunctionProgram11 (FFProgramCacheD3D11& cache, const FixedFunctionStateD3D11& state)
{
// Do we have one for this state already?
FFProgramCacheD3D11::iterator cachedProgIt = cache.find (state);
if (cachedProgIt != cache.end())
return cachedProgIt->second;
// Don't have one yet, create it
FixedFunctionProgramD3D11* ffProg = new FixedFunctionProgramD3D11 (state);
cache.insert (std::make_pair(state, ffProg));
return ffProg;
}
// --------------------------------------------------------------------------
void GfxDeviceD3D11::SetupDeferredDepthStencilState ()
{
ID3D11DepthStencilState* dss = m_CurrDSState;
if (!dss)
{
DepthStencilState state;
memset (&state, 0, sizeof(state));
if (m_CurrDepthState)
state.d = *m_CurrDepthState;
if (m_CurrStencilState)
state.s = *m_CurrStencilState;
CachedDepthStencilStates::iterator it = m_CachedDepthStencilStates.find(state);
if (it == m_CachedDepthStencilStates.end())
{
D3D11_DEPTH_STENCIL_DESC desc;
memset (&desc, 0, sizeof(desc));
if (m_CurrDepthState)
{
desc.DepthEnable = TRUE;
desc.DepthWriteMask = (m_CurrDepthState->sourceState.depthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO);
desc.DepthFunc = kCmpFuncD3D11[m_CurrDepthState->sourceState.depthFunc];
}
if (m_CurrStencilState)
{
desc.StencilEnable = m_CurrStencilState->sourceState.stencilEnable;
desc.StencilReadMask = m_CurrStencilState->sourceState.readMask;
desc.StencilWriteMask = m_CurrStencilState->sourceState.writeMask;
desc.FrontFace.StencilFunc = kCmpFuncD3D11[m_CurrStencilState->sourceState.stencilFuncFront];
desc.FrontFace.StencilFailOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilFailOpFront];
desc.FrontFace.StencilDepthFailOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilZFailOpFront];
desc.FrontFace.StencilPassOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilPassOpFront];
desc.BackFace.StencilFunc = kCmpFuncD3D11[m_CurrStencilState->sourceState.stencilFuncBack];
desc.BackFace.StencilFailOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilFailOpBack];
desc.BackFace.StencilDepthFailOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilZFailOpBack];
desc.BackFace.StencilPassOp = kStencilOpD3D11[m_CurrStencilState->sourceState.stencilPassOpBack];
}
ID3D11DepthStencilState* d3dstate = NULL;
HRESULT hr = GetD3D11Device()->CreateDepthStencilState (&desc, &d3dstate);
Assert(SUCCEEDED(hr));
SetDebugNameD3D11 (d3dstate, Format("DepthStencilState-%d-%d", desc.DepthWriteMask, desc.DepthFunc));
it = m_CachedDepthStencilStates.insert (std::make_pair(state, d3dstate)).first;
}
dss = it->second;
}
if (dss != m_CurrDSState || m_StencilRef != m_CurrStencilRef)
{
GetD3D11Context()->OMSetDepthStencilState (dss, m_StencilRef);
m_CurrDSState = dss;
m_CurrStencilRef = m_StencilRef;
}
}
void GfxDeviceD3D11::SetupDeferredRasterState ()
{
// raster state; needs to be deferred due to cull winding / scissor / wireframe
// not known at creation time
if (!m_CurrRasterState)
return;
ID3D11RasterizerState* rss = m_CurrRSState;
if (!rss)
{
FinalRasterState11 rsKey;
memcpy (&rsKey.raster, &m_CurrRasterState->sourceState, sizeof(rsKey.raster));
rsKey.backface = (m_CurrRasterState->sourceState.cullMode != kCullOff) && ((m_AppBackfaceMode==m_UserBackfaceMode) == m_InvertProjMatrix);
rsKey.wireframe = m_Wireframe;
rsKey.scissor = m_Scissor;
CachedFinalRasterStates::iterator it = m_CachedFinalRasterStates.find(rsKey);
if (it == m_CachedFinalRasterStates.end())
{
D3D11_RASTERIZER_DESC desc;
memset (&desc, 0, sizeof(desc));
desc.FrontCounterClockwise = rsKey.backface ? TRUE : FALSE;
//TODO: wtf??? DepthBias doesn't work at 9.1
if (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0)
desc.DepthBias = rsKey.raster.sourceState.depthBias;
desc.SlopeScaledDepthBias = rsKey.raster.sourceState.slopeScaledDepthBias;
desc.ScissorEnable = m_Scissor;
desc.MultisampleEnable = TRUE; // only applies to line drawing in MSAA; if set to FALSE lines will be aliased even when MSAA is used
desc.DepthClipEnable = TRUE;
desc.FillMode = rsKey.wireframe ? D3D11_FILL_WIREFRAME : D3D11_FILL_SOLID;
switch (rsKey.raster.sourceState.cullMode)
{
case kCullOff: desc.CullMode = D3D11_CULL_NONE; break;
case kCullFront: desc.CullMode = D3D11_CULL_FRONT; break;
case kCullBack: desc.CullMode = D3D11_CULL_BACK; break;
default: AssertIf("Unsupported cull mode!");
}
ID3D11RasterizerState* d3dstate = NULL;
HRESULT hr = GetD3D11Device()->CreateRasterizerState (&desc, &d3dstate);
Assert(SUCCEEDED(hr));
SetDebugNameD3D11 (d3dstate, Format("RasterizerState-%d-%d", desc.FrontCounterClockwise, desc.FillMode));
it = m_CachedFinalRasterStates.insert (std::make_pair(rsKey, d3dstate)).first;
}
rss = it->second;
}
if (rss != m_CurrRSState)
{
GetD3D11Context()->RSSetState (rss);
m_CurrRSState = rss;
}
}
void UpdateChannelBindingsD3D11 (const ChannelAssigns& channels)
{
DX11_LOG_ENTER_FUNCTION("UpdateChannelBindingsD3D11");
GfxDeviceD3D11& device = static_cast<GfxDeviceD3D11&>(GetRealGfxDevice());
if (!device.IsShaderActive(kShaderVertex))
{
const int maxTexCoords = gGraphicsCaps.maxTexCoords; // fetch here once
UInt64 textureSources = device.m_FFState.texUnitSources;
for (int i = 0; i < maxTexCoords; ++i)
{
UInt32 source = (textureSources >> (i*4)) & 0xF;
if (source > kTexSourceUV7)
continue;
ShaderChannel texCoordChannel = channels.GetSourceForTarget ((VertexComponent)(kVertexCompTexCoord0 + i));
if (texCoordChannel == kShaderChannelTexCoord0)
textureSources = textureSources & ~(0xFUL<<i*4) | (UInt64(kTexSourceUV0)<<i*4);
else if (texCoordChannel == kShaderChannelTexCoord1)
textureSources = textureSources & ~(0xFUL<<i*4) | (UInt64(kTexSourceUV1)<<i*4);
else if (texCoordChannel != kShaderChannelNone) {
AssertString( "Bad texcoord index" );
}
}
device.m_FFState.texUnitSources = textureSources;
}
device.m_FFState.useUniformInsteadOfVertexColor = !(channels.GetTargetMap() & (1<<kVertexCompColor));
}
struct SetValuesFunctorD3D11
{
SetValuesFunctorD3D11(GfxDevice& device, ConstantBuffersD3D11& cbs) : m_Device(device), m_CBs(cbs) { }
GfxDevice& m_Device;
ConstantBuffersD3D11& m_CBs;
void SetVectorVal (ShaderType shaderType, ShaderParamType type, int index, const float* ptr, int cols, const GpuProgramParameters& params, int cbIndex)
{
const GpuProgramParameters::ConstantBuffer& cb = params.GetConstantBuffers()[cbIndex];
int idx = m_CBs.FindAndBindCB (cb.m_Name.index, shaderType, cb.m_BindIndex, cb.m_Size);
if (type != kShaderParamInt)
m_CBs.SetCBConstant (idx, index, ptr, cols*4);
else
{
int vali[4] = {ptr[0], ptr[1], ptr[2], ptr[3]};
m_CBs.SetCBConstant (idx, index, vali, cols*4);
}
}
void SetMatrixVal (ShaderType shaderType, int index, const Matrix4x4f* ptr, int rows, const GpuProgramParameters& params, int cbIndex)
{
DebugAssert(rows == 4);
const GpuProgramParameters::ConstantBuffer& cb = params.GetConstantBuffers()[cbIndex];
int idx = m_CBs.FindAndBindCB (cb.m_Name.index, shaderType, cb.m_BindIndex, cb.m_Size);
m_CBs.SetCBConstant (idx, index, ptr, 64);
}
void SetTextureVal (ShaderType shaderType, int index, int samplerIndex, TextureDimension dim, TextureID texID)
{
m_Device.SetTexture (shaderType, index, samplerIndex, texID, dim, std::numeric_limits<float>::infinity());
}
};
void GfxDeviceD3D11::BeforeDrawCall( bool immediateMode )
{
DX11_LOG_ENTER_FUNCTION("GfxDeviceD3D11::BeforeDrawCall");
ID3D11DeviceContext* ctx = GetD3D11Context();
HRESULT hr;
SetupDeferredSRGBWrite ();
SetupDeferredDepthStencilState ();
SetupDeferredRasterState ();
m_TransformState.UpdateWorldViewMatrix (m_BuiltinParamValues);
if (m_FogParams.mode != kFogDisabled)
{
float diff = m_FogParams.mode == kFogLinear ? m_FogParams.end - m_FogParams.start : 0.0f;
float invDiff = Abs(diff) > 0.0001f ? 1.0f/diff : 0.0f;
Vector4f fogParams(m_FogParams.density * 1.2011224087f,
m_FogParams.density * 1.4426950408f,
m_FogParams.mode == kFogLinear ? -invDiff : 0.0f,
m_FogParams.mode == kFogLinear ? m_FogParams.end * invDiff : 0.0f
);
m_BuiltinParamValues.SetVectorParam(kShaderVecFFFogParams, fogParams);
m_BuiltinParamValues.SetVectorParam(kShaderVecFFFogColor, m_FogParams.color);
}
void* shader[kShaderTypeCount];
for (int pt = 0; pt < kShaderTypeCount; ++pt)
{
shader[pt] = NULL;
m_BuiltinParamIndices[pt] = &m_NullParamIndices;
}
if (m_ActiveGpuProgram[kShaderVertex] && m_ActiveGpuProgram[kShaderFragment])
{
// Programmable shaders
const bool haveDomainShader = m_ActiveGpuProgram[kShaderDomain];
bool resetToNoFog = false;
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
if (m_ActiveGpuProgram[pt])
{
DebugAssert (!m_ActiveGpuProgram[pt] || m_ActiveGpuProgram[pt]->GetImplType() == pt);
m_BuiltinParamIndices[pt] = &m_ActiveGpuProgramParams[pt]->GetBuiltinParams();
D3D11CommonShader* prog = static_cast<D3D11CommonShader*>(m_ActiveGpuProgram[pt]);
shader[pt] = prog->GetShader(m_FogParams.mode, haveDomainShader, resetToNoFog);
if (resetToNoFog)
m_FogParams.mode = kFogDisabled;
}
}
// Apply fog parameters if needed
if (m_FogParams.mode > kFogDisabled)
{
const int cbIndex = m_CBs.FindAndBindCB (kSLPropFogCB.index, kShaderFragment, k11FogConstantBufferBind, k11FogSize*16);
m_CBs.SetCBConstant (cbIndex, k11FogColor*16, m_FogParams.color.GetPtr(), 16);
float params[4];
params[0] = m_FogParams.density * 1.2011224087f ; // density / sqrt(ln(2))
params[1] = m_FogParams.density * 1.4426950408f; // density / ln(2)
if (m_FogParams.mode == kFogLinear)
{
float diff = m_FogParams.end - m_FogParams.start;
float invDiff = Abs(diff) > 0.0001f ? 1.0f/diff : 0.0f;
params[2] = -invDiff;
params[3] = m_FogParams.end * invDiff;
}
else
{
params[2] = 0.0f;
params[3] = 0.0f;
}
m_CBs.SetCBConstant (cbIndex, k11FogParams*16, params, 16);
}
}
else
{
// Emulate fixed function
m_FFState.fogMode = m_FogParams.mode;
FixedFunctionProgramD3D11* program = GetFixedFunctionProgram11 (m_FFPrograms, m_FFState);
shader[kShaderVertex] = program->GetVertexShader();
shader[kShaderFragment] = program->GetPixelShader();
program->ApplyFFGpuProgram (m_BuiltinParamValues, m_CBs);
m_BuiltinParamIndices[kShaderVertex] = &program->GetVPMatrices();
}
// Set D3D shaders
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
if (m_ActiveShaders[pt] == shader[pt])
continue;
switch (pt) {
case kShaderVertex: D3D11_CALL(ctx->VSSetShader ((ID3D11VertexShader*)shader[pt], NULL, 0)); break;
case kShaderFragment: D3D11_CALL(ctx->PSSetShader ((ID3D11PixelShader*)shader[pt], NULL, 0)); break;
case kShaderGeometry: D3D11_CALL(ctx->GSSetShader ((ID3D11GeometryShader*)shader[pt], NULL, 0)); break;
case kShaderHull: D3D11_CALL(ctx->HSSetShader ((ID3D11HullShader*)shader[pt], NULL, 0)); break;
case kShaderDomain: D3D11_CALL(ctx->DSSetShader ((ID3D11DomainShader*)shader[pt], NULL, 0)); break;
}
m_ActiveShaders[pt] = shader[pt];
}
// Set Unity built-in parameters
bool anyGpuIndexValid;
int gpuIndex[kShaderTypeCount];
#define SET_BUILTIN_MATRIX_BEGIN(idx) \
anyGpuIndexValid = false; \
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt) { \
int gi = m_BuiltinParamIndices[pt]->mat[idx].gpuIndex; \
if (gi >= 0) anyGpuIndexValid = true; \
gpuIndex[pt] = gi; \
} \
if (anyGpuIndexValid)
#define SET_BUILTIN_MATRIX_END(idx,mtx) \
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt) { \
int gi = gpuIndex[pt]; \
if (gi >= 0) m_CBs.SetBuiltinCBConstant (m_BuiltinParamIndices[pt]->mat[idx].cbID, gi, mtx.GetPtr(), sizeof(mtx)); \
}
// MVP matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatMVP)
{
Matrix4x4f mat;
MultiplyMatrices4x4 (&m_BuiltinParamValues.GetMatrixParam(kShaderMatProj), &m_TransformState.worldViewMatrix, &mat);
SET_BUILTIN_MATRIX_END(kShaderInstanceMatMVP,mat);
}
// MV matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatMV)
{
Matrix4x4f& mat = m_TransformState.worldViewMatrix;
SET_BUILTIN_MATRIX_END(kShaderInstanceMatMV,mat);
}
// Transpose MV matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatTransMV)
{
Matrix4x4f mat;
TransposeMatrix4x4 (&m_TransformState.worldViewMatrix, &mat);
SET_BUILTIN_MATRIX_END(kShaderInstanceMatTransMV,mat);
}
// Inverse transpose of MV matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatInvTransMV)
{
Matrix4x4f mat;
Matrix4x4f::Invert_Full (m_TransformState.worldViewMatrix, mat);
if (true) //@TODO m_VertexData.normalization == kNormalizationScale)
{
// Inverse transpose of modelview should be scaled by uniform
// normal scale (this will match state.matrix.invtrans.modelview
// and gl_NormalMatrix in OpenGL)
float scale = Magnitude (m_TransformState.worldMatrix.GetAxisX());
mat.Get (0, 0) *= scale;
mat.Get (1, 0) *= scale;
mat.Get (2, 0) *= scale;
mat.Get (0, 1) *= scale;
mat.Get (1, 1) *= scale;
mat.Get (2, 1) *= scale;
mat.Get (0, 2) *= scale;
mat.Get (1, 2) *= scale;
mat.Get (2, 2) *= scale;
}
Matrix4x4f transposed;
TransposeMatrix4x4 (&mat, &transposed);
SET_BUILTIN_MATRIX_END(kShaderInstanceMatInvTransMV,transposed);
}
// M matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatM)
{
Matrix4x4f& mat = m_TransformState.worldMatrix;
SET_BUILTIN_MATRIX_END(kShaderInstanceMatM,mat);
}
// Inverse M matrix
SET_BUILTIN_MATRIX_BEGIN(kShaderInstanceMatInvM)
{
Matrix4x4f mat = m_TransformState.worldMatrix;
if (true) //@TODO m_VertexData.normalization == kNormalizationScale)
{
// Kill scale in the world matrix before inverse
float invScale = m_BuiltinParamValues.GetInstanceVectorParam(kShaderInstanceVecScale).w;
mat.Get (0, 0) *= invScale;
mat.Get (1, 0) *= invScale;
mat.Get (2, 0) *= invScale;
mat.Get (0, 1) *= invScale;
mat.Get (1, 1) *= invScale;
mat.Get (2, 1) *= invScale;
mat.Get (0, 2) *= invScale;
mat.Get (1, 2) *= invScale;
mat.Get (2, 2) *= invScale;
}
Matrix4x4f inverseMat;
Matrix4x4f::Invert_General3D (mat, inverseMat);
SET_BUILTIN_MATRIX_END(kShaderInstanceMatInvM,inverseMat);
}
// Set instance vector parameters
for (int i = 0; i < kShaderInstanceVecCount; ++i)
{
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
int gi = m_BuiltinParamIndices[pt]->vec[i].gpuIndex;
if (gi >= 0)
{
m_CBs.SetBuiltinCBConstant (m_BuiltinParamIndices[pt]->vec[i].cbID, gi, m_BuiltinParamValues.GetInstanceVectorParam((ShaderBuiltinInstanceVectorParam)i).GetPtr(), m_BuiltinParamIndices[pt]->vec[i].dim*4);
}
}
}
// Texture matrices for vertex shader
for( int i = 0; i < 8; ++i )
{
const BuiltinShaderParamIndices::MatrixParamData* matParam = &m_BuiltinParamIndices[kShaderVertex]->mat[kShaderInstanceMatTexture0 + i];
if (matParam->gpuIndex >= 0)
{
const Matrix4x4f& mat = m_TextureUnits[i].matrix;
m_CBs.SetBuiltinCBConstant (matParam->cbID, matParam->gpuIndex, mat.GetPtr(), sizeof(mat));
}
}
// Material properties
SetValuesFunctorD3D11 setValuesFunc(*this, m_CBs);
ApplyMaterialPropertyBlockValues(m_MaterialProperties, m_ActiveGpuProgram, m_ActiveGpuProgramParams, setValuesFunc);
///@TODO the rest
m_CBs.UpdateBuffers ();
}
static const D3D11_BLEND kBlendModeD3D11[] = {
D3D11_BLEND_ZERO, D3D11_BLEND_ONE, D3D11_BLEND_DEST_COLOR, D3D11_BLEND_SRC_COLOR, D3D11_BLEND_INV_DEST_COLOR, D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_COLOR,
D3D11_BLEND_DEST_ALPHA, D3D11_BLEND_INV_DEST_ALPHA, D3D11_BLEND_SRC_ALPHA_SAT, D3D11_BLEND_INV_SRC_ALPHA,
};
static const D3D11_BLEND kBlendModeAlphaD3D11[] = {
D3D11_BLEND_ZERO, D3D11_BLEND_ONE, D3D11_BLEND_DEST_ALPHA, D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_DEST_ALPHA, D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA,
D3D11_BLEND_DEST_ALPHA, D3D11_BLEND_INV_DEST_ALPHA, D3D11_BLEND_SRC_ALPHA_SAT, D3D11_BLEND_INV_SRC_ALPHA,
};
static const D3D11_BLEND_OP kBlendOpD3D11[] = {
D3D11_BLEND_OP_ADD, D3D11_BLEND_OP_SUBTRACT, D3D11_BLEND_OP_REV_SUBTRACT, D3D11_BLEND_OP_MIN, D3D11_BLEND_OP_MAX,
/* ADD for all the logic op modes, used for fallback.*/
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
D3D11_BLEND_OP_ADD,
};
static const D3D11_LOGIC_OP kLogicOpD3D11[] = {
/* Zeroes for the blend modes */
D3D11_LOGIC_OP_CLEAR,
D3D11_LOGIC_OP_CLEAR,
D3D11_LOGIC_OP_CLEAR,
D3D11_LOGIC_OP_CLEAR,
D3D11_LOGIC_OP_CLEAR,
/* Actual logic ops */
D3D11_LOGIC_OP_CLEAR,
D3D11_LOGIC_OP_SET,
D3D11_LOGIC_OP_COPY,
D3D11_LOGIC_OP_COPY_INVERTED,
D3D11_LOGIC_OP_NOOP,
D3D11_LOGIC_OP_INVERT,
D3D11_LOGIC_OP_AND,
D3D11_LOGIC_OP_NAND,
D3D11_LOGIC_OP_OR,
D3D11_LOGIC_OP_NOR,
D3D11_LOGIC_OP_XOR,
D3D11_LOGIC_OP_EQUIV,
D3D11_LOGIC_OP_AND_REVERSE,
D3D11_LOGIC_OP_AND_INVERTED,
D3D11_LOGIC_OP_OR_REVERSE,
D3D11_LOGIC_OP_OR_INVERTED
};
DeviceBlendState* GfxDeviceD3D11::CreateBlendState (const GfxBlendState& state)
{
std::pair<CachedBlendStates::iterator, bool> result = m_CachedBlendStates.insert(std::make_pair(state, DeviceBlendStateD3D11()));
if (!result.second)
return &result.first->second;
DeviceBlendStateD3D11& d3dstate = result.first->second;
memcpy (&d3dstate.sourceState, &state, sizeof(d3dstate.sourceState));
// DX11.1 logic ops, falls through to ADD blendop if not supported
if(state.blendOp >= kBlendOpLogicalClear && state.blendOp <= kBlendOpLogicalOrInverted
&& gGraphicsCaps.hasBlendLogicOps)
{
D3D11_BLEND_DESC1 desc;
memset (&desc, 0, sizeof(desc));
if (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0)
desc.AlphaToCoverageEnable = state.alphaToMask;
desc.IndependentBlendEnable = FALSE;
D3D11_RENDER_TARGET_BLEND_DESC1& dst = desc.RenderTarget[0];
dst.BlendEnable = false;
dst.LogicOpEnable = true;
dst.LogicOp = kLogicOpD3D11[state.blendOp];
DWORD d3dmask = 0;
const UInt8 mask = state.renderTargetWriteMask;
if( mask & kColorWriteR ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_RED;
if( mask & kColorWriteG ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_GREEN;
if( mask & kColorWriteB ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_BLUE;
if( mask & kColorWriteA ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
dst.RenderTargetWriteMask = d3dmask;
// GetD3D11_1Device cannot return null if we're running on DX11 and have gGraphicsCaps.hasBlendLogicOps, so no need to check.
ID3D11BlendState1 *blendObj = NULL;
HRESULT hr = GetD3D11_1Device()->CreateBlendState1 (&desc, &blendObj);
d3dstate.deviceState = blendObj;
AssertIf(FAILED(hr));
SetDebugNameD3D11 (d3dstate.deviceState, Format("BlendState-%d-%d", dst.SrcBlend, dst.DestBlend));
}
else
{
D3D11_BLEND_DESC desc;
memset (&desc, 0, sizeof(desc));
if (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0)
desc.AlphaToCoverageEnable = state.alphaToMask;
desc.IndependentBlendEnable = FALSE;
D3D11_RENDER_TARGET_BLEND_DESC& dst = desc.RenderTarget[0];
dst.BlendEnable = state.srcBlend != kBlendOne || state.dstBlend != kBlendZero || state.srcBlendAlpha != kBlendOne || state.dstBlendAlpha != kBlendZero;
dst.SrcBlend = kBlendModeD3D11[state.srcBlend];
dst.DestBlend = kBlendModeD3D11[state.dstBlend];
dst.BlendOp = kBlendOpD3D11[state.blendOp];
dst.SrcBlendAlpha = kBlendModeAlphaD3D11[state.srcBlendAlpha];
dst.DestBlendAlpha = kBlendModeAlphaD3D11[state.dstBlendAlpha];
dst.BlendOpAlpha = kBlendOpD3D11[state.blendOpAlpha];
DWORD d3dmask = 0;
const UInt8 mask = state.renderTargetWriteMask;
if( mask & kColorWriteR ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_RED;
if( mask & kColorWriteG ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_GREEN;
if( mask & kColorWriteB ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_BLUE;
if( mask & kColorWriteA ) d3dmask |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
dst.RenderTargetWriteMask = d3dmask;
HRESULT hr = GetD3D11Device()->CreateBlendState (&desc, &d3dstate.deviceState);
AssertIf(FAILED(hr));
SetDebugNameD3D11 (d3dstate.deviceState, Format("BlendState-%d-%d", dst.SrcBlend, dst.DestBlend));
}
return &result.first->second;
}
DeviceDepthState* GfxDeviceD3D11::CreateDepthState(const GfxDepthState& state)
{
std::pair<CachedDepthStates::iterator, bool> result = m_CachedDepthStates.insert(std::make_pair(state, DeviceDepthState()));
if (!result.second)
return &result.first->second;
DeviceDepthState& st = result.first->second;
memcpy(&st.sourceState, &state, sizeof(st.sourceState));
return &result.first->second;
}
DeviceStencilState* GfxDeviceD3D11::CreateStencilState(const GfxStencilState& state)
{
std::pair<CachedStencilStates::iterator, bool> result = m_CachedStencilStates.insert(std::make_pair(state, DeviceStencilState()));
if (!result.second)
return &result.first->second;
DeviceStencilState& st = result.first->second;
memcpy(&st.sourceState, &state, sizeof(state));
return &result.first->second;
}
DeviceRasterState* GfxDeviceD3D11::CreateRasterState(const GfxRasterState& state)
{
std::pair<CachedRasterStates::iterator, bool> result = m_CachedRasterStates.insert(std::make_pair(state, DeviceRasterState()));
if (!result.second)
return &result.first->second;
DeviceRasterState& st = result.first->second;
memcpy(&st.sourceState, &state, sizeof(state));
return &result.first->second;
}
void GfxDeviceD3D11::SetBlendState(const DeviceBlendState* state, float alphaRef)
{
if (state != m_CurrBlendState)
{
m_CurrBlendState = state;
DeviceBlendStateD3D11* devstate = (DeviceBlendStateD3D11*)state;
GetD3D11Context()->OMSetBlendState (devstate->deviceState, NULL, 0xFFFFFFFF);
}
// alpha test
m_FFState.alphaTest = state->sourceState.alphaTest;
m_BuiltinParamValues.SetVectorParam(kShaderVecFFAlphaTestRef, Vector4f(alphaRef, alphaRef, alphaRef, alphaRef));
}
void GfxDeviceD3D11::SetRasterState(const DeviceRasterState* state)
{
if (m_CurrRasterState != state)
{
m_CurrRasterState = state;
m_CurrRSState = NULL;
}
}
void GfxDeviceD3D11::SetDepthState (const DeviceDepthState* state)
{
if (m_CurrDepthState != state)
{
m_CurrDepthState = state;
m_CurrDSState = NULL;
}
}
void GfxDeviceD3D11::SetStencilState(const DeviceStencilState* state, int stencilRef)
{
if (m_CurrStencilState != state)
{
m_CurrStencilState = state;
m_CurrDSState = NULL;
}
m_StencilRef = stencilRef;
}
void GfxDeviceD3D11::SetupDeferredSRGBWrite()
{
if (m_SRGBWrite == m_ActualSRGBWrite)
return;
// sRGB write is not just a render state on DX11; we need to actually rebind the render target views with
// a different format. Looks like some drivers do not optimize useless RT changes away, causing
// a lot of performance being wasted. So only apply sRGB write change when actually needed.
m_ActualSRGBWrite = m_SRGBWrite;
RebindActiveRenderTargets (&m_Textures);
}
void GfxDeviceD3D11::SetSRGBWrite (bool enable)
{
m_SRGBWrite = enable;
}
bool GfxDeviceD3D11::GetSRGBWrite ()
{
return m_SRGBWrite;
}
void GfxDeviceD3D11::DiscardContents (RenderSurfaceHandle& rs)
{
# if UNITY_WINRT // WSA/WP8 guaranteed to have DX11.1 runtime, needed for DiscardResource
if(!rs.IsValid())
return;
RenderSurfaceD3D11 *surf = reinterpret_cast<RenderSurfaceD3D11*>( rs.object );
if (surf->m_Texture)
{
ID3D11DeviceContext1 * ctx = (ID3D11DeviceContext1 *)GetD3D11Context();
DX11_CHK(ctx->DiscardResource(surf->m_Texture));
}
# endif
}
GfxDevice* CreateD3D11GfxDevice()
{
if( !InitializeD3D11() )
return NULL;
gGraphicsCaps.InitD3D11();
GfxDeviceD3D11* device = UNITY_NEW_AS_ROOT(GfxDeviceD3D11(), kMemGfxDevice, "D3D11GfxDevice", "");
return device;
}
GfxDeviceD3D11::GfxDeviceD3D11()
{
m_DynamicVBO = NULL;
InvalidateState();
ResetFrameStats();
m_Renderer = kGfxRendererD3D11;
m_UsesOpenGLTextureCoords = false;
m_UsesHalfTexelOffset = false;
m_IsThreadable = true;
m_MaxBufferedFrames = -1; // no limiting
m_Viewport[0] = m_Viewport[1] = m_Viewport[2] = m_Viewport[3] = 0;
m_ScissorRect[0] = m_ScissorRect[1] = m_ScissorRect[2] = m_ScissorRect[3] = 0;
m_CurrTargetWidth = 0;
m_CurrTargetHeight = 0;
m_CurrWindowWidth = 0;
m_CurrWindowHeight = 0;
m_InvertProjMatrix = false;
m_AppBackfaceMode = false;
m_UserBackfaceMode = false;
m_Wireframe = false;
m_Scissor = false;
m_SRGBWrite = false;
m_ActualSRGBWrite = false;
m_FramebufferDepthFormat = kDepthFormat24;
// constant buffer for fog params
m_CBs.SetCBInfo (kSLPropFogCB.index, k11FogSize*16);
extern RenderSurfaceBase* DummyColorBackBuferD3D11();
SetBackBufferColorSurface(DummyColorBackBuferD3D11());
extern RenderSurfaceBase* DummyDepthBackBuferD3D11();
SetBackBufferDepthSurface(DummyDepthBackBuferD3D11());
}
GfxDeviceD3D11::~GfxDeviceD3D11()
{
#if !ENABLE_GFXDEVICE_REMOTE_PROCESS_WORKER
PluginsSetGraphicsDevice (GetD3D11Device(), kGfxRendererD3D11, kGfxDeviceEventShutdown);
#endif
StreamOutSkinningInfo::CleanUp();
#if ENABLE_PROFILER
g_TimerQueriesD3D11.ReleaseAllQueries();
#endif
D3D11VBO::CleanupSharedBuffers();
if( m_DynamicVBO )
delete m_DynamicVBO;
for (FFProgramCacheD3D11::iterator it = m_FFPrograms.begin(); it != m_FFPrograms.end(); ++it)
delete it->second;
for (CachedBlendStates::iterator it = m_CachedBlendStates.begin(); it != m_CachedBlendStates.end(); ++it)
it->second.deviceState->Release();
for (CachedDepthStencilStates::iterator it = m_CachedDepthStencilStates.begin(); it != m_CachedDepthStencilStates.end(); ++it)
it->second->Release();
for (CachedFinalRasterStates::iterator it = m_CachedFinalRasterStates.begin(); it != m_CachedFinalRasterStates.end(); ++it)
it->second->Release();
m_Imm.Cleanup();
m_VertexDecls.Clear();
m_CBs.Clear();
m_Textures.ClearTextureResources();
m_Resolves.Clear();
DestroyD3D11Device();
CleanupD3D11();
}
void GfxDeviceD3D11::InvalidateState()
{
g_ActiveInputLayoutD3D11 = NULL;
g_CurrentVSInputD3D11 = NULL;
g_ActiveTopologyD3D11 = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED;
m_TransformState.Invalidate(m_BuiltinParamValues);
m_FogParams.Invalidate();
//m_State.Invalidate(*this);
m_Imm.Invalidate();
//m_VSConstantCache.Invalidate();
//m_PSConstantCache.Invalidate();
memset (&m_FFState, 0, sizeof(m_FFState));
m_FFState.useUniformInsteadOfVertexColor = true;
m_CurrBlendState = NULL;
m_CurrRasterState = NULL;
m_CurrDepthState = NULL;
m_CurrStencilState = NULL;
m_CurrRSState = NULL;
m_CurrDSState = NULL;
m_CurrStencilRef = -1;
for (int pt = 0; pt < kShaderTypeCount; ++pt)
{
m_ActiveGpuProgram[pt] = NULL;
m_ActiveGpuProgramParams[pt] = NULL;
m_ActiveShaders[pt] = NULL;
for (int i = 0; i < kMaxSupportedTextureUnits; ++i)
{
m_ActiveTextures[pt][i].m_ID = -1;
m_ActiveSamplers[pt][i].m_ID = -1;
}
}
m_Textures.InvalidateSamplers();
m_CBs.InvalidateState();
ID3D11DeviceContext* ctx = GetD3D11Context(true);
if (ctx)
{
D3D11_CALL(ctx->VSSetShader (NULL, NULL, 0));
D3D11_CALL(ctx->PSSetShader (NULL, NULL, 0));
D3D11_CALL(ctx->GSSetShader (NULL, NULL, 0));
D3D11_CALL(ctx->HSSetShader (NULL, NULL, 0));
D3D11_CALL(ctx->DSSetShader (NULL, NULL, 0));
}
}
void GfxDeviceD3D11::Clear (UInt32 clearFlags, const float color[4], float depth, int stencil)
{
DX11_LOG_ENTER_FUNCTION("Clear(%d, (%.2f, %.2f, %.2f, %.2f), %.2f, %d)", clearFlags, color[0], color[1], color[2], color[3], depth, stencil);
SetupDeferredSRGBWrite ();
ID3D11DeviceContext* ctx = GetD3D11Context();
if ((clearFlags & kGfxClearColor) && g_D3D11CurrRT)
DX11_CHK(ctx->ClearRenderTargetView (g_D3D11CurrRT, color));
if ((clearFlags & kGfxClearDepthStencil) && g_D3D11CurrDS)
{
UINT flags = 0;
if (clearFlags & kGfxClearDepth)
flags |= D3D11_CLEAR_DEPTH;
if (clearFlags & kGfxClearStencil)
flags |= D3D11_CLEAR_STENCIL;
DX11_CHK(ctx->ClearDepthStencilView (g_D3D11CurrDS, flags, depth, stencil));
}
}
void GfxDeviceD3D11::SetUserBackfaceMode( bool enable )
{
if (m_UserBackfaceMode != enable)
{
m_UserBackfaceMode = enable;
m_CurrRSState = NULL;
}
}
void GfxDeviceD3D11::SetWireframe (bool wire)
{
if (m_Wireframe != wire)
{
m_Wireframe = wire;
m_CurrRSState = NULL;
}
}
bool GfxDeviceD3D11::GetWireframe() const
{
return m_Wireframe;
}
void GfxDeviceD3D11::SetInvertProjectionMatrix( bool enable )
{
if (m_InvertProjMatrix == enable)
return;
m_InvertProjMatrix = enable;
// When setting up "invert" flag, invert the matrix as well.
Matrix4x4f& m = m_BuiltinParamValues.GetWritableMatrixParam(kShaderMatProj);
m.Get(1,1) = -m.Get(1,1);
m.Get(1,3) = -m.Get(1,3);
m_TransformState.dirtyFlags |= TransformState::kProjDirty;
m_CurrRSState = NULL;
}
bool GfxDeviceD3D11::GetInvertProjectionMatrix() const
{
return m_InvertProjMatrix;
}
void GfxDeviceD3D11::SetWorldMatrix( const float matrix[16] )
{
CopyMatrix( matrix, m_TransformState.worldMatrix.GetPtr() );
m_TransformState.dirtyFlags |= TransformState::kWorldDirty;
}
void GfxDeviceD3D11::SetViewMatrix( const float matrix[16] )
{
m_TransformState.SetViewMatrix (matrix, m_BuiltinParamValues);
}
void GfxDeviceD3D11::SetProjectionMatrix (const Matrix4x4f& matrix)
{
Matrix4x4f& m = m_BuiltinParamValues.GetWritableMatrixParam(kShaderMatProj);
CopyMatrix (matrix.GetPtr(), m.GetPtr());
CopyMatrix (matrix.GetPtr(), m_TransformState.projectionMatrixOriginal.GetPtr());
CalculateDeviceProjectionMatrix (m, m_UsesOpenGLTextureCoords, m_InvertProjMatrix);
m_TransformState.dirtyFlags |= TransformState::kProjDirty;
}
void GfxDeviceD3D11::GetMatrix( float outMatrix[16] ) const
{
m_TransformState.UpdateWorldViewMatrix (m_BuiltinParamValues);
CopyMatrix (m_TransformState.worldViewMatrix.GetPtr(), outMatrix);
}
const float* GfxDeviceD3D11::GetWorldMatrix() const
{
return m_TransformState.worldMatrix.GetPtr();
}
const float* GfxDeviceD3D11::GetViewMatrix() const
{
return m_BuiltinParamValues.GetMatrixParam(kShaderMatView).GetPtr();
}
const float* GfxDeviceD3D11::GetProjectionMatrix() const
{
return m_TransformState.projectionMatrixOriginal.GetPtr();
}
const float* GfxDeviceD3D11::GetDeviceProjectionMatrix() const
{
return m_BuiltinParamValues.GetMatrixParam(kShaderMatProj).GetPtr();
}
void GfxDeviceD3D11::SetNormalizationBackface( NormalizationMode mode, bool backface )
{
if (m_AppBackfaceMode != backface)
{
m_AppBackfaceMode = backface;
m_CurrRSState = NULL;
}
}
void GfxDeviceD3D11::SetFFLighting( bool on, bool separateSpecular, ColorMaterialMode colorMaterial )
{
DX11_LOG_ENTER_FUNCTION("SetFFLighting(%s, %s, %d)", GetDX11BoolString(on), GetDX11BoolString(separateSpecular), colorMaterial);
DebugAssert(colorMaterial!=kColorMatUnknown);
m_FFState.lightingEnabled = on;
m_FFState.specularEnabled = on && separateSpecular;
m_FFState.colorMaterial = colorMaterial;
}
void GfxDeviceD3D11::SetMaterial( const float ambient[4], const float diffuse[4], const float specular[4], const float emissive[4], const float shininess )
{
DX11_LOG_ENTER_FUNCTION("SetMaterial((%.2f, %.2f, %.2f, %.2f), (%.2f, %.2f, %.2f, %.2f), (%.2f, %.2f, %.2f, %.2f), (%.2f, %.2f, %.2f, %.2f), %.2f)",
ambient[0], ambient[1], ambient[2], ambient[3],
diffuse[0], diffuse[1], diffuse[2], diffuse[3],
specular[0], specular[1], specular[2], specular[3],
emissive[0], emissive[1], emissive[2], emissive[3],
shininess);
float glshine = clamp01 (shininess) * 128.0f;
m_BuiltinParamValues.SetVectorParam(kShaderVecFFMatAmbient, Vector4f(ambient[0], ambient[1], ambient[2], 1.0F));
m_BuiltinParamValues.SetVectorParam(kShaderVecFFMatDiffuse, Vector4f(diffuse));
m_BuiltinParamValues.SetVectorParam(kShaderVecFFMatSpecular, Vector4f(specular[0], specular[1], specular[2], glshine));
m_BuiltinParamValues.SetVectorParam(kShaderVecFFMatEmission, Vector4f(emissive[0], emissive[1], emissive[2], 1.0F));
}
void GfxDeviceD3D11::SetColor( const float color[4] )
{
m_BuiltinParamValues.SetVectorParam(kShaderVecFFColor, Vector4f(color));
}
void GfxDeviceD3D11::SetViewport( int x, int y, int width, int height )
{
DX11_LOG_ENTER_FUNCTION("SetViewport(%d, %d, %d, %d)", x, y, width, height);
m_Viewport[0] = x;
m_Viewport[1] = y;
m_Viewport[2] = width;
m_Viewport[3] = height;
D3D11_VIEWPORT view;
view.TopLeftX = x;
view.TopLeftY = y;
view.Width = width;
view.Height = height;
view.MinDepth = 0.0f;
view.MaxDepth = 1.0f;
ID3D11DeviceContext* ctx = GetD3D11Context();
//@TODO
//if( !dev ) // happens on startup, when deleting all render textures
// return;
ctx->RSSetViewports (1, &view);
}
void GfxDeviceD3D11::GetViewport( int* port ) const
{
port[0] = m_Viewport[0];
port[1] = m_Viewport[1];
port[2] = m_Viewport[2];
port[3] = m_Viewport[3];
}
void GfxDeviceD3D11::SetScissorRect (int x, int y, int width, int height)
{
DX11_LOG_ENTER_FUNCTION("SetScissorRect(%d, %d, %d, %d)", x, y, width, height);
if (!m_Scissor)
{
m_Scissor = true;
m_CurrRSState = NULL;
}
m_ScissorRect[0] = x;
m_ScissorRect[1] = y;
m_ScissorRect[2] = width;
m_ScissorRect[3] = height;
D3D11_RECT rc;
rc.left = x;
rc.top = y;
rc.right = x + width;
rc.bottom = y + height;
GetD3D11Context()->RSSetScissorRects (1, &rc);
}
void GfxDeviceD3D11::DisableScissor()
{
if (m_Scissor)
{
m_Scissor = false;
m_CurrRSState = NULL;
}
}
bool GfxDeviceD3D11::IsScissorEnabled() const
{
return m_Scissor;
}
void GfxDeviceD3D11::GetScissorRect (int scissor[4]) const
{
scissor[0] = m_ScissorRect[0];
scissor[1] = m_ScissorRect[1];
scissor[2] = m_ScissorRect[2];
scissor[3] = m_ScissorRect[3];
}
struct TextureCombiners11
{
const ShaderLab::TextureBinding* texEnvs;
int count;
};
bool GfxDeviceD3D11::IsCombineModeSupported( unsigned int combiner )
{
return true;
}
TextureCombinersHandle GfxDeviceD3D11::CreateTextureCombiners (int count, const ShaderLab::TextureBinding* texEnvs, const ShaderLab::PropertySheet* props, bool hasVertexColorOrLighting, bool usesAddSpecular)
{
DX11_LOG_ENTER_FUNCTION("CreateTextureCombiners()");
if (count > gGraphicsCaps.maxTexUnits)
return TextureCombinersHandle(NULL);
TextureCombiners11* combiners = new TextureCombiners11();
combiners->texEnvs = texEnvs;
combiners->count = count;
return TextureCombinersHandle(combiners);
}
void GfxDeviceD3D11::DeleteTextureCombiners (TextureCombinersHandle& textureCombiners)
{
DX11_LOG_ENTER_FUNCTION("DeleteTextureCombiners()");
TextureCombiners11* combiners = OBJECT_FROM_HANDLE(textureCombiners,TextureCombiners11);
delete combiners;
textureCombiners.Reset();
}
void GfxDeviceD3D11::SetTextureCombinersThreadable( TextureCombinersHandle textureCombiners, const TexEnvData* texEnvData, const Vector4f* texColors )
{
DX11_LOG_ENTER_FUNCTION("SetTextureCombinersThreadable()");
TextureCombiners11* combiners = OBJECT_FROM_HANDLE(textureCombiners,TextureCombiners11);
Assert (combiners);
const int count = std::min(combiners->count, gGraphicsCaps.maxTexUnits);
m_FFState.texUnitCount = count;
for (int i = 0; i < count; ++i)
{
const ShaderLab::TextureBinding& binding = combiners->texEnvs[i];
ApplyTexEnvData (i, i, texEnvData[i]);
m_BuiltinParamValues.SetVectorParam ((BuiltinShaderVectorParam)(kShaderVecFFTextureEnvColor0 + i), texColors[i]);
m_FFState.texUnitColorCombiner[i] = binding.m_CombColor;
m_FFState.texUnitAlphaCombiner[i] = binding.m_CombAlpha;
}
// unused textures
UInt32 mask = (1<<count)-1;
m_FFState.texUnitCube &= mask;
m_FFState.texUnit3D &= mask;
m_FFState.texUnitProjected &= mask;
}
void GfxDeviceD3D11::SetTextureCombiners( TextureCombinersHandle textureCombiners, const ShaderLab::PropertySheet* props )
{
DX11_LOG_ENTER_FUNCTION("SetTextureCombiners()");
TextureCombiners11* combiners = OBJECT_FROM_HANDLE(textureCombiners,TextureCombiners11);
Assert(combiners);
const int count = std::min(combiners->count, gGraphicsCaps.maxTexUnits);
// Fill in arrays
TexEnvData* texEnvData;
ALLOC_TEMP (texEnvData, TexEnvData, count);
for (int i = 0; i < count; ++i)
{
const ShaderLab::TextureBinding& binding = combiners->texEnvs[i];
ShaderLab::TexEnv *te = ShaderLab::GetTexEnvForBinding(binding, props);
Assert(te != NULL);
te->PrepareData (binding.m_TextureName.index, binding.m_MatrixName, props, &texEnvData[i]);
}
Vector4f* texColors;
ALLOC_TEMP (texColors, Vector4f, count);
for (int i = 0; i < count; ++i)
{
const ShaderLab::TextureBinding& binding = combiners->texEnvs[i];
texColors[i] = binding.GetTexColor().Get (props);
}
GfxDeviceD3D11::SetTextureCombinersThreadable (textureCombiners, texEnvData, texColors);
}
void UnbindTextureD3D11 (TextureID texture)
{
DX11_LOG_ENTER_FUNCTION("UnbindTextureD3D11(%d)", texture.m_ID);
GfxDeviceD3D11& device = static_cast<GfxDeviceD3D11&>(GetRealGfxDevice());
ID3D11DeviceContext* ctx = GetD3D11Context();
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
for (int i = 0; i < kMaxSupportedTextureUnits; ++i)
{
if (device.m_ActiveTextures[pt][i]==texture)
{
ID3D11ShaderResourceView* srv = NULL;
switch (pt) {
case kShaderVertex: ctx->VSSetShaderResources (i, 1, &srv); break;
case kShaderFragment: ctx->PSSetShaderResources (i, 1, &srv); break;
case kShaderGeometry: ctx->GSSetShaderResources (i, 1, &srv); break;
case kShaderHull: ctx->HSSetShaderResources (i, 1, &srv); break;
case kShaderDomain: ctx->DSSetShaderResources (i, 1, &srv); break;
default: AssertString("unknown shader type");
}
device.m_ActiveTextures[pt][i].m_ID = -1;
}
if (device.m_ActiveSamplers[pt][i]==texture)
{
device.m_ActiveSamplers[pt][i].m_ID = -1;
}
}
}
}
void GfxDeviceD3D11::SetTexture (ShaderType shaderType, int unit, int samplerUnit, TextureID texture, TextureDimension dim, float bias)
{
DebugAssertIf (dim < kTexDim2D || dim > kTexDimCUBE);
DebugAssertIf (unit < 0 || unit >= kMaxSupportedTextureUnits);
// WP8 seems to have a driver bug (?) with occasionally losing texture state; can't do redundant bind early out here.
// Repros on Shadowgun flyby on Nokia Not For Sale.
#if !UNITY_WP8
if (m_ActiveTextures[shaderType][unit] == texture && (samplerUnit >= 0 && m_ActiveSamplers[shaderType][samplerUnit] == texture))
return;
#endif
if (m_Textures.SetTexture (shaderType, unit, samplerUnit, texture, bias))
{
m_Stats.AddUsedTexture(texture);
m_ActiveTextures[shaderType][unit] = texture;
if (samplerUnit >= 0)
m_ActiveSamplers[shaderType][samplerUnit] = texture;
}
if (shaderType == kShaderFragment && unit < kMaxSupportedTextureCoords)
{
if (m_FFState.texUnitCount <= unit)
m_FFState.texUnitCount = unit+1;
UInt32 mask = 1<<unit;
if (dim==kTexDimCUBE)
m_FFState.texUnitCube |= mask;
else
m_FFState.texUnitCube &= ~mask;
if (dim==kTexDim3D)
m_FFState.texUnit3D |= mask;
else
m_FFState.texUnit3D &= ~mask;
}
}
void GfxDeviceD3D11::SetTextureTransform( int unit, TextureDimension dim, TexGenMode texGen, bool identity, const float matrix[16])
{
Assert (unit >= 0 && unit < kMaxSupportedTextureCoords);
TextureSourceD3D11 texSource = texGen == kTexGenDisabled ? kTexSourceUV0 : static_cast<TextureSourceD3D11>(texGen + kTexSourceUV7);
m_FFState.texUnitSources = m_FFState.texUnitSources & ~(15<<(unit*4)) | (UInt64(texSource)<<(unit*4));
if (identity)
m_TextureUnits[unit].matrix.SetIdentity();
else
CopyMatrix (matrix, m_TextureUnits[unit].matrix.GetPtr());
// Detect if we have a projective texture matrix
m_FFState.texUnitProjected &= ~(1<<unit);
if (!identity && dim==kTexDim2D)
{
if (matrix[3] != 0.0f || matrix[7] != 0.0f || matrix[11] != 0.0f || matrix[15] != 1.0f)
m_FFState.texUnitProjected |= (1<<unit);
}
}
void GfxDeviceD3D11::SetTextureParams( TextureID texture, TextureDimension texDim, TextureFilterMode filter, TextureWrapMode wrap, int anisoLevel, bool hasMipMap, TextureColorSpace colorSpace )
{
UnbindTextureD3D11 (texture);
m_Textures.SetTextureParams (texture, texDim, filter, wrap, anisoLevel, hasMipMap, colorSpace);
}
void GfxDeviceD3D11::SetShadersThreadable (GpuProgram* programs[kShaderTypeCount], const GpuProgramParameters* params[kShaderTypeCount], UInt8 const * const paramsBuffer[kShaderTypeCount])
{
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
m_ActiveGpuProgram[pt] = programs[pt];
m_ActiveGpuProgramParams[pt] = params[pt];
}
// Apply programmable shader parameters
if (m_ActiveGpuProgram[kShaderVertex] && m_ActiveGpuProgram[kShaderFragment])
{
for (int pt = kShaderVertex; pt < kShaderTypeCount; ++pt)
{
if (m_ActiveGpuProgram[pt])
{
DebugAssert (!m_ActiveGpuProgram[pt] || m_ActiveGpuProgram[pt]->GetImplType() == pt);
D3D11CommonShader* prog = static_cast<D3D11CommonShader*>(m_ActiveGpuProgram[pt]);
m_ActiveGpuProgram[pt]->ApplyGpuProgram (*params[pt], paramsBuffer[pt]);
}
}
}
}
bool GfxDeviceD3D11::IsShaderActive( ShaderType type ) const
{
return (m_ActiveGpuProgram[type] != 0);
}
void GfxDeviceD3D11::DestroySubProgram( ShaderLab::SubProgram* subprogram )
{
delete subprogram;
}
void GfxDeviceD3D11::SetConstantBufferInfo (int id, int size)
{
m_CBs.SetCBInfo (id, size);
}
void GfxDeviceD3D11::DisableLights( int startLight )
{
startLight = std::min (startLight, gGraphicsCaps.maxLights);
m_FFState.lightCount = startLight;
const Vector4f black(0.0F, 0.0F, 0.0F, 0.0F);
const Vector4f zpos(0.0F, 0.0F, 1.0F, 0.0F);
for (int i = startLight; i < gGraphicsCaps.maxLights; ++i)
{
m_BuiltinParamValues.SetVectorParam(BuiltinShaderVectorParam(kShaderVecLight0Position + i), zpos);
m_BuiltinParamValues.SetVectorParam(BuiltinShaderVectorParam(kShaderVecLight0Diffuse + i), black);
}
}
void GfxDeviceD3D11::SetLight( int light, const GfxVertexLight& data)
{
if (light >= gGraphicsCaps.maxLights)
return;
SetupVertexLightParams (light, data);
}
void GfxDeviceD3D11::SetAmbient( const float ambient[4] )
{
m_BuiltinParamValues.SetVectorParam(kShaderVecLightModelAmbient, Vector4f(ambient));
}
void GfxDeviceD3D11::EnableFog (const GfxFogParams& fog)
{
DebugAssert (fog.mode > kFogDisabled);
m_FogParams = fog;
//@TODO: fog DXBC patching not implemented for 9.x level; and something still wrong with FF shaders in 9.x level as well
// (e.g. crashes WARP). Just disable fog for now.
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level10_0)
m_FogParams.mode = kFogDisabled;
}
void GfxDeviceD3D11::DisableFog()
{
m_FogParams.mode = kFogDisabled;
m_FogParams.density = 0.0f;
}
VBO* GfxDeviceD3D11::CreateVBO()
{
VBO* vbo = new D3D11VBO();
OnCreateVBO(vbo);
return vbo;
}
void GfxDeviceD3D11::DeleteVBO( VBO* vbo )
{
OnDeleteVBO(vbo);
delete vbo;
}
DynamicVBO& GfxDeviceD3D11::GetDynamicVBO()
{
if( !m_DynamicVBO ) {
m_DynamicVBO = new DynamicD3D11VBO( 1024 * 1024, 65536 ); // initial 1 MiB VB, 64 KiB IB
}
return *m_DynamicVBO;
}
/*
void GfxDeviceD3D11::ResetDynamicResources()
{
delete m_DynamicVBO;
m_DynamicVBO = NULL;
CleanupEventQueries ();
for( ListIterator<D3D11VBO*> i = m_DynamicVBOs.begin(); i != m_DynamicVBOs.end(); ++i )
{
D3D11VBO* vbo = *i;
vbo->ResetDynamicVB();
}
}
*/
GfxDeviceD3D11& GetD3D11GfxDevice()
{
GfxDevice& device = GetRealGfxDevice();
DebugAssert(device.GetRenderer() == kGfxRendererD3D11);
return static_cast<GfxDeviceD3D11&>(device);
}
ID3D11InputLayout* GetD3D11VertexDeclaration (const ChannelInfoArray& channels)
{
GfxDevice& device = GetRealGfxDevice();
DebugAssert(device.GetRenderer() == kGfxRendererD3D11);
GfxDeviceD3D11* deviceD3D = static_cast<GfxDeviceD3D11*>( &device );
return deviceD3D->GetVertexDecls().GetVertexDecl (channels, g_CurrentVSInputD3D11);
}
const InputSignatureD3D11* GetD3D11InputSignature (void* code, unsigned length)
{
GfxDevice& device = GetRealGfxDevice();
DebugAssert(device.GetRenderer() == kGfxRendererD3D11);
GfxDeviceD3D11* deviceD3D = static_cast<GfxDeviceD3D11*>( &device );
return deviceD3D->GetVertexDecls().GetShaderInputSignature (code, length);
}
ConstantBuffersD3D11& GetD3D11ConstantBuffers (GfxDevice& device)
{
Assert (device.GetRenderer() == kGfxRendererD3D11);
GfxDeviceD3D11& deviceD3D = static_cast<GfxDeviceD3D11&>(device);
return deviceD3D.GetConstantBuffers();
}
TexturesD3D11& GetD3D11Textures (GfxDevice& device)
{
Assert (device.GetRenderer() == kGfxRendererD3D11);
GfxDeviceD3D11& deviceD3D = static_cast<GfxDeviceD3D11&>(device);
return deviceD3D.GetTextures();
}
// ---------- render textures
RenderSurfaceHandle CreateRenderColorSurfaceD3D11( TextureID textureID, int width, int height, int samples, int depth, TextureDimension dim, UInt32 createFlags, RenderTextureFormat format, TexturesD3D11& textures);
RenderSurfaceHandle CreateRenderDepthSurfaceD3D11( TextureID textureID, int width, int height, int samples, TextureDimension dim, DepthBufferFormat depthFormat, UInt32 createFlags, TexturesD3D11& textures);
void DestroyRenderSurfaceD3D11 (RenderSurfaceHandle& rsHandle, TexturesD3D11& textures);
bool SetRenderTargetD3D11 (int count, RenderSurfaceHandle* colorHandles, RenderSurfaceHandle depthHandle, int mipLevel, CubemapFace face, int* outTargetWidth, int* outTargetHeight, TexturesD3D11* textures);
RenderSurfaceHandle GetActiveRenderColorSurfaceD3D11(int index);
RenderSurfaceHandle GetActiveRenderDepthSurfaceD3D11();
RenderSurfaceHandle GetActiveRenderColorSurfaceBBD3D11();
RenderSurfaceHandle GfxDeviceD3D11::CreateRenderColorSurface (TextureID textureID, int width, int height, int samples, int depth, TextureDimension dim, RenderTextureFormat format, UInt32 createFlags)
{
DX11_LOG_ENTER_FUNCTION("CreateRenderColorSurface(%d, %d, %d, %d, %d)", textureID.m_ID, width, height, format, createFlags);
return CreateRenderColorSurfaceD3D11 (textureID, width, height, samples, depth, dim, createFlags, format, m_Textures);
}
RenderSurfaceHandle GfxDeviceD3D11::CreateRenderDepthSurface (TextureID textureID, int width, int height, int samples, TextureDimension dim, DepthBufferFormat depthFormat, UInt32 createFlags)
{
DX11_LOG_ENTER_FUNCTION("CreateRenderDepthSurface(%d, %d, %d, %d, %d, %d)", textureID.m_ID, width, height, dim, depthFormat, createFlags);
return CreateRenderDepthSurfaceD3D11 (textureID, width, height, samples, dim, depthFormat, createFlags, m_Textures);
}
void GfxDeviceD3D11::DestroyRenderSurface (RenderSurfaceHandle& rs)
{
DX11_LOG_ENTER_FUNCTION("DestroyRenderSurface()");
DestroyRenderSurfaceD3D11 (rs, m_Textures);
}
void GfxDeviceD3D11::SetRenderTargets (int count, RenderSurfaceHandle* colorHandles, RenderSurfaceHandle depthHandle, int mipLevel, CubemapFace face)
{
DX11_LOG_ENTER_FUNCTION("SetRenderTargets(%i, c0=%p, d=%p, mip=%i, f=%i)", count, colorHandles[0].object, depthHandle.object, mipLevel, face);
SetupDeferredSRGBWrite ();
m_CurrTargetWidth = m_CurrWindowWidth;
m_CurrTargetHeight = m_CurrWindowHeight;
if (SetRenderTargetD3D11 (count, colorHandles, depthHandle, mipLevel, face, &m_CurrTargetWidth, &m_CurrTargetHeight, &m_Textures))
{
// changing render target might mean different color clear flags; so reset current state
m_CurrBlendState = NULL;
}
}
void GfxDeviceD3D11::ResolveDepthIntoTexture (RenderSurfaceHandle colorHandle, RenderSurfaceHandle depthHandle)
{
DX11_LOG_ENTER_FUNCTION("ResolveDepthIntoTexture(%p, %p)", colorHandle.object, depthHandle.object);
RenderSurfaceD3D11* depthSurf = reinterpret_cast<RenderSurfaceD3D11*>(depthHandle.object);
TexturesD3D11::D3D11Texture* destTexture = m_Textures.GetTexture (depthSurf->textureID);
DebugAssert (destTexture);
if (!destTexture)
return;
DebugAssert (g_D3D11CurrDepthRT);
if (!g_D3D11CurrDepthRT || !g_D3D11CurrDepthRT->m_Texture)
return;
GetD3D11Context()->CopyResource (destTexture->m_Texture, g_D3D11CurrDepthRT->m_Texture);
}
void GfxDeviceD3D11::ResolveColorSurface (RenderSurfaceHandle srcHandle, RenderSurfaceHandle dstHandle)
{
Assert (srcHandle.IsValid());
Assert (dstHandle.IsValid());
RenderColorSurfaceD3D11* src = reinterpret_cast<RenderColorSurfaceD3D11*>(srcHandle.object);
RenderColorSurfaceD3D11* dst = reinterpret_cast<RenderColorSurfaceD3D11*>(dstHandle.object);
if (!src->colorSurface || !dst->colorSurface)
{
WarningString("RenderTexture: Resolving non-color surfaces.");
return;
}
if (src->dim != dst->dim)
{
WarningString("RenderTexture: Resolving surfaces of different types.");
return;
}
if (src->format != dst->format)
{
WarningString("RenderTexture: Resolving surfaces of different formats.");
return;
}
if (src->width != dst->width || src->height != dst->height)
{
WarningString("RenderTexture: Resolving surfaces of different sizes.");
return;
}
ID3D11DeviceContext* ctx = GetD3D11Context();
if (src->samples <= 1 && dst->samples <= 1)
{
ctx->CopyResource (dst->m_Texture, src->m_Texture);
}
else
{
extern DXGI_FORMAT kD3D11RenderTextureFormatsNorm[kRTFormatCount];
ctx->ResolveSubresource (dst->m_Texture, 0, src->m_Texture, 0, kD3D11RenderTextureFormatsNorm[dst->format]);
if ((dst->flags & kSurfaceCreateMipmap) &&
(dst->flags & kSurfaceCreateAutoGenMips) &&
dst->m_SRViewForMips)
{
ctx->GenerateMips (dst->m_SRViewForMips);
}
}
}
RenderSurfaceHandle GfxDeviceD3D11::GetActiveRenderColorSurface(int index)
{
DX11_LOG_ENTER_FUNCTION("GetActiveRenderColorSurface(%d)", index);
return GetActiveRenderColorSurfaceD3D11(index);
}
RenderSurfaceHandle GfxDeviceD3D11::GetActiveRenderDepthSurface()
{
DX11_LOG_ENTER_FUNCTION("GetActiveRenderDepthSurface");
return GetActiveRenderDepthSurfaceD3D11();
}
void GfxDeviceD3D11::SetSurfaceFlags (RenderSurfaceHandle surf, UInt32 flags, UInt32 keepFlags)
{
}
// ---------- uploading textures
void GfxDeviceD3D11::UploadTexture2D( TextureID texture, TextureDimension dimension, UInt8* srcData, int srcSize, int width, int height, TextureFormat format, int mipCount, UInt32 uploadFlags, int skipMipLevels, TextureUsageMode usageMode, TextureColorSpace colorSpace )
{
DX11_LOG_ENTER_FUNCTION("UploadTexture2D(%d, %d, <srcData>, %d, %d, %d, %d, %d, %d, %d)",
texture.m_ID, dimension, width, height, format, mipCount, uploadFlags, skipMipLevels, usageMode);
UnbindTextureD3D11 (texture);
m_Textures.UploadTexture2D (texture, dimension, srcData, width, height, format, mipCount, uploadFlags, skipMipLevels, usageMode, colorSpace);
}
void GfxDeviceD3D11::UploadTextureSubData2D( TextureID texture, UInt8* srcData, int srcSize, int mipLevel, int x, int y, int width, int height, TextureFormat format, TextureColorSpace colorSpace )
{
DX11_LOG_ENTER_FUNCTION("UploadTextureSubData2D(%d, <srcData>, ...)", texture.m_ID)
m_Textures.UploadTextureSubData2D (texture, srcData, mipLevel, x, y, width, height, format, colorSpace);
}
void GfxDeviceD3D11::UploadTextureCube( TextureID texture, UInt8* srcData, int srcSize, int faceDataSize, int size, TextureFormat format, int mipCount, UInt32 uploadFlags, TextureColorSpace colorSpace )
{
DX11_LOG_ENTER_FUNCTION("UploadTextureCube(%d, <srcData>, ...)", texture.m_ID)
UnbindTextureD3D11 (texture);
m_Textures.UploadTextureCube (texture, srcData, faceDataSize, size, format, mipCount, uploadFlags, colorSpace);
}
void GfxDeviceD3D11::UploadTexture3D( TextureID texture, UInt8* srcData, int srcSize, int width, int height, int depth, TextureFormat format, int mipCount, UInt32 uploadFlags )
{
DX11_LOG_ENTER_FUNCTION("UploadTexture3D(%d, <srcData>, ...)", texture.m_ID)
UnbindTextureD3D11 (texture);
m_Textures.UploadTexture3D (texture, srcData, width, height, depth, format, mipCount, uploadFlags);
}
void GfxDeviceD3D11::DeleteTexture( TextureID texture )
{
DX11_LOG_ENTER_FUNCTION("DeleteTexture(%d)", texture.m_ID)
UnbindTextureD3D11 (texture);
m_Textures.DeleteTexture (texture);
}
// ---------- context
GfxDevice::PresentMode GfxDeviceD3D11::GetPresentMode()
{
return kPresentBeforeUpdate;
}
void GfxDeviceD3D11::BeginFrame()
{
DX11_LOG_OUTPUT("*****************************************");
DX11_LOG_OUTPUT("*****************************************");
DX11_LOG_OUTPUT("*****************************************");
DX11_LOG_ENTER_FUNCTION("BeginFrame()");
DX11_MARK_FRAME_BEGIN();
m_InsideFrame = true;
#if UNITY_WINRT
ActivateD3D11BackBuffer(this); // ?!-
#endif
}
void GfxDeviceD3D11::EndFrame()
{
DX11_LOG_ENTER_FUNCTION("EndFrame()");
DX11_MARK_FRAME_END();
m_InsideFrame = false;
}
bool GfxDeviceD3D11::IsValidState()
{
return true;
}
void GfxDeviceD3D11::PresentFrame()
{
#if !UNITY_WP8
IDXGISwapChain* swapChain = GetD3D11SwapChain();
if (swapChain)
swapChain->Present (GetD3D11SyncInterval(), 0);
#endif
m_CBs.NewFrame();
}
void GfxDeviceD3D11::FinishRendering()
{
// not needed on D3D
}
// ---------- immediate mode rendering
// we break very large immediate mode submissions into multiple batches internally
const int kMaxImmediateVerticesPerDraw = 8192;
ImmediateModeD3D11::ImmediateModeD3D11()
: m_VB(NULL)
, m_VBUsedBytes(0)
, m_VBStartVertex(0)
{
}
ImmediateModeD3D11::~ImmediateModeD3D11()
{
Assert (!m_VB);
}
void ImmediateModeD3D11::Cleanup()
{
REGISTER_EXTERNAL_GFX_DEALLOCATION(m_VB);
SAFE_RELEASE(m_VB);
m_VBUsedBytes = 0;
}
void ImmediateModeD3D11::Invalidate()
{
m_Vertices.clear();
memset( &m_Current, 0, sizeof(m_Current) );
m_HadColor = false;
}
void GfxDeviceD3D11::ImmediateVertex( float x, float y, float z )
{
// If the current batch is becoming too large, internally end it and begin it again.
size_t currentSize = m_Imm.m_Vertices.size();
if( currentSize >= kMaxImmediateVerticesPerDraw - 4 )
{
GfxPrimitiveType mode = m_Imm.m_Mode;
// For triangles, break batch when multiple of 3's is reached.
if( mode == kPrimitiveTriangles && currentSize % 3 == 0 )
{
bool hadColor = m_Imm.m_HadColor;
ImmediateEnd();
ImmediateBegin( mode );
m_Imm.m_HadColor = hadColor;
}
// For other primitives, break on multiple of 4's.
// NOTE: This won't quite work for triangle strips, but we'll just pretend
// that will never happen.
else if( mode != kPrimitiveTriangles && currentSize % 4 == 0 )
{
bool hadColor = m_Imm.m_HadColor;
ImmediateEnd();
ImmediateBegin( mode );
m_Imm.m_HadColor = hadColor;
}
}
Vector3f& vert = m_Imm.m_Current.vertex;
vert.x = x;
vert.y = y;
vert.z = z;
m_Imm.m_Vertices.push_back( m_Imm.m_Current );
}
void GfxDeviceD3D11::ImmediateNormal( float x, float y, float z )
{
m_Imm.m_Current.normal.x = x;
m_Imm.m_Current.normal.y = y;
m_Imm.m_Current.normal.z = z;
}
void GfxDeviceD3D11::ImmediateColor( float r, float g, float b, float a )
{
m_Imm.m_Current.color.Set (ColorRGBAf(r,g,b,a));
m_Imm.m_HadColor = true;
}
void GfxDeviceD3D11::ImmediateTexCoordAll( float x, float y, float z )
{
for( int i = 0; i < 8; ++i )
{
Vector3f& uv = m_Imm.m_Current.texCoords[i];
uv.x = x;
uv.y = y;
uv.z = z;
}
}
void GfxDeviceD3D11::ImmediateTexCoord( int unit, float x, float y, float z )
{
if( unit < 0 || unit >= 8 )
{
ErrorString( "Invalid unit for texcoord" );
return;
}
Vector3f& uv = m_Imm.m_Current.texCoords[unit];
uv.x = x;
uv.y = y;
uv.z = z;
}
void GfxDeviceD3D11::ImmediateBegin( GfxPrimitiveType type )
{
m_Imm.m_Mode = type;
m_Imm.m_Vertices.clear();
m_Imm.m_HadColor = false;
}
bool GfxDeviceD3D11::ImmediateEndSetup()
{
if( m_Imm.m_Vertices.empty() )
return false;
HRESULT hr = S_OK;
ID3D11DeviceContext* ctx = GetD3D11Context();
// vertex buffer
const int kImmediateVBSize = kMaxImmediateVerticesPerDraw * sizeof(ImmediateVertexD3D11);
if (!m_Imm.m_VB)
{
ID3D11Device* dev = GetD3D11Device();
D3D11_BUFFER_DESC desc;
desc.ByteWidth = kImmediateVBSize;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
hr = dev->CreateBuffer (&desc, NULL, &m_Imm.m_VB);
REGISTER_EXTERNAL_GFX_ALLOCATION_REF(m_Imm.m_VB,kImmediateVBSize,this);
SetDebugNameD3D11 (m_Imm.m_VB, "VertexBufferImmediate");
m_Imm.m_VBUsedBytes = 0;
m_Imm.m_VBStartVertex = 0;
}
const ImmediateVertexD3D11* vb = &m_Imm.m_Vertices[0];
const int vertexCount = m_Imm.m_Vertices.size();
const int vertexDataSize = vertexCount * sizeof(vb[0]);
D3D11_MAPPED_SUBRESOURCE mapped;
if (m_Imm.m_VBUsedBytes + vertexDataSize > kImmediateVBSize)
{
D3D11_CALL_HR(ctx->Map (m_Imm.m_VB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
m_Imm.m_VBUsedBytes = 0;
}
else
{
D3D11_CALL_HR(ctx->Map (m_Imm.m_VB, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mapped));
}
m_Imm.m_VBStartVertex = m_Imm.m_VBUsedBytes / sizeof(vb[0]);
memcpy ((UInt8*)mapped.pData + m_Imm.m_VBUsedBytes, vb, vertexDataSize);
D3D11_CALL_HR(ctx->Unmap (m_Imm.m_VB, 0));
m_Imm.m_VBUsedBytes += vertexDataSize;
UINT strides = sizeof(vb[0]);
UINT offsets = 0;
D3D11_CALL (ctx->IASetVertexBuffers(0, 1, &m_Imm.m_VB, &strides, &offsets));
m_FFState.useUniformInsteadOfVertexColor = !m_Imm.m_HadColor;
if (!IsShaderActive(kShaderVertex))
{
UInt64 textureSources = m_FFState.texUnitSources;
for (int i = 0; i < gGraphicsCaps.maxTexCoords; ++i)
{
UInt32 source = (textureSources >> (i*4)) & 0xF;
// In immediate mode, each texcoord binds to it's own stage, unless we have texgen
// on some of them.
if (source <= kTexSourceUV7)
{
textureSources = textureSources & ~(0xFUL<<i*4) | (UInt64(kTexSourceUV0+i) << i*4);
}
}
m_FFState.texUnitSources = textureSources;
}
BeforeDrawCall (true);
return true;
}
void GfxDeviceD3D11::ImmediateEndDraw()
{
ID3D11DeviceContext* ctx = GetD3D11Context();
int vertexCount = m_Imm.m_Vertices.size();
// vertex layout
ID3D11InputLayout* inputLayout = m_VertexDecls.GetImmVertexDecl (g_CurrentVSInputD3D11);
if (inputLayout)
{
SetInputLayoutD3D11 (ctx, inputLayout);
if (SetTopologyD3D11 (m_Imm.m_Mode, *this, ctx))
{
// draw
switch (m_Imm.m_Mode)
{
case kPrimitiveTriangles:
D3D11_CALL(ctx->Draw (vertexCount, m_Imm.m_VBStartVertex));
m_Stats.AddDrawCall (vertexCount / 3, vertexCount);
break;
case kPrimitiveTriangleStripDeprecated:
D3D11_CALL(ctx->Draw (vertexCount, m_Imm.m_VBStartVertex));
m_Stats.AddDrawCall (vertexCount - 2, vertexCount);
break;
case kPrimitiveQuads:
GetDynamicVBO(); // ensure it's created
D3D11_CALL(ctx->IASetIndexBuffer (m_DynamicVBO->GetQuadsIB(), DXGI_FORMAT_R16_UINT, 0));
D3D11_CALL(ctx->DrawIndexed (vertexCount/4*6, 0, m_Imm.m_VBStartVertex));
m_Stats.AddDrawCall( vertexCount / 4 * 2, vertexCount );
break;
case kPrimitiveLines:
D3D11_CALL(ctx->Draw (vertexCount, m_Imm.m_VBStartVertex));
m_Stats.AddDrawCall( vertexCount / 2, vertexCount );
break;
default:
AssertString("ImmediateEnd: unknown draw mode");
}
}
}
// clear vertices
m_Imm.m_Vertices.clear();
}
void GfxDeviceD3D11::ImmediateEnd()
{
if (ImmediateEndSetup())
ImmediateEndDraw();
}
typedef SmartComPointer<ID3D11RenderTargetView> RTVPointer;
typedef SmartComPointer<ID3D11Resource> ResourcePointer;
typedef SmartComPointer<ID3D11Texture2D> Texture2DPointer;
bool GfxDeviceD3D11::CaptureScreenshot( int left, int bottom, int width, int height, UInt8* rgba32 )
{
DX11_LOG_ENTER_FUNCTION("CaptureScreenshot(%d, %d, %dx%d)", left, bottom, width, height);
HRESULT hr;
ID3D11DeviceContext* ctx = GetD3D11Context();
SetupDeferredSRGBWrite ();
RenderSurfaceHandle currColorSurface = GetActiveRenderColorSurfaceBBD3D11();
RenderColorSurfaceD3D11* colorSurf = reinterpret_cast<RenderColorSurfaceD3D11*>(currColorSurface.object);
if (!colorSurf)
return false;
RTVPointer rtView;
ctx->OMGetRenderTargets (1, &rtView, NULL);
if (!rtView)
return false;
ResourcePointer rtRes;
rtView->GetResource (&rtRes);
if (!rtRes)
return false;
D3D11_RESOURCE_DIMENSION rtType;
rtRes->GetType (&rtType);
if (rtType != D3D11_RESOURCE_DIMENSION_TEXTURE2D)
return false;
ID3D11Texture2D* rtTex = static_cast<ID3D11Texture2D*>((ID3D11Resource*)rtRes);
D3D11_TEXTURE2D_DESC rtDesc;
rtTex->GetDesc (&rtDesc);
if (rtDesc.Format != DXGI_FORMAT_R8G8B8A8_UNORM &&
rtDesc.Format != DXGI_FORMAT_R8G8B8A8_TYPELESS &&
rtDesc.Format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB &&
rtDesc.Format != DXGI_FORMAT_B8G8R8A8_UNORM)
return false;
ID3D11Device* dev = GetD3D11Device();
ResolveTexturePool::Entry* resolved = NULL;
if (rtDesc.SampleDesc.Count != 1)
{
resolved = m_Resolves.GetResolveTexture (rtDesc.Width, rtDesc.Height, colorSurf->format, m_SRGBWrite);
if (!resolved)
return false;
ctx->ResolveSubresource (resolved->texture, 0, rtTex, 0, rtDesc.Format);
rtTex = resolved->texture;
}
Texture2DPointer stagingTex;
D3D11_TEXTURE2D_DESC stagingDesc;
stagingDesc.Width = width;
stagingDesc.Height = height;
stagingDesc.MipLevels = 1;
stagingDesc.ArraySize = 1;
bool useRGBA = rtDesc.Format == DXGI_FORMAT_R8G8B8A8_UNORM ||
rtDesc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS ||
rtDesc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
stagingDesc.Format = useRGBA ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM;
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
hr = dev->CreateTexture2D (&stagingDesc, NULL, &stagingTex);
if (FAILED(hr))
return false;
SetDebugNameD3D11 (stagingTex, Format("CaptureScreenshot-Texture2D-%dx%d", width, height));
D3D11_BOX srcBox;
srcBox.left = left;
srcBox.right = left + width;
#if UNITY_WP8
/* In WP8 m_CurrTargetHeight seems not to match
* ID3D11DeviceContext height */
srcBox.top = bottom;
srcBox.bottom = bottom + height;
#else
srcBox.top = m_CurrTargetHeight - (bottom + height);
srcBox.bottom = m_CurrTargetHeight - (bottom);
#endif
srcBox.front = 0;
srcBox.back = 1;
ctx->CopySubresourceRegion (stagingTex, 0, 0, 0, 0, rtTex, 0, &srcBox);
D3D11_MAPPED_SUBRESOURCE mapped;
hr = ctx->Map (stagingTex, 0, D3D11_MAP_READ, 0, &mapped);
if (FAILED(hr))
return false;
rgba32 += (height-1) * width * sizeof(UInt32);
const UInt8* src = (const UInt8*)mapped.pData;
for (int y = 0; y < height; ++y)
{
if (useRGBA)
{
memcpy (rgba32, src, width*4);
}
else
{
for (int x = 0; x < width*4; x +=4)
{
rgba32[x] = src[x + 2];
rgba32[x + 1] = src[x + 1];
rgba32[x + 2] = src[x + 0];
rgba32[x + 3] = src[x + 3];
}
}
rgba32 -= width * sizeof(UInt32);
src += mapped.RowPitch;
}
ctx->Unmap (stagingTex, 0);
return true;
}
bool GfxDeviceD3D11::ReadbackImage( ImageReference& image, int left, int bottom, int width, int height, int destX, int destY )
{
Assert (image.GetFormat() == kTexFormatARGB32 || image.GetFormat() == kTexFormatRGB24);
SetupDeferredSRGBWrite ();
HRESULT hr;
ID3D11DeviceContext* ctx = GetD3D11Context();
RenderSurfaceHandle currColorSurface = GetActiveRenderColorSurfaceBBD3D11();
RenderColorSurfaceD3D11* colorSurf = reinterpret_cast<RenderColorSurfaceD3D11*>(currColorSurface.object);
if (!colorSurf)
return false;
RTVPointer rtView;
ctx->OMGetRenderTargets (1, &rtView, NULL);
if (!rtView)
return false;
ResourcePointer rtRes;
rtView->GetResource (&rtRes);
if (!rtRes)
return false;
D3D11_RESOURCE_DIMENSION rtType;
rtRes->GetType (&rtType);
if (rtType != D3D11_RESOURCE_DIMENSION_TEXTURE2D)
return false;
ID3D11Texture2D* rtTex = static_cast<ID3D11Texture2D*>((ID3D11Resource*)rtRes);
D3D11_TEXTURE2D_DESC rtDesc;
rtTex->GetDesc (&rtDesc);
if (rtDesc.Format != DXGI_FORMAT_R8G8B8A8_UNORM && rtDesc.Format != DXGI_FORMAT_R8G8B8A8_TYPELESS && rtDesc.Format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
return false;
ID3D11Device* dev = GetD3D11Device();
ResolveTexturePool::Entry* resolved = NULL;
if (rtDesc.SampleDesc.Count != 1)
{
resolved = m_Resolves.GetResolveTexture (rtDesc.Width, rtDesc.Height, colorSurf->format, m_SRGBWrite);
if (!resolved)
return false;
ctx->ResolveSubresource (resolved->texture, 0, rtTex, 0, rtDesc.Format);
rtTex = resolved->texture;
}
Texture2DPointer stagingTex;
D3D11_TEXTURE2D_DESC stagingDesc;
stagingDesc.Width = width;
stagingDesc.Height = height;
stagingDesc.MipLevels = 1;
stagingDesc.ArraySize = 1;
stagingDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
hr = dev->CreateTexture2D (&stagingDesc, NULL, &stagingTex);
if (FAILED(hr))
return false;
SetDebugNameD3D11 (stagingTex, Format("Readback-Texture2D-%dx%d", width, height));
D3D11_BOX srcBox;
srcBox.left = left;
srcBox.right = left + width;
srcBox.top = m_CurrTargetHeight - (bottom + height);
srcBox.bottom = m_CurrTargetHeight - (bottom);
srcBox.front = 0;
srcBox.back = 1;
ctx->CopySubresourceRegion (stagingTex, 0, 0, 0, 0, rtTex, 0, &srcBox);
D3D11_MAPPED_SUBRESOURCE mapped;
hr = ctx->Map (stagingTex, 0, D3D11_MAP_READ, 0, &mapped);
if (FAILED(hr))
return false;
const UInt8* src = (const UInt8*)mapped.pData;
if (image.GetFormat() == kTexFormatARGB32)
{
for (int y = height-1; y >= 0; --y)
{
const UInt32* srcPtr = (const UInt32*)src;
UInt32* dstPtr = (UInt32*)(image.GetRowPtr(destY+y) + destX * 4);
for (int x = 0; x < width; ++x)
{
UInt32 abgrCol = *srcPtr;
UInt32 bgraCol = ((abgrCol & 0x00FFFFFF) << 8) | ((abgrCol&0xFF000000) >> 24);
*dstPtr = bgraCol;
++srcPtr;
++dstPtr;
}
src += mapped.RowPitch;
}
}
else if (image.GetFormat() == kTexFormatRGB24)
{
for (int y = height-1; y >= 0; --y)
{
const UInt32* srcPtr = (const UInt32*)src;
UInt8* dstPtr = image.GetRowPtr(destY+y) + destX * 3;
for (int x = 0; x < width; ++x)
{
UInt32 abgrCol = *srcPtr;
dstPtr[0] = (abgrCol & 0x000000FF);
dstPtr[1] = (abgrCol & 0x0000FF00) >> 8;
dstPtr[2] = (abgrCol & 0x00FF0000) >> 16;
++srcPtr;
dstPtr += 3;
}
src += mapped.RowPitch;
}
}
ctx->Unmap (stagingTex, 0);
return true;
}
void GfxDeviceD3D11::GrabIntoRenderTexture(RenderSurfaceHandle rtHandle, RenderSurfaceHandle rd, int x, int y, int width, int height)
{
DX11_LOG_ENTER_FUNCTION("GrabIntoRenderTexture(%p, %p, %d, %d, %dx%d)", rtHandle.object, rd.object, x, y, width, height);
if (!rtHandle.IsValid())
return;
if (!g_D3D11CurrColorRT)
return;
RenderSurfaceHandle currColorSurface = GetActiveRenderColorSurfaceBBD3D11();
RenderColorSurfaceD3D11* colorSurf = reinterpret_cast<RenderColorSurfaceD3D11*>(currColorSurface.object);
if (!colorSurf)
return;
const bool sRGB = (gGraphicsCaps.d3d11.featureLevel >= kDX11Level10_0) ? (colorSurf->flags & kSurfaceCreateSRGB) : false;
RenderColorSurfaceD3D11* renderTexture = reinterpret_cast<RenderColorSurfaceD3D11*>(rtHandle.object);
TexturesD3D11::D3D11Texture* texturePointer = m_Textures.GetTexture (renderTexture->textureID);
if (!texturePointer)
return;
SetupDeferredSRGBWrite ();
ID3D11Resource* srcResource = g_D3D11CurrColorRT->m_Texture;
ID3D11Texture2D* srcTex = static_cast<ID3D11Texture2D*>(srcResource);
D3D11_TEXTURE2D_DESC rtDesc;
srcTex->GetDesc (&rtDesc);
Assert (rtDesc.Width == colorSurf->width && rtDesc.Height == colorSurf->height);
ID3D11DeviceContext* ctx = GetD3D11Context();
ResolveTexturePool::Entry* resolved = NULL;
if (rtDesc.SampleDesc.Count != 1)
{
resolved = m_Resolves.GetResolveTexture (rtDesc.Width, rtDesc.Height, colorSurf->format, sRGB);
if (!resolved)
return;
ctx->ResolveSubresource (resolved->texture, 0, srcResource, 0, GetRenderTextureFormat(colorSurf->format, sRGB));
srcResource = resolved->texture;
}
ID3D11Texture2D* dstTex = static_cast<ID3D11Texture2D*>(texturePointer->m_Texture);
D3D11_TEXTURE2D_DESC dstDesc;
dstTex->GetDesc (&dstDesc);
if (GetBPPFromDXGIFormat(rtDesc.Format) == GetBPPFromDXGIFormat(dstDesc.Format))
{
D3D11_BOX srcBox;
srcBox.left = x;
srcBox.right = x + width;
srcBox.top = m_CurrTargetHeight - (y + height);
srcBox.bottom = m_CurrTargetHeight - (y);
srcBox.front = 0;
srcBox.back = 1;
ctx->CopySubresourceRegion (texturePointer->m_Texture, 0, 0, 0, 0, srcResource, 0, &srcBox);
}
else
{
// formats not compatible; have to draw a quad into destination, sampling the source texture
RenderColorSurfaceD3D11* currRT = g_D3D11CurrColorRT;
int oldTargetHeight = m_CurrTargetHeight;
int oldView[4];
GetViewport (oldView);
bool oldScissor = IsScissorEnabled();
int oldScissorRect[4];
GetScissorRect (oldScissorRect);
SetViewport (0, 0, dstDesc.Width, dstDesc.Height);
DisableScissor ();
RenderSurfaceHandle currColor = GetActiveRenderColorSurface(0);
RenderSurfaceHandle currDepth = GetActiveRenderDepthSurface();
SetRenderTargets (1, &rtHandle, rd, 0, kCubeFaceUnknown);
const float u0 = x / float(rtDesc.Width);
const float u1 = (x+width) / float(rtDesc.Width);
const float v0 = (rtDesc.Height - y) / float(rtDesc.Height);
const float v1 = (rtDesc.Height - (y+height)) / float(rtDesc.Height);
ID3D11ShaderResourceView* srv = currRT ? currRT->m_SRView : NULL;
if (resolved)
srv = resolved->srv;
DrawQuad (u0, v0, u1, v1, 0.0f, srv);
SetRenderTargets (1, &currColor, currDepth, 0, kCubeFaceUnknown);
SetViewport (oldView[0], oldView[1], oldView[2], oldView[3]);
if (oldScissor)
SetScissorRect (oldScissorRect[0], oldScissorRect[1], oldScissorRect[2], oldScissorRect[3]);
}
}
void GfxDeviceD3D11::DrawQuad (float u0, float v0, float u1, float v1, float z, ID3D11ShaderResourceView* texture)
{
// Can't use DeviceMVPMatricesState since that tries to get potentially threaded device.
// We need to access our own device directly.
Matrix4x4f m_World, m_View, m_Proj;
CopyMatrix(GetViewMatrix(), m_View.GetPtr());
CopyMatrix(GetWorldMatrix(), m_World.GetPtr());
CopyMatrix(GetProjectionMatrix(), m_Proj.GetPtr());
// Can't use LoadFullScreenOrthoMatrix for the same reason.
Matrix4x4f matrix;
matrix.SetOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 100.0f);
SetProjectionMatrix (matrix);
SetViewMatrix (Matrix4x4f::identity.GetPtr()); // implicitly sets world to identity
DisableFog ();
SetFFLighting (false, false, kColorMatDisabled);
DisableLights (0);
ShaderLab::SubProgram* programs[kShaderTypeCount] = {0};
GraphicsHelper::SetShaders (*this, programs, NULL);
GfxBlendState blendDesc;
DeviceBlendState* blendState = CreateBlendState(blendDesc);
SetBlendState (blendState, 0.0f);
GfxDepthState depthDesc; depthDesc.depthWrite = false; depthDesc.depthFunc = kFuncAlways;
DeviceDepthState* depthState = CreateDepthState(depthDesc);
SetDepthState (depthState);
GfxRasterState rasterDesc; rasterDesc.cullMode = kCullOff;
DeviceRasterState* rasterState = CreateRasterState(rasterDesc);
SetRasterState (rasterState);
ShaderLab::TextureBinding texEnv;
texEnv.m_TextureName.index = kShaderTexEnvWhite | ShaderLab::FastPropertyName::kBuiltinTexEnvMask;
TextureCombinersHandle combiners = CreateTextureCombiners (1, &texEnv, NULL, false, false);
// Can't call SetTextureCombiners here since that expects to be called on main thread,
// and we might be on the device thread here. So do the work manually and call
// SetTextureCombinersThreadable.
TexEnvData texEnvData;
memset(&texEnvData, 0, sizeof(texEnvData));
texEnvData.textureID = TextureID();
texEnvData.texDim = kTexDim2D;
texEnvData.texGen = kTexGenDisabled;
texEnvData.identityMatrix = true;
Vector4f texColors;
texColors.Set(1,1,1,1);
SetTextureCombinersThreadable (combiners, &texEnvData, &texColors);
ImmediateBegin (kPrimitiveQuads);
ImmediateTexCoord(0,u0,v0,0.0f); ImmediateVertex (0.0f, 0.0f, z);
ImmediateTexCoord(0,u0,v1,0.0f); ImmediateVertex (0.0f, 1.0f, z);
ImmediateTexCoord(0,u1,v1,0.0f); ImmediateVertex (1.0f, 1.0f, z);
ImmediateTexCoord(0,u1,v0,0.0f); ImmediateVertex (1.0f, 0.0f, z);
if (ImmediateEndSetup ())
{
ID3D11SamplerState* sampler = m_Textures.GetSampler (kSamplerPointClamp);
Assert (sampler);
ID3D11DeviceContext* ctx = GetD3D11Context();
ctx->PSSetShaderResources (0, 1, &texture);
ctx->PSSetSamplers (0, 1, &sampler);
m_Textures.InvalidateSampler (kShaderFragment, 0);
m_ActiveTextures[kShaderFragment][0].m_ID = -1;
m_ActiveSamplers[kShaderFragment][0].m_ID = -1;
ImmediateEndDraw ();
ID3D11ShaderResourceView* nullTex = NULL;
ctx->PSSetShaderResources (0, 1, &nullTex);
}
// restore matrices
SetViewMatrix(m_View.GetPtr());
SetWorldMatrix(m_World.GetPtr());
SetProjectionMatrix(m_Proj);
}
void* GfxDeviceD3D11::GetNativeGfxDevice()
{
return GetD3D11Device();
}
void* GfxDeviceD3D11::GetNativeTexturePointer(TextureID id)
{
TexturesD3D11::D3D11Texture* tex = m_Textures.GetTexture(id);
if (!tex)
return NULL;
return tex->m_Texture;
}
intptr_t GfxDeviceD3D11::CreateExternalTextureFromNative(intptr_t nativeTex)
{
return m_Textures.RegisterNativeTexture((ID3D11ShaderResourceView*)nativeTex);
}
void GfxDeviceD3D11::UpdateExternalTextureFromNative(TextureID tex, intptr_t nativeTex)
{
m_Textures.UpdateNativeTexture(tex, (ID3D11ShaderResourceView*)nativeTex);
}
#if ENABLE_PROFILER
void GfxDeviceD3D11::BeginProfileEvent (const char* name)
{
if (g_D3D11BeginEventFunc)
{
wchar_t wideName[100];
UTF8ToWide (name, wideName, 100);
g_D3D11BeginEventFunc (0, wideName);
}
}
void GfxDeviceD3D11::EndProfileEvent ()
{
if (g_D3D11EndEventFunc)
{
g_D3D11EndEventFunc ();
}
}
GfxTimerQuery* GfxDeviceD3D11::CreateTimerQuery()
{
Assert(gGraphicsCaps.hasTimerQuery);
return g_TimerQueriesD3D11.CreateTimerQuery();
}
void GfxDeviceD3D11::DeleteTimerQuery(GfxTimerQuery* query)
{
delete query;
}
void GfxDeviceD3D11::BeginTimerQueries()
{
if(!gGraphicsCaps.hasTimerQuery)
return;
g_TimerQueriesD3D11.BeginTimerQueries();
}
void GfxDeviceD3D11::EndTimerQueries()
{
if(!gGraphicsCaps.hasTimerQuery)
return;
g_TimerQueriesD3D11.EndTimerQueries();
}
#endif // ENABLE_PROFILER
// -------- editor only functions
#if UNITY_EDITOR
void GfxDeviceD3D11::SetAntiAliasFlag (bool aa)
{
}
void GfxDeviceD3D11::DrawUserPrimitives (GfxPrimitiveType type, int vertexCount, UInt32 vertexChannels, const void* data, int stride)
{
if (vertexCount == 0)
return;
Assert(vertexCount <= 60000); // TODO: handle this by multi-batching
Assert(data && vertexCount >= 0 && vertexChannels != 0);
DynamicD3D11VBO& vbo = static_cast<DynamicD3D11VBO&>(GetDynamicVBO());
void* vbPtr;
//@TODO: hack to pass kDrawTriangleStrip, but we only need that to determine if we need index buffer or not (we don't)
if (!vbo.GetChunk(vertexChannels, vertexCount, 0, DynamicVBO::kDrawTriangleStrip, &vbPtr, NULL))
return;
memcpy (vbPtr, data, vertexCount * stride);
vbo.ReleaseChunk (vertexCount, 0);
vbo.DrawChunkUserPrimitives (type);
}
int GfxDeviceD3D11::GetCurrentTargetAA() const
{
return 0; //@TODO
}
GfxDeviceWindow* GfxDeviceD3D11::CreateGfxWindow (HWND window, int width, int height, DepthBufferFormat depthFormat, int antiAlias)
{
return new D3D11Window(window, width, height, depthFormat, antiAlias);
}
static ID3D11Texture2D* FindD3D11TextureByID (TextureID tid)
{
GfxDevice& device = GetRealGfxDevice();
if (device.GetRenderer() != kGfxRendererD3D11)
return NULL;
GfxDeviceD3D11& dev = static_cast<GfxDeviceD3D11&>(device);
TexturesD3D11::D3D11Texture* basetex = dev.GetTextures().GetTexture(tid);
if (!basetex || !basetex->m_Texture)
return NULL;
D3D11_RESOURCE_DIMENSION dim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
basetex->m_Texture->GetType(&dim);
if (dim != D3D11_RESOURCE_DIMENSION_TEXTURE2D)
return NULL;
return static_cast<ID3D11Texture2D*>(basetex->m_Texture);
}
HDC AcquireHDCForTextureD3D11 (TextureID tid, int& outWidth, int& outHeight)
{
ID3D11Texture2D* tex = FindD3D11TextureByID (tid);
if (!tex)
return NULL;
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc (&desc);
outWidth = desc.Width;
outHeight = desc.Height;
IDXGISurface1* dxgiSurface = NULL;
tex->QueryInterface(__uuidof(IDXGISurface1), (void**)(&dxgiSurface));
HDC dc = NULL;
if (dxgiSurface)
{
dxgiSurface->GetDC (false, &dc);
dxgiSurface->Release();
}
return dc;
}
void ReleaseHDCForTextureD3D11 (TextureID tid, HDC dc)
{
ID3D11Texture2D* tex = FindD3D11TextureByID (tid);
if (!tex)
return;
IDXGISurface1* dxgiSurface = NULL;
tex->QueryInterface(__uuidof(IDXGISurface1), (void**)(&dxgiSurface));
if (dxgiSurface)
{
dxgiSurface->ReleaseDC(NULL);
dxgiSurface->Release();
}
}
#endif // UNITY_EDITOR
int GfxDeviceD3D11::GetCurrentTargetWidth() const
{
return m_CurrTargetWidth;
}
int GfxDeviceD3D11::GetCurrentTargetHeight() const
{
return m_CurrTargetHeight;
}
void GfxDeviceD3D11::SetCurrentTargetSize(int width, int height)
{
m_CurrTargetWidth = width;
m_CurrTargetHeight = height;
}
void GfxDeviceD3D11::SetCurrentWindowSize(int width, int height)
{
m_CurrWindowWidth = m_CurrTargetWidth = width;
m_CurrWindowHeight = m_CurrTargetHeight = height;
}
// ----------------------------------------------------------------------
void GfxDeviceD3D11::SetComputeBuffer11 (ShaderType shaderType, int unit, ComputeBufferID bufferHandle)
{
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(bufferHandle);
ID3D11ShaderResourceView* srv = buffer ? buffer->srv : NULL;
ID3D11DeviceContext* ctx = GetD3D11Context();
switch (shaderType) {
case kShaderVertex: ctx->VSSetShaderResources (unit, 1, &srv); break;
case kShaderFragment: ctx->PSSetShaderResources (unit, 1, &srv); break;
case kShaderGeometry: ctx->GSSetShaderResources (unit, 1, &srv); break;
case kShaderHull: ctx->HSSetShaderResources (unit, 1, &srv); break;
case kShaderDomain: ctx->DSSetShaderResources (unit, 1, &srv); break;
default: AssertString("unknown shader type");
}
m_ActiveTextures[shaderType][unit].m_ID = 0;
}
void GfxDeviceD3D11::SetComputeBufferData (ComputeBufferID bufferHandle, const void* data, size_t size)
{
if (!data || !size)
return;
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(bufferHandle);
if (!buffer || !buffer->buffer)
return;
ID3D11DeviceContext* ctx = GetD3D11Context();
D3D11_BOX box;
box.left = 0;
box.top = 0;
box.front = 0;
box.right = size;
box.bottom = 1;
box.back = 1;
ctx->UpdateSubresource (buffer->buffer, 0, &box, data, 0, 0);
}
void GfxDeviceD3D11::GetComputeBufferData (ComputeBufferID bufferHandle, void* dest, size_t destSize)
{
if (!dest || !destSize)
return;
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(bufferHandle);
if (!buffer || !buffer->buffer)
return;
ID3D11DeviceContext* ctx = GetD3D11Context();
ID3D11Buffer* cpuBuffer = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory (&desc, sizeof(desc));
buffer->buffer->GetDesc (&desc);
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0;
HRESULT hr = GetD3D11Device()->CreateBuffer(&desc, NULL, &cpuBuffer);
if (FAILED(hr))
return;
SetDebugNameD3D11 (cpuBuffer, Format("CSGetData-Staging-%d", desc.ByteWidth));
ctx->CopyResource (cpuBuffer, buffer->buffer);
D3D11_MAPPED_SUBRESOURCE mapped;
hr = ctx->Map (cpuBuffer, 0, D3D11_MAP_READ, 0, &mapped);
if (SUCCEEDED(hr))
{
memcpy (dest, mapped.pData, destSize);
ctx->Unmap (cpuBuffer, 0);
}
SAFE_RELEASE (cpuBuffer);
}
void GfxDeviceD3D11::CopyComputeBufferCount (ComputeBufferID srcBuffer, ComputeBufferID dstBuffer, UInt32 dstOffset)
{
ComputeBuffer11* src = m_Textures.GetComputeBuffer(srcBuffer);
if (!src || !src->uav)
return;
ComputeBuffer11* dst = m_Textures.GetComputeBuffer(dstBuffer);
if (!dst || !dst->buffer)
return;
ID3D11DeviceContext* ctx = GetD3D11Context();
ctx->CopyStructureCount (dst->buffer, dstOffset, src->uav);
}
void GfxDeviceD3D11::SetRandomWriteTargetTexture (int index, TextureID tid)
{
void SetRandomWriteTargetTextureD3D11 (int index, TextureID tid);
SetRandomWriteTargetTextureD3D11 (index, tid);
}
void GfxDeviceD3D11::SetRandomWriteTargetBuffer (int index, ComputeBufferID bufferHandle)
{
void SetRandomWriteTargetBufferD3D11 (int index, ComputeBufferID bufferHandle);
SetRandomWriteTargetBufferD3D11 (index, bufferHandle);
}
void GfxDeviceD3D11::ClearRandomWriteTargets ()
{
void ClearRandomWriteTargetsD3D11 (TexturesD3D11* textures);
ClearRandomWriteTargetsD3D11 (&m_Textures);
}
ComputeProgramHandle GfxDeviceD3D11::CreateComputeProgram (const UInt8* code, size_t codeSize)
{
ComputeProgramHandle cpHandle;
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level11_0)
return cpHandle;
ID3D11Device* dev = GetD3D11Device();
HRESULT hr;
ID3D11ComputeShader* cs = NULL;
hr = dev->CreateComputeShader (code, codeSize, NULL, &cs);
if (FAILED(hr))
return cpHandle;
SetDebugNameD3D11 (cs, Format("ComputeShader-%d", (int)codeSize));
cpHandle.object = cs;
return cpHandle;
}
void GfxDeviceD3D11::DestroyComputeProgram (ComputeProgramHandle& cpHandle)
{
if (!cpHandle.IsValid())
return;
ID3D11ComputeShader* cs = reinterpret_cast<ID3D11ComputeShader*>(cpHandle.object);
SAFE_RELEASE(cs);
cpHandle.Reset();
}
void GfxDeviceD3D11::CreateComputeConstantBuffers (unsigned count, const UInt32* sizes, ConstantBufferHandle* outCBs)
{
ID3D11Device* dev = GetD3D11Device();
HRESULT hr;
D3D11_BUFFER_DESC desc;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
for (unsigned i = 0; i < count; ++i)
{
desc.ByteWidth = sizes[i];
ID3D11Buffer* cb = NULL;
hr = dev->CreateBuffer (&desc, NULL, &cb);
if (cb)
REGISTER_EXTERNAL_GFX_ALLOCATION_REF(cb,sizes[i],this);
Assert (SUCCEEDED(hr));
outCBs[i].object = cb;
SetDebugNameD3D11 (cb, Format("CSConstantBuffer-%d-%d", i, sizes[i]));
}
}
void GfxDeviceD3D11::DestroyComputeConstantBuffers (unsigned count, ConstantBufferHandle* cbs)
{
for (unsigned i = 0; i < count; ++i)
{
ID3D11Buffer* cb = reinterpret_cast<ID3D11Buffer*>(cbs[i].object);
REGISTER_EXTERNAL_GFX_DEALLOCATION(cb);
SAFE_RELEASE(cb);
cbs[i].Reset();
}
}
void GfxDeviceD3D11::CreateComputeBuffer (ComputeBufferID id, size_t count, size_t stride, UInt32 flags)
{
ComputeBuffer11 buffer;
buffer.buffer = NULL;
buffer.srv = NULL;
buffer.uav = NULL;
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level10_0)
return;
ID3D11Device* dev = GetD3D11Device();
HRESULT hr;
// buffer
D3D11_BUFFER_DESC bufferDesc;
memset (&bufferDesc, 0, sizeof(bufferDesc));
bufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
if (gGraphicsCaps.d3d11.featureLevel >= kDX11Level11_0)
bufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
bufferDesc.ByteWidth = count * stride;
if (flags & kCBFlagDrawIndirect)
bufferDesc.MiscFlags = (gGraphicsCaps.d3d11.featureLevel >= kDX11Level11_0 ? D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS : 0);
else if (flags & kCBFlagRaw)
bufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
else
bufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
bufferDesc.StructureByteStride = stride;
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
hr = dev->CreateBuffer (&bufferDesc, NULL, &buffer.buffer);
if (buffer.buffer)
REGISTER_EXTERNAL_GFX_ALLOCATION_REF(buffer.buffer,count * stride,this);
Assert (SUCCEEDED(hr));
SetDebugNameD3D11 (buffer.buffer, Format("ComputeBuffer-%dx%d", (int)count, (int)stride));
// unordered access view, only on DX11+ HW
if (gGraphicsCaps.d3d11.featureLevel >= kDX11Level11_0 && !(flags & kCBFlagDrawIndirect))
{
D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
memset (&uavDesc, 0, sizeof(uavDesc));
uavDesc.Format = (flags & kCBFlagRaw) ? DXGI_FORMAT_R32_TYPELESS : DXGI_FORMAT_UNKNOWN;
uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
uavDesc.Buffer.FirstElement = 0;
uavDesc.Buffer.NumElements = count;
uavDesc.Buffer.Flags = flags & kCBFlagTypeMask;
hr = dev->CreateUnorderedAccessView (buffer.buffer, &uavDesc, &buffer.uav);
Assert (SUCCEEDED(hr));
SetDebugNameD3D11 (buffer.uav, Format("ComputeBuffer-UAV-%dx%d", (int)count, (int)stride));
// shader resource view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
memset (&srvDesc, 0, sizeof(srvDesc));
if (flags & kCBFlagRaw)
{
srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
srvDesc.BufferEx.FirstElement = 0;
srvDesc.BufferEx.NumElements = count;
srvDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
}
else
{
srvDesc.Format = DXGI_FORMAT_UNKNOWN;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
srvDesc.Buffer.FirstElement = 0;
srvDesc.Buffer.NumElements = count;
}
hr = dev->CreateShaderResourceView (buffer.buffer, &srvDesc, &buffer.srv);
Assert (SUCCEEDED(hr));
SetDebugNameD3D11 (buffer.uav, Format("ComputeBuffer-SRV-%dx%d", (int)count, (int)stride));
}
m_Textures.AddComputeBuffer (id, buffer);
}
void GfxDeviceD3D11::DestroyComputeBuffer (ComputeBufferID handle)
{
if (!handle.IsValid())
return;
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(handle);
if (buffer)
{
REGISTER_EXTERNAL_GFX_DEALLOCATION(buffer->buffer);
SAFE_RELEASE(buffer->buffer);
SAFE_RELEASE(buffer->srv);
SAFE_RELEASE(buffer->uav);
}
m_Textures.RemoveComputeBuffer (handle);
}
void GfxDeviceD3D11::UpdateComputeConstantBuffers (unsigned count, ConstantBufferHandle* cbs, UInt32 cbDirty, size_t dataSize, const UInt8* data, const UInt32* cbSizes, const UInt32* cbOffsets, const int* bindPoints)
{
ID3D11DeviceContext* ctx = GetD3D11Context();
// go over constant buffers in use
for (unsigned i = 0; i < count; ++i)
{
if (bindPoints[i] < 0)
continue; // CB not going to be used, no point in updating it
ID3D11Buffer* cb = reinterpret_cast<ID3D11Buffer*>(cbs[i].object);
// update buffer if dirty
UInt32 dirtyMask = (1<<i);
if (cbDirty & dirtyMask)
{
D3D11_MAPPED_SUBRESOURCE mapped;
HRESULT hr;
hr = ctx->Map (cb, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
Assert (SUCCEEDED(hr));
memcpy (mapped.pData, data + cbOffsets[i], cbSizes[i]);
ctx->Unmap (cb, 0);
}
// bind it
ctx->CSSetConstantBuffers (bindPoints[i], 1, &cb);
}
}
void GfxDeviceD3D11::UpdateComputeResources (
unsigned texCount, const TextureID* textures, const int* texBindPoints,
unsigned samplerCount, const unsigned* samplers,
unsigned inBufferCount, const ComputeBufferID* inBuffers, const int* inBufferBindPoints,
unsigned outBufferCount, const ComputeBufferID* outBuffers, const TextureID* outTextures, const UInt32* outBufferBindPoints)
{
ID3D11DeviceContext* ctx = GetD3D11Context();
for (unsigned i = 0; i < texCount; ++i)
{
if (textures[i].m_ID == 0)
continue;
TexturesD3D11::D3D11Texture* tex = m_Textures.GetTexture (textures[i]);
if (!tex)
continue;
// if texture is bound as render target: unbind it (set backbuffer as RT)
if ((g_D3D11CurrColorRT && g_D3D11CurrColorRT->m_Texture == tex->m_Texture) ||
(g_D3D11CurrDepthRT && g_D3D11CurrDepthRT->m_Texture == tex->m_Texture))
{
RenderSurfaceHandle defaultColor = GetBackBufferColorSurface();
RenderSurfaceHandle defaultDepth = GetBackBufferDepthSurface();
SetRenderTargets (1, &defaultColor, defaultDepth, 0, kCubeFaceUnknown);
}
ctx->CSSetShaderResources (texBindPoints[i] & 0xFFFF, 1, &tex->m_SRV);
unsigned samplerBindPoint = (texBindPoints[i] >> 16) & 0xFFFF;
if (samplerBindPoint != 0xFFFF)
{
ID3D11SamplerState* smp = m_Textures.GetSampler(tex->m_Sampler);
ctx->CSSetSamplers (samplerBindPoint, 1, &smp);
}
}
for (unsigned i = 0; i < samplerCount; ++i)
{
BuiltinSamplerState type = (BuiltinSamplerState)((samplers[i] & 0xFFFF0000) >> 16);
unsigned bindPoint = samplers[i] & 0xFFFF;
ID3D11SamplerState* smp = m_Textures.GetSampler (type);
Assert (smp);
ctx->CSSetSamplers (bindPoint, 1, &smp);
}
for (unsigned i = 0; i < inBufferCount; ++i)
{
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(inBuffers[i]);
if (!buffer)
continue;
ctx->CSSetShaderResources (inBufferBindPoints[i], 1, &buffer->srv);
}
for (unsigned i = 0; i < outBufferCount; ++i)
{
ID3D11UnorderedAccessView* uav = NULL;
if (outBufferBindPoints[i] & 0x80000000)
{
// UAV comes from texture
if (outTextures[i].m_ID == 0)
continue;
TexturesD3D11::D3D11Texture* tex = m_Textures.GetTexture (outTextures[i]);
if (!tex || !tex->m_UAV)
continue;
uav = tex->m_UAV;
}
else
{
// UAV is raw buffer
if (!outBuffers[i].IsValid())
continue;
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(outBuffers[i]);
if (!buffer)
continue;
uav = buffer->uav;
}
UINT uavInitialCounts[] = { -1 }; // keeps current offsets for Appendable/Consumeable UAVs
ctx->CSSetUnorderedAccessViews (outBufferBindPoints[i] & 0x7FFFFFFF, 1, &uav, uavInitialCounts);
}
}
void GfxDeviceD3D11::DispatchComputeProgram (ComputeProgramHandle cpHandle, unsigned threadsX, unsigned threadsY, unsigned threadsZ)
{
if (!cpHandle.IsValid())
return;
ID3D11DeviceContext* ctx = GetD3D11Context();
ID3D11ComputeShader* cs = reinterpret_cast<ID3D11ComputeShader*>(cpHandle.object);
ctx->CSSetShader (cs, NULL, 0);
ctx->Dispatch (threadsX, threadsY, threadsZ);
// DEBUG: readback output UAV contents
#if 0 && !UNITY_RELEASE
ID3D11UnorderedAccessView* uav;
ctx->CSGetUnorderedAccessViews (0, 1, &uav);
ID3D11Buffer* res;
uav->GetResource ((ID3D11Resource**)&res);
ID3D11Buffer* debugbuf = NULL;
D3D11_BUFFER_DESC desc;
ZeroMemory (&desc, sizeof(desc));
res->GetDesc (&desc);
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.MiscFlags = 0;
GetD3D11Device()->CreateBuffer(&desc, NULL, &debugbuf);
ctx->CopyResource (debugbuf, res);
D3D11_MAPPED_SUBRESOURCE mapped;
ctx->Map(debugbuf, 0, D3D11_MAP_READ, 0, &mapped);
ctx->Unmap(debugbuf, 0);
SAFE_RELEASE(debugbuf);
#endif
ID3D11UnorderedAccessView* nullUAVs[8] = {0};
ctx->CSSetUnorderedAccessViews (0, 8, nullUAVs, NULL);
}
// ----------------------------------------------------------------------
void GfxDeviceD3D11::DrawNullGeometry (GfxPrimitiveType topology, int vertexCount, int instanceCount)
{
ID3D11DeviceContext* ctx = GetD3D11Context();
UINT strides = 0;
UINT offsets = 0;
ID3D11Buffer* vb = NULL;
D3D11_CALL (ctx->IASetVertexBuffers(0, 1, &vb, &strides, &offsets));
BeforeDrawCall (false);
// vertex layout
SetInputLayoutD3D11 (ctx, NULL);
// draw
if (!SetTopologyD3D11 (topology, *this, ctx))
return;
if (instanceCount > 1)
{
D3D11_CALL (ctx->DrawInstanced (vertexCount, instanceCount, 0, 0));
}
else
{
D3D11_CALL (ctx->Draw (vertexCount, 0));
}
}
void GfxDeviceD3D11::DrawNullGeometryIndirect (GfxPrimitiveType topology, ComputeBufferID bufferHandle, UInt32 bufferOffset)
{
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level11_0)
return;
ID3D11DeviceContext* ctx = GetD3D11Context();
UINT strides = 0;
UINT offsets = 0;
ID3D11Buffer* vb = NULL;
D3D11_CALL (ctx->IASetVertexBuffers(0, 1, &vb, &strides, &offsets));
BeforeDrawCall (false);
// vertex layout
SetInputLayoutD3D11 (ctx, NULL);
// draw
if (!SetTopologyD3D11 (topology, *this, ctx))
return;
ComputeBuffer11* buffer = m_Textures.GetComputeBuffer(bufferHandle);
if (!buffer || !buffer->buffer)
return;
D3D11_CALL (ctx->DrawInstancedIndirect (buffer->buffer, bufferOffset));
}
// GPU skinning functionality
GPUSkinningInfo * GfxDeviceD3D11::CreateGPUSkinningInfo()
{
// stream-out requires at least DX10.0
if (gGraphicsCaps.d3d11.featureLevel < kDX11Level10_0)
return NULL;
return new StreamOutSkinningInfo();
}
void GfxDeviceD3D11::DeleteGPUSkinningInfo(GPUSkinningInfo *info)
{
delete reinterpret_cast<StreamOutSkinningInfo *>(info);
}
// All actual functionality is performed in StreamOutSkinningInfo, just forward the calls
void GfxDeviceD3D11::SkinOnGPU( GPUSkinningInfo * info, bool lastThisFrame )
{
reinterpret_cast<StreamOutSkinningInfo *>(info)->SkinMesh(lastThisFrame);
}
void GfxDeviceD3D11::UpdateSkinSourceData(GPUSkinningInfo *info, const void *vertData, const BoneInfluence *skinData, bool dirty)
{
reinterpret_cast<StreamOutSkinningInfo *>(info)->UpdateSourceData(vertData, skinData, dirty);
}
void GfxDeviceD3D11::UpdateSkinBonePoses(GPUSkinningInfo *info, const int boneCount, const Matrix4x4f* poses)
{
reinterpret_cast<StreamOutSkinningInfo *>(info)->UpdateSourceBones(boneCount, poses);
}
// ----------------------------------------------------------------------
// verification of state
#if GFX_DEVICE_VERIFY_ENABLE
void GfxDeviceD3D11::VerifyState()
{
}
#endif // GFX_DEVICE_VERIFY_ENABLE
|