1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include "render_pch.h"
#include "shadowmgr.h"
#include "utllinkedlist.h"
#include "utlvector.h"
#include "interface.h"
#include "mathlib/vmatrix.h"
#include "bsptreedata.h"
#include "materialsystem/itexture.h"
#include "filesystem.h"
#include "utlbidirectionalset.h"
#include "l_studio.h"
#include "istudiorender.h"
#include "engine/ivmodelrender.h"
#include "collisionutils.h"
#include "debugoverlay.h"
#include "tier0/vprof.h"
#include "disp.h"
#include "gl_rmain.h"
#include "MaterialBuckets.h"
#include "r_decal.h"
#include "cmodel_engine.h"
#include "iclientrenderable.h"
#include "cdll_engine_int.h"
#include "sys_dll.h"
#include "render.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Shadow-related functionality exported by the engine
//
// We have two shadow-related caches in this system
// 1) A surface cache. We keep track of which surfaces the shadows can
// potentially hit. The computation of the surface cache should be
// as fast as possible
// 2) A surface vertex cache. Once we know what surfaces the shadow
// hits, we caompute the actual polygons using a clip. This is only
// useful for shadows that we know don't change too frequently, so
// we pass in a flag when making the shadow to indicate whether the
// vertex cache should be used or not. The assumption is that the client
// of this system should know whether the shadows are always changing or not
//
// The first cache is generated when the shadow is initially projected, and
// the second cache is generated when the surfaces are actually being rendered.
//
// For rendering, I assign a sort order ID to all materials used by shadow
// decals. The sort order serves the identical purpose to the material's EnumID
// but I remap those IDs so I can keep a small list of decals to render with
// that enum ID (the other option would be to allocate an array with a number
// of elements == to the number of material enumeration IDs, which is pretty large).
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// forward decarations
//-----------------------------------------------------------------------------
extern int r_surfacevisframe;
extern IStudioRender *g_pStudioRender;
#define BACKFACE_EPSILON 0.01f
// Max number of vertices per shadow decal
enum
{
SHADOW_VERTEX_SMALL_CACHE_COUNT = 8,
SHADOW_VERTEX_LARGE_CACHE_COUNT = 32,
SHADOW_VERTEX_TEMP_COUNT = 48,
MAX_CLIP_PLANE_COUNT = 4,
SURFACE_BOUNDS_CACHE_COUNT = 1024,
//=============================================================================
// HPE_BEGIN:
// [smessick] Cache size for the shadow decals. This used to be on the stack.
//=============================================================================
SHADOW_DECAL_CACHE_COUNT = 16*1024,
MAX_SHADOW_DECAL_CACHE_COUNT = 64*1024,
//=============================================================================
// HPE_END
//=============================================================================
};
//-----------------------------------------------------------------------------
// Used to clip the shadow decals
//-----------------------------------------------------------------------------
struct ShadowClipState_t
{
int m_CurrVert;
int m_TempCount;
int m_ClipCount;
ShadowVertex_t m_pTempVertices[SHADOW_VERTEX_TEMP_COUNT];
ShadowVertex_t* RESTRICT m_ppClipVertices[2][SHADOW_VERTEX_TEMP_COUNT];
};
//-----------------------------------------------------------------------------
// ConVars (must be defined before CShadowMgr is instanced!)
//-----------------------------------------------------------------------------
ConVar r_shadows("r_shadows", "1");
ConVar r_shadows_gamecontrol("r_shadows_gamecontrol", "-1", FCVAR_CHEAT ); // Shadow override controlled by game entities (shadow_controller)
static ConVar r_shadowwireframe("r_shadowwireframe", "0", FCVAR_CHEAT );
static ConVar r_shadowids("r_shadowids", "0", FCVAR_CHEAT );
static ConVar r_flashlightdrawsweptbbox( "r_flashlightdrawsweptbbox", "0" );
static ConVar r_flashlightdrawfrustumbbox( "r_flashlightdrawfrustumbbox", "0" );
static ConVar r_flashlightnodraw( "r_flashlightnodraw", "0" );
static ConVar r_flashlightupdatedepth( "r_flashlightupdatedepth", "1" );
static ConVar r_flashlightdrawdepth( "r_flashlightdrawdepth", "0" );
static ConVar r_flashlightrenderworld( "r_flashlightrenderworld", "1" );
static ConVar r_flashlightrendermodels( "r_flashlightrendermodels", "1" );
static ConVar r_flashlightrender( "r_flashlightrender", "1" );
static ConVar r_flashlightculldepth( "r_flashlightculldepth", "1" );
ConVar r_flashlight_version2( "r_flashlight_version2", "0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
//-----------------------------------------------------------------------------
// Implementation of IShadowMgr
//-----------------------------------------------------------------------------
class CShadowMgr : public IShadowMgrInternal, ISpatialLeafEnumerator
{
public:
// constructor
CShadowMgr();
// Methods inherited from IShadowMgr
virtual ShadowHandle_t CreateShadow( IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy, int creationFlags );
virtual ShadowHandle_t CreateShadowEx( IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy, int creationFlags );
virtual void DestroyShadow( ShadowHandle_t handle );
virtual void SetShadowMaterial( ShadowHandle_t handle, IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy );
virtual void EnableShadow( ShadowHandle_t handle, bool bEnable );
virtual void ProjectFlashlight( ShadowHandle_t handle, const VMatrix& worldToShadow, int nLeafCount, const int *pLeafList );
virtual void ProjectShadow( ShadowHandle_t handle, const Vector &origin,
const Vector& projectionDir, const VMatrix& worldToShadow, const Vector2D& size,
int nLeafCount, const int *pLeafList,
float maxHeight, float falloffOffset, float falloffAmount, const Vector &vecCasterOrigin );
virtual const Frustum_t &GetFlashlightFrustum( ShadowHandle_t handle );
virtual const FlashlightState_t &GetFlashlightState( ShadowHandle_t handle );
virtual int ProjectAndClipVertices( ShadowHandle_t handle, int count,
Vector** ppPosition, ShadowVertex_t*** ppOutVertex );
virtual void AddShadowToBrushModel( ShadowHandle_t handle, model_t* pModel,
const Vector& origin, const QAngle& angles );
virtual void RemoveAllShadowsFromBrushModel( model_t* pModel );
virtual void AddShadowToModel( ShadowHandle_t shadow, ModelInstanceHandle_t handle );
virtual void RemoveAllShadowsFromModel( ModelInstanceHandle_t handle );
virtual const ShadowInfo_t& GetInfo( ShadowHandle_t handle );
virtual void SetFlashlightRenderState( ShadowHandle_t handle );
// Methods inherited from IShadowMgrInternal
virtual void LevelInit( int nSurfCount );
virtual void LevelShutdown();
virtual void AddShadowsOnSurfaceToRenderList( ShadowDecalHandle_t decalHandle );
virtual void ClearShadowRenderList();
virtual void ComputeRenderInfo( ShadowDecalRenderInfo_t* pInfo, ShadowHandle_t handle ) const;
virtual void SetModelShadowState( ModelInstanceHandle_t instance );
virtual unsigned short InvalidShadowIndex( );
// Methods of ISpatialLeafEnumerator
virtual bool EnumerateLeaf( int leaf, int context );
// Sets the texture coordinate range for a shadow...
virtual void SetShadowTexCoord( ShadowHandle_t handle, float x, float y, float w, float h );
// Set extra clip planes related to shadows...
// These are used to prevent pokethru and back-casting
virtual void ClearExtraClipPlanes( ShadowHandle_t shadow );
virtual void AddExtraClipPlane( ShadowHandle_t shadow, const Vector& normal, float dist );
// Gets the first model associated with a shadow
unsigned short& FirstModelInShadow( ShadowHandle_t h ) { return m_Shadows[h].m_FirstModel; }
// Set the darkness falloff bias
virtual void SetFalloffBias( ShadowHandle_t shadow, unsigned char ucBias );
// Set the number of world material buckets. This should happen exactly once per level load.
virtual void SetNumWorldMaterialBuckets( int numMaterialSortBins );
// Update the state for a flashlight.
virtual void UpdateFlashlightState( ShadowHandle_t shadowHandle, const FlashlightState_t &lightState );
virtual void DrawFlashlightDecals( int sortGroup, bool bDoMasking );
virtual void DrawFlashlightDecalsOnSingleSurface( SurfaceHandle_t surfID, bool bDoMasking );
virtual void DrawFlashlightOverlays( int sortGroup, bool bDoMasking );
virtual void DrawFlashlightDepthTexture( );
virtual void SetFlashlightDepthTexture( ShadowHandle_t shadowHandle, ITexture *pFlashlightDepthTexture, unsigned char ucShadowStencilBit );
virtual void AddFlashlightRenderable( ShadowHandle_t shadow, IClientRenderable *pRenderable );
virtual void DrawFlashlightDecalsOnDisplacements( int sortGroup, CDispInfo **visibleDisps, int nVisibleDisps, bool bDoMasking );
virtual bool ModelHasShadows( ModelInstanceHandle_t instance );
private:
enum
{
SHADOW_DISABLED = (SHADOW_LAST_FLAG << 1),
};
typedef CUtlFixedLinkedList< ShadowDecalHandle_t >::IndexType_t ShadowSurfaceIndex_t;
struct SurfaceBounds_t
{
fltx4 m_vecMins;
fltx4 m_vecMaxs;
Vector m_vecCenter;
float m_flRadius;
int m_nSurfaceIndex;
};
struct ShadowVertexSmallList_t
{
ShadowVertex_t m_Verts[SHADOW_VERTEX_SMALL_CACHE_COUNT];
};
struct ShadowVertexLargeList_t
{
ShadowVertex_t m_Verts[SHADOW_VERTEX_LARGE_CACHE_COUNT];
};
// A cache entries' worth of vertices....
struct ShadowVertexCache_t
{
unsigned short m_Count;
ShadowHandle_t m_Shadow;
unsigned short m_CachedVerts;
ShadowVertex_t* m_pVerts;
};
typedef unsigned short FlashlightHandle_t;
// Shadow state
struct Shadow_t : public ShadowInfo_t
{
Vector m_ProjectionDir;
IMaterial* m_pMaterial; // material for rendering surfaces
IMaterial* m_pModelMaterial; // material for rendering models
void* m_pBindProxy;
unsigned short m_Flags;
unsigned short m_SortOrder;
float m_flSphereRadius; // Radius of sphere surrounding the shadow
Ray_t m_Ray; // NOTE: Ray needs to be on 16-byte boundaries.
Vector m_vecSphereCenter; // Sphere surrounding the shadow
FlashlightHandle_t m_FlashlightHandle;
ITexture *m_pFlashlightDepthTexture;
// Extra clip planes
unsigned short m_ClipPlaneCount;
Vector m_ClipPlane[MAX_CLIP_PLANE_COUNT];
float m_ClipDist[MAX_CLIP_PLANE_COUNT];
// First shadow decal the shadow has
ShadowSurfaceIndex_t m_FirstDecal;
// First model the shadow is projected onto
unsigned short m_FirstModel;
// Stencil bit used to mask this shadow
unsigned char m_ucShadowStencilBit;
};
// Each surface has one of these, they reference the main shadow
// projector and cached off shadow decals.
struct ShadowDecal_t
{
SurfaceHandle_t m_SurfID;
ShadowSurfaceIndex_t m_ShadowListIndex;
ShadowHandle_t m_Shadow;
DispShadowHandle_t m_DispShadow;
unsigned short m_ShadowVerts;
// This is a handle of the next shadow decal to be rendered
ShadowDecalHandle_t m_NextRender;
};
// This structure is used when building new shadow information
struct ShadowBuildInfo_t
{
ShadowHandle_t m_Shadow;
Vector m_RayStart;
Vector m_ProjectionDirection;
Vector m_vecSphereCenter; // Sphere surrounding the shadow
float m_flSphereRadius; // Radius of sphere surrounding the shadow
const byte *m_pVis; // Vis from the ray start
};
// This structure contains rendering information
struct ShadowRenderInfo_t
{
int m_VertexCount;
int m_IndexCount;
int m_nMaxVertices;
int m_nMaxIndices;
int m_Count;
int* m_pCache;
int m_DispCount;
const VMatrix* m_pModelToWorld;
VMatrix m_WorldToModel;
DispShadowHandle_t* m_pDispCache;
};
// Structures used to assign sort order handles
struct SortOrderInfo_t
{
int m_MaterialEnum;
int m_RefCount;
};
typedef void (*ShadowDebugFunc_t)( ShadowHandle_t shadowHandle, const Vector &vecCentroid );
// m_FlashlightWorldMaterialBuckets is where surfaces are stored per flashlight each frame.
typedef CUtlVector<FlashlightHandle_t> WorldMaterialBuckets_t;
struct FlashlightInfo_t
{
FlashlightState_t m_FlashlightState;
unsigned short m_Shadow;
Frustum_t m_Frustum;
CMaterialsBuckets<SurfaceHandle_t> m_MaterialBuckets;
CMaterialsBuckets<SurfaceHandle_t> m_OccluderBuckets;
CUtlVector< IClientRenderable *> m_Renderables;
};
private:
// Applies a flashlight to all surfaces in the leaf
void ApplyFlashlightToLeaf( const Shadow_t &shadow, mleaf_t* pLeaf, ShadowBuildInfo_t* pBuild );
// Applies a shadow to all surfaces in the leaf
void ApplyShadowToLeaf( const Shadow_t &shadow, mleaf_t* RESTRICT pLeaf, ShadowBuildInfo_t* RESTRICT pBuild );
// These functions deal with creation of render sort ids
void SetMaterial( Shadow_t& shadow, IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy );
void CleanupMaterial( Shadow_t& shadow );
// These functions add/remove shadow decals to surfaces
ShadowDecalHandle_t AddShadowDecalToSurface( SurfaceHandle_t surfID, ShadowHandle_t handle );
void RemoveShadowDecalFromSurface( SurfaceHandle_t surfID, ShadowDecalHandle_t decalHandle );
// Adds the surface to the list for this shadow
bool AddDecalToShadowList( ShadowHandle_t handle, ShadowDecalHandle_t decalHandle );
// Removes the shadow to the list of surfaces
void RemoveDecalFromShadowList( ShadowHandle_t handle, ShadowDecalHandle_t decalHandle );
// Actually projects + clips vertices
int ProjectAndClipVertices( const Shadow_t& shadow, const VMatrix& worldToShadow,
const VMatrix *pWorldToModel, int count, Vector** ppPosition, ShadowVertex_t*** ppOutVertex );
// These functions hook/unhook shadows up to surfaces + vice versa
void AddSurfaceToShadow( ShadowHandle_t handle, SurfaceHandle_t surfID );
void RemoveSurfaceFromShadow( ShadowHandle_t handle, SurfaceHandle_t surfID );
void RemoveAllSurfacesFromShadow( ShadowHandle_t handle );
void RemoveAllShadowsFromSurface( SurfaceHandle_t surfID );
// Deals with model shadow management
void RemoveAllModelsFromShadow( ShadowHandle_t handle );
// Applies the shadow to a surface
void ApplyShadowToSurface( ShadowBuildInfo_t& build, SurfaceHandle_t surfID );
// Applies the shadow to a displacement
void ApplyShadowToDisplacement( ShadowBuildInfo_t& build, IDispInfo *pDispInfo, bool bIsFlashlight );
// Renders shadows that all share a material enumeration
void RenderShadowList( IMatRenderContext *pRenderContext, ShadowDecalHandle_t decalHandle, const VMatrix* pModelToWorld );
// Should we cache vertices?
bool ShouldCacheVertices( const ShadowDecal_t& decal );
// Generates a list displacement shadow vertices to render
bool GenerateDispShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecal_t& decal, ShadowRenderInfo_t& info );
// Generates a list shadow vertices to render
bool GenerateNormalShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecal_t& decal, ShadowRenderInfo_t& info );
// Adds normal shadows to the mesh builder
int AddNormalShadowsToMeshBuilder( CMeshBuilder& meshBuilder, ShadowRenderInfo_t& info );
// Adds displacement shadows to the mesh builder
int AddDisplacementShadowsToMeshBuilder( CMeshBuilder& meshBuilder,
ShadowRenderInfo_t& info, int baseIndex );
// Does the actual work of computing shadow vertices
bool ComputeShadowVertices( ShadowDecal_t& decal, const VMatrix* pModelToWorld, const VMatrix* pWorldToModel, ShadowVertexCache_t* pVertexCache );
// Project vertices into shadow space
bool ProjectVerticesIntoShadowSpace( const VMatrix& modelToShadow,
float maxDist, int count, Vector** RESTRICT ppPosition, ShadowClipState_t& clip );
// Copies vertex info from the clipped vertices
void CopyClippedVertices( int count, ShadowVertex_t** ppSrcVert, ShadowVertex_t* pDstVert, const Vector &vToAdd );
// Allocate, free vertices
ShadowVertex_t* AllocateVertices( ShadowVertexCache_t& cache, int count );
void FreeVertices( ShadowVertexCache_t& cache );
// Gets at cache entry...
ShadowVertex_t* GetCachedVerts( const ShadowVertexCache_t& cache );
// Clears out vertices in the temporary cache
void ClearTempCache( );
// Renders debugging information
void RenderDebuggingInfo( const ShadowRenderInfo_t &info, ShadowDebugFunc_t func );
// Methods for dealing with world material buckets for flashlights.
void ClearAllFlashlightMaterialBuckets( void );
void AddSurfaceToFlashlightMaterialBuckets( ShadowHandle_t handle, SurfaceHandle_t surfID );
void AllocFlashlightMaterialBuckets( FlashlightHandle_t flashlightID );
// Render all projected textures (including shadows and flashlights)
void RenderProjectedTextures( const VMatrix* pModelToWorld );
void RenderFlashlights( bool bDoMasking, const VMatrix* pModelToWorld );
void SetFlashlightStencilMasks( bool bDoMasking );
void SetStencilAndScissor( IMatRenderContext *pRenderContext, FlashlightInfo_t &flashlightInfo, bool bUseStencil );
void EnableStencilAndScissorMasking( IMatRenderContext *pRenderContext, const FlashlightInfo_t &flashlightInfo, bool bDoMasking );
void DisableStencilAndScissorMasking( IMatRenderContext *pRenderContext );
void RenderShadows( const VMatrix* pModelToWorld );
// Generates a list shadow vertices to render
void GenerateShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecalHandle_t decalHandle, ShadowRenderInfo_t& info );
// Methods related to the surface bounds cache
void ComputeSurfaceBounds( SurfaceBounds_t* pBounds, SurfaceHandle_t nSurfID );
const SurfaceBounds_t* GetSurfaceBounds( SurfaceHandle_t nSurfID );
bool IsShadowNearSurface( ShadowHandle_t h, SurfaceHandle_t nSurfID, const VMatrix* pModelToWorld, const VMatrix* pWorldToModel );
private:
// List of all shadows (one per cast shadow)
// Align it so the Ray in the Shadow_t is aligned
CUtlLinkedList< Shadow_t, ShadowHandle_t, false, int, CUtlMemoryAligned< UtlLinkedListElem_t< Shadow_t, ShadowHandle_t >, 16 > > m_Shadows;
// List of all shadow decals (one per surface hit by a shadow)
CUtlLinkedList< ShadowDecal_t, ShadowDecalHandle_t, true, int > m_ShadowDecals;
// List of all shadow decals associated with a particular shadow
CUtlFixedLinkedList< ShadowDecalHandle_t > m_ShadowSurfaces;
// List of queued decals waiting to be rendered....
CUtlVector<ShadowDecalHandle_t> m_RenderQueue;
// Used to assign sort order handles
CUtlLinkedList<SortOrderInfo_t, unsigned short> m_SortOrderIds;
// A cache of shadow vertex data...
CUtlLinkedList<ShadowVertexCache_t, unsigned short> m_VertexCache;
// This is temporary, not saved off....
CUtlVector<ShadowVertexCache_t> m_TempVertexCache;
// Vertex data
CUtlLinkedList<ShadowVertexSmallList_t, unsigned short> m_SmallVertexList;
CUtlLinkedList<ShadowVertexLargeList_t, unsigned short> m_LargeVertexList;
// Model-shadow association
CBidirectionalSet< ModelInstanceHandle_t, ShadowHandle_t, unsigned short > m_ShadowsOnModels;
// Cache of information for surface bounds
typedef CUtlLinkedList< SurfaceBounds_t, unsigned short, false, int, CUtlMemoryFixed< UtlLinkedListElem_t< SurfaceBounds_t, unsigned short >, SURFACE_BOUNDS_CACHE_COUNT, 16 > > SurfaceBoundsCache_t;
typedef SurfaceBoundsCache_t::IndexType_t SurfaceBoundsCacheIndex_t;
SurfaceBoundsCache_t m_SurfaceBoundsCache;
SurfaceBoundsCacheIndex_t *m_pSurfaceBounds;
// The number of decals we're gonna need to render
int m_DecalsToRender;
CUtlLinkedList<FlashlightInfo_t> m_FlashlightStates;
int m_NumWorldMaterialBuckets;
bool m_bInitialized;
//=============================================================================
// HPE_BEGIN:
// [smessick] These used to be dynamically allocated on the stack.
//=============================================================================
CUtlMemory<int> m_ShadowDecalCache;
CUtlMemory<DispShadowHandle_t> m_DispShadowDecalCache;
//=============================================================================
// HPE_END
//=============================================================================
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CShadowMgr s_ShadowMgr;
IShadowMgrInternal* g_pShadowMgr = &s_ShadowMgr;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CShadowMgr, IShadowMgr,
ENGINE_SHADOWMGR_INTERFACE_VERSION, s_ShadowMgr);
//-----------------------------------------------------------------------------
// Shadows on model instances
//-----------------------------------------------------------------------------
unsigned short& FirstShadowOnModel( ModelInstanceHandle_t h )
{
// See l_studio.cpp
return FirstShadowOnModelInstance( h );
}
unsigned short& FirstModelInShadow( ShadowHandle_t h )
{
return s_ShadowMgr.FirstModelInShadow(h);
}
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CShadowMgr::CShadowMgr()
{
m_ShadowSurfaces.SetGrowSize( 4096 );
m_ShadowDecals.SetGrowSize( 4096 );
m_ShadowsOnModels.Init( ::FirstShadowOnModel, ::FirstModelInShadow );
m_NumWorldMaterialBuckets = 0;
m_pSurfaceBounds = NULL;
m_bInitialized = false;
ClearShadowRenderList();
//=============================================================================
// HPE_BEGIN:
// [smessick] Initialize the shadow decal caches. These used to be dynamically
// allocated on the stack, but we were getting stack overflows.
//=============================================================================
m_ShadowDecalCache.SetGrowSize( 4096 );
m_DispShadowDecalCache.SetGrowSize( 4096 );
m_ShadowDecalCache.Grow( SHADOW_DECAL_CACHE_COUNT );
m_DispShadowDecalCache.Grow( SHADOW_DECAL_CACHE_COUNT );
//=============================================================================
// HPE_END
//=============================================================================
}
//-----------------------------------------------------------------------------
// Level init, shutdown
//-----------------------------------------------------------------------------
void CShadowMgr::LevelInit( int nSurfCount )
{
if ( m_bInitialized )
return;
m_bInitialized = true;
m_pSurfaceBounds = new SurfaceBoundsCacheIndex_t[nSurfCount];
// NOTE: Need to memset to 0 if we switch to integer SurfaceBoundsCacheIndex_t here
COMPILE_TIME_ASSERT( sizeof(SurfaceBoundsCacheIndex_t) == 2 );
memset( m_pSurfaceBounds, 0xFF, nSurfCount * sizeof(SurfaceBoundsCacheIndex_t) );
}
void CShadowMgr::LevelShutdown()
{
if ( !m_bInitialized )
return;
if ( m_pSurfaceBounds )
{
delete[] m_pSurfaceBounds;
m_pSurfaceBounds = NULL;
}
m_SurfaceBoundsCache.RemoveAll();
m_bInitialized = false;
}
//-----------------------------------------------------------------------------
// Create, destroy material sort order ids...
//-----------------------------------------------------------------------------
void CShadowMgr::SetMaterial( Shadow_t& shadow, IMaterial* pMaterial, IMaterial* pModelMaterial, void *pBindProxy )
{
shadow.m_pMaterial = pMaterial;
shadow.m_pModelMaterial = pModelMaterial;
shadow.m_pBindProxy = pBindProxy;
// We're holding onto this material
if ( pMaterial )
{
pMaterial->IncrementReferenceCount();
}
if ( pModelMaterial )
{
pModelMaterial->IncrementReferenceCount();
}
// Search the sort order handles for an enumeration id match
int materialEnum = (int)pMaterial;
for (unsigned short i = m_SortOrderIds.Head(); i != m_SortOrderIds.InvalidIndex();
i = m_SortOrderIds.Next(i) )
{
// Found a match, lets increment the refcount of this sort order id
if (m_SortOrderIds[i].m_MaterialEnum == materialEnum)
{
++m_SortOrderIds[i].m_RefCount;
shadow.m_SortOrder = i;
return;
}
}
// Didn't find it, lets assign a new sort order ID, with a refcount of 1
shadow.m_SortOrder = m_SortOrderIds.AddToTail();
m_SortOrderIds[shadow.m_SortOrder].m_MaterialEnum = materialEnum;
m_SortOrderIds[shadow.m_SortOrder].m_RefCount = 1;
// Make sure the render queue has as many entries as the max sort order id.
int count = m_RenderQueue.Count();
while( count < m_SortOrderIds.MaxElementIndex() )
{
MEM_ALLOC_CREDIT();
m_RenderQueue.AddToTail( SHADOW_DECAL_HANDLE_INVALID );
++count;
}
}
void CShadowMgr::CleanupMaterial( Shadow_t& shadow )
{
// Decrease the sort order reference count
if (--m_SortOrderIds[shadow.m_SortOrder].m_RefCount <= 0)
{
// No one referencing the sort order number?
// Then lets clean up the sort order id
m_SortOrderIds.Remove(shadow.m_SortOrder);
}
// We're done with this material
if ( shadow.m_pMaterial )
{
shadow.m_pMaterial->DecrementReferenceCount();
}
if ( shadow.m_pModelMaterial )
{
shadow.m_pModelMaterial->DecrementReferenceCount();
}
}
//-----------------------------------------------------------------------------
// For the model shadow list
//-----------------------------------------------------------------------------
unsigned short CShadowMgr::InvalidShadowIndex( )
{
return m_ShadowsOnModels.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Create, destroy shadows
//-----------------------------------------------------------------------------
ShadowHandle_t CShadowMgr::CreateShadow( IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy, int creationFlags )
{
return CreateShadowEx( pMaterial, pModelMaterial, pBindProxy, creationFlags );
}
ShadowHandle_t CShadowMgr::CreateShadowEx( IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy, int creationFlags )
{
#ifndef SWDS
ShadowHandle_t h = m_Shadows.AddToTail();
//=============================================================================
// HPE_BEGIN:
// [smessick] Check for overflow.
//=============================================================================
if ( h == m_Shadows.InvalidIndex() )
{
ExecuteNTimes( 10, Warning( "CShadowMgr::CreateShadowEx - overflowed m_Shadows linked list!\n" ) );
return h;
}
//=============================================================================
// HPE_END
//=============================================================================
Shadow_t& shadow = m_Shadows[h];
SetMaterial( shadow, pMaterial, pModelMaterial, pBindProxy );
shadow.m_Flags = creationFlags;
shadow.m_FirstDecal = m_ShadowSurfaces.InvalidIndex();
shadow.m_FirstModel = m_ShadowsOnModels.InvalidIndex();
shadow.m_ProjectionDir.Init( 0, 0, 1 );
shadow.m_TexOrigin.Init( 0, 0 );
shadow.m_TexSize.Init( 1, 1 );
shadow.m_ClipPlaneCount = 0;
shadow.m_FalloffBias = 0;
shadow.m_pFlashlightDepthTexture = NULL;
shadow.m_FlashlightHandle = m_FlashlightStates.InvalidIndex();
if ( ( creationFlags & SHADOW_FLASHLIGHT ) != 0 )
{
shadow.m_FlashlightHandle = m_FlashlightStates.AddToTail();
m_FlashlightStates[shadow.m_FlashlightHandle].m_Shadow = h;
if ( !IsX360() && !r_flashlight_version2.GetInt() )
{
AllocFlashlightMaterialBuckets( shadow.m_FlashlightHandle );
}
}
MatrixSetIdentity( shadow.m_WorldToShadow );
return h;
#endif
}
void CShadowMgr::DestroyShadow( ShadowHandle_t handle )
{
CleanupMaterial( m_Shadows[handle] );
RemoveAllSurfacesFromShadow( handle );
RemoveAllModelsFromShadow( handle );
if( m_Shadows[handle].m_FlashlightHandle != m_FlashlightStates.InvalidIndex() )
{
m_FlashlightStates.Remove( m_Shadows[handle].m_FlashlightHandle );
}
m_Shadows.Remove(handle);
}
//-----------------------------------------------------------------------------
// Resets the shadow material (useful for shadow LOD.. doing blobby at distance)
//-----------------------------------------------------------------------------
void CShadowMgr::SetShadowMaterial( ShadowHandle_t handle, IMaterial* pMaterial, IMaterial* pModelMaterial, void* pBindProxy )
{
Shadow_t& shadow = m_Shadows[handle];
if ( (shadow.m_pMaterial != pMaterial) || (shadow.m_pModelMaterial != pModelMaterial) || (shadow.m_pBindProxy != pBindProxy) )
{
CleanupMaterial( shadow );
SetMaterial( shadow, pMaterial, pModelMaterial, pBindProxy );
}
}
//-----------------------------------------------------------------------------
// Sets the texture coordinate range for a shadow...
//-----------------------------------------------------------------------------
void CShadowMgr::SetShadowTexCoord( ShadowHandle_t handle, float x, float y, float w, float h )
{
Shadow_t& shadow = m_Shadows[handle];
shadow.m_TexOrigin.Init( x, y );
shadow.m_TexSize.Init( w, h );
}
//-----------------------------------------------------------------------------
// Set extra clip planes related to shadows...
//-----------------------------------------------------------------------------
void CShadowMgr::ClearExtraClipPlanes( ShadowHandle_t h )
{
m_Shadows[h].m_ClipPlaneCount = 0;
}
void CShadowMgr::AddExtraClipPlane( ShadowHandle_t h, const Vector& normal, float dist )
{
Shadow_t& shadow = m_Shadows[h];
Assert( shadow.m_ClipPlaneCount < MAX_CLIP_PLANE_COUNT );
VectorCopy( normal, shadow.m_ClipPlane[shadow.m_ClipPlaneCount] );
shadow.m_ClipDist[shadow.m_ClipPlaneCount] = dist;
++shadow.m_ClipPlaneCount;
}
//-----------------------------------------------------------------------------
// Gets at information about a particular shadow
//-----------------------------------------------------------------------------
const ShadowInfo_t& CShadowMgr::GetInfo( ShadowHandle_t handle )
{
return m_Shadows[handle];
}
//-----------------------------------------------------------------------------
// Gets at cache entry...
//-----------------------------------------------------------------------------
ShadowVertex_t* CShadowMgr::GetCachedVerts( const ShadowVertexCache_t& cache )
{
if (cache.m_Count == 0)
return 0 ;
if (cache.m_pVerts)
return cache.m_pVerts;
if (cache.m_Count <= SHADOW_VERTEX_SMALL_CACHE_COUNT)
return m_SmallVertexList[cache.m_CachedVerts].m_Verts;
return m_LargeVertexList[cache.m_CachedVerts].m_Verts;
}
//-----------------------------------------------------------------------------
// Allocates, cleans up vertex cache vertices
//-----------------------------------------------------------------------------
inline ShadowVertex_t* CShadowMgr::AllocateVertices( ShadowVertexCache_t& cache, int count )
{
cache.m_pVerts = 0;
if (count <= SHADOW_VERTEX_SMALL_CACHE_COUNT)
{
cache.m_Count = count;
cache.m_CachedVerts = m_SmallVertexList.AddToTail( );
return m_SmallVertexList[cache.m_CachedVerts].m_Verts;
}
else if (count <= SHADOW_VERTEX_LARGE_CACHE_COUNT)
{
cache.m_Count = count;
cache.m_CachedVerts = m_LargeVertexList.AddToTail( );
return m_LargeVertexList[cache.m_CachedVerts].m_Verts;
}
cache.m_Count = count;
if (count > 0)
{
cache.m_pVerts = new ShadowVertex_t[count];
}
cache.m_CachedVerts = m_LargeVertexList.InvalidIndex();
return cache.m_pVerts;
}
inline void CShadowMgr::FreeVertices( ShadowVertexCache_t& cache )
{
if (cache.m_Count == 0)
return;
if (cache.m_pVerts)
{
delete[] cache.m_pVerts;
}
else if (cache.m_Count <= SHADOW_VERTEX_SMALL_CACHE_COUNT)
{
m_SmallVertexList.Remove( cache.m_CachedVerts );
}
else
{
m_LargeVertexList.Remove( cache.m_CachedVerts );
}
}
//-----------------------------------------------------------------------------
// Clears out vertices in the temporary cache
//-----------------------------------------------------------------------------
void CShadowMgr::ClearTempCache( )
{
// Clear out the vertices
for (int i = m_TempVertexCache.Count(); --i >= 0; )
{
FreeVertices( m_TempVertexCache[i] );
}
m_TempVertexCache.RemoveAll();
}
//-----------------------------------------------------------------------------
// Adds the surface to the list for this shadow
//-----------------------------------------------------------------------------
bool CShadowMgr::AddDecalToShadowList( ShadowHandle_t handle, ShadowDecalHandle_t decalHandle )
{
// Add the shadow to the list of surfaces affected by this shadow
ShadowSurfaceIndex_t idx = m_ShadowSurfaces.Alloc( true );
if ( idx == m_ShadowSurfaces.InvalidIndex() )
{
ExecuteNTimes( 10, Warning( "CShadowMgr::AddDecalToShadowList - overflowed m_ShadowSurfaces linked list!\n" ) );
return false;
}
m_ShadowSurfaces[idx] = decalHandle;
if ( m_Shadows[handle].m_FirstDecal != m_ShadowSurfaces.InvalidIndex() )
{
m_ShadowSurfaces.LinkBefore( m_Shadows[handle].m_FirstDecal, idx );
}
m_Shadows[handle].m_FirstDecal = idx;
m_ShadowDecals[decalHandle].m_ShadowListIndex = idx;
return true;
}
//-----------------------------------------------------------------------------
// Removes the shadow to the list of surfaces
//-----------------------------------------------------------------------------
void CShadowMgr::RemoveDecalFromShadowList( ShadowHandle_t handle, ShadowDecalHandle_t decalHandle )
{
ShadowSurfaceIndex_t idx = m_ShadowDecals[decalHandle].m_ShadowListIndex;
// Make sure the list of shadow decals for a single shadow is ok
if ( m_Shadows[handle].m_FirstDecal == idx )
{
m_Shadows[handle].m_FirstDecal = m_ShadowSurfaces.Next(idx);
}
// Remove it from the shadow surfaces list
m_ShadowSurfaces.Free(idx);
// Blat out the decal index
m_ShadowDecals[decalHandle].m_ShadowListIndex = m_ShadowSurfaces.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Computes spherical bounds for a surface
//-----------------------------------------------------------------------------
void CShadowMgr::ComputeSurfaceBounds( SurfaceBounds_t* pBounds, SurfaceHandle_t nSurfID )
{
pBounds->m_vecCenter.Init();
pBounds->m_vecMins = ReplicateX4( FLT_MAX );
pBounds->m_vecMaxs = ReplicateX4( -FLT_MAX );
int nCount = MSurf_VertCount( nSurfID );
for ( int i = 0; i < nCount; ++i )
{
int nVertIndex = host_state.worldbrush->vertindices[ MSurf_FirstVertIndex( nSurfID ) + i ];
const Vector &position = host_state.worldbrush->vertexes[ nVertIndex ].position;
pBounds->m_vecCenter += position;
fltx4 pos4 = LoadUnaligned3SIMD( position.Base() );
pBounds->m_vecMins = MinSIMD( pos4, pBounds->m_vecMins );
pBounds->m_vecMaxs = MaxSIMD( pos4, pBounds->m_vecMaxs );
}
fltx4 eps = ReplicateX4( 1e-3 );
pBounds->m_vecMins = SetWToZeroSIMD( SubSIMD( pBounds->m_vecMins, eps ) );
pBounds->m_vecMaxs = SetWToZeroSIMD( AddSIMD( pBounds->m_vecMaxs, eps ) );
pBounds->m_vecCenter /= nCount;
pBounds->m_flRadius = 0.0f;
for ( int i = 0; i < nCount; ++i )
{
int nVertIndex = host_state.worldbrush->vertindices[ MSurf_FirstVertIndex( nSurfID ) + i ];
const Vector &position = host_state.worldbrush->vertexes[ nVertIndex ].position;
float flDistSq = position.DistToSqr( pBounds->m_vecCenter );
if ( flDistSq > pBounds->m_flRadius )
{
pBounds->m_flRadius = flDistSq;
}
}
pBounds->m_flRadius = sqrt( pBounds->m_flRadius );
}
//-----------------------------------------------------------------------------
// Get spherical bounds for a surface
//-----------------------------------------------------------------------------
const CShadowMgr::SurfaceBounds_t* CShadowMgr::GetSurfaceBounds( SurfaceHandle_t surfID )
{
int nSurfaceIndex = MSurf_Index( surfID );
// NOTE: We're not bumping the surface index to the front of the LRU
// here, but I think if we did the cost doing that would exceed the cost
// of anything else in this path.
// If this turns out to not be true, then we should make this a true LRU
if ( m_pSurfaceBounds[nSurfaceIndex] != m_SurfaceBoundsCache.InvalidIndex() )
return &m_SurfaceBoundsCache[ m_pSurfaceBounds[nSurfaceIndex] ];
SurfaceBoundsCacheIndex_t nIndex;
if ( m_SurfaceBoundsCache.Count() >= SURFACE_BOUNDS_CACHE_COUNT )
{
// Retire existing cache entry if we're out of space,
// move it to the head of the LRU cache
nIndex = m_SurfaceBoundsCache.Tail( );
m_SurfaceBoundsCache.Unlink( nIndex );
m_SurfaceBoundsCache.LinkToHead( nIndex );
m_pSurfaceBounds[ m_SurfaceBoundsCache[nIndex].m_nSurfaceIndex ] = m_SurfaceBoundsCache.InvalidIndex();
}
else
{
// Allocate new cache entry if we have more room
nIndex = m_SurfaceBoundsCache.AddToHead( );
}
m_pSurfaceBounds[ nSurfaceIndex ] = nIndex;
// Computes the surface bounds
SurfaceBounds_t &bounds = m_SurfaceBoundsCache[nIndex];
bounds.m_nSurfaceIndex = nSurfaceIndex;
ComputeSurfaceBounds( &bounds, surfID );
return &bounds;
}
//-----------------------------------------------------------------------------
// Is the shadow near the surface?
//-----------------------------------------------------------------------------
bool CShadowMgr::IsShadowNearSurface( ShadowHandle_t h, SurfaceHandle_t nSurfID,
const VMatrix* pModelToWorld, const VMatrix* pWorldToModel )
{
const Shadow_t &shadow = m_Shadows[h];
const SurfaceBounds_t* pBounds = GetSurfaceBounds( nSurfID );
Vector vecSurfCenter;
if ( !pModelToWorld )
{
vecSurfCenter = pBounds->m_vecCenter;
}
else
{
Vector3DMultiplyPosition( *pModelToWorld, pBounds->m_vecCenter, vecSurfCenter );
}
// Sphere check
Vector vecDelta;
VectorSubtract( shadow.m_vecSphereCenter, vecSurfCenter, vecDelta );
float flDistSqr = vecDelta.LengthSqr();
float flMinDistSqr = pBounds->m_flRadius + shadow.m_flSphereRadius;
flMinDistSqr *= flMinDistSqr;
if ( flDistSqr >= flMinDistSqr )
return false;
if ( !pModelToWorld )
return IsBoxIntersectingRay( pBounds->m_vecMins, pBounds->m_vecMaxs, shadow.m_Ray );
Ray_t transformedRay;
Vector3DMultiplyPosition( *pWorldToModel, shadow.m_Ray.m_Start, transformedRay.m_Start );
Vector3DMultiply( *pWorldToModel, shadow.m_Ray.m_Delta, transformedRay.m_Delta );
transformedRay.m_StartOffset = shadow.m_Ray.m_StartOffset;
transformedRay.m_Extents = shadow.m_Ray.m_Extents;
transformedRay.m_IsRay = shadow.m_Ray.m_IsRay;
transformedRay.m_IsSwept = shadow.m_Ray.m_IsSwept;
return IsBoxIntersectingRay( pBounds->m_vecMins, pBounds->m_vecMaxs, transformedRay );
}
//-----------------------------------------------------------------------------
// Adds the shadow decal reference to the surface
//-----------------------------------------------------------------------------
inline ShadowDecalHandle_t CShadowMgr::AddShadowDecalToSurface( SurfaceHandle_t surfID, ShadowHandle_t handle )
{
ShadowDecalHandle_t decalHandle = m_ShadowDecals.Alloc( true );
if ( decalHandle == m_ShadowDecals.InvalidIndex() )
{
ExecuteNTimes( 10, Warning( "CShadowMgr::AddShadowDecalToSurface - overflowed m_ShadowDecals linked list!\n" ) );
return decalHandle;
}
ShadowDecal_t& decal = m_ShadowDecals[decalHandle];
decal.m_SurfID = surfID;
m_ShadowDecals.LinkBefore( MSurf_ShadowDecals( surfID ), decalHandle );
MSurf_ShadowDecals( surfID ) = decalHandle;
// Hook the shadow into the displacement system....
if ( !SurfaceHasDispInfo( surfID ) )
{
decal.m_DispShadow = DISP_SHADOW_HANDLE_INVALID;
}
else
{
decal.m_DispShadow = MSurf_DispInfo( surfID )->AddShadowDecal( handle );
}
decal.m_Shadow = handle;
decal.m_ShadowVerts = m_VertexCache.InvalidIndex();
decal.m_NextRender = SHADOW_DECAL_HANDLE_INVALID;
decal.m_ShadowListIndex = m_ShadowSurfaces.InvalidIndex();
//=============================================================================
// HPE_BEGIN:
// [smessick] Check the return value of AddDecalToShadowList and make sure
// to delete the newly created shadow decal if there is a failure.
//=============================================================================
if ( !AddDecalToShadowList( handle, decalHandle ) )
{
m_ShadowDecals.Free( decalHandle );
decalHandle = m_ShadowDecals.InvalidIndex();
}
//=============================================================================
// HPE_END
//=============================================================================
return decalHandle;
}
inline void CShadowMgr::RemoveShadowDecalFromSurface( SurfaceHandle_t surfID, ShadowDecalHandle_t decalHandle )
{
// Clean up its shadow verts if it has any
ShadowDecal_t& decal = m_ShadowDecals[decalHandle];
if (decal.m_ShadowVerts != m_VertexCache.InvalidIndex())
{
FreeVertices( m_VertexCache[decal.m_ShadowVerts] );
m_VertexCache.Remove(decal.m_ShadowVerts);
decal.m_ShadowVerts = m_VertexCache.InvalidIndex();
}
// Clean up displacement...
if ( decal.m_DispShadow != DISP_SHADOW_HANDLE_INVALID )
{
MSurf_DispInfo( decal.m_SurfID )->RemoveShadowDecal( decal.m_DispShadow );
}
// Make sure the list of shadow decals on a surface is set up correctly
if ( MSurf_ShadowDecals( surfID ) == decalHandle )
{
MSurf_ShadowDecals( surfID ) = m_ShadowDecals.Next(decalHandle);
}
RemoveDecalFromShadowList( decal.m_Shadow, decalHandle );
// Kill the shadow decal
m_ShadowDecals.Free( decalHandle );
}
void CShadowMgr::AddSurfaceToFlashlightMaterialBuckets( ShadowHandle_t handle, SurfaceHandle_t surfID )
{
// Make sure that this is a flashlight.
Assert( m_Shadows[handle].m_Flags & SHADOW_FLASHLIGHT );
// Get the flashlight id for this particular shadow handle and make sure that it's valid.
FlashlightHandle_t flashlightID = m_Shadows[handle].m_FlashlightHandle;
Assert( flashlightID != m_FlashlightStates.InvalidIndex() );
m_FlashlightStates[flashlightID].m_MaterialBuckets.AddElement( MSurf_MaterialSortID( surfID ), surfID );
}
//-----------------------------------------------------------------------------
// Adds the shadow decal reference to the surface
// This causes a shadow decal to be made
//-----------------------------------------------------------------------------
void CShadowMgr::AddSurfaceToShadow( ShadowHandle_t handle, SurfaceHandle_t surfID )
{
// FIXME: We could make this work, but there's a perf cost...
// Basically, we'd need to have a separate rendering batch for
// each translucent material the shadow is projected onto. The
// material alpha would have to be taken into account, so that
// no multiplication occurs where the alpha == 0
// FLASHLIGHTFIXME: get rid of some of these checks for the ones that will work just fine with the flashlight.
bool bIsFlashlight = ( ( m_Shadows[handle].m_Flags & SHADOW_FLASHLIGHT ) != 0 );
if ( !bIsFlashlight && MSurf_Flags(surfID) & (SURFDRAW_TRANS | SURFDRAW_ALPHATEST | SURFDRAW_NOSHADOWS) )
return;
#ifdef _XBOX
// Don't let the flashlight get on water on XBox
if ( bIsFlashlight && ( MSurf_Flags(surfID) & SURFDRAW_WATERSURFACE ) )
return;
#endif
#if 0
// Make sure the surface has the shadow on it exactly once...
ShadowDecalHandle_t dh = MSurf_ShadowDecals( surfID );
while (dh != m_ShadowDecals.InvalidIndex() )
{
Assert ( m_ShadowDecals[dh].m_Shadow != handle );
dh = m_ShadowDecals.Next(dh);
}
#endif
// Create a shadow decal for this surface and add it to the surface
AddShadowDecalToSurface( surfID, handle );
}
void CShadowMgr::RemoveSurfaceFromShadow( ShadowHandle_t handle, SurfaceHandle_t surfID )
{
// Find the decal associated with the handle that lies on the surface
// FIXME: Linear search; bleah.
// Luckily the search is probably over only a couple items at most
// Linear searching over the shadow surfaces so we can remove the entry
// in the shadow surface list if we find a match
ASSERT_SURF_VALID( surfID );
ShadowSurfaceIndex_t i = m_Shadows[handle].m_FirstDecal;
while ( i != m_ShadowSurfaces.InvalidIndex() )
{
ShadowDecalHandle_t decalHandle = m_ShadowSurfaces[i];
if ( m_ShadowDecals[decalHandle].m_SurfID == surfID )
{
// Found a match! There should be at most one shadow decal
// associated with a particular shadow per surface
RemoveShadowDecalFromSurface( surfID, decalHandle );
// FIXME: Could check the shadow doesn't appear again in the list
return;
}
i = m_ShadowSurfaces.Next(i);
}
#ifdef _DEBUG
// Here, the shadow didn't have the surface in its list
// let's make sure the surface doesn't think it's got the shadow in its list
ShadowDecalHandle_t dh = MSurf_ShadowDecals( surfID );
while (dh != m_ShadowDecals.InvalidIndex() )
{
Assert ( m_ShadowDecals[dh].m_Shadow != handle );
dh = m_ShadowDecals.Next(dh);
}
#endif
}
void CShadowMgr::RemoveAllSurfacesFromShadow( ShadowHandle_t handle )
{
// Iterate over all the decals associated with a particular shadow
// Remove the decals from the surfaces they are associated with
ShadowSurfaceIndex_t i = m_Shadows[handle].m_FirstDecal;
ShadowSurfaceIndex_t next;
while ( i != m_ShadowSurfaces.InvalidIndex() )
{
ShadowDecalHandle_t decalHandle = m_ShadowSurfaces[i];
next = m_ShadowSurfaces.Next(i);
RemoveShadowDecalFromSurface( m_ShadowDecals[decalHandle].m_SurfID, decalHandle );
i = next;
}
m_Shadows[handle].m_FirstDecal = m_ShadowSurfaces.InvalidIndex();
}
void CShadowMgr::RemoveAllShadowsFromSurface( SurfaceHandle_t surfID )
{
// Iterate over all the decals associated with a particular shadow
// Remove the decals from the surfaces they are associated with
ShadowDecalHandle_t dh = MSurf_ShadowDecals( surfID );
while (dh != m_ShadowDecals.InvalidIndex() )
{
// Remove this shadow from the surface
ShadowDecalHandle_t next = m_ShadowDecals.Next(dh);
// Remove the surface from the shadow
RemoveShadowDecalFromSurface( m_ShadowDecals[dh].m_SurfID, dh );
dh = next;
}
MSurf_ShadowDecals( surfID ) = m_ShadowDecals.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Shadow/model association
//-----------------------------------------------------------------------------
void CShadowMgr::AddShadowToModel( ShadowHandle_t handle, ModelInstanceHandle_t model )
{
// FIXME: Add culling here based on the model bbox
// and the shadow bbox
// FIXME:
/*
// Trivial bbox reject.
Vector bbMin, bbMax;
pDisp->GetBoundingBox( bbMin, bbMax );
if( decalinfo->m_Position.x - decalinfo->m_Size < bbMax.x && decalinfo->m_Position.x + decalinfo->m_Size > bbMin.x &&
decalinfo->m_Position.y - decalinfo->m_Size < bbMax.y && decalinfo->m_Position.y + decalinfo->m_Size > bbMin.y &&
decalinfo->m_Position.z - decalinfo->m_Size < bbMax.z && decalinfo->m_Position.z + decalinfo->m_Size > bbMin.z )
*/
if ( model == MODEL_INSTANCE_INVALID )
{
// async data not loaded yet
return;
}
if( r_flashlightrender.GetBool()==false )
return;
m_ShadowsOnModels.AddElementToBucket( model, handle );
}
void CShadowMgr::RemoveAllShadowsFromModel( ModelInstanceHandle_t model )
{
if( model != MODEL_INSTANCE_INVALID )
{
m_ShadowsOnModels.RemoveBucket( model );
FOR_EACH_LL( m_FlashlightStates, i )
{
FlashlightInfo_t &info = m_FlashlightStates[i];
for( int j=0;j<info.m_Renderables.Count();j++ )
{
if( info.m_Renderables[j]->GetModelInstance() == model )
{
info.m_Renderables.Remove( j );
break;
}
}
}
}
}
void CShadowMgr::RemoveAllModelsFromShadow( ShadowHandle_t handle )
{
m_ShadowsOnModels.RemoveElement( handle );
FOR_EACH_LL( m_FlashlightStates, i )
{
FlashlightInfo_t &info = m_FlashlightStates[i];
if( info.m_Shadow==handle )
{
info.m_Renderables.RemoveAll();
}
}
}
//-----------------------------------------------------------------------------
// Shadow state...
//-----------------------------------------------------------------------------
void CShadowMgr::SetModelShadowState( ModelInstanceHandle_t instance )
{
#ifndef SWDS
g_pStudioRender->ClearAllShadows();
if (instance != MODEL_INSTANCE_INVALID && r_shadows.GetInt() )
{
bool bWireframe = r_shadowwireframe.GetBool();
unsigned short i = m_ShadowsOnModels.FirstElement( instance );
while ( i != m_ShadowsOnModels.InvalidIndex() )
{
Shadow_t& shadow = m_Shadows[m_ShadowsOnModels.Element(i)];
if( !bWireframe )
{
if( shadow.m_Flags & SHADOW_FLASHLIGHT )
{
// NULL means that the models material should be used.
// This is what we want in the case of the flashlight
// since we need to render the models material again with different lighting.
// Need to add something here to specify which flashlight.
g_pStudioRender->AddShadow( NULL, NULL, &m_FlashlightStates[shadow.m_FlashlightHandle].m_FlashlightState, &shadow.m_WorldToShadow, shadow.m_pFlashlightDepthTexture );
}
else if( r_shadows_gamecontrol.GetInt() != 0 )
{
g_pStudioRender->AddShadow( shadow.m_pModelMaterial, shadow.m_pBindProxy );
}
}
else if( ( shadow.m_Flags & SHADOW_FLASHLIGHT ) || r_shadows_gamecontrol.GetInt() != 0 )
{
g_pStudioRender->AddShadow( g_pMaterialMRMWireframe, NULL );
}
i = m_ShadowsOnModels.NextElement(i);
}
}
#endif
}
bool CShadowMgr::ModelHasShadows( ModelInstanceHandle_t instance )
{
if ( instance != MODEL_INSTANCE_INVALID )
{
if ( m_ShadowsOnModels.FirstElement(instance) != m_ShadowsOnModels.InvalidIndex() )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Applies the shadow to a surface
//-----------------------------------------------------------------------------
void CShadowMgr::ApplyShadowToSurface( ShadowBuildInfo_t& build, SurfaceHandle_t surfID )
{
// We've found a potential surface to add to the shadow
// At this point, we want to do fast culling to see whether we actually
// should apply the shadow or not before actually adding it to any lists
// FIXME: implement
// Put the texture extents into shadow space; see if there's an intersection
// If not, we can early out
// To do this, we're gonna want to project the surface into the space of the decal
// Therefore, we want to produce a surface->world transformation, and a
// world->shadow/light space transformation
// Then we transform the surface points into shadow space and apply the projection
// in shadow space.
/*
// Get the texture associated with this surface
mtexinfo_t* tex = pSurface->texinfo;
Vector4D &textureU = tex->textureVecsTexelsPerWorldUnits[0];
Vector4D &textureV = tex->textureVecsTexelsPerWorldUnits[1];
// project decal center into the texture space of the surface
float s = DotProduct( decalinfo->m_Position, textureU.AsVector3D() ) +
textureU.w - surf->textureMins[0];
float t = DotProduct( decalinfo->m_Position, textureV.AsVector3D() ) +
textureV.w - surf->textureMins[1];
*/
// Don't do any more computation at the moment, only do it if
// we end up rendering the surface later on
AddSurfaceToShadow( build.m_Shadow, surfID );
}
//-----------------------------------------------------------------------------
// Applies the shadow to a displacement
//-----------------------------------------------------------------------------
void CShadowMgr::ApplyShadowToDisplacement( ShadowBuildInfo_t& build, IDispInfo *pDispInfo, bool bIsFlashlight )
{
// Avoid noshadow displacements
if ( !bIsFlashlight && ( MSurf_Flags( pDispInfo->GetParent() ) & SURFDRAW_NOSHADOWS ) )
return;
// Trivial bbox reject.
Vector bbMin, bbMax;
pDispInfo->GetBoundingBox( bbMin, bbMax );
if ( !bIsFlashlight )
{
if ( !IsBoxIntersectingSphere( bbMin, bbMax, build.m_vecSphereCenter, build.m_flSphereRadius ) )
return;
}
else
{
if( R_CullBox( bbMin, bbMax, GetFlashlightFrustum( build.m_Shadow ) ) )
return;
}
SurfaceHandle_t surfID = pDispInfo->GetParent();
if ( surfID->m_bDynamicShadowsEnabled == false && !bIsFlashlight )
return;
AddSurfaceToShadow( build.m_Shadow, surfID );
}
//-----------------------------------------------------------------------------
// Allows us to disable particular shadows
//-----------------------------------------------------------------------------
void CShadowMgr::EnableShadow( ShadowHandle_t handle, bool bEnable )
{
if (!bEnable)
{
// We need to remove the shadow from all surfaces it may currently be in
RemoveAllSurfacesFromShadow( handle );
RemoveAllModelsFromShadow( handle );
m_Shadows[handle].m_Flags |= SHADOW_DISABLED;
}
else
{
// FIXME: Could make this recompute the cache...
m_Shadows[handle].m_Flags &= ~SHADOW_DISABLED;
}
}
//-----------------------------------------------------------------------------
// Purpose: Set the darkness falloff bias
// Input : shadow -
// ucBias -
//-----------------------------------------------------------------------------
void CShadowMgr::SetFalloffBias( ShadowHandle_t shadow, unsigned char ucBias )
{
m_Shadows[shadow].m_FalloffBias = ucBias;
}
//-----------------------------------------------------------------------------
// Recursive routine to find surface to apply a decal to. World coordinates of
// the decal are passed in r_recalpos like the rest of the engine. This should
// be called through R_DecalShoot()
//-----------------------------------------------------------------------------
void CShadowMgr::ProjectShadow( ShadowHandle_t handle, const Vector &origin,
const Vector& projectionDir, const VMatrix& worldToShadow, const Vector2D& size,
int nLeafCount, const int *pLeafList,
float maxHeight, float falloffOffset, float falloffAmount, const Vector &vecCasterOrigin )
{
VPROF_BUDGET( "CShadowMgr::ProjectShadow", VPROF_BUDGETGROUP_SHADOW_RENDERING );
// First, we need to remove the shadow from all surfaces it may
// currently be in; in other words we're invalidating the shadow surface cache
RemoveAllSurfacesFromShadow( handle );
RemoveAllModelsFromShadow( handle );
// Don't bother with this shadow if it's disabled
Shadow_t &shadow = m_Shadows[handle];
if ( shadow.m_Flags & SHADOW_DISABLED )
return;
// Don't compute the surface cache if shadows are off..
if ( !r_shadows.GetInt() )
return;
// Set the falloff coefficient
shadow.m_FalloffOffset = falloffOffset;
VectorCopy( projectionDir, shadow.m_ProjectionDir );
// We need to know about surfaces in leaves hit by the ray...
// We'd like to stop iterating as soon as the entire swept volume
// enters a solid leaf; that may be hard to determine. Instead,
// we should stop iterating when the ray center enters a solid leaf?
AssertFloatEquals( projectionDir.LengthSqr(), 1.0f, 1e-3 );
// The maximum ray distance is equal to the distance it takes the
// falloff to get to 15%.
shadow.m_MaxDist = maxHeight; //sqrt( coeff / 0.10f ) + falloffOffset;
shadow.m_FalloffAmount = falloffAmount;
MatrixCopy( worldToShadow, shadow.m_WorldToShadow );
// Compute a rough bounding sphere for the ray
float flRadius = sqrt( size.x * size.x + size.y * size.y ) * 0.5f;
VectorMA( origin, 0.5f * maxHeight, projectionDir, shadow.m_vecSphereCenter );
shadow.m_flSphereRadius = 0.5f * maxHeight + flRadius;
Vector vecEndPoint;
Vector vecMins( -flRadius, -flRadius, -flRadius );
Vector vecMaxs( flRadius, flRadius, flRadius );
VectorMA( origin, maxHeight, projectionDir, vecEndPoint );
shadow.m_Ray.Init( origin, vecEndPoint, vecMins, vecMaxs );
// No more work necessary if it hits no leaves
if ( nLeafCount == 0 )
return;
// We're hijacking the surface vis frame to make sure we enumerate
// surfaces only once;
++r_surfacevisframe;
// Clear out the displacement tags also
DispInfo_ClearAllTags( host_state.worldbrush->hDispInfos );
ShadowBuildInfo_t build;
build.m_Shadow = handle;
build.m_RayStart = origin;
build.m_pVis = NULL;
build.m_vecSphereCenter = shadow.m_vecSphereCenter;
build.m_flSphereRadius = shadow.m_flSphereRadius;
VectorCopy( projectionDir, build.m_ProjectionDirection );
// Enumerate leaves
for ( int i = 0; i < nLeafCount; ++i )
{
// NOTE: Scope specifier eliminates virtual function call
CShadowMgr::EnumerateLeaf( pLeafList[i], (int)&build );
}
}
void DrawFrustum( Frustum_t &frustum )
{
const int maxPoints = 8;
int i;
for( i = 0; i < FRUSTUM_NUMPLANES; i++ )
{
Vector points[maxPoints];
Vector points2[maxPoints];
int numPoints = PolyFromPlane( points, frustum.GetPlane( i )->normal, frustum.GetPlane( i )->dist );
Assert( numPoints <= maxPoints );
Vector *in, *out;
in = points;
out = points2;
int j;
for( j = 0; j < FRUSTUM_NUMPLANES; j++ )
{
if( i == j )
{
continue;
}
numPoints = ClipPolyToPlane( in, numPoints, out, frustum.GetPlane( j )->normal, frustum.GetPlane( j )->dist );
Assert( numPoints <= maxPoints );
V_swap( in, out );
}
int c;
for( c = 0; c < numPoints; c++ )
{
CDebugOverlay::AddLineOverlay( in[c], in[(c+1)%numPoints], 0, 255, 0, 255, true, 0.0f );
}
}
}
//static void LineDrawHelper( const Vector &startShadowSpace, const Vector &endShadowSpace,
// const VMatrix &shadowToWorld, unsigned char r, unsigned char g,
// unsigned char b, bool ignoreZ )
//{
// Vector startWorldSpace, endWorldSpace;
// Vector3DMultiplyPositionProjective( shadowToWorld, startShadowSpace, startWorldSpace );
// Vector3DMultiplyPositionProjective( shadowToWorld, endShadowSpace, endWorldSpace );
//
// CDebugOverlay::AddLineOverlay( startWorldSpace,
// endWorldSpace,
// r, g, b, ignoreZ
// , 0.0 );
//}
void CShadowMgr::ProjectFlashlight( ShadowHandle_t handle, const VMatrix& worldToShadow, int nLeafCount, const int *pLeafList )
{
VPROF_BUDGET( "CShadowMgr::ProjectFlashlight", VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING );
Shadow_t& shadow = m_Shadows[handle];
if ( !IsX360() && !r_flashlight_version2.GetInt() )
{
// First, we need to remove the shadow from all surfaces it may
// currently be in; in other words we're invalidating the shadow surface cache
RemoveAllSurfacesFromShadow( handle );
RemoveAllModelsFromShadow( handle );
m_FlashlightStates[ shadow.m_FlashlightHandle ].m_OccluderBuckets.Flush();
}
// Don't bother with this shadow if it's disabled
if ( m_Shadows[handle].m_Flags & SHADOW_DISABLED )
return;
// Don't compute the surface cache if shadows are off..
if ( !r_shadows.GetInt() )
return;
MatrixCopy( worldToShadow, shadow.m_WorldToShadow );
// We need this for our various bounding computations
VMatrix shadowToWorld;
MatrixInverseGeneral( shadow.m_WorldToShadow, shadowToWorld );
// Set up the frustum for the flashlight so that we can cull each leaf against it.
Assert( shadow.m_Flags & SHADOW_FLASHLIGHT );
Frustum_t &frustum = m_FlashlightStates[shadow.m_FlashlightHandle].m_Frustum;
FrustumPlanesFromMatrix( shadowToWorld, frustum );
CalculateSphereFromProjectionMatrixInverse( shadowToWorld, &shadow.m_vecSphereCenter, &shadow.m_flSphereRadius );
if ( nLeafCount == 0 )
return;
// We're hijacking the surface vis frame to make sure we enumerate
// surfaces only once;
++r_surfacevisframe;
// Clear out the displacement tags also
DispInfo_ClearAllTags( host_state.worldbrush->hDispInfos );
ShadowBuildInfo_t build;
build.m_Shadow = handle;
build.m_RayStart = m_FlashlightStates[shadow.m_FlashlightHandle].m_FlashlightState.m_vecLightOrigin;
build.m_pVis = NULL;
build.m_vecSphereCenter = shadow.m_vecSphereCenter;
build.m_flSphereRadius = shadow.m_flSphereRadius;
if( r_flashlightdrawfrustumbbox.GetBool() )
{
Vector mins, maxs;
CalculateAABBFromProjectionMatrixInverse( shadowToWorld, &mins, &maxs );
CDebugOverlay::AddBoxOverlay( Vector( 0.0f, 0.0f, 0.0f ), mins, maxs, QAngle( 0, 0, 0 ),
0, 0, 255, 100, 0.0f );
}
for ( int i = 0; i < nLeafCount; ++i )
{
// NOTE: Scope specifier eliminates virtual function call
CShadowMgr::EnumerateLeaf( pLeafList[i], (int)&build );
}
}
//-----------------------------------------------------------------------------
// Applies the flashlight to all surfaces in the leaf
//-----------------------------------------------------------------------------
void CShadowMgr::ApplyFlashlightToLeaf( const Shadow_t &shadow, mleaf_t* pLeaf, ShadowBuildInfo_t* pBuild )
{
// Get the bounds of the leaf so that we can test it against the flashlight frustum.
Vector leafMins, leafMaxs;
VectorAdd( pLeaf->m_vecCenter, pLeaf->m_vecHalfDiagonal, leafMaxs );
VectorSubtract( pLeaf->m_vecCenter, pLeaf->m_vecHalfDiagonal, leafMins );
// The flashlight frustum didn't intersect the bounding box for this leaf! Get outta here!
if( R_CullBox( leafMins, leafMaxs, GetFlashlightFrustum( pBuild->m_Shadow ) ) )
return;
// Iterate over all surfaces in the leaf, check for backfacing
// and apply the shadow to the surface if it's not backfaced.
// Note that this really only indicates that the shadow may potentially
// sit on the surface; when we render, we'll actually do the clipping
// computation and at that point we'll remove surfaces that don't
// actually hit the surface
bool bCullDepth = r_flashlightculldepth.GetBool();
SurfaceHandle_t *pHandle = &host_state.worldbrush->marksurfaces[pLeaf->firstmarksurface];
for ( int i = 0; i < pLeaf->nummarksurfaces; i++ )
{
SurfaceHandle_t surfID = pHandle[i];
// only process each surface once;
if( MSurf_VisFrame( surfID ) == r_surfacevisframe )
continue;
MSurf_VisFrame( surfID ) = r_surfacevisframe;
Assert( !MSurf_DispInfo( surfID ) );
// perspective projection
// world-space vertex
int vertIndex = host_state.worldbrush->vertindices[MSurf_FirstVertIndex( surfID )];
Vector& worldPos = host_state.worldbrush->vertexes[vertIndex].position;
// Get the lookdir
Vector lookdir;
VectorSubtract( worldPos, pBuild->m_RayStart, lookdir );
VectorNormalize( lookdir );
const cplane_t &surfPlane = MSurf_Plane( surfID );
// Now apply the spherical cull
float flDist = DotProduct( surfPlane.normal, pBuild->m_vecSphereCenter ) - surfPlane.dist;
if ( fabs(flDist) >= pBuild->m_flSphereRadius )
continue;
ApplyShadowToSurface( *pBuild, surfID );
// Backface cull
if( bCullDepth )
{
if ( (MSurf_Flags( surfID ) & SURFDRAW_NOCULL) == 0 )
{
if ( DotProduct(surfPlane.normal, lookdir) < BACKFACE_EPSILON )
continue;
}
else
{
// Avoid edge-on shadows regardless.
float dot = DotProduct(surfPlane.normal, lookdir);
if (fabs(dot) < BACKFACE_EPSILON)
continue;
}
}
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[ shadow.m_FlashlightHandle ];
flashlightInfo.m_OccluderBuckets.AddElement( MSurf_MaterialSortID( surfID ), surfID );
}
}
//-----------------------------------------------------------------------------
// Applies a shadow to all surfaces in the leaf
//-----------------------------------------------------------------------------
void CShadowMgr::ApplyShadowToLeaf( const Shadow_t &shadow, mleaf_t* RESTRICT pLeaf, ShadowBuildInfo_t* RESTRICT pBuild )
{
// Iterate over all surfaces in the leaf, check for backfacing
// and apply the shadow to the surface if it's not backfaced.
// Note that this really only indicates that the shadow may potentially
// sit on the surface; when we render, we'll actually do the clipping
// computation and at that point we'll remove surfaces that don't
// actually hit the surface
SurfaceHandle_t *pHandle = &host_state.worldbrush->marksurfaces[pLeaf->firstmarksurface];
for ( int i = 0; i < pLeaf->nummarksurfaces; i++ )
{
SurfaceHandleRestrict_t surfID = pHandle[i];
// only process each surface once;
if( MSurf_VisFrame( surfID ) == r_surfacevisframe )
continue;
MSurf_VisFrame( surfID ) = r_surfacevisframe;
Assert( !MSurf_DispInfo( surfID ) );
// If this surface has specifically had dynamic shadows disabled on it, then get out!
if ( !MSurf_AreDynamicShadowsEnabled( surfID ) )
continue;
// Backface cull
const cplane_t * RESTRICT pSurfPlane = &MSurf_Plane( surfID );
bool bInFront;
if ( (MSurf_Flags( surfID ) & SURFDRAW_NOCULL) == 0 )
{
if ( DotProduct( pSurfPlane->normal, pBuild->m_ProjectionDirection) > -BACKFACE_EPSILON )
continue;
bInFront = true;
}
else
{
// Avoid edge-on shadows regardless.
float dot = DotProduct( pSurfPlane->normal, pBuild->m_ProjectionDirection );
if (fabs(dot) < BACKFACE_EPSILON)
continue;
bInFront = (dot < 0);
}
// Here, it's front facing...
// Discard stuff on the wrong side of the ray start
if (bInFront)
{
if ( DotProduct( pSurfPlane->normal, pBuild->m_RayStart) < pSurfPlane->dist )
continue;
}
else
{
if ( DotProduct( pSurfPlane->normal, pBuild->m_RayStart) > pSurfPlane->dist )
continue;
}
// Now apply the spherical cull
float flDist = DotProduct( pSurfPlane->normal, pBuild->m_vecSphereCenter ) - pSurfPlane->dist;
if ( fabs(flDist) >= pBuild->m_flSphereRadius )
continue;
ApplyShadowToSurface( *pBuild, surfID );
}
}
#define BIT_SET( a, b ) ((a)[(b)>>3] & (1<<((b)&7)))
//-----------------------------------------------------------------------------
// Applies a projected texture to all surfaces in the leaf
//-----------------------------------------------------------------------------
bool CShadowMgr::EnumerateLeaf( int leaf, int context )
{
VPROF( "CShadowMgr::EnumerateLeaf" );
ShadowBuildInfo_t* pBuild = (ShadowBuildInfo_t*)context;
// Skip this leaf if it's not visible from the shadow caster
if ( pBuild->m_pVis )
{
int cluster = CM_LeafCluster( leaf );
if ( !BIT_SET( pBuild->m_pVis, cluster ) )
return true;
}
const Shadow_t &shadow = m_Shadows[pBuild->m_Shadow];
mleaf_t* pLeaf = &host_state.worldbrush->leafs[leaf];
bool bIsFlashlight;
if( shadow.m_Flags & SHADOW_FLASHLIGHT )
{
bIsFlashlight = true;
ApplyFlashlightToLeaf( shadow, pLeaf, pBuild );
}
else
{
bIsFlashlight = false;
ApplyShadowToLeaf( shadow, pLeaf, pBuild );
}
// Add the decal to each displacement in the leaf it touches.
for ( int i = 0; i < pLeaf->dispCount; i++ )
{
IDispInfo *pDispInfo = MLeaf_Disaplcement( pLeaf, i );
// Make sure the decal hasn't already been added to it.
if( pDispInfo->GetTag() )
continue;
pDispInfo->SetTag();
ApplyShadowToDisplacement( *pBuild, pDispInfo, bIsFlashlight );
}
return true;
}
//-----------------------------------------------------------------------------
// Adds a shadow to a brush model
//-----------------------------------------------------------------------------
void CShadowMgr::AddShadowToBrushModel( ShadowHandle_t handle, model_t* pModel,
const Vector& origin, const QAngle& angles )
{
// Don't compute the surface cache if shadows are off..
if ( !r_shadows.GetInt() )
return;
const Shadow_t * RESTRICT pShadow = &m_Shadows[handle];
// Transform the shadow ray direction into model space
Vector shadowDirInModelSpace;
bool bIsFlashlight = ( pShadow->m_Flags & SHADOW_FLASHLIGHT ) != 0;
if( !bIsFlashlight )
{
// FLASHLIGHTFIXME: should do backface culling for projective light sources.
matrix3x4_t worldToModel;
AngleIMatrix( angles, worldToModel );
VectorRotate( pShadow->m_ProjectionDir, worldToModel, shadowDirInModelSpace );
}
// Just add all non-backfacing brush surfaces to the list of potential
// surfaces that we may be casting a shadow onto.
SurfaceHandleRestrict_t surfID = SurfaceHandleFromIndex( pModel->brush.firstmodelsurface, pModel->brush.pShared );
for (int i=0; i<pModel->brush.nummodelsurfaces; ++i, ++surfID)
{
// Don't bother with nodraw surfaces
int nFlags = MSurf_Flags( surfID );
if ( nFlags & SURFDRAW_NODRAW )
continue;
if( !bIsFlashlight )
{
// FLASHLIGHTFIXME: should do backface culling for projective light sources.
// Don't bother with backfacing surfaces
if ( (nFlags & SURFDRAW_NOCULL) == 0 )
{
const cplane_t * RESTRICT pSurfPlane = &MSurf_Plane( surfID );
float dot = DotProduct( shadowDirInModelSpace, pSurfPlane->normal );
if ( dot > 0 )
continue;
}
}
// FIXME: We may want to do some more high-level per-surface culling
// If so, it'll be added to ApplyShadowToSurface. Call it instead.
AddSurfaceToShadow( handle, surfID );
}
}
//-----------------------------------------------------------------------------
// Removes all shadows from a brush model
//-----------------------------------------------------------------------------
void CShadowMgr::RemoveAllShadowsFromBrushModel( model_t* pModel )
{
SurfaceHandle_t surfID = SurfaceHandleFromIndex( pModel->brush.firstmodelsurface, pModel->brush.pShared );
for (int i=0; i<pModel->brush.nummodelsurfaces; ++i, ++surfID)
{
RemoveAllShadowsFromSurface( surfID );
}
}
//-----------------------------------------------------------------------------
// Adds the shadow decals on the surface to a queue of things to render
//-----------------------------------------------------------------------------
void CShadowMgr::AddShadowsOnSurfaceToRenderList( ShadowDecalHandle_t decalHandle )
{
// Don't compute the surface cache if shadows are off..
if (!r_shadows.GetInt() )
return;
// Add all surface decals into the appropriate render lists
while( decalHandle != m_ShadowDecals.InvalidIndex() )
{
ShadowDecal_t& shadowDecal = m_ShadowDecals[decalHandle];
if( m_Shadows[shadowDecal.m_Shadow].m_Flags & SHADOW_FLASHLIGHT )
{
AddSurfaceToFlashlightMaterialBuckets( shadowDecal.m_Shadow, shadowDecal.m_SurfID );
// We've got one more decal to render
++m_DecalsToRender;
}
else if( r_shadows_gamecontrol.GetInt() != 0 )
{
// For shadow rendering, hook the decal into the render list based on the shadow material, not the surface material.
int sortOrder = m_Shadows[shadowDecal.m_Shadow].m_SortOrder;
m_ShadowDecals[decalHandle].m_NextRender = m_RenderQueue[sortOrder];
m_RenderQueue[sortOrder] = decalHandle;
// We've got one more decal to render
++m_DecalsToRender;
}
decalHandle = m_ShadowDecals.Next(decalHandle);
}
}
void CShadowMgr::ClearShadowRenderList()
{
COMPILE_TIME_ASSERT( sizeof(ShadowDecalHandle_t) == 2 );
// Clear out the render list
if (m_RenderQueue.Count() > 0)
{
memset( m_RenderQueue.Base(), 0xFF, m_RenderQueue.Count() * sizeof(ShadowDecalHandle_t) );
}
m_DecalsToRender = 0;
// Clear all lists pertaining to flashlight decals that need to be rendered.
ClearAllFlashlightMaterialBuckets();
}
void CShadowMgr::RenderShadows( const VMatrix* pModelToWorld )
{
VPROF_BUDGET( "CShadowMgr::RenderShadows", VPROF_BUDGETGROUP_SHADOW_RENDERING );
// Iterate through all sort ids and render for regular shadows, which get their materials from the shadow material.
CMatRenderContextPtr pRenderContext( materials );
int i;
for( i = 0; i < m_RenderQueue.Count(); ++i )
{
if (m_RenderQueue[i] != m_ShadowDecals.InvalidIndex())
{
RenderShadowList(pRenderContext, m_RenderQueue[i], pModelToWorld );
}
}
}
void CShadowMgr::RenderProjectedTextures( const VMatrix* pModelToWorld )
{
VPROF_BUDGET( "CShadowMgr::RenderProjectedTextures", VPROF_BUDGETGROUP_SHADOW_RENDERING );
RenderFlashlights( true, pModelToWorld );
RenderShadows( pModelToWorld );
// Clear out the render list, we've rendered it now
ClearShadowRenderList();
}
//-----------------------------------------------------------------------------
// A 2D sutherland-hodgman clipper
//-----------------------------------------------------------------------------
class CClipTop
{
public:
static inline bool Inside( ShadowVertex_t const& vert ) { return vert.m_ShadowSpaceTexCoord.y < 1;}
static inline float Clip( const Vector& one, const Vector& two ) { return (1 - one.y) / (two.y - one.y);}
static inline bool IsPlane() {return false;}
static inline bool IsAbove() {return false;}
};
class CClipLeft
{
public:
static inline bool Inside( ShadowVertex_t const& vert ) { return vert.m_ShadowSpaceTexCoord.x > 0;}
static inline float Clip( const Vector& one, const Vector& two ) { return one.x / (one.x - two.x);}
static inline bool IsPlane() {return false;}
static inline bool IsAbove() {return false;}
};
class CClipRight
{
public:
static inline bool Inside( ShadowVertex_t const& vert ) {return vert.m_ShadowSpaceTexCoord.x < 1;}
static inline float Clip( const Vector& one, const Vector& two ) {return (1 - one.x) / (two.x - one.x);}
static inline bool IsPlane() {return false;}
static inline bool IsAbove() {return false;}
};
class CClipBottom
{
public:
static inline bool Inside( ShadowVertex_t const& vert ) {return vert.m_ShadowSpaceTexCoord.y > 0;}
static inline float Clip( const Vector& one, const Vector& two ) {return one.y / (one.y - two.y);}
static inline bool IsPlane() {return false;}
static inline bool IsAbove() {return false;}
};
class CClipAbove
{
public:
static inline bool Inside( ShadowVertex_t const& vert ) {return vert.m_ShadowSpaceTexCoord.z > 0;}
static inline float Clip( const Vector& one, const Vector& two ) {return one.z / (one.z - two.z);}
static inline bool IsPlane() {return false;}
static inline bool IsAbove() {return true;}
};
class CClipPlane
{
public:
static inline bool Inside( ShadowVertex_t const& vert )
{
return DotProduct( vert.m_Position, *m_pNormal ) < m_Dist;
}
static inline float Clip( const Vector& one, const Vector& two )
{
Vector dir;
VectorSubtract( two, one, dir );
return IntersectRayWithPlane( one, dir, *m_pNormal, m_Dist );
}
static inline bool IsAbove() {return false;}
static inline bool IsPlane() {return true;}
static void SetPlane( const Vector& normal, float dist )
{
m_pNormal = &normal;
m_Dist = dist;
}
private:
static const Vector *m_pNormal;
static float m_Dist;
};
const Vector *CClipPlane::m_pNormal;
float CClipPlane::m_Dist;
static inline void ClampTexCoord( ShadowVertex_t *pInVertex, ShadowVertex_t *pOutVertex )
{
if ( fabs(pInVertex->m_ShadowSpaceTexCoord[0]) < 1e-3 )
pOutVertex->m_ShadowSpaceTexCoord[0] = 0.0f;
else if ( fabs(pInVertex->m_ShadowSpaceTexCoord[0] - 1.0f) < 1e-3 )
pOutVertex->m_ShadowSpaceTexCoord[0] = 1.0f;
if ( fabs(pInVertex->m_ShadowSpaceTexCoord[1]) < 1e-3 )
pOutVertex->m_ShadowSpaceTexCoord[1] = 0.0f;
else if ( fabs(pInVertex->m_ShadowSpaceTexCoord[1] - 1.0f) < 1e-3 )
pOutVertex->m_ShadowSpaceTexCoord[1] = 1.0f;
}
template <class Clipper>
static inline void Intersect( ShadowVertex_t* pStart, ShadowVertex_t* pEnd, ShadowVertex_t* pOut, bool startInside, Clipper& clipper )
{
// Clip the edge to the clip plane
float t;
if (!Clipper::IsPlane())
{
if (!Clipper::IsAbove())
{
// This is the path the we always take for perspective light volumes.
t = Clipper::Clip( pStart->m_ShadowSpaceTexCoord, pEnd->m_ShadowSpaceTexCoord );
VectorLerp( pStart->m_ShadowSpaceTexCoord, pEnd->m_ShadowSpaceTexCoord, t, pOut->m_ShadowSpaceTexCoord );
}
else
{
t = Clipper::Clip( pStart->m_ShadowSpaceTexCoord, pEnd->m_ShadowSpaceTexCoord );
VectorLerp( pStart->m_ShadowSpaceTexCoord, pEnd->m_ShadowSpaceTexCoord, t, pOut->m_ShadowSpaceTexCoord );
// This is a special thing we do here to avoid hard-edged shadows
if (startInside)
ClampTexCoord( pEnd, pOut );
else
ClampTexCoord( pStart, pOut );
}
}
else
{
t = Clipper::Clip( pStart->m_Position, pEnd->m_Position );
VectorLerp( pStart->m_ShadowSpaceTexCoord, pEnd->m_ShadowSpaceTexCoord, t, pOut->m_ShadowSpaceTexCoord );
}
VectorLerp( pStart->m_Position, pEnd->m_Position, t, pOut->m_Position );
}
template <class Clipper>
static void ShadowClip( ShadowClipState_t& clip, Clipper& clipper )
{
if ( clip.m_ClipCount == 0 )
return;
// Ye Olde Sutherland-Hodgman clipping algorithm
int numOutVerts = 0;
ShadowVertex_t** pSrcVert = clip.m_ppClipVertices[clip.m_CurrVert];
ShadowVertex_t** pDestVert = clip.m_ppClipVertices[!clip.m_CurrVert];
int numVerts = clip.m_ClipCount;
ShadowVertex_t* pStart = pSrcVert[numVerts-1];
bool startInside = Clipper::Inside( *pStart );
for (int i = 0; i < numVerts; ++i)
{
ShadowVertex_t* pEnd = pSrcVert[i];
bool endInside = Clipper::Inside( *pEnd );
if (endInside)
{
if (!startInside)
{
// Started outside, ended inside, need to clip the edge
if ( clip.m_TempCount >= SHADOW_VERTEX_TEMP_COUNT )
return;
// Allocate a new clipped vertex
pDestVert[numOutVerts] = &clip.m_pTempVertices[clip.m_TempCount++];
// Clip the edge to the clip plane
Intersect( pStart, pEnd, pDestVert[numOutVerts], startInside, clipper );
++numOutVerts;
}
pDestVert[numOutVerts++] = pEnd;
}
else
{
if (startInside)
{
// Started inside, ended outside, need to clip the edge
if ( clip.m_TempCount >= SHADOW_VERTEX_TEMP_COUNT )
return;
// Allocate a new clipped vertex
pDestVert[numOutVerts] = &clip.m_pTempVertices[clip.m_TempCount++];
// Clip the edge to the clip plane
Intersect( pStart, pEnd, pDestVert[numOutVerts], startInside, clipper );
++numOutVerts;
}
}
pStart = pEnd;
startInside = endInside;
}
// Switch source lists
clip.m_CurrVert = 1 - clip.m_CurrVert;
clip.m_ClipCount = numOutVerts;
Assert( clip.m_ClipCount <= SHADOW_VERTEX_TEMP_COUNT );
}
//-----------------------------------------------------------------------------
// Project vertices into shadow space
//-----------------------------------------------------------------------------
bool CShadowMgr::ProjectVerticesIntoShadowSpace( const VMatrix& modelToShadow,
float maxDist, int count, Vector** RESTRICT ppPosition, ShadowClipState_t& clip )
{
bool insideVolume = false;
// Create vertices to clip to...
for (int i = 0; i < count; ++i )
{
Assert( ppPosition[i] );
VectorCopy( *ppPosition[i], clip.m_pTempVertices[i].m_Position );
// Project the points into shadow texture space
Vector3DMultiplyPosition( modelToShadow, *ppPosition[i], clip.m_pTempVertices[i].m_ShadowSpaceTexCoord );
// Set up clipping coords...
clip.m_ppClipVertices[0][i] = &clip.m_pTempVertices[i];
if (clip.m_pTempVertices[i].m_ShadowSpaceTexCoord[2] < maxDist )
{
insideVolume = true;
}
}
clip.m_TempCount = clip.m_ClipCount = count;
clip.m_CurrVert = 0;
return insideVolume;
}
//-----------------------------------------------------------------------------
// Projects + clips shadows
//-----------------------------------------------------------------------------
int CShadowMgr::ProjectAndClipVertices( const Shadow_t& shadow, const VMatrix& worldToShadow,
const VMatrix *pWorldToModel, int count, Vector** ppPosition, ShadowVertex_t*** ppOutVertex )
{
VPROF( "ProjectAndClipVertices" );
static ShadowClipState_t clip;
if ( !ProjectVerticesIntoShadowSpace( worldToShadow, shadow.m_MaxDist, count, ppPosition, clip ) )
return 0;
// Clippers...
CClipTop top;
CClipBottom bottom;
CClipLeft left;
CClipRight right;
CClipAbove above;
CClipPlane plane;
// Sutherland-hodgman clip
ShadowClip( clip, top );
ShadowClip( clip, bottom );
ShadowClip( clip, left );
ShadowClip( clip, right );
ShadowClip( clip, above );
// Planes to suppress back-casting
for (int i = 0; i < shadow.m_ClipPlaneCount; ++i)
{
if ( pWorldToModel )
{
cplane_t worldPlane, modelPlane;
worldPlane.normal = shadow.m_ClipPlane[i];
worldPlane.dist = shadow.m_ClipDist[i];
MatrixTransformPlane( *pWorldToModel, worldPlane, modelPlane );
plane.SetPlane( modelPlane.normal, modelPlane.dist );
}
else
{
plane.SetPlane( shadow.m_ClipPlane[i], shadow.m_ClipDist[i] );
}
ShadowClip( clip, plane );
}
if (clip.m_ClipCount < 3)
return 0;
// Return a pointer to the array of clipped vertices...
Assert(ppOutVertex);
*ppOutVertex = clip.m_ppClipVertices[clip.m_CurrVert];
return clip.m_ClipCount;
}
//-----------------------------------------------------------------------------
// Accessor for use by the displacements
//-----------------------------------------------------------------------------
int CShadowMgr::ProjectAndClipVertices( ShadowHandle_t handle, int count,
Vector** ppPosition, ShadowVertex_t*** ppOutVertex )
{
return ProjectAndClipVertices( m_Shadows[handle],
m_Shadows[handle].m_WorldToShadow, NULL, count, ppPosition, ppOutVertex );
}
//-----------------------------------------------------------------------------
// Copies vertex info from the clipped vertices
//-----------------------------------------------------------------------------
// This version treats texcoords as Vector
inline void CShadowMgr::CopyClippedVertices( int count, ShadowVertex_t** ppSrcVert, ShadowVertex_t* pDstVert, const Vector &vToAdd )
{
for (int i = 0; i < count; ++i)
{
pDstVert[i].m_Position = ppSrcVert[i]->m_Position + vToAdd;
pDstVert[i].m_ShadowSpaceTexCoord = ppSrcVert[i]->m_ShadowSpaceTexCoord;
// Make sure it's been clipped
Assert( ppSrcVert[i]->m_ShadowSpaceTexCoord[0] >= -1e-3f );
Assert( ppSrcVert[i]->m_ShadowSpaceTexCoord[0] - 1.0f <= 1e-3f );
Assert( ppSrcVert[i]->m_ShadowSpaceTexCoord[1] >= -1e-3f );
Assert( ppSrcVert[i]->m_ShadowSpaceTexCoord[1] - 1.0f <= 1e-3f );
}
}
//-----------------------------------------------------------------------------
// Does the actual work of computing shadow vertices
//-----------------------------------------------------------------------------
bool CShadowMgr::ComputeShadowVertices( ShadowDecal_t& decal,
const VMatrix* pModelToWorld, const VMatrix *pWorldToModel, ShadowVertexCache_t* pVertexCache )
{
VPROF( "CShadowMgr::ComputeShadowVertices" );
// Prepare for the clipping
Vector **ppVec = (Vector**)stackalloc( MSurf_VertCount( decal.m_SurfID ) * sizeof(Vector*) );
for (int i = 0; i < MSurf_VertCount( decal.m_SurfID ); ++i )
{
int vertIndex = host_state.worldbrush->vertindices[MSurf_FirstVertIndex( decal.m_SurfID )+i];
ppVec[i] = &host_state.worldbrush->vertexes[vertIndex].position;
}
// Compute the modelToShadow transform.
// In the case of the world, just use worldToShadow...
VMatrix* pModelToShadow = &m_Shadows[decal.m_Shadow].m_WorldToShadow;
VMatrix temp;
if ( pModelToWorld )
{
MatrixMultiply( *pModelToShadow, *pModelToWorld, temp );
pModelToShadow = &temp;
}
else
{
pWorldToModel = NULL;
}
// Create vertices to clip to...
ShadowVertex_t** ppSrcVert;
int clipCount = ProjectAndClipVertices( m_Shadows[decal.m_Shadow], *pModelToShadow, pWorldToModel,
MSurf_VertCount( decal.m_SurfID ), ppVec, &ppSrcVert );
if (clipCount == 0)
{
pVertexCache->m_Count = 0;
return false;
}
// Allocate the vertices we're going to use for the decal
ShadowVertex_t* pDstVert = AllocateVertices( *pVertexCache, clipCount );
Assert( pDstVert );
// Copy the clipped vertices into the cache
const Vector &vNormal = MSurf_Plane( decal.m_SurfID ).normal;
CopyClippedVertices( clipCount, ppSrcVert, pDstVert, vNormal * OVERLAY_AVOID_FLICKER_NORMAL_OFFSET );
// Indicate which shadow this is related to
pVertexCache->m_Shadow = decal.m_Shadow;
return true;
}
//-----------------------------------------------------------------------------
// Should we cache vertices?
//-----------------------------------------------------------------------------
inline bool CShadowMgr::ShouldCacheVertices( const ShadowDecal_t& decal )
{
return (m_Shadows[decal.m_Shadow].m_Flags & SHADOW_CACHE_VERTS) != 0;
}
//-----------------------------------------------------------------------------
// Generates a list displacement shadow vertices to render
//-----------------------------------------------------------------------------
inline bool CShadowMgr::GenerateDispShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecal_t& decal, ShadowRenderInfo_t& info )
{
//=============================================================================
// HPE_BEGIN:
// [smessick] Added an overflow condition for the max disp decal cache.
//=============================================================================
if ( info.m_DispCount >= MAX_SHADOW_DECAL_CACHE_COUNT )
{
info.m_DispCount = MAX_SHADOW_DECAL_CACHE_COUNT;
return true;
}
//=============================================================================
// HPE_END
//=============================================================================
int v, i;
if ( !MSurf_DispInfo( decal.m_SurfID )->ComputeShadowFragments( decal.m_DispShadow, v, i ) )
return false;
// Catch overflows....
if ( ( info.m_VertexCount + v >= info.m_nMaxVertices ) || ( info.m_IndexCount + i >= info.m_nMaxIndices ) )
return true;
info.m_VertexCount += v;
info.m_IndexCount += i;
info.m_pDispCache[info.m_DispCount++] = decal.m_DispShadow;
return true;
}
//-----------------------------------------------------------------------------
// Generates a list shadow vertices to render
//-----------------------------------------------------------------------------
inline bool CShadowMgr::GenerateNormalShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecal_t& decal, ShadowRenderInfo_t& info )
{
//=============================================================================
// HPE_BEGIN:
// [smessick] Check for cache overflow.
//=============================================================================
if ( info.m_Count >= MAX_SHADOW_DECAL_CACHE_COUNT )
{
info.m_Count = MAX_SHADOW_DECAL_CACHE_COUNT;
return true;
}
//=============================================================================
// HPE_END
//=============================================================================
// Look for a cache hit
ShadowVertexCache_t* pVertexCache;
if (decal.m_ShadowVerts != m_VertexCache.InvalidIndex())
{
// Ok, we've already computed the data, lets use it
info.m_pCache[info.m_Count] = decal.m_ShadowVerts;
pVertexCache = &m_VertexCache[decal.m_ShadowVerts];
}
else
{
// Attempt to cull the surface
bool bIsNear = IsShadowNearSurface( decal.m_Shadow, decal.m_SurfID, info.m_pModelToWorld, &info.m_WorldToModel );
if ( !bIsNear )
return false;
// In this case, we gotta recompute the shadow decal vertices
// and maybe even store it into the cache....
bool shouldCacheVerts = ShouldCacheVertices( decal );
if (shouldCacheVerts)
{
decal.m_ShadowVerts = m_VertexCache.AddToTail();
info.m_pCache[info.m_Count] = decal.m_ShadowVerts;
pVertexCache = &m_VertexCache[decal.m_ShadowVerts];
}
else
{
int i = m_TempVertexCache.AddToTail();
info.m_pCache[info.m_Count] = -i-1;
pVertexCache = &m_TempVertexCache[i];
Assert( info.m_pCache[info.m_Count] < 0 );
}
// Compute the shadow vertices
// If no vertices were created, indicate this surface should be removed from the cache
if ( !ComputeShadowVertices( decal, info.m_pModelToWorld, &info.m_WorldToModel, pVertexCache ) )
return false;
}
// Catch overflows....
int nAdditionalIndices = 3 * (pVertexCache->m_Count - 2);
if ( ( info.m_VertexCount + pVertexCache->m_Count >= info.m_nMaxVertices ) ||
( info.m_IndexCount + nAdditionalIndices >= info.m_nMaxIndices ) )
{
return true;
}
// Update vertex, index, and decal counts
info.m_VertexCount += pVertexCache->m_Count;
info.m_IndexCount += nAdditionalIndices;
++info.m_Count;
return true;
}
//-----------------------------------------------------------------------------
// Generates a list shadow vertices to render
//-----------------------------------------------------------------------------
void CShadowMgr::GenerateShadowRenderInfo( IMatRenderContext *pRenderContext, ShadowDecalHandle_t decalHandle, ShadowRenderInfo_t& info )
{
info.m_VertexCount = 0;
info.m_IndexCount = 0;
info.m_Count = 0;
info.m_DispCount = 0;
// Keep the lists only full of valid decals; that way we can preserve
// the render lists in the case that we discover a shadow isn't needed.
ShadowDecalHandle_t next;
for ( ; decalHandle != m_ShadowDecals.InvalidIndex(); decalHandle = next )
{
ShadowDecal_t& decal = m_ShadowDecals[decalHandle];
next = m_ShadowDecals[decalHandle].m_NextRender;
// Skip translucent shadows [ don't add their verts + indices to the render lists ]
Shadow_t &shadow = m_Shadows[ decal.m_Shadow ];
if ( shadow.m_FalloffBias == 255 )
continue;
bool keepShadow;
if ( decal.m_DispShadow != DISP_SHADOW_HANDLE_INVALID )
{
// Handle shadows on displacements...
keepShadow = GenerateDispShadowRenderInfo( pRenderContext, decal, info );
}
else
{
// Handle shadows on normal surfaces
keepShadow = GenerateNormalShadowRenderInfo( pRenderContext, decal, info );
}
// Retire the surface if the shadow didn't actually hit it
if ( !keepShadow && ShouldCacheVertices( decal ) )
{
// If no triangles were generated
// (the decal was completely clipped off)
// In this case, remove the decal from the surface cache
// so next time it'll be faster (for cached decals)
RemoveShadowDecalFromSurface( decal.m_SurfID, decalHandle );
}
}
}
//-----------------------------------------------------------------------------
// Computes information for rendering
//-----------------------------------------------------------------------------
void CShadowMgr::ComputeRenderInfo( ShadowDecalRenderInfo_t* pInfo, ShadowHandle_t handle ) const
{
const ShadowInfo_t& i = m_Shadows[handle];
pInfo->m_vTexOrigin = i.m_TexOrigin;
pInfo->m_vTexSize = i.m_TexSize;
pInfo->m_flFalloffOffset = i.m_FalloffOffset;
pInfo->m_flFalloffAmount = i.m_FalloffAmount;
pInfo->m_flFalloffBias = i.m_FalloffBias;
float flFalloffDist = i.m_MaxDist - i.m_FalloffOffset;
pInfo->m_flOOZFalloffDist = ( flFalloffDist > 0.0f ) ? 1.0f / flFalloffDist : 1.0f;
}
//-----------------------------------------------------------------------------
// Adds normal shadows to the mesh builder
//-----------------------------------------------------------------------------
int CShadowMgr::AddNormalShadowsToMeshBuilder( CMeshBuilder& meshBuilder, ShadowRenderInfo_t& info )
{
// Step through the cache and add all shadows on normal surfaces
ShadowDecalRenderInfo_t shadow;
int baseIndex = 0;
for (int i = 0; i < info.m_Count; ++i)
{
// Two loops here, basically to minimize the # of if statements we need
ShadowVertexCache_t* pVertexCache;
if (info.m_pCache[i] < 0)
{
pVertexCache = &m_TempVertexCache[-info.m_pCache[i]-1];
}
else
{
pVertexCache = &m_VertexCache[info.m_pCache[i]];
}
ShadowVertex_t* pVerts = GetCachedVerts( *pVertexCache );
g_pShadowMgr->ComputeRenderInfo( &shadow, pVertexCache->m_Shadow );
int j;
unsigned char c;
Vector2D texCoord;
int vCount = pVertexCache->m_Count - 2;
if ( vCount <= 0 )
continue;
for ( j = 0; j < vCount; ++j, ++pVerts )
{
// Transform + offset the texture coords
Vector2DMultiply( pVerts->m_ShadowSpaceTexCoord.AsVector2D(), shadow.m_vTexSize, texCoord );
texCoord += shadow.m_vTexOrigin;
c = ComputeDarkness( pVerts->m_ShadowSpaceTexCoord.z, shadow );
meshBuilder.Position3fv( pVerts->m_Position.Base() );
meshBuilder.Color4ub( c, c, c, c );
meshBuilder.TexCoord2fv( 0, texCoord.Base() );
meshBuilder.AdvanceVertex();
meshBuilder.FastIndex( baseIndex );
meshBuilder.FastIndex( j + baseIndex + 1 );
meshBuilder.FastIndex( j + baseIndex + 2 );
}
Vector2DMultiply( pVerts->m_ShadowSpaceTexCoord.AsVector2D(), shadow.m_vTexSize, texCoord );
texCoord += shadow.m_vTexOrigin;
c = ComputeDarkness( pVerts->m_ShadowSpaceTexCoord.z, shadow );
meshBuilder.Position3fv( pVerts->m_Position.Base() );
meshBuilder.Color4ub( c, c, c, c );
meshBuilder.TexCoord2fv( 0, texCoord.Base() );
meshBuilder.AdvanceVertex();
++pVerts;
Vector2DMultiply( pVerts->m_ShadowSpaceTexCoord.AsVector2D(), shadow.m_vTexSize, texCoord );
texCoord += shadow.m_vTexOrigin;
c = ComputeDarkness( pVerts->m_ShadowSpaceTexCoord.z, shadow );
meshBuilder.Position3fv( pVerts->m_Position.Base() );
meshBuilder.Color4ub( c, c, c, c );
meshBuilder.TexCoord2fv( 0, texCoord.Base() );
meshBuilder.AdvanceVertex();
// Update the base index
baseIndex += vCount + 2;
}
return baseIndex;
}
//-----------------------------------------------------------------------------
// Adds displacement shadows to the mesh builder
//-----------------------------------------------------------------------------
int CShadowMgr::AddDisplacementShadowsToMeshBuilder( CMeshBuilder& meshBuilder,
ShadowRenderInfo_t& info, int baseIndex )
{
if ( !r_DrawDisp.GetBool() )
return baseIndex;
// Step through the cache and add all shadows on displacement surfaces
for (int i = 0; i < info.m_DispCount; ++i)
{
baseIndex = DispInfo_AddShadowsToMeshBuilder( meshBuilder, info.m_pDispCache[i], baseIndex );
}
return baseIndex;
}
//-----------------------------------------------------------------------------
// The following methods will display debugging info in the middle of each shadow decal
//-----------------------------------------------------------------------------
static void DrawShadowID( ShadowHandle_t shadowHandle, const Vector &vecCentroid )
{
#ifndef SWDS
char buf[32];
Q_snprintf(buf, sizeof( buf ), "%d", shadowHandle );
CDebugOverlay::AddTextOverlay( vecCentroid, 0, buf );
#endif
}
void CShadowMgr::RenderDebuggingInfo( const ShadowRenderInfo_t &info, ShadowDebugFunc_t func )
{
// Step through the cache and add all shadows on normal surfaces
for (int i = 0; i < info.m_Count; ++i)
{
ShadowVertexCache_t* pVertexCache;
if (info.m_pCache[i] < 0)
{
pVertexCache = &m_TempVertexCache[-info.m_pCache[i]-1];
}
else
{
pVertexCache = &m_VertexCache[info.m_pCache[i]];
}
ShadowVertex_t* pVerts = GetCachedVerts( *pVertexCache );
Vector vecNormal;
float flTotalArea = 0.0f;
Vector vecCentroid(0,0,0);
Vector vecApex = pVerts[0].m_Position;
int vCount = pVertexCache->m_Count;
for ( int j = 0; j < vCount - 2; ++j )
{
Vector v1 = pVerts[j + 1].m_Position;
Vector v2 = pVerts[j + 2].m_Position;
CrossProduct( v2 - v1, v1 - vecApex, vecNormal );
float flArea = vecNormal.Length();
flTotalArea += flArea;
vecCentroid += (vecApex + v1 + v2) * flArea / 3.0f;
}
if (flTotalArea)
{
vecCentroid /= flTotalArea;
}
func( pVertexCache->m_Shadow, vecCentroid );
}
}
//-----------------------------------------------------------------------------
// Renders shadows that all share a material enumeration
//-----------------------------------------------------------------------------
void CShadowMgr::RenderShadowList( IMatRenderContext *pRenderContext, ShadowDecalHandle_t decalHandle, const VMatrix* pModelToWorld )
{
//=============================================================================
// HPE_BEGIN:
// [smessick] Make sure we don't overflow our caches.
//=============================================================================
if ( m_DecalsToRender > m_ShadowDecalCache.Count() )
{
// Don't grow past the MAX_SHADOW_DECAL_CACHE_COUNT cap.
int diff = min( m_DecalsToRender, (int)MAX_SHADOW_DECAL_CACHE_COUNT ) - m_ShadowDecalCache.Count();
if ( diff > 0 )
{
// Grow the cache.
m_ShadowDecalCache.Grow( diff );
DevMsg( "[CShadowMgr::RenderShadowList] growing shadow decal cache (decals: %d, cache: %d, diff: %d).\n", m_DecalsToRender, m_ShadowDecalCache.Count(), diff );
}
}
if ( m_DecalsToRender > m_DispShadowDecalCache.Count() )
{
// Don't grow past the MAX_SHADOW_DECAL_CACHE_COUNT cap.
int diff = min( m_DecalsToRender, (int)MAX_SHADOW_DECAL_CACHE_COUNT ) - m_DispShadowDecalCache.Count();
if ( diff > 0 )
{
// Grow the cache.
m_DispShadowDecalCache.Grow( diff );
DevMsg( "[CShadowMgr::RenderShadowList] growing disp shadow decal cache (decals: %d, cache: %d, diff: %d).\n", m_DecalsToRender, m_DispShadowDecalCache.Count(), diff );
}
}
//=============================================================================
// HPE_END
//=============================================================================
// Set the render state...
Shadow_t& shadow = m_Shadows[m_ShadowDecals[decalHandle].m_Shadow];
if ( r_shadowwireframe.GetInt() == 0 )
{
pRenderContext->Bind( shadow.m_pMaterial, shadow.m_pBindProxy );
}
else
{
pRenderContext->Bind( g_materialWorldWireframe );
}
// Blow away the temporary vertex cache (for normal surfaces)
ClearTempCache();
// Set up rendering info structure
ShadowRenderInfo_t info;
//=============================================================================
// HPE_BEGIN:
// [smessick] This code used to create the cache dynamically on the stack.
//=============================================================================
info.m_pCache = m_ShadowDecalCache.Base();
info.m_pDispCache = m_DispShadowDecalCache.Base();
//=============================================================================
// HPE_END
//=============================================================================
info.m_pModelToWorld = pModelToWorld;
if ( pModelToWorld )
{
MatrixInverseTR( *pModelToWorld, info.m_WorldToModel );
}
info.m_nMaxIndices = pRenderContext->GetMaxIndicesToRender();
info.m_nMaxVertices = pRenderContext->GetMaxVerticesToRender( shadow.m_pMaterial );
// Iterate over all decals in the decal list and generate polygon lists
// Creating them from scratch if their shadow poly cache is invalid
GenerateShadowRenderInfo(pRenderContext, decalHandle, info);
Assert( info.m_Count <= m_DecalsToRender );
Assert( info.m_DispCount <= m_DecalsToRender );
//=============================================================================
// HPE_BEGIN:
// [smessick] Also check against the max.
//=============================================================================
Assert( info.m_Count <= m_ShadowDecalCache.Count() &&
info.m_Count <= MAX_SHADOW_DECAL_CACHE_COUNT );
Assert( info.m_DispCount <= m_DispShadowDecalCache.Count() &&
info.m_DispCount <= MAX_SHADOW_DECAL_CACHE_COUNT );
//=============================================================================
// HPE_END
//=============================================================================
// Now that the vertex lists are created, render them
IMesh* pMesh = pRenderContext->GetDynamicMesh();
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, info.m_VertexCount, info.m_IndexCount );
// Add in shadows from both normal surfaces + displacement surfaces
int baseIndex = AddNormalShadowsToMeshBuilder( meshBuilder, info );
AddDisplacementShadowsToMeshBuilder( meshBuilder, info, baseIndex );
meshBuilder.End();
pMesh->Draw();
if (r_shadowids.GetInt() != 0)
{
RenderDebuggingInfo( info, DrawShadowID );
}
}
//-----------------------------------------------------------------------------
// Set the number of world material buckets. This should get called on level load.
//-----------------------------------------------------------------------------
void CShadowMgr::SetNumWorldMaterialBuckets( int numMaterialSortBins )
{
m_NumWorldMaterialBuckets = numMaterialSortBins;
FlashlightHandle_t flashlightID;
for( flashlightID = m_FlashlightStates.Head();
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
m_FlashlightStates[flashlightID].m_MaterialBuckets.SetNumMaterialSortIDs( numMaterialSortBins );
m_FlashlightStates[flashlightID].m_OccluderBuckets.SetNumMaterialSortIDs( numMaterialSortBins );
}
ClearAllFlashlightMaterialBuckets();
}
//-----------------------------------------------------------------------------
// Per frame call to clear all of the flashlight world material buckets.
//-----------------------------------------------------------------------------
void CShadowMgr::ClearAllFlashlightMaterialBuckets( void )
{
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
FlashlightHandle_t flashlightID;
for( flashlightID = m_FlashlightStates.Head();
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
m_FlashlightStates[flashlightID].m_MaterialBuckets.Flush();
}
}
//-----------------------------------------------------------------------------
// Allocate world material buckets for a particular flashlight. This should get called on flashlight creation.
//-----------------------------------------------------------------------------
void CShadowMgr::AllocFlashlightMaterialBuckets( FlashlightHandle_t flashlightID )
{
Assert( m_FlashlightStates.MaxElementIndex() >= flashlightID );
m_FlashlightStates[flashlightID].m_MaterialBuckets.SetNumMaterialSortIDs( m_NumWorldMaterialBuckets );
m_FlashlightStates[flashlightID].m_OccluderBuckets.SetNumMaterialSortIDs( m_NumWorldMaterialBuckets );
}
//-----------------------------------------------------------------------------
// Update a particular flashlight's state.
//-----------------------------------------------------------------------------
void CShadowMgr::UpdateFlashlightState( ShadowHandle_t shadowHandle, const FlashlightState_t &lightState )
{
m_FlashlightStates[m_Shadows[shadowHandle].m_FlashlightHandle].m_FlashlightState = lightState;
}
void CShadowMgr::SetFlashlightDepthTexture( ShadowHandle_t shadowHandle, ITexture *pFlashlightDepthTexture, unsigned char ucShadowStencilBit )
{
m_Shadows[shadowHandle].m_pFlashlightDepthTexture = pFlashlightDepthTexture;
m_Shadows[shadowHandle].m_ucShadowStencilBit = ucShadowStencilBit;
}
bool ScreenSpaceRectFromPoints( IMatRenderContext *pRenderContext, Vector vClippedPolygons[8][10], int *pNumPoints, int nNumPolygons, int *nLeft, int *nTop, int *nRight, int *nBottom )
{
if( nNumPolygons == 0 )
return false;
VMatrix matView, matProj, matViewProj;
pRenderContext->GetMatrix( MATERIAL_VIEW, &matView );
pRenderContext->GetMatrix( MATERIAL_PROJECTION, &matProj );
MatrixMultiply( matProj, matView, matViewProj );
float fMinX, fMaxX, fMinY, fMaxY; // Init bounding rect
fMinX = fMinY = FLT_MAX;
fMaxX = fMaxY = -FLT_MAX;
for ( int i=0; i<nNumPolygons; i++ )
{
for ( int j=0; j<pNumPoints[i]; j++ )
{
Vector vScreenSpacePoint;
matViewProj.V3Mul( vClippedPolygons[i][j], vScreenSpacePoint ); // Transform from World to screen space
fMinX = fpmin( fMinX, vScreenSpacePoint.x ); // Update mins/maxes
fMaxX = fpmax( fMaxX, vScreenSpacePoint.x ); //
fMinY = fpmin( fMinY, -vScreenSpacePoint.y ); // These are in -1 to +1 range
fMaxY = fpmax( fMaxY, -vScreenSpacePoint.y ); //
}
}
int nWidth, nHeight;
g_pMaterialSystem->GetBackBufferDimensions( nWidth, nHeight ); // Get render target dimensions
*nLeft = ((fMinX * 0.5f + 0.5f) * (float) nWidth ) - 1; // Convert to render target pixel units
*nTop = ((fMinY * 0.5f + 0.5f) * (float) nHeight) - 1;
*nRight = ((fMaxX * 0.5f + 0.5f) * (float) nWidth ) + 1;
*nBottom = ((fMaxY * 0.5f + 0.5f) * (float) nHeight) + 1;
*nLeft = clamp( *nLeft, 0, nWidth ); // Clamp to render target dimensions
*nTop = clamp( *nTop, 0, nHeight );
*nRight = clamp( *nRight, 0, nWidth );
*nBottom = clamp( *nBottom, 0, nHeight );
Assert( (*nLeft <= *nRight) && (*nTop <= *nBottom) );
// Do we have an actual subrect of the whole screen?
bool bWithinBounds = ((*nLeft > 0 ) || (*nTop > 0) || (*nRight < nWidth) || (*nBottom < nHeight));
// Compute valid area
nWidth = (*nRight - *nLeft);
nHeight = (*nBottom - *nTop);
int nArea = ( nWidth > 0 ) && ( nHeight > 0 ) ? nWidth * nHeight : 0;
// Valid rect?
return bWithinBounds && (nArea > 0);
}
// Turn this optimization off by default
static ConVar r_flashlightclip("r_flashlightclip", "0", FCVAR_CHEAT );
static ConVar r_flashlightdrawclip("r_flashlightdrawclip", "0", FCVAR_CHEAT );
static ConVar r_flashlightscissor( "r_flashlightscissor", "1", 0 );
void ExtractFrustumPlanes( Frustum frustumPlanes, float flPlaneEpsilon )
{
const CViewSetup &view = g_EngineRenderer->ViewGetCurrent();
float flFOVy = CalcFovY( view.fov, view.m_flAspectRatio );
Frustum_t frustum;
Vector vForward, vRight, vUp;
AngleVectors( view.angles, &vForward, &vRight, &vUp );
GeneratePerspectiveFrustum( view.origin, vForward, vRight, vUp,
view.zNear + flPlaneEpsilon, view.zFar - flPlaneEpsilon, // Apply epsilon to near and far
view.fov, flFOVy, frustum );
// Copy out to the planes that the engine renderer uses.
for( int i=0; i < FRUSTUM_NUMPLANES; i++ )
{
frustumPlanes[i].m_Normal = frustum.GetPlane(i)->normal;
frustumPlanes[i].m_Dist = frustum.GetPlane(i)->dist;
}
}
void ConstructNearAndFarPolygons( Vector *pVecNearPlane, Vector *pVecFarPlane, float flPlaneEpsilon )
{
const CViewSetup &view = g_EngineRenderer->ViewGetCurrent();
float fovY = CalcFovY( view.fov, view.m_flAspectRatio );
// Compute near and far plane half-width and half-height
float flTanHalfAngleRadians = tan( view.fov * ( 0.5f * M_PI / 180.0f ) );
float flHalfNearWidth = flTanHalfAngleRadians * ( view.zNear + flPlaneEpsilon );
float flHalfFarWidth = flTanHalfAngleRadians * ( view.zFar - flPlaneEpsilon );
flTanHalfAngleRadians = tan( fovY * ( 0.5f * M_PI / 180.0f ) );
float flHalfNearHeight = flTanHalfAngleRadians * ( view.zNear + flPlaneEpsilon );
float flHalfFarHeight = flTanHalfAngleRadians * ( view.zFar - flPlaneEpsilon );
// World-space orientation of viewer
Vector vForward, vRight, vUp;
AngleVectors( view.angles, &vForward, &vRight, &vUp );
vForward.NormalizeInPlace();
vRight.NormalizeInPlace();
vUp.NormalizeInPlace();
// Center of near and far planes in world space
Vector vCenterNear = view.origin + vForward * ( view.zNear + flPlaneEpsilon );
Vector vCenterFar = view.origin + vForward * ( view.zFar - flPlaneEpsilon );
pVecNearPlane[0] = vCenterNear - ( vRight * flHalfNearWidth ) - ( vUp * flHalfNearHeight );
pVecNearPlane[1] = vCenterNear - ( vRight * flHalfNearWidth ) + ( vUp * flHalfNearHeight );
pVecNearPlane[2] = vCenterNear + ( vRight * flHalfNearWidth ) + ( vUp * flHalfNearHeight );
pVecNearPlane[3] = vCenterNear + ( vRight * flHalfNearWidth ) - ( vUp * flHalfNearHeight );
pVecFarPlane[0] = vCenterNear - ( vRight * flHalfFarWidth ) - ( vUp * flHalfFarHeight );
pVecFarPlane[1] = vCenterNear + ( vRight * flHalfFarWidth ) - ( vUp * flHalfFarHeight );
pVecFarPlane[2] = vCenterNear + ( vRight * flHalfFarWidth ) + ( vUp * flHalfFarHeight );
pVecFarPlane[3] = vCenterNear - ( vRight * flHalfFarWidth ) + ( vUp * flHalfFarHeight );
}
void DrawDebugPolygon( int nNumVerts, Vector *pVecPoints, bool bFrontFacing, bool bNearPlane )
{
int r=0, g=0, b=0;
if ( bFrontFacing )
b = 255;
else
r = 255;
if ( bNearPlane ) // Draw near plane green for visualization
{
r = b = 0;
g = 255;
}
// Draw triangles fanned out from vertex zero
for (int i=1; i<(nNumVerts-1); i++)
{
Vector v0 = pVecPoints[0];
Vector v1 = pVecPoints[bFrontFacing ? i : i+1];
Vector v2 = pVecPoints[bFrontFacing ? i+1 : i];
CDebugOverlay::AddTriangleOverlay(v0, v1, v2, r, g, b, 20, true, 0 );
}
// Draw solid lines around the polygon
for (int i=0; i<nNumVerts; i++)
{
Vector v0 = pVecPoints[i];
Vector v1 = pVecPoints[ (i+1) % nNumVerts];
CDebugOverlay::AddLineOverlay( v0, v1, 255, 255, 255, 255, false, 0);
}
}
void DrawPolygonToStencil( IMatRenderContext *pRenderContext, int nNumVerts, Vector *pVecPoints, bool bFrontFacing, bool bNearPlane )
{
IMaterial *pMaterial = materials->FindMaterial( "engine/writestencil", TEXTURE_GROUP_OTHER, true );
pRenderContext->Bind( pMaterial );
IMesh* pMesh = pRenderContext->GetDynamicMesh( true );
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, nNumVerts-2 );
// Fan out from vertex zero
for (int i=1; i<(nNumVerts-1); i++)
{
meshBuilder.Position3f( pVecPoints[0].x, pVecPoints[0].y, pVecPoints[0].z );
meshBuilder.AdvanceVertex();
int index = bFrontFacing ? i : i+1;
meshBuilder.Position3f( pVecPoints[index].x, pVecPoints[index].y, pVecPoints[index].z );
meshBuilder.AdvanceVertex();
index = bFrontFacing ? i+1 : i;
meshBuilder.Position3f( pVecPoints[index].x, pVecPoints[index].y, pVecPoints[index].z );
meshBuilder.AdvanceVertex();
}
meshBuilder.End( false, true );
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PopMatrix();
}
// Determine if two Vectors are sufficiently close (Manhattan-ish distance, not Euclidean)
bool SufficientlyClose( Vector v1, Vector v2, float flEpsilon )
{
if ( fabs( v1.x - v2.x ) > flEpsilon ) // Bail if x components are sufficiently different
return false;
if ( fabs( v1.y - v2.y ) > flEpsilon ) // Bail if y components are sufficiently different
return false;
if ( fabs( v1.z - v2.z ) > flEpsilon ) // Bail if z components are sufficiently different
return false;
return true;
}
int ClipPlaneToFrustum( Vector *pInPoints, Vector *pOutPoints, Vector *pVecWorldFrustumPoints )
{
Vector vClipPing[10]; // Vector lists to ping-pong between while clipping
Vector vClipPong[10]; //
bool bPing = true; // Ping holds the latest polygon
vClipPing[0] = pInPoints[0]; // Copy into Ping
vClipPing[1] = pInPoints[1];
vClipPing[2] = pInPoints[2];
vClipPing[3] = pInPoints[3];
int nNumPoints = 4;
for ( int i=0; i < 6; i++ )
{
Vector vNormal;
float flDist;
if ( nNumPoints < 3 ) // If we're already clipped away, bail out entirely
break;
Vector *pClipPolygon = pVecWorldFrustumPoints+(4*i); // Polygon defining clip plane
ComputeTrianglePlane( pClipPolygon[0], pClipPolygon[1], pClipPolygon[2], vNormal, flDist ); // Compute plane normal and dist
if ( bPing )
nNumPoints = ClipPolyToPlane( vClipPing, nNumPoints, vClipPong, vNormal, flDist ); // Clip Ping into Pong
else
nNumPoints = ClipPolyToPlane( vClipPong, nNumPoints, vClipPing, vNormal, flDist ); // Clip Pong into Ping
bPing = !bPing; // Flip buffers
}
if ( nNumPoints < 3)
return 0;
if ( bPing )
memcpy( pOutPoints, vClipPing, nNumPoints * sizeof(Vector) );
else
memcpy( pOutPoints, vClipPong, nNumPoints * sizeof(Vector) );
return nNumPoints;
}
void CShadowMgr::SetStencilAndScissor( IMatRenderContext *pRenderContext, FlashlightInfo_t &flashlightInfo, bool bUseStencil )
{
VMatrix matFlashlightToWorld;
MatrixInverseGeneral( m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow, matFlashlightToWorld );
// Eight points defining the frustum in Flashlight space
Vector vFrustumPoints[24] = { Vector(0.0f, 0.0f, 0.0f), Vector(1.0f, 0.0f, 0.0f), Vector(1.0f, 1.0f, 0.0f), Vector(0.0f, 1.0f, 0.0f), // Near
Vector(0.0f, 0.0f, 1.0f), Vector(0.0f, 1.0f, 1.0f), Vector(1.0f, 1.0f, 1.0f), Vector(1.0f, 0.0f, 1.0f), // Far
Vector(1.0f, 0.0f, 0.0f), Vector(1.0f, 0.0f, 1.0f), Vector(1.0f, 1.0f, 1.0f), Vector(1.0f, 1.0f, 0.0f), // Right
Vector(0.0f, 0.0f, 0.0f), Vector(0.0f, 1.0f, 0.0f), Vector(0.0f, 1.0f, 1.0f), Vector(0.0f, 0.0f, 1.0f), // Left
Vector(0.0f, 1.0f, 0.0f), Vector(1.0f, 1.0f, 0.0f), Vector(1.0f, 1.0f, 1.0f), Vector(0.0f, 1.0f, 1.0f), // Bottom
Vector(0.0f, 0.0f, 0.0f), Vector(0.0f, 0.0f, 1.0f), Vector(1.0f, 0.0f, 1.0f), Vector(1.0f, 0.0f, 0.0f)}; // Top
// Transform points to world space
Vector vWorldFrustumPoints[24];
for ( int i=0; i < 24; i++ )
{
matFlashlightToWorld.V3Mul( vFrustumPoints[i], vWorldFrustumPoints[i] );
}
// Express near and far planes of View frustum in world space
Frustum frustumPlanes;
const float flPlaneEpsilon = 0.4f;
ExtractFrustumPlanes( frustumPlanes, flPlaneEpsilon );
Vector vNearNormal = frustumPlanes[FRUSTUM_NEARZ].m_Normal;
Vector vFarNormal = frustumPlanes[FRUSTUM_FARZ].m_Normal;
float flNearDist = frustumPlanes[FRUSTUM_NEARZ].m_Dist;
float flFarDist = frustumPlanes[FRUSTUM_FARZ].m_Dist;
Vector vTempFace[5];
Vector vClippedFace[6];
Vector vClippedPolygons[8][10]; // Array of up to eight polygons (10 verts is more than enough for each)
int nNumVertices[8]; // Number vertices on each of the of clipped polygons
int nNumPolygons = 0; // How many polygons have survived the clip
// Clip each face individually to near and far planes
for ( int i=0; i < 6; i++ )
{
Vector *inVerts = vWorldFrustumPoints+(4*i); // Series of quadrilateral inputs
Vector *tempVerts = vTempFace;
Vector *outVerts = vClippedFace;
int nClipCount = ClipPolyToPlane( inVerts, 4, tempVerts, vNearNormal, flNearDist ); // need to set fOnPlaneEpsilon?
if ( nClipCount > 2 ) // If the polygon survived the near clip, try the far as well
{
nClipCount = ClipPolyToPlane( tempVerts, nClipCount, outVerts, vFarNormal, flFarDist ); // need to set fOnPlaneEpsilon?
if ( nClipCount > 2 ) // If we still have a poly after clipping to both planes, add it to the list
{
memcpy( vClippedPolygons[nNumPolygons], outVerts, nClipCount * sizeof (Vector) );
nNumVertices[nNumPolygons] = nClipCount;
nNumPolygons++;
}
}
}
// Construct polygons for near and far planes
Vector vNearPlane[4], vFarPlane[4];
ConstructNearAndFarPolygons( vNearPlane, vFarPlane, flPlaneEpsilon );
bool bNearPlane = false;
// Clip near plane to flashlight frustum and tack on to list
int nClipCount = ClipPlaneToFrustum( vNearPlane, vClippedPolygons[nNumPolygons], vWorldFrustumPoints );
if ( nClipCount > 2 ) // If the near plane clipped and resulted in a polygon, take note in the polygon list
{
nNumVertices[nNumPolygons] = nClipCount;
nNumPolygons++;
bNearPlane = true;
}
/*
TODO: do we even need to do the far plane?
// Clip near plane to flashlight frustum and tack on to list
nClipCount = ClipPlaneToFrustum( vFarPlane, vClippedPolygons[nNumPolygons], vWorldFrustumPoints );
if ( nClipCount > 2 ) // If the near plane clipped and resulted in a polygon, take note in the polygon list
{
nNumVertices[nNumPolygons] = nClipCount;
nNumPolygons++;
}
*/
// Fuse positions of any verts which are within epsilon
for (int i=0; i<nNumPolygons; i++) // For each polygon
{
for (int j=0; j<nNumVertices[i]; j++) // For each vertex
{
for (int k=i+1; k<nNumPolygons; k++) // For each later polygon
{
for (int m=0; m<nNumVertices[k]; m++) // For each vertex
{
if ( SufficientlyClose(vClippedPolygons[i][j], vClippedPolygons[k][m], 0.1f) )
{
vClippedPolygons[k][m] = vClippedPolygons[i][j];
}
}
}
}
}
// Calculate scissoring rect
flashlightInfo.m_FlashlightState.m_bScissor = false;
if ( r_flashlightscissor.GetBool() && (nNumPolygons > 0) )
{
int nLeft, nTop, nRight, nBottom;
flashlightInfo.m_FlashlightState.m_bScissor = ScreenSpaceRectFromPoints( pRenderContext, vClippedPolygons, nNumVertices, nNumPolygons, &nLeft, &nTop, &nRight, &nBottom );
if ( flashlightInfo.m_FlashlightState.m_bScissor )
{
flashlightInfo.m_FlashlightState.m_nLeft = nLeft;
flashlightInfo.m_FlashlightState.m_nTop = nTop;
flashlightInfo.m_FlashlightState.m_nRight = nRight;
flashlightInfo.m_FlashlightState.m_nBottom = nBottom;
}
}
if ( r_flashlightdrawclip.GetBool() && r_flashlightclip.GetBool() && bUseStencil )
{
// Draw back facing debug polygons
for (int i=0; i<nNumPolygons; i++)
{
DrawDebugPolygon( nNumVertices[i], vClippedPolygons[i], false, false );
}
/*
// Draw front facing debug polygons
for (int i=0; i<nNumPolygons; i++)
{
DrawDebugPolygon( nNumVertices[i], vClippedPolygons[i], true, bNearPlane && (i == nNumPolygons-1) );
}
*/
}
if ( r_flashlightclip.GetBool() && bUseStencil )
{
/*
// The traditional settings...
// Set up to set stencil bit on front facing polygons
pRenderContext->SetStencilEnable( true );
pRenderContext->SetStencilFailOperation( STENCILOPERATION_KEEP ); // Stencil fails
pRenderContext->SetStencilZFailOperation( STENCILOPERATION_KEEP ); // Stencil passes but depth fails
pRenderContext->SetStencilPassOperation( STENCILOPERATION_REPLACE ); // Z and stencil both pass
pRenderContext->SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_ALWAYS ); // Stencil always pass
pRenderContext->SetStencilReferenceValue( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit );
pRenderContext->SetStencilTestMask( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit );
pRenderContext->SetStencilWriteMask( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit ); // Bit mask which is specific to this shadow
*/
// Just blast front faces into the stencil buffer no matter what...
pRenderContext->SetStencilEnable( true );
pRenderContext->SetStencilFailOperation( STENCILOPERATION_REPLACE ); // Stencil fails
pRenderContext->SetStencilZFailOperation( STENCILOPERATION_REPLACE ); // Stencil passes but depth fails
pRenderContext->SetStencilPassOperation( STENCILOPERATION_REPLACE ); // Z and stencil both pass
pRenderContext->SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_ALWAYS ); // Stencil always pass
pRenderContext->SetStencilReferenceValue( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit );
pRenderContext->SetStencilTestMask( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit );
pRenderContext->SetStencilWriteMask( m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit ); // Bit mask which is specific to this shadow
for ( int i=0; i<nNumPolygons; i++ ) // Set the stencil bit on front facing
{
DrawPolygonToStencil( pRenderContext, nNumVertices[i], vClippedPolygons[i], true, false );
}
/*
pRenderContext->SetStencilReferenceValue( 0x00000000 ); // All bits cleared
for (int i=0; i<nNumPolygons; i++) // Clear the stencil bit on back facing
{
DrawPolygonToStencil( nNumVertices[i], vClippedPolygons[i], false, false );
}
*/
pRenderContext->SetStencilEnable( false );
}
}
//---------------------------------------------------------------------------------------
// Set masking stencil bits for all flashlights
//---------------------------------------------------------------------------------------
void CShadowMgr::SetFlashlightStencilMasks( bool bDoMasking )
{
VPROF_BUDGET( "CShadowMgr::RenderFlashlights", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
// Bail out if we're not doing any of these optimizations
if ( !( r_flashlightclip.GetBool() || r_flashlightscissor.GetBool()) )
return;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
CMatRenderContextPtr pRenderContext( materials );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
SetStencilAndScissor( pRenderContext, flashlightInfo, m_Shadows[flashlightInfo.m_Shadow].m_pFlashlightDepthTexture != NULL );
}
}
void CShadowMgr::DisableStencilAndScissorMasking( IMatRenderContext *pRenderContext )
{
if ( r_flashlightclip.GetBool() )
{
pRenderContext->SetStencilEnable( false );
}
// Scissor even if we're not shadow depth mapping
if ( r_flashlightscissor.GetBool() )
{
pRenderContext->SetScissorRect( -1, -1, -1, -1, false );
}
}
//---------------------------------------------------------------------------------------
// Enable/Disable masking based on stencil bit
//---------------------------------------------------------------------------------------
void CShadowMgr::EnableStencilAndScissorMasking( IMatRenderContext *pRenderContext, const FlashlightInfo_t &flashlightInfo, bool bDoMasking )
{
// Bail out if we're not doing any of these optimizations
if ( !( r_flashlightclip.GetBool() || r_flashlightscissor.GetBool()) || !bDoMasking )
return;
// Only turn on scissor when rendering to the back buffer
if ( pRenderContext->GetRenderTarget() == NULL )
{
// Only do the stencil optimization when shadow depth mapping
if ( r_flashlightclip.GetBool() && m_Shadows[flashlightInfo.m_Shadow].m_pFlashlightDepthTexture != NULL )
{
unsigned char ucShadowStencilBit = m_Shadows[flashlightInfo.m_Shadow].m_ucShadowStencilBit;
pRenderContext->SetStencilEnable( true );
pRenderContext->SetStencilFailOperation( STENCILOPERATION_KEEP ); // Stencil fails
pRenderContext->SetStencilZFailOperation( STENCILOPERATION_KEEP ); // Stencil passes but depth fails
pRenderContext->SetStencilPassOperation( STENCILOPERATION_KEEP ); // Z and stencil both pass
pRenderContext->SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ); // Bit must be set
pRenderContext->SetStencilReferenceValue( ucShadowStencilBit ); // Specific bit
pRenderContext->SetStencilTestMask( ucShadowStencilBit ); // Specific bit
pRenderContext->SetStencilWriteMask( 0x00000000 );
}
// Scissor even if we're not shadow depth mapping
if ( r_flashlightscissor.GetBool() && flashlightInfo.m_FlashlightState.m_bScissor )
{
pRenderContext->SetScissorRect( flashlightInfo.m_FlashlightState.m_nLeft, flashlightInfo.m_FlashlightState.m_nTop,
flashlightInfo.m_FlashlightState.m_nRight, flashlightInfo.m_FlashlightState.m_nBottom, true );
}
}
else // disable
{
DisableStencilAndScissorMasking( pRenderContext );
}
}
//---------------------------------------------------------------------------------------
// Sets the render states necessary to render a flashlight
//---------------------------------------------------------------------------------------
void CShadowMgr::SetFlashlightRenderState( ShadowHandle_t handle )
{
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
if ( handle == SHADOW_HANDLE_INVALID )
{
pRenderContext->SetFlashlightMode( false );
return;
}
const Shadow_t &shadow = m_Shadows[handle];
pRenderContext->SetFlashlightMode( true );
const FlashlightInfo_t &flashlightInfo = m_FlashlightStates[ shadow.m_FlashlightHandle ];
pRenderContext->SetFlashlightStateEx( flashlightInfo.m_FlashlightState, shadow.m_WorldToShadow, shadow.m_pFlashlightDepthTexture );
}
//---------------------------------------------------------------------------------------
// Render all of the world and displacement surfaces that need to be drawn for flashlights
//---------------------------------------------------------------------------------------
void CShadowMgr::RenderFlashlights( bool bDoMasking, const VMatrix* pModelToWorld )
{
#ifndef SWDS
VPROF_BUDGET( "CShadowMgr::RenderFlashlights", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
if( r_flashlightrender.GetBool()==false )
return;
// Draw the projective light sources, which get their material
// from the surface and not from the shadow.
// Tell the materialsystem that we are drawing additive flashlight lighting.
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
bool bWireframe = r_shadowwireframe.GetBool();
CMatRenderContextPtr pRenderContext( materials );
PIXEVENT( pRenderContext, "CShadowMgr::RenderFlashlights" );
pRenderContext->SetFlashlightMode( true );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
CMaterialsBuckets<SurfaceHandle_t> &materialBuckets = flashlightInfo.m_MaterialBuckets;
CMaterialsBuckets<SurfaceHandle_t>::SortIDHandle_t sortIDHandle = materialBuckets.GetFirstUsedSortID();
if ( sortIDHandle == materialBuckets.InvalidSortIDHandle() )
continue;
pRenderContext->SetFlashlightStateEx(flashlightInfo.m_FlashlightState, m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow, m_Shadows[flashlightInfo.m_Shadow].m_pFlashlightDepthTexture );
EnableStencilAndScissorMasking( pRenderContext, flashlightInfo, bDoMasking );
for( ; sortIDHandle != materialBuckets.InvalidSortIDHandle();
sortIDHandle = materialBuckets.GetNextUsedSortID( sortIDHandle ) )
{
int sortID = materialBuckets.GetSortID( sortIDHandle );
if( bWireframe )
{
pRenderContext->Bind( g_materialWorldWireframe );
}
else
{
pRenderContext->Bind( materialSortInfoArray[sortID].material );
pRenderContext->BindLightmapPage( materialSortInfoArray[sortID].lightmapPageID );
}
CMaterialsBuckets<SurfaceHandle_t>::ElementHandle_t elemHandle;
// Figure out how many indices we have.
int numIndices = 0;
for( elemHandle = materialBuckets.GetElementListHead( sortID );
elemHandle != materialBuckets.InvalidElementHandle();
elemHandle = materialBuckets.GetElementListNext( elemHandle ) )
{
SurfaceHandle_t surfID = materialBuckets.GetElement( elemHandle );
if( !SurfaceHasDispInfo( surfID ) )
{
numIndices += 3 * ( MSurf_VertCount( surfID ) - 2 );
}
}
if( numIndices > 0 )
{
// NOTE: If we ever need to make this faster, we could get larger
// batches here.
// Draw this batch.
#if NEWMESH
IIndexBuffer *pIndexBuffer = pRenderContext->GetDynamicIndexBuffer( MATERIAL_INDEX_FORMAT_16BIT );
CIndexBufferBuilder indexBufferBuilder;
indexBufferBuilder.Begin( pIndexBuffer, numIndices );
#else
IMesh *pMesh = pRenderContext->GetDynamicMesh( false, g_WorldStaticMeshes[sortID], 0 );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, 0, numIndices );
#endif
for( elemHandle = materialBuckets.GetElementListHead( sortID );
elemHandle != materialBuckets.InvalidElementHandle();
elemHandle = materialBuckets.GetElementListNext( elemHandle ) )
{
SurfaceHandle_t surfID = materialBuckets.GetElement( elemHandle );
if( !SurfaceHasDispInfo( surfID ) )
{
#if NEWMESH
BuildIndicesForWorldSurface( indexBufferBuilder, surfID, host_state.worldbrush );
#else
BuildIndicesForWorldSurface( meshBuilder, surfID, host_state.worldbrush );
#endif
}
}
// close out the index buffer
#if NEWMESH
indexBufferBuilder.End( false ); // haven't tested this one yet (flashlights)
// FIXME: IMaterial::GetVertexFormat() should do this stripping (add a separate 'SupportsCompression' accessor)
VertexFormat_t vertexFormat = materialSortInfoArray[sortID].material->GetVertexFormat() & ~VERTEX_FORMAT_COMPRESSED;
pRenderContext->BindVertexBuffer( 0, g_WorldStaticMeshes[sortID], 0, materialSortInfoArray[sortID].material->GetVertexFormat() ); // hack fixme. . . use currently bound material format instead of passing in?
pRenderContext->BindIndexBuffer( pIndexBuffer, 0 );
pRenderContext->Draw( MATERIAL_TRIANGLES, 0, numIndices );
#else
meshBuilder.End( false, true );
#endif
}
// NOTE: If we ever need to make this faster, we could get larger batches here.
// Draw displacements
for( elemHandle = materialBuckets.GetElementListHead( sortID );
elemHandle != materialBuckets.InvalidElementHandle();
elemHandle = materialBuckets.GetElementListNext( elemHandle ) )
{
SurfaceHandle_t surfID = materialBuckets.GetElement( elemHandle );
if( SurfaceHasDispInfo( surfID ) )
{
CDispInfo *pDisp = ( CDispInfo * )MSurf_DispInfo( surfID );
Assert( pDisp );
if( bWireframe )
{
pDisp->SpecifyDynamicMesh();
}
else
{
Assert( pDisp && pDisp->m_pMesh && pDisp->m_pMesh->m_pMesh );
pDisp->m_pMesh->m_pMesh->Draw( pDisp->m_iIndexOffset, pDisp->m_nIndices );
}
}
}
}
}
// Tell the materialsystem that we are finished drawing additive flashlight lighting.
pRenderContext->SetFlashlightMode( false );
// Turn off stencil masking
DisableStencilAndScissorMasking( pRenderContext );
#endif
}
const Frustum_t &CShadowMgr::GetFlashlightFrustum( ShadowHandle_t handle )
{
Assert( m_Shadows[handle].m_Flags & SHADOW_FLASHLIGHT );
Assert( m_Shadows[handle].m_FlashlightHandle != m_Shadows.InvalidIndex() );
return m_FlashlightStates[m_Shadows[handle].m_FlashlightHandle].m_Frustum;
}
const FlashlightState_t &CShadowMgr::GetFlashlightState( ShadowHandle_t handle )
{
Assert( m_Shadows[handle].m_Flags & SHADOW_FLASHLIGHT );
Assert( m_Shadows[handle].m_FlashlightHandle != m_Shadows.InvalidIndex() );
return m_FlashlightStates[m_Shadows[handle].m_FlashlightHandle].m_FlashlightState;
}
void CShadowMgr::DrawFlashlightDecals( int sortGroup, bool bDoMasking )
{
VPROF_BUDGET( "CShadowMgr::DrawFlashlightDecals", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->SetFlashlightMode( true );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
pRenderContext->SetFlashlightState(flashlightInfo.m_FlashlightState, m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow );
EnableStencilAndScissorMasking( pRenderContext, flashlightInfo, bDoMasking );
DecalSurfaceDraw( pRenderContext, sortGroup );
}
// Tell the materialsystem that we are finished drawing additive flashlight lighting.
pRenderContext->SetFlashlightMode( false );
// Turn off stencil masking
DisableStencilAndScissorMasking( pRenderContext );
}
void CShadowMgr::DrawFlashlightDecalsOnDisplacements( int sortGroup, CDispInfo *visibleDisps[MAX_MAP_DISPINFO], int nVisibleDisps, bool bDoMasking )
{
VPROF_BUDGET( "CShadowMgr::DrawFlashlightDecalsOnDisplacements", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->SetFlashlightMode( true );
DispInfo_BatchDecals( visibleDisps, nVisibleDisps );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
pRenderContext->SetFlashlightState(flashlightInfo.m_FlashlightState, m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow );
EnableStencilAndScissorMasking( pRenderContext, flashlightInfo, bDoMasking );
DispInfo_DrawDecals( visibleDisps, nVisibleDisps );
}
// Tell the materialsystem that we are finished drawing additive flashlight lighting.
pRenderContext->SetFlashlightMode( false );
// Turn off stencil masking
DisableStencilAndScissorMasking( pRenderContext );
}
void CShadowMgr::DrawFlashlightDecalsOnSingleSurface( SurfaceHandle_t surfID, bool bDoMasking )
{
VPROF_BUDGET( "CShadowMgr::DrawFlashlightDecalsOnSingleSurface", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->SetFlashlightMode( true );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
pRenderContext->SetFlashlightState(flashlightInfo.m_FlashlightState, m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow );
EnableStencilAndScissorMasking( pRenderContext, flashlightInfo, bDoMasking );
DrawDecalsOnSingleSurface( pRenderContext, surfID );
}
// Tell the materialsystem that we are finished drawing additive flashlight lighting.
pRenderContext->SetFlashlightMode( false );
// Turn off stencil masking
DisableStencilAndScissorMasking( pRenderContext );
}
void CShadowMgr::DrawFlashlightOverlays( int nSortGroup, bool bDoMasking )
{
VPROF_BUDGET( "CShadowMgr::DrawFlashlightOverlays", VPROF_BUDGETGROUP_SHADOW_RENDERING );
if ( IsX360() || r_flashlight_version2.GetInt() )
return;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
if ( flashlightID == m_FlashlightStates.InvalidIndex() )
return;
if ( r_flashlightrender.GetBool()==false )
return;
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->SetFlashlightMode( true );
for( ;
flashlightID != m_FlashlightStates.InvalidIndex();
flashlightID = m_FlashlightStates.Next( flashlightID ) )
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[flashlightID];
pRenderContext->SetFlashlightState(flashlightInfo.m_FlashlightState, m_Shadows[flashlightInfo.m_Shadow].m_WorldToShadow );
EnableStencilAndScissorMasking( pRenderContext, flashlightInfo, bDoMasking );
OverlayMgr()->RenderOverlays( nSortGroup );
}
// Tell the materialsystem that we are finished drawing additive flashlight lighting.
pRenderContext->SetFlashlightMode( false );
// Turn off stencil masking
DisableStencilAndScissorMasking( pRenderContext );
}
void CShadowMgr::DrawFlashlightDepthTexture( )
{
int i = 0;
FlashlightHandle_t flashlightID = m_FlashlightStates.Head();
while ( flashlightID != m_FlashlightStates.InvalidIndex() ) // Count up the shadows
{
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[ flashlightID ];
if( m_Shadows[ flashlightInfo.m_Shadow ].m_pFlashlightDepthTexture )
{
bool foundVar;
IMaterial *pMaterial = materials->FindMaterial( "debug/showz", TEXTURE_GROUP_OTHER, true );
IMaterialVar *BaseTextureVar = pMaterial->FindVar( "$basetexture", &foundVar, false );
if (!foundVar)
return;
IMaterialVar *FrameVar = pMaterial->FindVar( "$frame", &foundVar, false );
if (!foundVar)
return;
float w = 256.0f, h = 256.0f;
float wOffset = (i % 2) * 256.0f; // Even|Odd go left|right
float hOffset = (i / 2) * 256.0f; // Rows of two
BaseTextureVar->SetTextureValue( m_Shadows[ flashlightInfo.m_Shadow ].m_pFlashlightDepthTexture );
FrameVar->SetIntValue( 0 );
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->Bind( pMaterial );
IMesh* pMesh = pRenderContext->GetDynamicMesh( true );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Position3f( wOffset, hOffset, 0.0f );
#ifdef DX_TO_GL_ABSTRACTION
meshBuilder.TexCoord2f( 0, 0.0f, 1.0f ); // Posix is rotated due to render target origin differences
#else
meshBuilder.TexCoord2f( 0, 0.0f, 0.0f );
#endif
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( wOffset + w, hOffset, 0.0f );
#ifdef DX_TO_GL_ABSTRACTION
meshBuilder.TexCoord2f( 0, 0.0f, 0.0f );
#else
meshBuilder.TexCoord2f( 0, 1.0f, 0.0f );
#endif
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( wOffset + w, hOffset + h, 0.0f );
#ifdef DX_TO_GL_ABSTRACTION
meshBuilder.TexCoord2f( 0, 1.0f, 0.0f );
#else
meshBuilder.TexCoord2f( 0, 1.0f, 1.0f );
#endif
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( wOffset, hOffset + h, 0.0f );
#ifdef DX_TO_GL_ABSTRACTION
meshBuilder.TexCoord2f( 0, 1.0f, 1.0f );
#else
meshBuilder.TexCoord2f( 0, 0.0f, 1.0f );
#endif
meshBuilder.AdvanceVertex();
meshBuilder.End();
pMesh->Draw();
i++;
}
flashlightID = m_FlashlightStates.Next( flashlightID );
}
}
void CShadowMgr::AddFlashlightRenderable( ShadowHandle_t shadowHandle, IClientRenderable *pRenderable )
{
Shadow_t &shadow = m_Shadows[ shadowHandle ];
FlashlightInfo_t &flashlightInfo = m_FlashlightStates[ shadow.m_FlashlightHandle ];
if( pRenderable->GetModelInstance() != MODEL_INSTANCE_INVALID )
{
flashlightInfo.m_Renderables.AddToTail( pRenderable );
}
}
|