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
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Revision: $
// $NoKeywords: $
//
// This file contains code to allow us to associate client data with bsp leaves.
//
//=============================================================================//
#include "vrad.h"
#include "mathlib/vector.h"
#include "UtlBuffer.h"
#include "utlvector.h"
#include "GameBSPFile.h"
#include "BSPTreeData.h"
#include "VPhysics_Interface.h"
#include "Studio.h"
#include "Optimize.h"
#include "Bsplib.h"
#include "CModel.h"
#include "PhysDll.h"
#include "phyfile.h"
#include "collisionutils.h"
#include "tier1/KeyValues.h"
#include "pacifier.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/hardwareverts.h"
#include "materialsystem/hardwaretexels.h"
#include "byteswap.h"
#include "mpivrad.h"
#include "vtf/vtf.h"
#include "tier1/utldict.h"
#include "tier1/utlsymbol.h"
#include "bitmap/tgawriter.h"
#include "messbuf.h"
#include "vmpi.h"
#include "vmpi_distribute_work.h"
#define ALIGN_TO_POW2(x,y) (((x)+(y-1))&~(y-1))
// identifies a vertex embedded in solid
// lighting will be copied from nearest valid neighbor
struct badVertex_t
{
int m_ColorVertex;
Vector m_Position;
Vector m_Normal;
};
// a final colored vertex
struct colorVertex_t
{
Vector m_Color;
Vector m_Position;
bool m_bValid;
};
// a texel suitable for a model
struct colorTexel_t
{
Vector m_Color;
Vector m_WorldPosition;
Vector m_WorldNormal;
float m_fDistanceToTri; // If we are outside of the triangle, how far away is it?
bool m_bValid;
bool m_bPossiblyInteresting;
};
class CComputeStaticPropLightingResults
{
public:
~CComputeStaticPropLightingResults()
{
m_ColorVertsArrays.PurgeAndDeleteElements();
m_ColorTexelsArrays.PurgeAndDeleteElements();
}
CUtlVector< CUtlVector<colorVertex_t>* > m_ColorVertsArrays;
CUtlVector< CUtlVector<colorTexel_t>* > m_ColorTexelsArrays;
};
//-----------------------------------------------------------------------------
struct Rasterizer
{
struct Location
{
Vector barycentric;
Vector2D uv;
bool insideTriangle;
};
Rasterizer(Vector2D t0, Vector2D t1, Vector2D t2, size_t resX, size_t resY)
: mT0(t0)
, mT1(t1)
, mT2(t2)
, mResX(resX)
, mResY(resY)
, mUvStepX(1.0f / resX)
, mUvStepY(1.0f / resY)
{
Build();
}
CUtlVector< Location >::iterator begin() { return mRasterizedLocations.begin(); }
CUtlVector< Location >::iterator end() { return mRasterizedLocations.end(); }
void Build();
inline size_t GetRow(float y) const { return size_t(y * mResY); }
inline size_t GetCol(float x) const { return size_t(x * mResX); }
inline size_t GetLinearPos( const CUtlVector< Location >::iterator& it ) const
{
// Given an iterator, return what the linear position in the buffer would be for the data.
return (size_t)(GetRow(it->uv.y) * mResX)
+ (size_t)(GetCol(it->uv.x));
}
private:
const Vector2D mT0, mT1, mT2;
const size_t mResX, mResY;
const float mUvStepX, mUvStepY;
// Right now, we just fill this out and directly iterate over it.
// It could be large. This is a memory/speed tradeoff. We could instead generate them
// on demand.
CUtlVector< Location > mRasterizedLocations;
};
//-----------------------------------------------------------------------------
inline Vector ComputeBarycentric( Vector2D _edgeC, Vector2D _edgeA, Vector2D _edgeB, float _dAA, float _dAB, float _dBB, float _invDenom )
{
float dCA = _edgeC.Dot(_edgeA);
float dCB = _edgeC.Dot(_edgeB);
Vector retVal;
retVal.y = (_dBB * dCA - _dAB * dCB) * _invDenom;
retVal.z = (_dAA * dCB - _dAB * dCA) * _invDenom;
retVal.x = 1.0f - retVal.y - retVal.z;
return retVal;
}
//-----------------------------------------------------------------------------
void Rasterizer::Build()
{
// For now, use the barycentric method. It's easy, I'm lazy.
// We can optimize later if it's a performance issue.
const float baseX = mUvStepX / 2.0f;
const float baseY = mUvStepY / 2.0f;
float fMinX = min(min(mT0.x, mT1.x), mT2.x);
float fMinY = min(min(mT0.y, mT1.y), mT2.y);
float fMaxX = max(max(mT0.x, mT1.x), mT2.x);
float fMaxY = max(max(mT0.y, mT1.y), mT2.y);
// Degenerate. Consider warning about these, but otherwise no problem.
if (fMinX == fMaxX || fMinY == fMaxY)
return;
// Clamp to 0..1
fMinX = max(0, fMinX);
fMinY = max(0, fMinY);
fMaxX = min(1.0f, fMaxX);
fMaxY = min(1.0f, fMaxY);
// We puff the interesting area up by 1 so we can hit an inflated region for the necessary bilerp data.
// If we wanted to support better texturing (almost definitely unnecessary), we'd change this to a larger size.
const int kFilterSampleRadius = 1;
int iMinX = GetCol(fMinX) - kFilterSampleRadius;
int iMinY = GetRow(fMinY) - kFilterSampleRadius;
int iMaxX = GetCol(fMaxX) + 1 + kFilterSampleRadius;
int iMaxY = GetRow(fMaxY) + 1 + kFilterSampleRadius;
// Clamp to valid texture (integer) locations
iMinX = max(0, iMinX);
iMinY = max(0, iMinY);
iMaxX = min(iMaxX, mResX - 1);
iMaxY = min(iMaxY, mResY - 1);
// Set the size to be as expected.
// TODO: Pass this in from outside to minimize allocations
int count = (iMaxY - iMinY + 1)
* (iMaxX - iMinX + 1);
mRasterizedLocations.EnsureCount(count);
memset( mRasterizedLocations.Base(), 0, mRasterizedLocations.Count() * sizeof( Location ) );
// Computing Barycentrics adapted from here http://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates
Vector2D edgeA = mT1 - mT0;
Vector2D edgeB = mT2 - mT0;
float dAA = edgeA.Dot(edgeA);
float dAB = edgeA.Dot(edgeB);
float dBB = edgeB.Dot(edgeB);
float invDenom = 1.0f / (dAA * dBB - dAB * dAB);
int linearPos = 0;
for (int j = iMinY; j <= iMaxY; ++j) {
for (int i = iMinX; i <= iMaxX; ++i) {
Vector2D testPt( i * mUvStepX + baseX, j * mUvStepY + baseY );
Vector barycentric = ComputeBarycentric( testPt - mT0, edgeA, edgeB, dAA, dAB, dBB, invDenom );
// Test whether the point is inside the triangle.
// MCJOHNTODO: Edge rules and whatnot--right now we re-rasterize points on the edge.
Location& newLoc = mRasterizedLocations[linearPos++];
newLoc.barycentric = barycentric;
newLoc.uv = testPt;
newLoc.insideTriangle = (barycentric.x >= 0.0f && barycentric.x <= 1.0f && barycentric.y >= 0.0f && barycentric.y <= 1.0f && barycentric.z >= 0.0f && barycentric.z <= 1.0f);
}
}
}
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
CUtlSymbolTable g_ForcedTextureShadowsModels;
// DON'T USE THIS FROM WITHIN A THREAD. THERE IS A THREAD CONTEXT CREATED
// INSIDE PropTested_t. USE THAT INSTEAD.
IPhysicsCollision *s_pPhysCollision = NULL;
static void ConvertTexelDataToTexture(unsigned int _resX, unsigned int _resY, ImageFormat _destFmt, const CUtlVector<colorTexel_t>& _srcTexels, CUtlMemory<byte>* _outTexture);
// Such a monstrosity. :(
static void GenerateLightmapSamplesForMesh( const matrix3x4_t& _matPos, const matrix3x4_t& _matNormal, int _iThread, int _skipProp, int _nFlags, int _lightmapResX, int _lightmapResY,
studiohdr_t* _pStudioHdr, mstudiomodel_t* _pStudioModel, OptimizedModel::ModelHeader_t* _pVtxModel, int _meshID,
CComputeStaticPropLightingResults *_pResults );
// Debug function, converts lightmaps to linear space then dumps them out.
// TODO: Write out the file in a .dds instead of a .tga, in whatever format we're supposed to use.
static void DumpLightmapLinear( const char* _dstFilename, const CUtlVector<colorTexel_t>& _srcTexels, int _width, int _height );
//-----------------------------------------------------------------------------
// Vrad's static prop manager
//-----------------------------------------------------------------------------
class CVradStaticPropMgr : public IVradStaticPropMgr
{
public:
// constructor, destructor
CVradStaticPropMgr();
virtual ~CVradStaticPropMgr();
// methods of IStaticPropMgr
void Init();
void Shutdown();
// iterate all the instanced static props and compute their vertex lighting
void ComputeLighting( int iThread );
private:
// VMPI stuff.
static void VMPI_ProcessStaticProp_Static( int iThread, uint64 iStaticProp, MessageBuffer *pBuf );
static void VMPI_ReceiveStaticPropResults_Static( uint64 iStaticProp, MessageBuffer *pBuf, int iWorker );
void VMPI_ProcessStaticProp( int iThread, int iStaticProp, MessageBuffer *pBuf );
void VMPI_ReceiveStaticPropResults( int iStaticProp, MessageBuffer *pBuf, int iWorker );
// local thread version
static void ThreadComputeStaticPropLighting( int iThread, void *pUserData );
void ComputeLightingForProp( int iThread, int iStaticProp );
// Methods associated with unserializing static props
void UnserializeModelDict( CUtlBuffer& buf );
void UnserializeModels( CUtlBuffer& buf );
void UnserializeStaticProps();
// Creates a collision model
void CreateCollisionModel( char const* pModelName );
private:
// Unique static prop models
struct StaticPropDict_t
{
vcollide_t m_loadedModel;
CPhysCollide* m_pModel;
Vector m_Mins; // Bounding box is in local coordinates
Vector m_Maxs;
studiohdr_t* m_pStudioHdr;
CUtlBuffer m_VtxBuf;
CUtlVector<int> m_textureShadowIndex; // each texture has an index if this model casts texture shadows
CUtlVector<int> m_triangleMaterialIndex;// each triangle has an index if this model casts texture shadows
};
struct MeshData_t
{
CUtlVector<Vector> m_VertexColors;
CUtlMemory<byte> m_TexelsEncoded;
int m_nLod;
};
// A static prop instance
struct CStaticProp
{
Vector m_Origin;
QAngle m_Angles;
Vector m_mins;
Vector m_maxs;
Vector m_LightingOrigin;
int m_ModelIdx;
BSPTreeDataHandle_t m_Handle;
CUtlVector<MeshData_t> m_MeshData;
int m_Flags;
bool m_bLightingOriginValid;
// Note that all lightmaps for a given prop share the same resolution (and format)--and there can be multiple lightmaps
// per prop (if there are multiple pieces--the watercooler is an example).
// This is effectively because there's not a good way in hammer for a prop to say "this should be the resolution
// of each of my sub-pieces."
ImageFormat m_LightmapImageFormat;
unsigned int m_LightmapImageWidth;
unsigned int m_LightmapImageHeight;
};
// Enumeration context
struct EnumContext_t
{
PropTested_t* m_pPropTested;
Ray_t const* m_pRay;
};
// The list of all static props
CUtlVector <StaticPropDict_t> m_StaticPropDict;
CUtlVector <CStaticProp> m_StaticProps;
bool m_bIgnoreStaticPropTrace;
void ComputeLighting( CStaticProp &prop, int iThread, int prop_index, CComputeStaticPropLightingResults *pResults );
void ApplyLightingToStaticProp( int iStaticProp, CStaticProp &prop, const CComputeStaticPropLightingResults *pResults );
void SerializeLighting();
void AddPolysForRayTrace();
void BuildTriList( CStaticProp &prop );
};
//-----------------------------------------------------------------------------
// Expose IVradStaticPropMgr to vrad
//-----------------------------------------------------------------------------
static CVradStaticPropMgr g_StaticPropMgr;
IVradStaticPropMgr* StaticPropMgr()
{
return &g_StaticPropMgr;
}
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CVradStaticPropMgr::CVradStaticPropMgr()
{
// set to ignore static prop traces
m_bIgnoreStaticPropTrace = false;
}
CVradStaticPropMgr::~CVradStaticPropMgr()
{
}
//-----------------------------------------------------------------------------
// Makes sure the studio model is a static prop
//-----------------------------------------------------------------------------
bool IsStaticProp( studiohdr_t* pHdr )
{
if (!(pHdr->flags & STUDIOHDR_FLAGS_STATIC_PROP))
return false;
return true;
}
//-----------------------------------------------------------------------------
// Load a file into a Utlbuf
//-----------------------------------------------------------------------------
static bool LoadFile( char const* pFileName, CUtlBuffer& buf )
{
if ( !g_pFullFileSystem )
return false;
return g_pFullFileSystem->ReadFile( pFileName, NULL, buf );
}
//-----------------------------------------------------------------------------
// Constructs the file name from the model name
//-----------------------------------------------------------------------------
static char const* ConstructFileName( char const* pModelName )
{
static char buf[1024];
sprintf( buf, "%s%s", gamedir, pModelName );
return buf;
}
//-----------------------------------------------------------------------------
// Computes a convex hull from a studio mesh
//-----------------------------------------------------------------------------
static CPhysConvex* ComputeConvexHull( mstudiomesh_t* pMesh, studiohdr_t *pStudioHdr )
{
const mstudio_meshvertexdata_t *vertData = pMesh->GetVertexData( (void *)pStudioHdr );
Assert( vertData ); // This can only return NULL on X360 for now
// Generate a list of all verts in the mesh
Vector** ppVerts = (Vector**)_alloca(pMesh->numvertices * sizeof(Vector*) );
for (int i = 0; i < pMesh->numvertices; ++i)
{
ppVerts[i] = vertData->Position(i);
}
// Generate a convex hull from the verts
return s_pPhysCollision->ConvexFromVerts( ppVerts, pMesh->numvertices );
}
//-----------------------------------------------------------------------------
// Computes a convex hull from the studio model
//-----------------------------------------------------------------------------
CPhysCollide* ComputeConvexHull( studiohdr_t* pStudioHdr )
{
CUtlVector<CPhysConvex*> convexHulls;
for (int body = 0; body < pStudioHdr->numbodyparts; ++body )
{
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( body );
for( int model = 0; model < pBodyPart->nummodels; ++model )
{
mstudiomodel_t *pStudioModel = pBodyPart->pModel( model );
for( int mesh = 0; mesh < pStudioModel->nummeshes; ++mesh )
{
// Make a convex hull for each mesh
// NOTE: This won't work unless the model has been compiled
// with $staticprop
mstudiomesh_t *pStudioMesh = pStudioModel->pMesh( mesh );
convexHulls.AddToTail( ComputeConvexHull( pStudioMesh, pStudioHdr ) );
}
}
}
// Convert an array of convex elements to a compiled collision model
// (this deletes the convex elements)
return s_pPhysCollision->ConvertConvexToCollide( convexHulls.Base(), convexHulls.Size() );
}
//-----------------------------------------------------------------------------
// Load studio model vertex data from a file...
//-----------------------------------------------------------------------------
bool LoadStudioModel( char const* pModelName, CUtlBuffer& buf )
{
// No luck, gotta build it
// Construct the file name...
if (!LoadFile( pModelName, buf ))
{
Warning("Error! Unable to load model \"%s\"\n", pModelName );
return false;
}
// Check that it's valid
if (strncmp ((const char *) buf.PeekGet(), "IDST", 4) &&
strncmp ((const char *) buf.PeekGet(), "IDAG", 4))
{
Warning("Error! Invalid model file \"%s\"\n", pModelName );
return false;
}
studiohdr_t* pHdr = (studiohdr_t*)buf.PeekGet();
Studio_ConvertStudioHdrToNewVersion( pHdr );
if (pHdr->version != STUDIO_VERSION)
{
Warning("Error! Invalid model version \"%s\"\n", pModelName );
return false;
}
if (!IsStaticProp(pHdr))
{
Warning("Error! To use model \"%s\"\n"
" as a static prop, it must be compiled with $staticprop!\n", pModelName );
return false;
}
// ensure reset
pHdr->pVertexBase = NULL;
pHdr->pIndexBase = NULL;
return true;
}
bool LoadStudioCollisionModel( char const* pModelName, CUtlBuffer& buf )
{
char tmp[1024];
Q_strncpy( tmp, pModelName, sizeof( tmp ) );
Q_SetExtension( tmp, ".phy", sizeof( tmp ) );
// No luck, gotta build it
if (!LoadFile( tmp, buf ))
{
// this is not an error, the model simply has no PHY file
return false;
}
phyheader_t *header = (phyheader_t *)buf.PeekGet();
if ( header->size != sizeof(*header) || header->solidCount <= 0 )
return false;
return true;
}
bool LoadVTXFile( char const* pModelName, const studiohdr_t *pStudioHdr, CUtlBuffer& buf )
{
char filename[MAX_PATH];
// construct filename
Q_StripExtension( pModelName, filename, sizeof( filename ) );
strcat( filename, ".dx80.vtx" );
if ( !LoadFile( filename, buf ) )
{
Warning( "Error! Unable to load file \"%s\"\n", filename );
return false;
}
OptimizedModel::FileHeader_t* pVtxHdr = (OptimizedModel::FileHeader_t *)buf.Base();
// Check that it's valid
if ( pVtxHdr->version != OPTIMIZED_MODEL_FILE_VERSION )
{
Warning( "Error! Invalid VTX file version: %d, expected %d \"%s\"\n", pVtxHdr->version, OPTIMIZED_MODEL_FILE_VERSION, filename );
return false;
}
if ( pVtxHdr->checkSum != pStudioHdr->checksum )
{
Warning( "Error! Invalid VTX file checksum: %d, expected %d \"%s\"\n", pVtxHdr->checkSum, pStudioHdr->checksum, filename );
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Gets a vertex position from a strip index
//-----------------------------------------------------------------------------
inline static Vector* PositionFromIndex( const mstudio_meshvertexdata_t *vertData, mstudiomesh_t* pMesh, OptimizedModel::StripGroupHeader_t* pStripGroup, int i )
{
OptimizedModel::Vertex_t* pVert = pStripGroup->pVertex( i );
return vertData->Position( pVert->origMeshVertID );
}
//-----------------------------------------------------------------------------
// Purpose: Writes a glview text file containing the collision surface in question
// Input : *pCollide -
// *pFilename -
//-----------------------------------------------------------------------------
void DumpCollideToGlView( vcollide_t *pCollide, const char *pFilename )
{
if ( !pCollide )
return;
Msg("Writing %s...\n", pFilename );
FILE *fp = fopen( pFilename, "w" );
for (int i = 0; i < pCollide->solidCount; ++i)
{
Vector *outVerts;
int vertCount = s_pPhysCollision->CreateDebugMesh( pCollide->solids[i], &outVerts );
int triCount = vertCount / 3;
int vert = 0;
unsigned char r = (i & 1) * 64 + 64;
unsigned char g = (i & 2) * 64 + 64;
unsigned char b = (i & 4) * 64 + 64;
float fr = r / 255.0f;
float fg = g / 255.0f;
float fb = b / 255.0f;
for ( int i = 0; i < triCount; i++ )
{
fprintf( fp, "3\n" );
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
fprintf( fp, "%6.3f %6.3f %6.3f %.2f %.3f %.3f\n",
outVerts[vert].x, outVerts[vert].y, outVerts[vert].z, fr, fg, fb );
vert++;
}
s_pPhysCollision->DestroyDebugMesh( vertCount, outVerts );
}
fclose( fp );
}
static bool PointInTriangle( const Vector2D &p, const Vector2D &v0, const Vector2D &v1, const Vector2D &v2 )
{
float coords[3];
GetBarycentricCoords2D( v0, v1, v2, p, coords );
for ( int i = 0; i < 3; i++ )
{
if ( coords[i] < 0.0f || coords[i] > 1.0f )
return false;
}
float sum = coords[0] + coords[1] + coords[2];
if ( sum > 1.0f )
return false;
return true;
}
bool LoadFileIntoBuffer( CUtlBuffer &buf, const char *pFilename )
{
FileHandle_t fileHandle = g_pFileSystem->Open( pFilename, "rb" );
if ( !fileHandle )
return false;
// Get the file size
int texSize = g_pFileSystem->Size( fileHandle );
buf.EnsureCapacity( texSize );
int nBytesRead = g_pFileSystem->Read( buf.Base(), texSize, fileHandle );
g_pFileSystem->Close( fileHandle );
buf.SeekPut( CUtlBuffer::SEEK_HEAD, nBytesRead );
buf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
return true;
}
// keeps a list of all textures that cast shadows via alpha channel
class CShadowTextureList
{
public:
// This loads a vtf and converts it to RGB8888 format
unsigned char *LoadVTFRGB8888( const char *pName, int *pWidth, int *pHeight, bool *pClampU, bool *pClampV )
{
char szPath[MAX_PATH];
Q_strncpy( szPath, "materials/", sizeof( szPath ) );
Q_strncat( szPath, pName, sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_strncat( szPath, ".vtf", sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_FixSlashes( szPath, CORRECT_PATH_SEPARATOR );
CUtlBuffer buf;
if ( !LoadFileIntoBuffer( buf, szPath ) )
return NULL;
IVTFTexture *pTex = CreateVTFTexture();
if (!pTex->Unserialize( buf ))
return NULL;
Msg("Loaded alpha texture %s\n", szPath );
unsigned char *pSrcImage = pTex->ImageData( 0, 0, 0, 0, 0, 0 );
int iWidth = pTex->Width();
int iHeight = pTex->Height();
ImageFormat dstFormat = IMAGE_FORMAT_RGBA8888;
ImageFormat srcFormat = pTex->Format();
*pClampU = (pTex->Flags() & TEXTUREFLAGS_CLAMPS) ? true : false;
*pClampV = (pTex->Flags() & TEXTUREFLAGS_CLAMPT) ? true : false;
unsigned char *pDstImage = new unsigned char[ImageLoader::GetMemRequired( iWidth, iHeight, 1, dstFormat, false )];
if( !ImageLoader::ConvertImageFormat( pSrcImage, srcFormat,
pDstImage, dstFormat, iWidth, iHeight, 0, 0 ) )
{
delete[] pDstImage;
return NULL;
}
*pWidth = iWidth;
*pHeight = iHeight;
return pDstImage;
}
// Checks the database for the material and loads if necessary
// returns true if found and pIndex will be the index, -1 if no alpha shadows
bool FindOrLoadIfValid( const char *pMaterialName, int *pIndex )
{
*pIndex = -1;
int index = m_Textures.Find(pMaterialName);
bool bFound = false;
if ( index != m_Textures.InvalidIndex() )
{
bFound = true;
*pIndex = index;
}
else
{
KeyValues *pVMT = new KeyValues("vmt");
CUtlBuffer buf(0,0,CUtlBuffer::TEXT_BUFFER);
LoadFileIntoBuffer( buf, pMaterialName );
if ( pVMT->LoadFromBuffer( pMaterialName, buf ) )
{
bFound = true;
if ( pVMT->FindKey("$translucent") || pVMT->FindKey("$alphatest") )
{
KeyValues *pBaseTexture = pVMT->FindKey("$basetexture");
if ( pBaseTexture )
{
const char *pBaseTextureName = pBaseTexture->GetString();
if ( pBaseTextureName )
{
int w, h;
bool bClampU = false;
bool bClampV = false;
unsigned char *pImageBits = LoadVTFRGB8888( pBaseTextureName, &w, &h, &bClampU, &bClampV );
if ( pImageBits )
{
int index = m_Textures.Insert( pMaterialName );
m_Textures[index].InitFromRGB8888( w, h, pImageBits );
*pIndex = index;
if ( pVMT->FindKey("$nocull") )
{
// UNDONE: Support this? Do we need to emit two triangles?
m_Textures[index].allowBackface = true;
}
m_Textures[index].clampU = bClampU;
m_Textures[index].clampV = bClampV;
delete[] pImageBits;
}
}
}
}
}
pVMT->deleteThis();
}
return bFound;
}
// iterate the textures for the model and load each one into the database
// this is used on models marked to cast texture shadows
void LoadAllTexturesForModel( studiohdr_t *pHdr, int *pTextureList )
{
for ( int i = 0; i < pHdr->numtextures; i++ )
{
int textureIndex = -1;
// try to add each texture to the transparent shadow manager
char szPath[MAX_PATH];
// iterate quietly through all specified directories until a valid material is found
for ( int j = 0; j < pHdr->numcdtextures; j++ )
{
Q_strncpy( szPath, "materials/", sizeof( szPath ) );
Q_strncat( szPath, pHdr->pCdtexture( j ), sizeof( szPath ) );
const char *textureName = pHdr->pTexture( i )->pszName();
Q_strncat( szPath, textureName, sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_strncat( szPath, ".vmt", sizeof( szPath ), COPY_ALL_CHARACTERS );
Q_FixSlashes( szPath, CORRECT_PATH_SEPARATOR );
if ( FindOrLoadIfValid( szPath, &textureIndex ) )
break;
}
pTextureList[i] = textureIndex;
}
}
int AddMaterialEntry( int shadowTextureIndex, const Vector2D &t0, const Vector2D &t1, const Vector2D &t2 )
{
int index = m_MaterialEntries.AddToTail();
m_MaterialEntries[index].textureIndex = shadowTextureIndex;
m_MaterialEntries[index].uv[0] = t0;
m_MaterialEntries[index].uv[1] = t1;
m_MaterialEntries[index].uv[2] = t2;
return index;
}
// HACKHACK: Compute the average coverage for this triangle by sampling the AABB of its texture space
float ComputeCoverageForTriangle( int shadowTextureIndex, const Vector2D &t0, const Vector2D &t1, const Vector2D &t2 )
{
float umin = min(t0.x, t1.x);
umin = min(umin, t2.x);
float umax = max(t0.x, t1.x);
umax = max(umax, t2.x);
float vmin = min(t0.y, t1.y);
vmin = min(vmin, t2.y);
float vmax = max(t0.y, t1.y);
vmax = max(vmax, t2.y);
// UNDONE: Do something about tiling
umin = clamp(umin, 0, 1);
umax = clamp(umax, 0, 1);
vmin = clamp(vmin, 0, 1);
vmax = clamp(vmax, 0, 1);
Assert(umin>=0.0f && umax <= 1.0f);
Assert(vmin>=0.0f && vmax <= 1.0f);
const alphatexture_t &tex = m_Textures.Element(shadowTextureIndex);
int u0 = umin * (tex.width-1);
int u1 = umax * (tex.width-1);
int v0 = vmin * (tex.height-1);
int v1 = vmax * (tex.height-1);
int total = 0;
int count = 0;
for ( int v = v0; v <= v1; v++ )
{
int row = (v * tex.width);
for ( int u = u0; u <= u1; u++ )
{
total += tex.pAlphaTexels[row + u];
count++;
}
}
if ( count )
{
float coverage = float(total) / (count * 255.0f);
return coverage;
}
return 1.0f;
}
int SampleMaterial( int materialIndex, const Vector &coords, bool bBackface )
{
const materialentry_t &mat = m_MaterialEntries[materialIndex];
const alphatexture_t &tex = m_Textures.Element(m_MaterialEntries[materialIndex].textureIndex);
if ( bBackface && !tex.allowBackface )
return 0;
Vector2D uv = coords.x * mat.uv[0] + coords.y * mat.uv[1] + coords.z * mat.uv[2];
int u = RoundFloatToInt( uv[0] * tex.width );
int v = RoundFloatToInt( uv[1] * tex.height );
// asume power of 2, clamp or wrap
// UNDONE: Support clamp? This code should work
#if 0
u = tex.clampU ? clamp(u,0,(tex.width-1)) : (u & (tex.width-1));
v = tex.clampV ? clamp(v,0,(tex.height-1)) : (v & (tex.height-1));
#else
// for now always wrap
u &= (tex.width-1);
v &= (tex.height-1);
#endif
return tex.pAlphaTexels[v * tex.width + u];
}
struct alphatexture_t
{
short width;
short height;
bool allowBackface;
bool clampU;
bool clampV;
unsigned char *pAlphaTexels;
void InitFromRGB8888( int w, int h, unsigned char *pTexels )
{
width = w;
height = h;
pAlphaTexels = new unsigned char[w*h];
for ( int i = 0; i < h; i++ )
{
for ( int j = 0; j < w; j++ )
{
int index = (i*w) + j;
pAlphaTexels[index] = pTexels[index*4 + 3];
}
}
}
};
struct materialentry_t
{
int textureIndex;
Vector2D uv[3];
};
// this is the list of textures we've loaded
// only load each one once
CUtlDict< alphatexture_t, unsigned short > m_Textures;
CUtlVector<materialentry_t> m_MaterialEntries;
};
// global to keep the shadow-casting texture list and their alpha bits
CShadowTextureList g_ShadowTextureList;
float ComputeCoverageFromTexture( float b0, float b1, float b2, int32 hitID )
{
const float alphaScale = 1.0f / 255.0f;
// UNDONE: Pass ray down to determine backfacing?
//Vector normal( tri.m_flNx, tri.m_flNy, tri.m_flNz );
//bool bBackface = DotProduct(delta, tri.N) > 0 ? true : false;
Vector coords(b0,b1,b2);
return alphaScale * g_ShadowTextureList.SampleMaterial( g_RtEnv.GetTriangleMaterial(hitID), coords, false );
}
// this is here to strip models/ or .mdl or whatnot
void CleanModelName( const char *pModelName, char *pOutput, int outLen )
{
// strip off leading models/ if it exists
const char *pModelDir = "models/";
int modelLen = Q_strlen(pModelDir);
if ( !Q_strnicmp(pModelName, pModelDir, modelLen ) )
{
pModelName += modelLen;
}
Q_strncpy( pOutput, pModelName, outLen );
// truncate any .mdl extension
char *dot = strchr(pOutput,'.');
if ( dot )
{
*dot = 0;
}
}
void ForceTextureShadowsOnModel( const char *pModelName )
{
char buf[1024];
CleanModelName( pModelName, buf, sizeof(buf) );
if ( !g_ForcedTextureShadowsModels.Find(buf).IsValid())
{
g_ForcedTextureShadowsModels.AddString(buf);
}
}
bool IsModelTextureShadowsForced( const char *pModelName )
{
char buf[1024];
CleanModelName( pModelName, buf, sizeof(buf) );
return g_ForcedTextureShadowsModels.Find(buf).IsValid();
}
//-----------------------------------------------------------------------------
// Creates a collision model (based on the render geometry!)
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::CreateCollisionModel( char const* pModelName )
{
CUtlBuffer buf;
CUtlBuffer bufvtx;
CUtlBuffer bufphy;
int i = m_StaticPropDict.AddToTail();
m_StaticPropDict[i].m_pModel = NULL;
m_StaticPropDict[i].m_pStudioHdr = NULL;
if ( !LoadStudioModel( pModelName, buf ) )
{
VectorCopy( vec3_origin, m_StaticPropDict[i].m_Mins );
VectorCopy( vec3_origin, m_StaticPropDict[i].m_Maxs );
return;
}
studiohdr_t* pHdr = (studiohdr_t*)buf.Base();
VectorCopy( pHdr->hull_min, m_StaticPropDict[i].m_Mins );
VectorCopy( pHdr->hull_max, m_StaticPropDict[i].m_Maxs );
if ( LoadStudioCollisionModel( pModelName, bufphy ) )
{
phyheader_t header;
bufphy.Get( &header, sizeof(header) );
vcollide_t *pCollide = &m_StaticPropDict[i].m_loadedModel;
s_pPhysCollision->VCollideLoad( pCollide, header.solidCount, (const char *)bufphy.PeekGet(), bufphy.TellPut() - bufphy.TellGet() );
m_StaticPropDict[i].m_pModel = m_StaticPropDict[i].m_loadedModel.solids[0];
/*
static int propNum = 0;
char tmp[128];
sprintf( tmp, "staticprop%03d.txt", propNum );
DumpCollideToGlView( pCollide, tmp );
++propNum;
*/
}
else
{
// mark this as unused
m_StaticPropDict[i].m_loadedModel.solidCount = 0;
// CPhysCollide* pPhys = CreatePhysCollide( pHdr, pVtxHdr );
m_StaticPropDict[i].m_pModel = ComputeConvexHull( pHdr );
}
// clone it
m_StaticPropDict[i].m_pStudioHdr = (studiohdr_t *)malloc( buf.Size() );
memcpy( m_StaticPropDict[i].m_pStudioHdr, (studiohdr_t*)buf.Base(), buf.Size() );
if ( !LoadVTXFile( pModelName, m_StaticPropDict[i].m_pStudioHdr, m_StaticPropDict[i].m_VtxBuf ) )
{
// failed, leave state identified as disabled
m_StaticPropDict[i].m_VtxBuf.Purge();
}
if ( g_bTextureShadows )
{
if ( (pHdr->flags & STUDIOHDR_FLAGS_CAST_TEXTURE_SHADOWS) || IsModelTextureShadowsForced(pModelName) )
{
m_StaticPropDict[i].m_textureShadowIndex.RemoveAll();
m_StaticPropDict[i].m_triangleMaterialIndex.RemoveAll();
m_StaticPropDict[i].m_textureShadowIndex.AddMultipleToTail( pHdr->numtextures );
g_ShadowTextureList.LoadAllTexturesForModel( pHdr, m_StaticPropDict[i].m_textureShadowIndex.Base() );
}
}
}
//-----------------------------------------------------------------------------
// Unserialize static prop model dictionary
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::UnserializeModelDict( CUtlBuffer& buf )
{
int count = buf.GetInt();
while ( --count >= 0 )
{
StaticPropDictLump_t lump;
buf.Get( &lump, sizeof(StaticPropDictLump_t) );
CreateCollisionModel( lump.m_Name );
}
}
void CVradStaticPropMgr::UnserializeModels( CUtlBuffer& buf )
{
int count = buf.GetInt();
m_StaticProps.AddMultipleToTail(count);
for ( int i = 0; i < count; ++i )
{
StaticPropLump_t lump;
buf.Get( &lump, sizeof(StaticPropLump_t) );
VectorCopy( lump.m_Origin, m_StaticProps[i].m_Origin );
VectorCopy( lump.m_Angles, m_StaticProps[i].m_Angles );
VectorCopy( lump.m_LightingOrigin, m_StaticProps[i].m_LightingOrigin );
m_StaticProps[i].m_bLightingOriginValid = ( lump.m_Flags & STATIC_PROP_USE_LIGHTING_ORIGIN ) > 0;
m_StaticProps[i].m_ModelIdx = lump.m_PropType;
m_StaticProps[i].m_Handle = TREEDATA_INVALID_HANDLE;
m_StaticProps[i].m_Flags = lump.m_Flags;
// Changed this from using DXT1 to RGB888 because the compression artifacts were pretty nasty.
// TODO: Consider changing back or basing this on user selection in hammer.
m_StaticProps[i].m_LightmapImageFormat = IMAGE_FORMAT_RGB888;
m_StaticProps[i].m_LightmapImageWidth = lump.m_nLightmapResolutionX;
m_StaticProps[i].m_LightmapImageHeight = lump.m_nLightmapResolutionY;
}
}
//-----------------------------------------------------------------------------
// Unserialize static props
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::UnserializeStaticProps()
{
// Unserialize static props, insert them into the appropriate leaves
GameLumpHandle_t handle = g_GameLumps.GetGameLumpHandle( GAMELUMP_STATIC_PROPS );
int size = g_GameLumps.GameLumpSize( handle );
if (!size)
return;
if ( g_GameLumps.GetGameLumpVersion( handle ) != GAMELUMP_STATIC_PROPS_VERSION )
{
Error( "Cannot load the static props... encountered a stale map version. Re-vbsp the map." );
}
if ( g_GameLumps.GetGameLump( handle ) )
{
CUtlBuffer buf( g_GameLumps.GetGameLump(handle), size, CUtlBuffer::READ_ONLY );
UnserializeModelDict( buf );
// Skip the leaf list data
int count = buf.GetInt();
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, count * sizeof(StaticPropLeafLump_t) );
UnserializeModels( buf );
}
}
//-----------------------------------------------------------------------------
// Level init, shutdown
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::Init()
{
CreateInterfaceFn physicsFactory = GetPhysicsFactory();
if ( !physicsFactory )
Error( "Unable to load vphysics DLL." );
s_pPhysCollision = (IPhysicsCollision *)physicsFactory( VPHYSICS_COLLISION_INTERFACE_VERSION, NULL );
if( !s_pPhysCollision )
{
Error( "Unable to get '%s' for physics interface.", VPHYSICS_COLLISION_INTERFACE_VERSION );
return;
}
// Read in static props that have been compiled into the bsp file
UnserializeStaticProps();
}
void CVradStaticPropMgr::Shutdown()
{
// Remove all static prop model data
for (int i = m_StaticPropDict.Size(); --i >= 0; )
{
studiohdr_t *pStudioHdr = m_StaticPropDict[i].m_pStudioHdr;
if ( pStudioHdr )
{
if ( pStudioHdr->pVertexBase )
{
free( pStudioHdr->pVertexBase );
}
free( pStudioHdr );
}
}
m_StaticProps.Purge();
m_StaticPropDict.Purge();
}
void ComputeLightmapColor( dface_t* pFace, Vector &color )
{
texinfo_t* pTex = &texinfo[pFace->texinfo];
if ( pTex->flags & SURF_SKY )
{
// sky ambient already accounted for in direct component
return;
}
}
bool PositionInSolid( Vector &position )
{
int ndxLeaf = PointLeafnum( position );
if ( dleafs[ndxLeaf].contents & CONTENTS_SOLID )
{
// position embedded in solid
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Trace from a vertex to each direct light source, accumulating its contribution.
//-----------------------------------------------------------------------------
void ComputeDirectLightingAtPoint( Vector &position, Vector &normal, Vector &outColor, int iThread,
int static_prop_id_to_skip=-1, int nLFlags = 0)
{
SSE_sampleLightOutput_t sampleOutput;
outColor.Init();
// Iterate over all direct lights and accumulate their contribution
int cluster = ClusterFromPoint( position );
for ( directlight_t *dl = activelights; dl != NULL; dl = dl->next )
{
if ( dl->light.style )
{
// skip lights with style
continue;
}
// is this lights cluster visible?
if ( !PVSCheck( dl->pvs, cluster ) )
continue;
// push the vertex towards the light to avoid surface acne
Vector adjusted_pos = position;
float flEpsilon = 0.0;
if (dl->light.type != emit_skyambient)
{
// push towards the light
Vector fudge;
if ( dl->light.type == emit_skylight )
fudge = -( dl->light.normal);
else
{
fudge = dl->light.origin-position;
VectorNormalize( fudge );
}
fudge *= 4.0;
adjusted_pos += fudge;
}
else
{
// push out along normal
adjusted_pos += 4.0 * normal;
// flEpsilon = 1.0;
}
FourVectors adjusted_pos4;
FourVectors normal4;
adjusted_pos4.DuplicateVector( adjusted_pos );
normal4.DuplicateVector( normal );
GatherSampleLightSSE( sampleOutput, dl, -1, adjusted_pos4, &normal4, 1, iThread, nLFlags | GATHERLFLAGS_FORCE_FAST,
static_prop_id_to_skip, flEpsilon );
VectorMA( outColor, sampleOutput.m_flFalloff.m128_f32[0] * sampleOutput.m_flDot[0].m128_f32[0], dl->light.intensity, outColor );
}
}
//-----------------------------------------------------------------------------
// Takes the results from a ComputeLighting call and applies it to the static prop in question.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::ApplyLightingToStaticProp( int iStaticProp, CStaticProp &prop, const CComputeStaticPropLightingResults *pResults )
{
if ( pResults->m_ColorVertsArrays.Count() == 0 && pResults->m_ColorTexelsArrays.Count() == 0 )
return;
StaticPropDict_t &dict = m_StaticPropDict[prop.m_ModelIdx];
studiohdr_t *pStudioHdr = dict.m_pStudioHdr;
OptimizedModel::FileHeader_t *pVtxHdr = (OptimizedModel::FileHeader_t *)dict.m_VtxBuf.Base();
Assert( pStudioHdr && pVtxHdr );
int iCurColorVertsArray = 0;
int iCurColorTexelsArray = 0;
for ( int bodyID = 0; bodyID < pStudioHdr->numbodyparts; ++bodyID )
{
OptimizedModel::BodyPartHeader_t* pVtxBodyPart = pVtxHdr->pBodyPart( bodyID );
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( bodyID );
for ( int modelID = 0; modelID < pBodyPart->nummodels; ++modelID )
{
OptimizedModel::ModelHeader_t* pVtxModel = pVtxBodyPart->pModel( modelID );
mstudiomodel_t *pStudioModel = pBodyPart->pModel( modelID );
const CUtlVector<colorVertex_t> *colorVerts = pResults->m_ColorVertsArrays.Count() ? pResults->m_ColorVertsArrays[iCurColorVertsArray++] : nullptr;
const CUtlVector<colorTexel_t> *colorTexels = pResults->m_ColorTexelsArrays.Count() ? pResults->m_ColorTexelsArrays[iCurColorTexelsArray++] : nullptr;
for ( int nLod = 0; nLod < pVtxHdr->numLODs; nLod++ )
{
OptimizedModel::ModelLODHeader_t *pVtxLOD = pVtxModel->pLOD( nLod );
for ( int nMesh = 0; nMesh < pStudioModel->nummeshes; ++nMesh )
{
mstudiomesh_t* pMesh = pStudioModel->pMesh( nMesh );
OptimizedModel::MeshHeader_t* pVtxMesh = pVtxLOD->pMesh( nMesh );
for ( int nGroup = 0; nGroup < pVtxMesh->numStripGroups; ++nGroup )
{
OptimizedModel::StripGroupHeader_t* pStripGroup = pVtxMesh->pStripGroup( nGroup );
int nMeshIdx = prop.m_MeshData.AddToTail();
if (colorVerts)
{
prop.m_MeshData[nMeshIdx].m_VertexColors.AddMultipleToTail( pStripGroup->numVerts );
prop.m_MeshData[nMeshIdx].m_nLod = nLod;
for ( int nVertex = 0; nVertex < pStripGroup->numVerts; ++nVertex )
{
int nIndex = pMesh->vertexoffset + pStripGroup->pVertex( nVertex )->origMeshVertID;
Assert( nIndex < pStudioModel->numvertices );
prop.m_MeshData[nMeshIdx].m_VertexColors[nVertex] = (*colorVerts)[nIndex].m_Color;
}
}
if (colorTexels)
{
// TODO: Consider doing this work in the worker threads, because then we distribute it.
ConvertTexelDataToTexture(prop.m_LightmapImageWidth, prop.m_LightmapImageHeight, prop.m_LightmapImageFormat, (*colorTexels), &prop.m_MeshData[nMeshIdx].m_TexelsEncoded);
if (g_bDumpPropLightmaps)
{
char buffer[_MAX_PATH];
V_snprintf(
buffer,
_MAX_PATH - 1,
"staticprop_lightmap_%d_%.0f_%.0f_%.0f_%s_%d_%d_%d_%d_%d.tga",
iStaticProp,
prop.m_Origin.x,
prop.m_Origin.y,
prop.m_Origin.z,
dict.m_pStudioHdr->pszName(),
bodyID,
modelID,
nLod,
nMesh,
nGroup
);
for ( int i = 0; buffer[i]; ++i )
{
if (buffer[i] == '/' || buffer[i] == '\\')
buffer[i] = '-';
}
DumpLightmapLinear( buffer, (*colorTexels), prop.m_LightmapImageWidth, prop.m_LightmapImageHeight );
}
}
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// Trace rays from each unique vertex, accumulating direct and indirect
// sources at each ray termination. Use the winding data to distribute the unique vertexes
// into the rendering layout.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::ComputeLighting( CStaticProp &prop, int iThread, int prop_index, CComputeStaticPropLightingResults *pResults )
{
CUtlVector<badVertex_t> badVerts;
StaticPropDict_t &dict = m_StaticPropDict[prop.m_ModelIdx];
studiohdr_t *pStudioHdr = dict.m_pStudioHdr;
OptimizedModel::FileHeader_t *pVtxHdr = (OptimizedModel::FileHeader_t *)dict.m_VtxBuf.Base();
if ( !pStudioHdr || !pVtxHdr )
{
// must have model and its verts for lighting computation
// game will fallback to fullbright
return;
}
const bool withVertexLighting = (prop.m_Flags & STATIC_PROP_NO_PER_VERTEX_LIGHTING) == 0;
const bool withTexelLighting = (prop.m_Flags & STATIC_PROP_NO_PER_TEXEL_LIGHTING) == 0;
if (!withVertexLighting && !withTexelLighting)
return;
const int skip_prop = (g_bDisablePropSelfShadowing || (prop.m_Flags & STATIC_PROP_NO_SELF_SHADOWING)) ? prop_index : -1;
const int nFlags = ( prop.m_Flags & STATIC_PROP_IGNORE_NORMALS ) ? GATHERLFLAGS_IGNORE_NORMALS : 0;
VMPI_SetCurrentStage( "ComputeLighting" );
matrix3x4_t matPos, matNormal;
AngleMatrix(prop.m_Angles, prop.m_Origin, matPos);
AngleMatrix(prop.m_Angles, matNormal);
for ( int bodyID = 0; bodyID < pStudioHdr->numbodyparts; ++bodyID )
{
OptimizedModel::BodyPartHeader_t* pVtxBodyPart = pVtxHdr->pBodyPart( bodyID );
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( bodyID );
for ( int modelID = 0; modelID < pBodyPart->nummodels; ++modelID )
{
OptimizedModel::ModelHeader_t* pVtxModel = pVtxBodyPart->pModel(modelID);
mstudiomodel_t *pStudioModel = pBodyPart->pModel( modelID );
if (withTexelLighting)
{
CUtlVector<colorTexel_t> *pColorTexelArray = new CUtlVector<colorTexel_t>;
pResults->m_ColorTexelsArrays.AddToTail(pColorTexelArray);
}
// light all unique vertexes
CUtlVector<colorVertex_t> *pColorVertsArray = new CUtlVector<colorVertex_t>;
pResults->m_ColorVertsArrays.AddToTail( pColorVertsArray );
CUtlVector<colorVertex_t> &colorVerts = *pColorVertsArray;
colorVerts.EnsureCount( pStudioModel->numvertices );
memset( colorVerts.Base(), 0, colorVerts.Count() * sizeof(colorVertex_t) );
int numVertexes = 0;
for ( int meshID = 0; meshID < pStudioModel->nummeshes; ++meshID )
{
mstudiomesh_t *pStudioMesh = pStudioModel->pMesh( meshID );
const mstudio_meshvertexdata_t *vertData = pStudioMesh->GetVertexData((void *)pStudioHdr);
Assert(vertData); // This can only return NULL on X360 for now
// TODO: Move this into its own function. In fact, refactor this whole function.
if (withTexelLighting)
{
GenerateLightmapSamplesForMesh( matPos, matNormal, iThread, skip_prop, nFlags, prop.m_LightmapImageWidth, prop.m_LightmapImageHeight, pStudioHdr, pStudioModel, pVtxModel, meshID, pResults );
}
// If we do lightmapping, we also do vertex lighting as a potential fallback. This may change.
for ( int vertexID = 0; vertexID < pStudioMesh->numvertices; ++vertexID )
{
Vector sampleNormal;
Vector samplePosition;
// transform position and normal into world coordinate system
VectorTransform(*vertData->Position(vertexID), matPos, samplePosition);
VectorTransform(*vertData->Normal(vertexID), matNormal, sampleNormal);
if ( PositionInSolid( samplePosition ) )
{
// vertex is in solid, add to the bad list, and recover later
badVertex_t badVertex;
badVertex.m_ColorVertex = numVertexes;
badVertex.m_Position = samplePosition;
badVertex.m_Normal = sampleNormal;
badVerts.AddToTail( badVertex );
}
else
{
Vector direct_pos=samplePosition;
Vector directColor(0,0,0);
ComputeDirectLightingAtPoint( direct_pos,
sampleNormal, directColor, iThread,
skip_prop, nFlags );
Vector indirectColor(0,0,0);
if (g_bShowStaticPropNormals)
{
directColor= sampleNormal;
directColor += Vector(1.0,1.0,1.0);
directColor *= 50.0;
}
else
{
if (numbounce >= 1)
ComputeIndirectLightingAtPoint(
samplePosition, sampleNormal,
indirectColor, iThread, true,
( prop.m_Flags & STATIC_PROP_IGNORE_NORMALS) != 0 );
}
colorVerts[numVertexes].m_bValid = true;
colorVerts[numVertexes].m_Position = samplePosition;
VectorAdd( directColor, indirectColor, colorVerts[numVertexes].m_Color );
}
numVertexes++;
}
}
// color in the bad vertexes
// when entire model has no lighting origin and no valid neighbors
// must punt, leave black coloring
if ( badVerts.Count() && ( prop.m_bLightingOriginValid || badVerts.Count() != numVertexes ) )
{
for ( int nBadVertex = 0; nBadVertex < badVerts.Count(); nBadVertex++ )
{
Vector bestPosition;
if ( prop.m_bLightingOriginValid )
{
// use the specified lighting origin
VectorCopy( prop.m_LightingOrigin, bestPosition );
}
else
{
// find the closest valid neighbor
int best = 0;
float closest = FLT_MAX;
for ( int nColorVertex = 0; nColorVertex < numVertexes; nColorVertex++ )
{
if ( !colorVerts[nColorVertex].m_bValid )
{
// skip invalid neighbors
continue;
}
Vector delta;
VectorSubtract( colorVerts[nColorVertex].m_Position, badVerts[nBadVertex].m_Position, delta );
float distance = VectorLength( delta );
if ( distance < closest )
{
closest = distance;
best = nColorVertex;
}
}
// use the best neighbor as the direction to crawl
VectorCopy( colorVerts[best].m_Position, bestPosition );
}
// crawl toward best position
// sudivide to determine a closer valid point to the bad vertex, and re-light
Vector midPosition;
int numIterations = 20;
while ( --numIterations > 0 )
{
VectorAdd( bestPosition, badVerts[nBadVertex].m_Position, midPosition );
VectorScale( midPosition, 0.5f, midPosition );
if ( PositionInSolid( midPosition ) )
break;
bestPosition = midPosition;
}
// re-light from better position
Vector directColor;
ComputeDirectLightingAtPoint( bestPosition, badVerts[nBadVertex].m_Normal, directColor, iThread );
Vector indirectColor;
ComputeIndirectLightingAtPoint( bestPosition, badVerts[nBadVertex].m_Normal,
indirectColor, iThread, true );
// save results, not changing valid status
// to ensure this offset position is not considered as a viable candidate
colorVerts[badVerts[nBadVertex].m_ColorVertex].m_Position = bestPosition;
VectorAdd( directColor, indirectColor, colorVerts[badVerts[nBadVertex].m_ColorVertex].m_Color );
}
}
// discard bad verts
badVerts.Purge();
}
}
}
//-----------------------------------------------------------------------------
// Write the lighitng to bsp pak lump
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::SerializeLighting()
{
char filename[MAX_PATH];
CUtlBuffer utlBuf;
// illuminate them all
int count = m_StaticProps.Count();
if ( !count )
{
// nothing to do
return;
}
char mapName[MAX_PATH];
Q_FileBase( source, mapName, sizeof( mapName ) );
int size;
for (int i = 0; i < count; ++i)
{
// no need to write this file if we didn't compute the data
// props marked this way will not load the info anyway
if ( m_StaticProps[i].m_Flags & STATIC_PROP_NO_PER_VERTEX_LIGHTING )
continue;
if (g_bHDR)
{
sprintf( filename, "sp_hdr_%d.vhv", i );
}
else
{
sprintf( filename, "sp_%d.vhv", i );
}
int totalVertexes = 0;
for ( int j=0; j<m_StaticProps[i].m_MeshData.Count(); j++ )
{
totalVertexes += m_StaticProps[i].m_MeshData[j].m_VertexColors.Count();
}
// allocate a buffer with enough padding for alignment
size = sizeof( HardwareVerts::FileHeader_t ) +
m_StaticProps[i].m_MeshData.Count()*sizeof(HardwareVerts::MeshHeader_t) +
totalVertexes*4 + 2*512;
utlBuf.EnsureCapacity( size );
Q_memset( utlBuf.Base(), 0, size );
HardwareVerts::FileHeader_t *pVhvHdr = (HardwareVerts::FileHeader_t *)utlBuf.Base();
// align to start of vertex data
unsigned char *pVertexData = (unsigned char *)(sizeof( HardwareVerts::FileHeader_t ) + m_StaticProps[i].m_MeshData.Count()*sizeof(HardwareVerts::MeshHeader_t));
pVertexData = (unsigned char*)pVhvHdr + ALIGN_TO_POW2( (unsigned int)pVertexData, 512 );
// construct header
pVhvHdr->m_nVersion = VHV_VERSION;
pVhvHdr->m_nChecksum = m_StaticPropDict[m_StaticProps[i].m_ModelIdx].m_pStudioHdr->checksum;
pVhvHdr->m_nVertexFlags = VERTEX_COLOR;
pVhvHdr->m_nVertexSize = 4;
pVhvHdr->m_nVertexes = totalVertexes;
pVhvHdr->m_nMeshes = m_StaticProps[i].m_MeshData.Count();
for (int n=0; n<pVhvHdr->m_nMeshes; n++)
{
// construct mesh dictionary
HardwareVerts::MeshHeader_t *pMesh = pVhvHdr->pMesh( n );
pMesh->m_nLod = m_StaticProps[i].m_MeshData[n].m_nLod;
pMesh->m_nVertexes = m_StaticProps[i].m_MeshData[n].m_VertexColors.Count();
pMesh->m_nOffset = (unsigned int)pVertexData - (unsigned int)pVhvHdr;
// construct vertexes
for (int k=0; k<pMesh->m_nVertexes; k++)
{
Vector &vertexColor = m_StaticProps[i].m_MeshData[n].m_VertexColors[k];
ColorRGBExp32 rgbColor;
VectorToColorRGBExp32( vertexColor, rgbColor );
unsigned char dstColor[4];
ConvertRGBExp32ToRGBA8888( &rgbColor, dstColor );
// b,g,r,a order
pVertexData[0] = dstColor[2];
pVertexData[1] = dstColor[1];
pVertexData[2] = dstColor[0];
pVertexData[3] = dstColor[3];
pVertexData += 4;
}
}
// align to end of file
pVertexData = (unsigned char *)((unsigned int)pVertexData - (unsigned int)pVhvHdr);
pVertexData = (unsigned char*)pVhvHdr + ALIGN_TO_POW2( (unsigned int)pVertexData, 512 );
AddBufferToPak( GetPakFile(), filename, (void*)pVhvHdr, pVertexData - (unsigned char*)pVhvHdr, false );
}
for (int i = 0; i < count; ++i)
{
const int kAlignment = 512;
// no need to write this file if we didn't compute the data
// props marked this way will not load the info anyway
if (m_StaticProps[i].m_Flags & STATIC_PROP_NO_PER_TEXEL_LIGHTING)
continue;
sprintf(filename, "texelslighting_%d.ppl", i);
ImageFormat fmt = m_StaticProps[i].m_LightmapImageFormat;
unsigned int totalTexelSizeBytes = 0;
for (int j = 0; j < m_StaticProps[i].m_MeshData.Count(); j++)
{
totalTexelSizeBytes += m_StaticProps[i].m_MeshData[j].m_TexelsEncoded.Count();
}
// allocate a buffer with enough padding for alignment
size = sizeof(HardwareTexels::FileHeader_t)
+ m_StaticProps[i].m_MeshData.Count() * sizeof(HardwareTexels::MeshHeader_t)
+ totalTexelSizeBytes
+ 2 * kAlignment;
utlBuf.EnsureCapacity(size);
Q_memset(utlBuf.Base(), 0, size);
HardwareTexels::FileHeader_t *pVhtHdr = (HardwareTexels::FileHeader_t *)utlBuf.Base();
// align start of texel data
unsigned char *pTexelData = (unsigned char *)(sizeof(HardwareTexels::FileHeader_t) + m_StaticProps[i].m_MeshData.Count() * sizeof(HardwareTexels::MeshHeader_t));
pTexelData = (unsigned char*)pVhtHdr + ALIGN_TO_POW2((unsigned int)pTexelData, kAlignment);
pVhtHdr->m_nVersion = VHT_VERSION;
pVhtHdr->m_nChecksum = m_StaticPropDict[m_StaticProps[i].m_ModelIdx].m_pStudioHdr->checksum;
pVhtHdr->m_nTexelFormat = fmt;
pVhtHdr->m_nMeshes = m_StaticProps[i].m_MeshData.Count();
for (int n = 0; n < pVhtHdr->m_nMeshes; n++)
{
HardwareTexels::MeshHeader_t *pMesh = pVhtHdr->pMesh(n);
pMesh->m_nLod = m_StaticProps[i].m_MeshData[n].m_nLod;
pMesh->m_nOffset = (unsigned int)pTexelData - (unsigned int)pVhtHdr;
pMesh->m_nBytes = m_StaticProps[i].m_MeshData[n].m_TexelsEncoded.Count();
pMesh->m_nWidth = m_StaticProps[i].m_LightmapImageWidth;
pMesh->m_nHeight = m_StaticProps[i].m_LightmapImageHeight;
Q_memcpy(pTexelData, m_StaticProps[i].m_MeshData[n].m_TexelsEncoded.Base(), m_StaticProps[i].m_MeshData[n].m_TexelsEncoded.Count());
pTexelData += m_StaticProps[i].m_MeshData[n].m_TexelsEncoded.Count();
}
pTexelData = (unsigned char *)((unsigned int)pTexelData - (unsigned int)pVhtHdr);
pTexelData = (unsigned char*)pVhtHdr + ALIGN_TO_POW2((unsigned int)pTexelData, kAlignment);
AddBufferToPak(GetPakFile(), filename, (void*)pVhtHdr, pTexelData - (unsigned char*)pVhtHdr, false);
}
}
void CVradStaticPropMgr::VMPI_ProcessStaticProp_Static( int iThread, uint64 iStaticProp, MessageBuffer *pBuf )
{
g_StaticPropMgr.VMPI_ProcessStaticProp( iThread, iStaticProp, pBuf );
}
void CVradStaticPropMgr::VMPI_ReceiveStaticPropResults_Static( uint64 iStaticProp, MessageBuffer *pBuf, int iWorker )
{
g_StaticPropMgr.VMPI_ReceiveStaticPropResults( iStaticProp, pBuf, iWorker );
}
//-----------------------------------------------------------------------------
// Called on workers to do the computation for a static prop and send
// it to the master.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::VMPI_ProcessStaticProp( int iThread, int iStaticProp, MessageBuffer *pBuf )
{
// Compute the lighting.
CComputeStaticPropLightingResults results;
ComputeLighting( m_StaticProps[iStaticProp], iThread, iStaticProp, &results );
VMPI_SetCurrentStage( "EncodeLightingResults" );
// Encode the results.
int nLists = results.m_ColorVertsArrays.Count();
pBuf->write( &nLists, sizeof( nLists ) );
for ( int i=0; i < nLists; i++ )
{
CUtlVector<colorVertex_t> &curList = *results.m_ColorVertsArrays[i];
int count = curList.Count();
pBuf->write( &count, sizeof( count ) );
pBuf->write( curList.Base(), curList.Count() * sizeof( colorVertex_t ) );
}
nLists = results.m_ColorTexelsArrays.Count();
pBuf->write(&nLists, sizeof(nLists));
for (int i = 0; i < nLists; i++)
{
CUtlVector<colorTexel_t> &curList = *results.m_ColorTexelsArrays[i];
int count = curList.Count();
pBuf->write(&count, sizeof(count));
pBuf->write(curList.Base(), curList.Count() * sizeof(colorTexel_t));
}
}
//-----------------------------------------------------------------------------
// Called on the master when a worker finishes processing a static prop.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::VMPI_ReceiveStaticPropResults( int iStaticProp, MessageBuffer *pBuf, int iWorker )
{
// Read in the results.
CComputeStaticPropLightingResults results;
int nLists;
pBuf->read( &nLists, sizeof( nLists ) );
for ( int i=0; i < nLists; i++ )
{
CUtlVector<colorVertex_t> *pList = new CUtlVector<colorVertex_t>;
results.m_ColorVertsArrays.AddToTail( pList );
int count;
pBuf->read( &count, sizeof( count ) );
pList->SetSize( count );
pBuf->read( pList->Base(), count * sizeof( colorVertex_t ) );
}
pBuf->read(&nLists, sizeof(nLists));
for (int i = 0; i < nLists; i++)
{
CUtlVector<colorTexel_t> *pList = new CUtlVector<colorTexel_t>;
results.m_ColorTexelsArrays.AddToTail(pList);
int count;
pBuf->read(&count, sizeof(count));
pList->SetSize(count);
pBuf->read(pList->Base(), count * sizeof(colorTexel_t));
}
// Apply the results.
ApplyLightingToStaticProp( iStaticProp, m_StaticProps[iStaticProp], &results );
}
void CVradStaticPropMgr::ComputeLightingForProp( int iThread, int iStaticProp )
{
// Compute the lighting.
CComputeStaticPropLightingResults results;
ComputeLighting( m_StaticProps[iStaticProp], iThread, iStaticProp, &results );
ApplyLightingToStaticProp( iStaticProp, m_StaticProps[iStaticProp], &results );
}
void CVradStaticPropMgr::ThreadComputeStaticPropLighting( int iThread, void *pUserData )
{
while (1)
{
int j = GetThreadWork ();
if (j == -1)
break;
CComputeStaticPropLightingResults results;
g_StaticPropMgr.ComputeLightingForProp( iThread, j );
}
}
//-----------------------------------------------------------------------------
// Computes lighting for the static props.
// Must be after all other surface lighting has been computed for the indirect sampling.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::ComputeLighting( int iThread )
{
// illuminate them all
int count = m_StaticProps.Count();
if ( !count )
{
// nothing to do
return;
}
StartPacifier( "Computing static prop lighting : " );
// ensure any traces against us are ignored because we have no inherit lighting contribution
m_bIgnoreStaticPropTrace = true;
if ( g_bUseMPI )
{
// Distribute the work among the workers.
VMPI_SetCurrentStage( "CVradStaticPropMgr::ComputeLighting" );
DistributeWork(
count,
VMPI_DISTRIBUTEWORK_PACKETID,
&CVradStaticPropMgr::VMPI_ProcessStaticProp_Static,
&CVradStaticPropMgr::VMPI_ReceiveStaticPropResults_Static );
}
else
{
RunThreadsOn(count, true, ThreadComputeStaticPropLighting);
}
// restore default
m_bIgnoreStaticPropTrace = false;
// save data to bsp
SerializeLighting();
EndPacifier( true );
}
//-----------------------------------------------------------------------------
// Adds all static prop polys to the ray trace store.
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::AddPolysForRayTrace( void )
{
int count = m_StaticProps.Count();
if ( !count )
{
// nothing to do
return;
}
// Triangle coverage of 1 (full coverage)
Vector fullCoverage;
fullCoverage.x = 1.0f;
for ( int nProp = 0; nProp < count; ++nProp )
{
CStaticProp &prop = m_StaticProps[nProp];
StaticPropDict_t &dict = m_StaticPropDict[prop.m_ModelIdx];
if ( prop.m_Flags & STATIC_PROP_NO_SHADOW )
continue;
// If not using static prop polys, use AABB
if ( !g_bStaticPropPolys )
{
if ( dict.m_pModel )
{
VMatrix xform;
xform.SetupMatrixOrgAngles ( prop.m_Origin, prop.m_Angles );
ICollisionQuery *queryModel = s_pPhysCollision->CreateQueryModel( dict.m_pModel );
for ( int nConvex = 0; nConvex < queryModel->ConvexCount(); ++nConvex )
{
for ( int nTri = 0; nTri < queryModel->TriangleCount( nConvex ); ++nTri )
{
Vector verts[3];
queryModel->GetTriangleVerts( nConvex, nTri, verts );
for ( int nVert = 0; nVert < 3; ++nVert )
verts[nVert] = xform.VMul4x3(verts[nVert]);
g_RtEnv.AddTriangle ( TRACE_ID_STATICPROP | nProp, verts[0], verts[1], verts[2], fullCoverage );
}
}
s_pPhysCollision->DestroyQueryModel( queryModel );
}
else
{
VectorAdd ( dict.m_Mins, prop.m_Origin, prop.m_mins );
VectorAdd ( dict.m_Maxs, prop.m_Origin, prop.m_maxs );
g_RtEnv.AddAxisAlignedRectangularSolid ( TRACE_ID_STATICPROP | nProp, prop.m_mins, prop.m_maxs, fullCoverage );
}
continue;
}
studiohdr_t *pStudioHdr = dict.m_pStudioHdr;
OptimizedModel::FileHeader_t *pVtxHdr = (OptimizedModel::FileHeader_t *)dict.m_VtxBuf.Base();
if ( !pStudioHdr || !pVtxHdr )
{
// must have model and its verts for decoding triangles
return;
}
// only init the triangle table the first time
bool bInitTriangles = dict.m_triangleMaterialIndex.Count() ? false : true;
int triangleIndex = 0;
// meshes are deeply hierarchial, divided between three stores, follow the white rabbit
// body parts -> models -> lod meshes -> strip groups -> strips
// the vertices and indices are pooled, the trick is knowing the offset to determine your indexed base
for ( int bodyID = 0; bodyID < pStudioHdr->numbodyparts; ++bodyID )
{
OptimizedModel::BodyPartHeader_t* pVtxBodyPart = pVtxHdr->pBodyPart( bodyID );
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( bodyID );
for ( int modelID = 0; modelID < pBodyPart->nummodels; ++modelID )
{
OptimizedModel::ModelHeader_t* pVtxModel = pVtxBodyPart->pModel( modelID );
mstudiomodel_t *pStudioModel = pBodyPart->pModel( modelID );
// assuming lod 0, could iterate if required
int nLod = 0;
OptimizedModel::ModelLODHeader_t *pVtxLOD = pVtxModel->pLOD( nLod );
for ( int nMesh = 0; nMesh < pStudioModel->nummeshes; ++nMesh )
{
// check if this mesh's material is in the no shadow material name list
mstudiomesh_t* pMesh = pStudioModel->pMesh( nMesh );
mstudiotexture_t *pTxtr=pStudioHdr->pTexture(pMesh->material);
//printf("mat idx=%d mat name=%s\n",pMesh->material,pTxtr->pszName());
bool bSkipThisMesh = false;
for(int check=0; check<g_NonShadowCastingMaterialStrings.Count(); check++)
{
if ( Q_stristr( pTxtr->pszName(),
g_NonShadowCastingMaterialStrings[check] ) )
{
//printf("skip mat name=%s\n",pTxtr->pszName());
bSkipThisMesh = true;
break;
}
}
if ( bSkipThisMesh)
continue;
int shadowTextureIndex = -1;
if ( dict.m_textureShadowIndex.Count() )
{
shadowTextureIndex = dict.m_textureShadowIndex[pMesh->material];
}
OptimizedModel::MeshHeader_t* pVtxMesh = pVtxLOD->pMesh( nMesh );
const mstudio_meshvertexdata_t *vertData = pMesh->GetVertexData( (void *)pStudioHdr );
Assert( vertData ); // This can only return NULL on X360 for now
for ( int nGroup = 0; nGroup < pVtxMesh->numStripGroups; ++nGroup )
{
OptimizedModel::StripGroupHeader_t* pStripGroup = pVtxMesh->pStripGroup( nGroup );
int nStrip;
for ( nStrip = 0; nStrip < pStripGroup->numStrips; nStrip++ )
{
OptimizedModel::StripHeader_t *pStrip = pStripGroup->pStrip( nStrip );
if ( pStrip->flags & OptimizedModel::STRIP_IS_TRILIST )
{
for ( int i = 0; i < pStrip->numIndices; i += 3 )
{
int idx = pStrip->indexOffset + i;
unsigned short i1 = *pStripGroup->pIndex( idx );
unsigned short i2 = *pStripGroup->pIndex( idx + 1 );
unsigned short i3 = *pStripGroup->pIndex( idx + 2 );
int vertex1 = pStripGroup->pVertex( i1 )->origMeshVertID;
int vertex2 = pStripGroup->pVertex( i2 )->origMeshVertID;
int vertex3 = pStripGroup->pVertex( i3 )->origMeshVertID;
// transform position into world coordinate system
matrix3x4_t matrix;
AngleMatrix( prop.m_Angles, prop.m_Origin, matrix );
Vector position1;
Vector position2;
Vector position3;
VectorTransform( *vertData->Position( vertex1 ), matrix, position1 );
VectorTransform( *vertData->Position( vertex2 ), matrix, position2 );
VectorTransform( *vertData->Position( vertex3 ), matrix, position3 );
unsigned short flags = 0;
int materialIndex = -1;
Vector color = vec3_origin;
if ( shadowTextureIndex >= 0 )
{
if ( bInitTriangles )
{
// add texture space and texture index to material database
// now
float coverage = g_ShadowTextureList.ComputeCoverageForTriangle(shadowTextureIndex, *vertData->Texcoord(vertex1), *vertData->Texcoord(vertex2), *vertData->Texcoord(vertex3) );
if ( coverage < 1.0f )
{
materialIndex = g_ShadowTextureList.AddMaterialEntry( shadowTextureIndex, *vertData->Texcoord(vertex1), *vertData->Texcoord(vertex2), *vertData->Texcoord(vertex3) );
color.x = coverage;
}
else
{
materialIndex = -1;
}
dict.m_triangleMaterialIndex.AddToTail(materialIndex);
}
else
{
materialIndex = dict.m_triangleMaterialIndex[triangleIndex];
triangleIndex++;
}
if ( materialIndex >= 0 )
{
flags = FCACHETRI_TRANSPARENT;
}
}
// printf( "\ngl 3\n" );
// printf( "gl %6.3f %6.3f %6.3f 1 0 0\n", XYZ(position1));
// printf( "gl %6.3f %6.3f %6.3f 0 1 0\n", XYZ(position2));
// printf( "gl %6.3f %6.3f %6.3f 0 0 1\n", XYZ(position3));
g_RtEnv.AddTriangle( TRACE_ID_STATICPROP | nProp,
position1, position2, position3,
color, flags, materialIndex);
}
}
else
{
// all tris expected to be discrete tri lists
// must fixme if stripping ever occurs
printf( "unexpected strips found\n" );
Assert( 0 );
return;
}
}
}
}
}
}
}
}
struct tl_tri_t
{
Vector p0;
Vector p1;
Vector p2;
Vector n0;
Vector n1;
Vector n2;
bool operator == (const tl_tri_t &t) const
{
return ( p0 == t.p0 &&
p1 == t.p1 &&
p2 == t.p2 &&
n0 == t.n0 &&
n1 == t.n1 &&
n2 == t.n2 );
}
};
struct tl_vert_t
{
Vector m_position;
CUtlLinkedList< tl_tri_t, int > m_triList;
};
void AddTriVertsToList( CUtlVector< tl_vert_t > &triListVerts, int vertIndex, Vector vertPosition, Vector p0, Vector p1, Vector p2, Vector n0, Vector n1, Vector n2 )
{
tl_tri_t tlTri;
tlTri.p0 = p0;
tlTri.p1 = p1;
tlTri.p2 = p2;
tlTri.n0 = n0;
tlTri.n1 = n1;
tlTri.n2 = n2;
triListVerts.EnsureCapacity( vertIndex+1 );
triListVerts[vertIndex].m_position = vertPosition;
int index = triListVerts[vertIndex].m_triList.Find( tlTri );
if ( !triListVerts[vertIndex].m_triList.IsValidIndex( index ) )
{
// not in list, add to list of triangles
triListVerts[vertIndex].m_triList.AddToTail( tlTri );
}
}
//-----------------------------------------------------------------------------
// Builds a list of tris for every vertex
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::BuildTriList( CStaticProp &prop )
{
// the generated list will consist of a list of verts
// each vert will have a linked list of triangles that it belongs to
CUtlVector< tl_vert_t > triListVerts;
StaticPropDict_t &dict = m_StaticPropDict[prop.m_ModelIdx];
studiohdr_t *pStudioHdr = dict.m_pStudioHdr;
OptimizedModel::FileHeader_t *pVtxHdr = (OptimizedModel::FileHeader_t *)dict.m_VtxBuf.Base();
if ( !pStudioHdr || !pVtxHdr )
{
// must have model and its verts for decoding triangles
return;
}
// meshes are deeply hierarchial, divided between three stores, follow the white rabbit
// body parts -> models -> lod meshes -> strip groups -> strips
// the vertices and indices are pooled, the trick is knowing the offset to determine your indexed base
for ( int bodyID = 0; bodyID < pStudioHdr->numbodyparts; ++bodyID )
{
OptimizedModel::BodyPartHeader_t* pVtxBodyPart = pVtxHdr->pBodyPart( bodyID );
mstudiobodyparts_t *pBodyPart = pStudioHdr->pBodypart( bodyID );
for ( int modelID = 0; modelID < pBodyPart->nummodels; ++modelID )
{
OptimizedModel::ModelHeader_t* pVtxModel = pVtxBodyPart->pModel( modelID );
mstudiomodel_t *pStudioModel = pBodyPart->pModel( modelID );
// get the specified lod, assuming lod 0
int nLod = 0;
OptimizedModel::ModelLODHeader_t *pVtxLOD = pVtxModel->pLOD( nLod );
// must reset because each model has their own vertexes [0..n]
// in order for this to be monolithic for the entire prop the list must be segmented
triListVerts.Purge();
for ( int nMesh = 0; nMesh < pStudioModel->nummeshes; ++nMesh )
{
mstudiomesh_t* pMesh = pStudioModel->pMesh( nMesh );
OptimizedModel::MeshHeader_t* pVtxMesh = pVtxLOD->pMesh( nMesh );
const mstudio_meshvertexdata_t *vertData = pMesh->GetVertexData( (void *)pStudioHdr );
Assert( vertData ); // This can only return NULL on X360 for now
for ( int nGroup = 0; nGroup < pVtxMesh->numStripGroups; ++nGroup )
{
OptimizedModel::StripGroupHeader_t* pStripGroup = pVtxMesh->pStripGroup( nGroup );
int nStrip;
for ( nStrip = 0; nStrip < pStripGroup->numStrips; nStrip++ )
{
OptimizedModel::StripHeader_t *pStrip = pStripGroup->pStrip( nStrip );
if ( pStrip->flags & OptimizedModel::STRIP_IS_TRILIST )
{
for ( int i = 0; i < pStrip->numIndices; i += 3 )
{
int idx = pStrip->indexOffset + i;
unsigned short i1 = *pStripGroup->pIndex( idx );
unsigned short i2 = *pStripGroup->pIndex( idx + 1 );
unsigned short i3 = *pStripGroup->pIndex( idx + 2 );
int vertex1 = pStripGroup->pVertex( i1 )->origMeshVertID;
int vertex2 = pStripGroup->pVertex( i2 )->origMeshVertID;
int vertex3 = pStripGroup->pVertex( i3 )->origMeshVertID;
// transform position into world coordinate system
matrix3x4_t matrix;
AngleMatrix( prop.m_Angles, prop.m_Origin, matrix );
Vector position1;
Vector position2;
Vector position3;
VectorTransform( *vertData->Position( vertex1 ), matrix, position1 );
VectorTransform( *vertData->Position( vertex2 ), matrix, position2 );
VectorTransform( *vertData->Position( vertex3 ), matrix, position3 );
Vector normal1;
Vector normal2;
Vector normal3;
VectorTransform( *vertData->Normal( vertex1 ), matrix, normal1 );
VectorTransform( *vertData->Normal( vertex2 ), matrix, normal2 );
VectorTransform( *vertData->Normal( vertex3 ), matrix, normal3 );
AddTriVertsToList( triListVerts, pMesh->vertexoffset + vertex1, position1, position1, position2, position3, normal1, normal2, normal3 );
AddTriVertsToList( triListVerts, pMesh->vertexoffset + vertex2, position2, position1, position2, position3, normal1, normal2, normal3 );
AddTriVertsToList( triListVerts, pMesh->vertexoffset + vertex3, position3, position1, position2, position3, normal1, normal2, normal3 );
}
}
else
{
// all tris expected to be discrete tri lists
// must fixme if stripping ever occurs
printf( "unexpected strips found\n" );
Assert( 0 );
return;
}
}
}
}
}
}
}
const vertexFileHeader_t * mstudiomodel_t::CacheVertexData( void *pModelData )
{
studiohdr_t *pActiveStudioHdr = static_cast<studiohdr_t *>(pModelData);
Assert( pActiveStudioHdr );
if ( pActiveStudioHdr->pVertexBase )
{
return (vertexFileHeader_t *)pActiveStudioHdr->pVertexBase;
}
// mandatory callback to make requested data resident
// load and persist the vertex file
char fileName[MAX_PATH];
strcpy( fileName, "models/" );
strcat( fileName, pActiveStudioHdr->pszName() );
Q_StripExtension( fileName, fileName, sizeof( fileName ) );
strcat( fileName, ".vvd" );
// load the model
FileHandle_t fileHandle = g_pFileSystem->Open( fileName, "rb" );
if ( !fileHandle )
{
Error( "Unable to load vertex data \"%s\"\n", fileName );
}
// Get the file size
int vvdSize = g_pFileSystem->Size( fileHandle );
if ( vvdSize == 0 )
{
g_pFileSystem->Close( fileHandle );
Error( "Bad size for vertex data \"%s\"\n", fileName );
}
vertexFileHeader_t *pVvdHdr = (vertexFileHeader_t *)malloc( vvdSize );
g_pFileSystem->Read( pVvdHdr, vvdSize, fileHandle );
g_pFileSystem->Close( fileHandle );
// check header
if ( pVvdHdr->id != MODEL_VERTEX_FILE_ID )
{
Error("Error Vertex File %s id %d should be %d\n", fileName, pVvdHdr->id, MODEL_VERTEX_FILE_ID);
}
if ( pVvdHdr->version != MODEL_VERTEX_FILE_VERSION )
{
Error("Error Vertex File %s version %d should be %d\n", fileName, pVvdHdr->version, MODEL_VERTEX_FILE_VERSION);
}
if ( pVvdHdr->checksum != pActiveStudioHdr->checksum )
{
Error("Error Vertex File %s checksum %d should be %d\n", fileName, pVvdHdr->checksum, pActiveStudioHdr->checksum);
}
// need to perform mesh relocation fixups
// allocate a new copy
vertexFileHeader_t *pNewVvdHdr = (vertexFileHeader_t *)malloc( vvdSize );
if ( !pNewVvdHdr )
{
Error( "Error allocating %d bytes for Vertex File '%s'\n", vvdSize, fileName );
}
// load vertexes and run fixups
Studio_LoadVertexes( pVvdHdr, pNewVvdHdr, 0, true );
// discard original
free( pVvdHdr );
pVvdHdr = pNewVvdHdr;
pActiveStudioHdr->pVertexBase = (void*)pVvdHdr;
return pVvdHdr;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
struct ColorTexelValue
{
Vector mLinearColor; // Linear color value for this texel
bool mValidData; // Whether there is valid data in this texel.
size_t mTriangleIndex; // Which triangle we used to generate the texel.
};
// ------------------------------------------------------------------------------------------------
inline int ComputeLinearPos( int _x, int _y, int _resX, int _resY )
{
return Min( Max( 0, _y ), _resY - 1 ) * _resX
+ Min( Max( 0, _x ), _resX - 1 );
}
// ------------------------------------------------------------------------------------------------
inline float ComputeBarycentricDistanceToTri( Vector _barycentricCoord, Vector2D _v[3] )
{
Vector2D realPos = _barycentricCoord.x * _v[0]
+ _barycentricCoord.y * _v[1]
+ _barycentricCoord.z * _v[2];
int minIndex = 0;
float minVal = _barycentricCoord[0];
for (int i = 1; i < 3; ++i) {
if (_barycentricCoord[i] < minVal) {
minVal = _barycentricCoord[i];
minIndex = i;
}
}
Vector2D& first = _v[ (minIndex + 1) % 3];
Vector2D& second = _v[ (minIndex + 2) % 3];
return CalcDistanceToLineSegment2D( realPos, first, second );
}
// ------------------------------------------------------------------------------------------------
static void GenerateLightmapSamplesForMesh( const matrix3x4_t& _matPos, const matrix3x4_t& _matNormal, int _iThread, int _skipProp, int _flags, int _lightmapResX, int _lightmapResY, studiohdr_t* _pStudioHdr, mstudiomodel_t* _pStudioModel, OptimizedModel::ModelHeader_t* _pVtxModel, int _meshID, CComputeStaticPropLightingResults *_outResults )
{
// Could iterate and gen this if needed.
int nLod = 0;
OptimizedModel::ModelLODHeader_t *pVtxLOD = _pVtxModel->pLOD(nLod);
CUtlVector<colorTexel_t> &colorTexels = (*_outResults->m_ColorTexelsArrays.Tail());
const int cTotalPixelCount = _lightmapResX * _lightmapResY;
colorTexels.EnsureCount(cTotalPixelCount);
memset(colorTexels.Base(), 0, colorTexels.Count() * sizeof(colorTexel_t));
for (int i = 0; i < colorTexels.Count(); ++i) {
colorTexels[i].m_fDistanceToTri = FLT_MAX;
}
mstudiomesh_t* pMesh = _pStudioModel->pMesh(_meshID);
OptimizedModel::MeshHeader_t* pVtxMesh = pVtxLOD->pMesh(_meshID);
const mstudio_meshvertexdata_t *vertData = pMesh->GetVertexData((void *)_pStudioHdr);
Assert(vertData); // This can only return NULL on X360 for now
for (int nGroup = 0; nGroup < pVtxMesh->numStripGroups; ++nGroup)
{
OptimizedModel::StripGroupHeader_t* pStripGroup = pVtxMesh->pStripGroup(nGroup);
int nStrip;
for (nStrip = 0; nStrip < pStripGroup->numStrips; nStrip++)
{
OptimizedModel::StripHeader_t *pStrip = pStripGroup->pStrip(nStrip);
// If this hits, re-factor the code to iterate over triangles, and build the triangles
// from the underlying structures.
Assert((pStrip->flags & OptimizedModel::STRIP_IS_TRISTRIP) == 0);
if (pStrip->flags & OptimizedModel::STRIP_IS_TRILIST)
{
for (int i = 0; i < pStrip->numIndices; i += 3)
{
int idx = pStrip->indexOffset + i;
unsigned short i1 = *pStripGroup->pIndex(idx);
unsigned short i2 = *pStripGroup->pIndex(idx + 1);
unsigned short i3 = *pStripGroup->pIndex(idx + 2);
int vertex1 = pStripGroup->pVertex(i1)->origMeshVertID;
int vertex2 = pStripGroup->pVertex(i2)->origMeshVertID;
int vertex3 = pStripGroup->pVertex(i3)->origMeshVertID;
Vector modelPos[3] = {
*vertData->Position(vertex1),
*vertData->Position(vertex2),
*vertData->Position(vertex3)
};
Vector modelNormal[3] = {
*vertData->Normal(vertex1),
*vertData->Normal(vertex2),
*vertData->Normal(vertex3)
};
Vector worldPos[3];
Vector worldNormal[3];
VectorTransform(modelPos[0], _matPos, worldPos[0]);
VectorTransform(modelPos[1], _matPos, worldPos[1]);
VectorTransform(modelPos[2], _matPos, worldPos[2]);
VectorTransform(modelNormal[0], _matNormal, worldNormal[0]);
VectorTransform(modelNormal[1], _matNormal, worldNormal[1]);
VectorTransform(modelNormal[2], _matNormal, worldNormal[2]);
Vector2D texcoord[3] = {
*vertData->Texcoord(vertex1),
*vertData->Texcoord(vertex2),
*vertData->Texcoord(vertex3)
};
Rasterizer rasterizer(texcoord[0], texcoord[1], texcoord[2],
_lightmapResX, _lightmapResY);
for (auto it = rasterizer.begin(); it != rasterizer.end(); ++it)
{
size_t linearPos = rasterizer.GetLinearPos(it);
Assert(linearPos < cTotalPixelCount);
if ( colorTexels[linearPos].m_bValid )
{
continue;
}
float ourDistancetoTri = ComputeBarycentricDistanceToTri( it->barycentric, texcoord );
bool doWrite = it->insideTriangle
|| !colorTexels[linearPos].m_bPossiblyInteresting
|| colorTexels[linearPos].m_fDistanceToTri > ourDistancetoTri;
if (doWrite)
{
Vector itWorldPos = worldPos[0] * it->barycentric.x
+ worldPos[1] * it->barycentric.y
+ worldPos[2] * it->barycentric.z;
Vector itWorldNormal = worldNormal[0] * it->barycentric.x
+ worldNormal[1] * it->barycentric.y
+ worldNormal[2] * it->barycentric.z;
itWorldNormal.NormalizeInPlace();
colorTexels[linearPos].m_WorldPosition = itWorldPos;
colorTexels[linearPos].m_WorldNormal = itWorldNormal;
colorTexels[linearPos].m_bValid = it->insideTriangle;
colorTexels[linearPos].m_bPossiblyInteresting = true;
colorTexels[linearPos].m_fDistanceToTri = ourDistancetoTri;
}
}
}
}
}
}
// Process neighbors to the valid region. Walk through the existing array, look for samples that
// are not valid but are adjacent to valid samples. Works if we are only bilinearly sampling
// on the other side.
// First attempt: Just pretend the triangle was larger and cast a ray from this new world pos
// as above.
int linearPos = 0;
for ( int j = 0; j < _lightmapResY; ++j )
{
for (int i = 0; i < _lightmapResX; ++i )
{
bool shouldProcess = colorTexels[linearPos].m_bValid;
// Are any of the eight neighbors valid??
if ( colorTexels[linearPos].m_bPossiblyInteresting )
{
// Look at our neighborhood (3x3 centerd on us).
shouldProcess = shouldProcess
|| colorTexels[ComputeLinearPos( i - 1, j - 1, _lightmapResX, _lightmapResY )].m_bValid // TL
|| colorTexels[ComputeLinearPos( i , j - 1, _lightmapResX, _lightmapResY )].m_bValid // T
|| colorTexels[ComputeLinearPos( i + 1, j - 1, _lightmapResX, _lightmapResY )].m_bValid // TR
|| colorTexels[ComputeLinearPos( i - 1, j , _lightmapResX, _lightmapResY )].m_bValid // L
|| colorTexels[ComputeLinearPos( i + 1, j , _lightmapResX, _lightmapResY )].m_bValid // R
|| colorTexels[ComputeLinearPos( i - 1, j + 1, _lightmapResX, _lightmapResY )].m_bValid // BL
|| colorTexels[ComputeLinearPos( i , j + 1, _lightmapResX, _lightmapResY )].m_bValid // B
|| colorTexels[ComputeLinearPos( i + 1, j + 1, _lightmapResX, _lightmapResY )].m_bValid; // BR
}
if (shouldProcess)
{
Vector directColor(0, 0, 0),
indirectColor(0, 0, 0);
ComputeDirectLightingAtPoint( colorTexels[linearPos].m_WorldPosition, colorTexels[linearPos].m_WorldNormal, directColor, _iThread, _skipProp, _flags);
if (numbounce >= 1) {
ComputeIndirectLightingAtPoint( colorTexels[linearPos].m_WorldPosition, colorTexels[linearPos].m_WorldNormal, indirectColor, _iThread, true, (_flags & GATHERLFLAGS_IGNORE_NORMALS) != 0 );
}
VectorAdd(directColor, indirectColor, colorTexels[linearPos].m_Color);
}
++linearPos;
}
}
}
// ------------------------------------------------------------------------------------------------
static int GetTexelCount(unsigned int _resX, unsigned int _resY, bool _mipmaps)
{
// Because they are unsigned, this is a != check--but if we were to change to ints, this would be
// the right assert (and it's no worse than != now).
Assert(_resX > 0 && _resY > 0);
if (_mipmaps == false)
return _resX * _resY;
int retVal = 0;
while (_resX > 1 || _resY > 1)
{
retVal += _resX * _resY;
_resX = max(1, _resX >> 1);
_resY = max(1, _resY >> 1);
}
// Add in the 1x1 mipmap level, which wasn't hit above. This could be done in the initializer of
// retVal, but it's more obvious here.
retVal += 1;
return retVal;
}
// ------------------------------------------------------------------------------------------------
static void FilterFineMipmap(unsigned int _resX, unsigned int _resY, const CUtlVector<colorTexel_t>& _srcTexels, CUtlVector<Vector>* _outLinear)
{
Assert(_outLinear);
// We can't filter in place, so go ahead and create a linear buffer here.
CUtlVector<Vector> filterSrc;
filterSrc.EnsureCount(_srcTexels.Count());
for (int i = 0; i < _srcTexels.Count(); ++i)
{
ColorRGBExp32 rgbColor;
VectorToColorRGBExp32(_srcTexels[i].m_Color, rgbColor);
ConvertRGBExp32ToLinear( &rgbColor, &(filterSrc[i]) );
}
const int cRadius = 1;
const float cOneOverDiameter = 1.0f / pow(2.0f * cRadius + 1.0f, 2.0f) ;
// Filter here.
for (int j = 0; j < _resY; ++j)
{
for (int i = 0; i < _resX; ++i)
{
Vector value(0, 0, 0);
int thisIndex = ComputeLinearPos(i, j, _resX, _resY);
if (!_srcTexels[thisIndex].m_bValid)
{
(*_outLinear)[thisIndex] = filterSrc[thisIndex];
continue;
}
// TODO: Check ASM for this, unroll by hand if needed.
for ( int offsetJ = -cRadius; offsetJ <= cRadius; ++offsetJ )
{
for ( int offsetI = -cRadius; offsetI <= cRadius; ++offsetI )
{
int finalIndex = ComputeLinearPos( i + offsetI, j + offsetJ, _resX, _resY );
if ( !_srcTexels[finalIndex].m_bValid )
{
finalIndex = thisIndex;
}
value += filterSrc[finalIndex];
}
}
(*_outLinear)[thisIndex] = value * cOneOverDiameter;
}
}
}
// ------------------------------------------------------------------------------------------------
static void BuildFineMipmap(unsigned int _resX, unsigned int _resY, bool _applyFilter, const CUtlVector<colorTexel_t>& _srcTexels, CUtlVector<RGB888_t>* _outTexelsRGB888, CUtlVector<Vector>* _outLinear)
{
// At least one of these needs to be non-null, otherwise what are we doing here?
Assert(_outTexelsRGB888 || _outLinear);
Assert(!_applyFilter || _outLinear);
Assert(_srcTexels.Count() == GetTexelCount(_resX, _resY, false));
int texelCount = GetTexelCount(_resX, _resY, true);
if (_outTexelsRGB888)
(*_outTexelsRGB888).EnsureCount(texelCount);
if (_outLinear)
(*_outLinear).EnsureCount(GetTexelCount(_resX, _resY, false));
// This code can take awhile, so minimize the branchiness of the inner-loop.
if (_applyFilter)
{
FilterFineMipmap(_resX, _resY, _srcTexels, _outLinear);
if ( _outTexelsRGB888 )
{
for (int i = 0; i < _srcTexels.Count(); ++i)
{
RGBA8888_t encodedColor;
Vector linearColor = (*_outLinear)[i];
ConvertLinearToRGBA8888( &linearColor, (unsigned char*)&encodedColor );
(*_outTexelsRGB888)[i].r = encodedColor.r;
(*_outTexelsRGB888)[i].g = encodedColor.g;
(*_outTexelsRGB888)[i].b = encodedColor.b;
}
}
}
else
{
for (int i = 0; i < _srcTexels.Count(); ++i)
{
ColorRGBExp32 rgbColor;
RGBA8888_t encodedColor;
VectorToColorRGBExp32(_srcTexels[i].m_Color, rgbColor);
ConvertRGBExp32ToRGBA8888(&rgbColor, (unsigned char*)&encodedColor, (_outLinear ? (&(*_outLinear)[i]) : NULL) );
// We drop alpha on the floor here, if this were to fire we'd need to consider using a different compressed format.
Assert(encodedColor.a == 0xFF);
if (_outTexelsRGB888)
{
(*_outTexelsRGB888)[i].r = encodedColor.r;
(*_outTexelsRGB888)[i].g = encodedColor.g;
(*_outTexelsRGB888)[i].b = encodedColor.b;
}
}
}
}
// ------------------------------------------------------------------------------------------------
static void FilterCoarserMipmaps(unsigned int _resX, unsigned int _resY, CUtlVector<Vector>* _scratchLinear, CUtlVector<RGB888_t> *_outTexelsRGB888)
{
Assert(_outTexelsRGB888);
int srcResX = _resX;
int srcResY = _resY;
int dstResX = max(1, (srcResX >> 1));
int dstResY = max(1, (srcResY >> 1));
int dstOffset = GetTexelCount(srcResX, srcResY, false);
// Build mipmaps here, after being converted to linear space.
// TODO: Should do better filtering for downsampling. But this will work for now.
while (srcResX > 1 || srcResY > 1)
{
for (int j = 0; j < srcResY; j += 2) {
for (int i = 0; i < srcResX; i += 2) {
int srcCol0 = i;
int srcCol1 = i + 1 > srcResX - 1 ? srcResX - 1 : i + 1;
int srcRow0 = j;
int srcRow1 = j + 1 > srcResY - 1 ? srcResY - 1 : j + 1;;
int dstCol = i >> 1;
int dstRow = j >> 1;
const Vector& tl = (*_scratchLinear)[srcCol0 + (srcRow0 * srcResX)];
const Vector& tr = (*_scratchLinear)[srcCol1 + (srcRow0 * srcResX)];
const Vector& bl = (*_scratchLinear)[srcCol0 + (srcRow1 * srcResX)];
const Vector& br = (*_scratchLinear)[srcCol1 + (srcRow1 * srcResX)];
Vector sample = (tl + tr + bl + br) / 4.0f;
ConvertLinearToRGBA8888(&sample, (unsigned char*)&(*_outTexelsRGB888)[dstOffset + dstCol + dstRow * dstResX]);
// Also overwrite the srcBuffer to filter the next loop. This is safe because we won't be reading this source value
// again during this mipmap level.
(*_scratchLinear)[dstCol + dstRow * dstResX] = sample;
}
}
srcResX = dstResX;
srcResY = dstResY;
dstResX = max(1, (srcResX >> 1));
dstResY = max(1, (srcResY >> 1));
dstOffset += GetTexelCount(srcResX, srcResY, false);
}
}
// ------------------------------------------------------------------------------------------------
static void ConvertToDestinationFormat(unsigned int _resX, unsigned int _resY, ImageFormat _destFmt, const CUtlVector<RGB888_t>& _scratchRBG888, CUtlMemory<byte>* _outTexture)
{
const ImageFormat cSrcImageFormat = IMAGE_FORMAT_RGB888;
// Converts from the scratch RGB888 buffer, which should be fully filled out to the output texture.
int destMemoryUsage = ImageLoader::GetMemRequired(_resX, _resY, 1, _destFmt, true);
(*_outTexture).EnsureCapacity(destMemoryUsage);
int srcResX = _resX;
int srcResY = _resY;
int srcOffset = 0;
int dstOffset = 0;
// The usual case--that they'll be different.
if (cSrcImageFormat != _destFmt)
{
while (srcResX > 1 || srcResY > 1)
{
// Convert this mipmap level.
ImageLoader::ConvertImageFormat((unsigned char*)(&_scratchRBG888[srcOffset]), cSrcImageFormat, (*_outTexture).Base() + dstOffset, _destFmt, srcResX, srcResY);
// Then update offsets for the next mipmap level.
srcOffset += GetTexelCount(srcResX, srcResY, false);
dstOffset += ImageLoader::GetMemRequired(srcResX, srcResY, 1, _destFmt, false);
srcResX = max(1, (srcResX >> 1));
srcResY = max(1, (srcResY >> 1));
}
// Do the 1x1 level also.
ImageLoader::ConvertImageFormat((unsigned char*)_scratchRBG888.Base() + srcOffset, cSrcImageFormat, (*_outTexture).Base() + dstOffset, _destFmt, srcResX, srcResY);
} else {
// But sometimes (particularly for debugging) they will be the same.
Q_memcpy( (*_outTexture).Base(), _scratchRBG888.Base(), destMemoryUsage );
}
}
// ------------------------------------------------------------------------------------------------
static void ConvertTexelDataToTexture(unsigned int _resX, unsigned int _resY, ImageFormat _destFmt, const CUtlVector<colorTexel_t>& _srcTexels, CUtlMemory<byte>* _outTexture)
{
Assert(_outTexture);
Assert(_srcTexels.Count() == _resX * _resY);
CUtlVector<RGB888_t> scratchRGB888;
CUtlVector<Vector> scratchLinear;
BuildFineMipmap(_resX, _resY, true, _srcTexels, &scratchRGB888, &scratchLinear);
FilterCoarserMipmaps(_resX, _resY, &scratchLinear, &scratchRGB888 );
ConvertToDestinationFormat(_resX, _resY, _destFmt, scratchRGB888, _outTexture);
}
// ------------------------------------------------------------------------------------------------
static void DumpLightmapLinear( const char* _dstFilename, const CUtlVector<colorTexel_t>& _srcTexels, int _width, int _height )
{
CUtlVector< Vector > linearFloats;
CUtlVector< BGR888_t > linearBuffer;
BuildFineMipmap( _width, _height, true, _srcTexels, NULL, &linearFloats );
linearBuffer.SetCount( linearFloats.Count() );
for ( int i = 0; i < linearFloats.Count(); ++i ) {
linearBuffer[i].b = RoundFloatToByte(linearFloats[i].z * 255.0f);
linearBuffer[i].g = RoundFloatToByte(linearFloats[i].y * 255.0f);
linearBuffer[i].r = RoundFloatToByte(linearFloats[i].x * 255.0f);
}
TGAWriter::WriteTGAFile( _dstFilename, _width, _height, IMAGE_FORMAT_BGR888, (uint8*)(linearBuffer.Base()), _width * ImageLoader::SizeInBytes(IMAGE_FORMAT_BGR888) );
}
|