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
|
//========= Copyright Valve Corporation, All rights reserved. ============//
// TOGL CODE LICENSE
//
// Copyright 2011-2014 Valve Corporation
// All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// cglmtex.cpp
//
//===============================================================================
#include "togl/rendermechanism.h"
#include "tier0/icommandline.h"
#include "glmtexinlines.h"
// memdbgon -must- be the last include file in a .cpp file.
#include "tier0/memdbgon.h"
#if defined(OSX)
#include "appframework/ilaunchermgr.h"
extern ILauncherMgr *g_pLauncherMgr;
#endif
//===============================================================================
#if GLMDEBUG
CGLMTex *g_pFirstCGMLTex;
#endif
ConVar gl_pow2_tempmem( "gl_pow2_tempmem", "0", FCVAR_INTERNAL_USE,
"If set, use power-of-two allocations for temporary texture memory during uploads. "
"May help with fragmentation on certain systems caused by heavy churn of large allocations." );
#define TEXSPACE_LOGGING 0
// encoding layout to an index where the bits read
// 4 : 1 if compressed
// 2 : 1 if not power of two
// 1 : 1 if mipmapped
bool pwroftwo (int val )
{
return (val & (val-1)) == 0;
}
int sEncodeLayoutAsIndex( GLMTexLayoutKey *key )
{
int index = 0;
if (key->m_texFlags & kGLMTexMipped)
{
index |= 1;
}
if ( ! ( pwroftwo(key->m_xSize) && pwroftwo(key->m_ySize) && pwroftwo(key->m_zSize) ) )
{
// if not all power of two
index |= 2;
}
if (GetFormatDesc( key->m_texFormat )->m_chunkSize >1 )
{
index |= 4;
}
return index;
}
static unsigned long g_texGlobalBytes[8];
//===============================================================================
const GLMTexFormatDesc g_formatDescTable[] =
{
// not yet handled by this table:
// D3DFMT_INDEX16, D3DFMT_VERTEXDATA // D3DFMT_INDEX32,
// WTF { D3DFMT_R5G6R5 ???, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
// WTF { D3DFMT_A ???, GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
// ??? D3DFMT_V8U8,
// ??? D3DFMT_Q8W8V8U8,
// ??? D3DFMT_X8L8V8U8,
// ??? D3DFMT_R32F,
// ??? D3DFMT_D24X4S4 unsure how to handle or if it is ever used..
// ??? D3DFMT_D15S1 ever used ?
// ??? D3DFMT_D24X8 ever used?
// summ-name d3d-format gl-int-format gl-int-format-srgb gl-data-format gl-data-type chunksize, bytes-per-sqchunk
{ "_D16", D3DFMT_D16, GL_DEPTH_COMPONENT16, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 1, 2 },
{ "_D24X8", D3DFMT_D24X8, GL_DEPTH_COMPONENT24, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 1, 4 }, // ??? unsure on this one
{ "_D24S8", D3DFMT_D24S8, GL_DEPTH24_STENCIL8_EXT, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, 1, 4 },
{ "_A8R8G8B8", D3DFMT_A8R8G8B8, GL_RGBA8, GL_SRGB8_ALPHA8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
{ "_A4R4G4B4", D3DFMT_A4R4G4B4, GL_RGBA4, 0, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, 1, 2 },
{ "_X8R8G8B8", D3DFMT_X8R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
{ "_X1R5G5B5", D3DFMT_X1R5G5B5, GL_RGB5, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
{ "_A1R5G5B5", D3DFMT_A1R5G5B5, GL_RGB5_A1, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
{ "_L8", D3DFMT_L8, GL_LUMINANCE8, GL_SLUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 1 },
{ "_A8L8", D3DFMT_A8L8, GL_LUMINANCE8_ALPHA8, GL_SLUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 1, 2 },
{ "_DXT1", D3DFMT_DXT1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, GL_RGB, GL_UNSIGNED_BYTE, 4, 8 },
{ "_DXT3", D3DFMT_DXT3, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
{ "_DXT5", D3DFMT_DXT5, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
{ "_A16B16G16R16F", D3DFMT_A16B16G16R16F, GL_RGBA16F_ARB, 0, GL_RGBA, GL_HALF_FLOAT_ARB, 1, 8 },
{ "_A16B16G16R16", D3DFMT_A16B16G16R16, GL_RGBA16, 0, GL_RGBA, GL_UNSIGNED_SHORT, 1, 8 }, // 16bpc integer tex
{ "_A32B32G32R32F", D3DFMT_A32B32G32R32F, GL_RGBA32F_ARB, 0, GL_RGBA, GL_FLOAT, 1, 16 },
{ "_R8G8B8", D3DFMT_R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGR, GL_UNSIGNED_BYTE, 1, 3 },
{ "_A8", D3DFMT_A8, GL_ALPHA8, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
{ "_R5G6B5", D3DFMT_R5G6B5, GL_RGB, GL_SRGB_EXT, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
// fakey tex formats: the stated GL format and the memory layout may not agree (U8V8 for example)
// _Q8W8V8U8 we just pass through as RGBA bytes. Shader does scale/bias fix
{ "_Q8W8V8U8", D3DFMT_Q8W8V8U8, GL_RGBA8, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 }, // straight ripoff of D3DFMT_A8R8G8B8
// U8V8 is exposed to the client as 2-bytes per texel, but we download it as 3-byte RGB.
// WriteTexels needs to do that conversion from rg8 to rgb8 in order to be able to download it correctly
{ "_V8U8", D3DFMT_V8U8, GL_RGB8, 0, GL_RG, GL_BYTE, 1, 2 },
{ "_R32F", D3DFMT_R32F, GL_R32F, GL_R32F, GL_RED, GL_FLOAT, 1, 4 },
//$ TODO: Need to merge bitmap changes over from Dota to get these formats.
#if 0
{ "_A2R10G10B10", D3DFMT_A2R10G10B10, GL_RGB10_A2, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_10_10_10_2, 1, 4 },
{ "_A2B10G10R10", D3DFMT_A2B10G10R10, GL_RGB10_A2, GL_RGB10_A2, GL_BGRA, GL_UNSIGNED_INT_10_10_10_2, 1, 4 },
#endif
/*
// NV shadow depth tex
D3DFMT_NV_INTZ = 0x5a544e49, // MAKEFOURCC('I','N','T','Z')
D3DFMT_NV_RAWZ = 0x5a574152, // MAKEFOURCC('R','A','W','Z')
// NV null tex
D3DFMT_NV_NULL = 0x4c4c554e, // MAKEFOURCC('N','U','L','L')
// ATI shadow depth tex
D3DFMT_ATI_D16 = 0x36314644, // MAKEFOURCC('D','F','1','6')
D3DFMT_ATI_D24S8 = 0x34324644, // MAKEFOURCC('D','F','2','4')
// ATI 1N and 2N compressed tex
D3DFMT_ATI_2N = 0x32495441, // MAKEFOURCC('A', 'T', 'I', '2')
D3DFMT_ATI_1N = 0x31495441, // MAKEFOURCC('A', 'T', 'I', '1')
*/
};
int g_formatDescTableCount = sizeof(g_formatDescTable) / sizeof( g_formatDescTable[0] );
const GLMTexFormatDesc *GetFormatDesc( D3DFORMAT format )
{
for( int i=0; i<g_formatDescTableCount; i++)
{
if (g_formatDescTable[i].m_d3dFormat == format)
{
return &g_formatDescTable[i];
}
}
return (const GLMTexFormatDesc *)NULL; // not found
}
//===============================================================================
void InsertTexelComponentFixed( float value, int width, unsigned long *valuebuf )
{
unsigned long range = (1<<width);
unsigned long scaled = (value * (float) range) * (range-1) / (range);
if (scaled >= range) DebuggerBreak();
*valuebuf = (*valuebuf << width) | scaled;
}
// return true if successful
bool GLMGenTexels( GLMGenTexelParams *params )
{
unsigned char chunkbuf[256]; // can't think of any chunk this big..
const GLMTexFormatDesc *format = GetFormatDesc( params->m_format );
if (!format)
{
return FALSE; // fail
}
// this section just generates one square chunk in the desired format
unsigned long *temp32 = (unsigned long*)chunkbuf;
unsigned int chunksize = 0; // we can sanity check against the format table with this
switch( params->m_format )
{
// comment shows byte order in RAM
// lowercase is bit arrangement in a byte
case D3DFMT_A8R8G8B8: // B G R A
InsertTexelComponentFixed( params->a, 8, temp32 ); // A is inserted first and winds up at most significant bits after insertions follow
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 4;
break;
case D3DFMT_A4R4G4B4: // [ggggbbbb] [aaaarrrr] RA (nibbles)
InsertTexelComponentFixed( params->a, 4, temp32 );
InsertTexelComponentFixed( params->r, 4, temp32 );
InsertTexelComponentFixed( params->g, 4, temp32 );
InsertTexelComponentFixed( params->b, 4, temp32 );
chunksize = 2;
break;
case D3DFMT_X8R8G8B8: // B G R X
InsertTexelComponentFixed( 0.0, 8, temp32 );
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 4;
break;
case D3DFMT_X1R5G5B5: // [gggbbbbb] [xrrrrrgg]
InsertTexelComponentFixed( 0.0, 1, temp32 );
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 5, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_A1R5G5B5: // [gggbbbbb] [arrrrrgg]
InsertTexelComponentFixed( params->a, 1, temp32 );
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 5, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_L8: // L // caller, use R for L
InsertTexelComponentFixed( params->r, 8, temp32 );
chunksize = 1;
break;
case D3DFMT_A8L8: // L A // caller, use R for L and A for A
InsertTexelComponentFixed( params->a, 8, temp32 );
InsertTexelComponentFixed( params->r, 8, temp32 );
chunksize = 2;
break;
case D3DFMT_R8G8B8: // B G R
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 3;
break;
case D3DFMT_A8: // A
InsertTexelComponentFixed( params->a, 8, temp32 );
chunksize = 1;
break;
case D3DFMT_R5G6B5: // [gggbbbbb] [rrrrrggg]
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 6, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_DXT1:
{
memset( temp32, 0, 8 ); // zap 8 bytes
// two 565 RGB words followed by 32 bits of 2-bit interp values for a 4x4 block
// we write the same color to both slots and all zeroes for the mask (one color total)
unsigned long dxt1_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt1_color );
InsertTexelComponentFixed( params->g, 6, &dxt1_color );
InsertTexelComponentFixed( params->b, 5, &dxt1_color );
// dupe
dxt1_color = dxt1_color | (dxt1_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[0] = dxt1_color;
// color mask bits after that are already set to all zeroes. chunk is done.
chunksize = 8;
}
break;
case D3DFMT_DXT3:
{
memset( temp32, 0, 16 ); // zap 16 bytes
// eight bytes of alpha (16 4-bit alpha nibbles)
// followed by a DXT1 block
unsigned long dxt3_alpha = 0;
for( int i=0; i<8; i++)
{
// splat same alpha through block
InsertTexelComponentFixed( params->a, 4, &dxt3_alpha );
}
unsigned long dxt3_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt3_color );
InsertTexelComponentFixed( params->g, 6, &dxt3_color );
InsertTexelComponentFixed( params->b, 5, &dxt3_color );
// dupe
dxt3_color = dxt3_color | (dxt3_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[0] = dxt3_alpha;
*(unsigned long*)&chunkbuf[4] = dxt3_alpha;
*(unsigned long*)&chunkbuf[8] = dxt3_color;
*(unsigned long*)&chunkbuf[12] = dxt3_color;
chunksize = 16;
}
break;
case D3DFMT_DXT5:
{
memset( temp32, 0, 16 ); // zap 16 bytes
// DXT5 has 8 bytes of compressed alpha, then 8 bytes of compressed RGB like DXT1.
// the 8 alpha bytes are 2 bytes of endpoint alpha values, then 16x3 bits of interpolants.
// so to write a single alpha value, just figure out the value, store it in both the first two bytes then store zeroes.
InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
// rest of the alpha mask was already zeroed.
// now do colors
unsigned long dxt5_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt5_color );
InsertTexelComponentFixed( params->g, 6, &dxt5_color );
InsertTexelComponentFixed( params->b, 5, &dxt5_color );
// dupe
dxt5_color = dxt5_color | (dxt5_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[8] = dxt5_color;
*(unsigned long*)&chunkbuf[12] = dxt5_color;
chunksize = 16;
}
break;
case D3DFMT_A32B32G32R32F:
{
*(float*)&chunkbuf[0] = params->r;
*(float*)&chunkbuf[4] = params->g;
*(float*)&chunkbuf[8] = params->b;
*(float*)&chunkbuf[12] = params->a;
chunksize = 16;
}
break;
case D3DFMT_A16B16G16R16:
memset( chunkbuf, 0, 8 );
// R and G wind up in the first 32 bits
// B and A wind up in the second 32 bits
InsertTexelComponentFixed( params->a, 16, (unsigned long*)&chunkbuf[4] ); // winds up as MSW of second word (note [4]) - thus last in RAM
InsertTexelComponentFixed( params->b, 16, (unsigned long*)&chunkbuf[4] );
InsertTexelComponentFixed( params->g, 16, (unsigned long*)&chunkbuf[0] );
InsertTexelComponentFixed( params->r, 16, (unsigned long*)&chunkbuf[0] ); // winds up as LSW of first word, thus first in RAM
chunksize = 8;
break;
// not done yet
//case D3DFMT_D16:
//case D3DFMT_D24X8:
//case D3DFMT_D24S8:
//case D3DFMT_A16B16G16R16F:
default:
return FALSE; // fail
break;
}
// once the chunk buffer is filled..
// sanity check the reported chunk size.
if (static_cast<int>(chunksize) != format->m_bytesPerSquareChunk)
{
DebuggerBreak();
return FALSE;
}
// verify that the amount you want to write will not exceed the limit byte count
unsigned long destByteCount = chunksize * params->m_chunkCount;
if (static_cast<int>(destByteCount) > params->m_byteCountLimit)
{
DebuggerBreak();
return FALSE;
}
// write the bytes.
unsigned char *destP = (unsigned char*)params->m_dest;
for( int chunk=0; chunk < params->m_chunkCount; chunk++)
{
for( uint byteindex = 0; byteindex < chunksize; byteindex++)
{
*destP++ = chunkbuf[byteindex];
}
}
params->m_bytesWritten = destP - (unsigned char*)params->m_dest;
return TRUE;
}
//===============================================================================
bool LessFunc_GLMTexLayoutKey( const GLMTexLayoutKey &a, const GLMTexLayoutKey &b )
{
#define DO_LESS(fff) if (a.fff != b.fff) { return (a.fff< b.fff); }
DO_LESS(m_texGLTarget);
DO_LESS(m_texFormat);
DO_LESS(m_texFlags);
DO_LESS(m_texSamples);
DO_LESS(m_xSize);
DO_LESS(m_ySize)
DO_LESS(m_zSize);
#undef DO_LESS
return false; // they are equal
}
CGLMTexLayoutTable::CGLMTexLayoutTable()
{
m_layoutMap.SetLessFunc( LessFunc_GLMTexLayoutKey );
}
GLMTexLayout *CGLMTexLayoutTable::NewLayoutRef( GLMTexLayoutKey *pDesiredKey )
{
GLMTexLayoutKey tempKey;
GLMTexLayoutKey *key = pDesiredKey;
// look up 'key' in the map and see if it's a hit, if so, bump the refcount and return
// if not, generate a completed layout based on the key, add to map, set refcount to 1, return that
const GLMTexFormatDesc *formatDesc = GetFormatDesc( key->m_texFormat );
//bool compression = (formatDesc->m_chunkSize > 1) != 0;
if (!formatDesc)
{
GLMStop(); // bad news
}
if ( gGL->m_bHave_GL_EXT_texture_sRGB_decode )
{
if ( ( formatDesc->m_glIntFormatSRGB != 0 ) && ( ( key->m_texFlags & kGLMTexSRGB ) == 0 ) )
{
tempKey = *pDesiredKey;
key = &tempKey;
// Slam on SRGB texture flag, and we'll use GL_EXT_texture_sRGB_decode to selectively turn it off in the samplers
key->m_texFlags |= kGLMTexSRGB;
}
}
unsigned short index = m_layoutMap.Find( *key );
if (index != m_layoutMap.InvalidIndex())
{
// found it
//printf(" -hit- ");
GLMTexLayout *layout = m_layoutMap[ index ];
// bump ref count
layout->m_refCount ++;
return layout;
}
else
{
//printf(" -miss- ");
// need to make a new one
// to allocate it, we need to know how big to make it (slice count)
// figure out how many mip levels are in play
int mipCount = 1;
if (key->m_texFlags & kGLMTexMipped)
{
int largestAxis = key->m_xSize;
if (key->m_ySize > largestAxis)
largestAxis = key->m_ySize;
if (key->m_zSize > largestAxis)
largestAxis = key->m_zSize;
mipCount = 0;
while( largestAxis > 0 )
{
mipCount ++;
largestAxis >>= 1;
}
}
int faceCount = 1;
if (key->m_texGLTarget == GL_TEXTURE_CUBE_MAP)
{
faceCount = 6;
}
int sliceCount = mipCount * faceCount;
if (key->m_texFlags & kGLMTexMultisampled)
{
Assert( (key->m_texGLTarget == GL_TEXTURE_2D) );
Assert( sliceCount == 1 );
// assume non mipped
Assert( (key->m_texFlags & kGLMTexMipped) == 0 );
Assert( (key->m_texFlags & kGLMTexMippedAuto) == 0 );
// assume renderable and srgb
Assert( (key->m_texFlags & kGLMTexRenderable) !=0 );
//Assert( (key->m_texFlags & kGLMTexSRGB) !=0 ); //FIXME don't assert on making depthstencil surfaces which are non srgb
// double check sample count (FIXME need real limit check here against device/driver)
Assert( (key->m_texSamples==2) || (key->m_texSamples==4) || (key->m_texSamples==6) || (key->m_texSamples==8) );
}
// now we know enough to allocate and populate the new tex layout.
// malloc the new layout
int layoutSize = sizeof( GLMTexLayout ) + (sliceCount * sizeof( GLMTexLayoutSlice ));
GLMTexLayout *layout = (GLMTexLayout *)malloc( layoutSize );
memset( layout, 0, layoutSize );
// clone the key in there
memset( &layout->m_key, 0x00, sizeof(layout->m_key) );
layout->m_key = *key;
// set refcount
layout->m_refCount = 1;
// save the format desc
layout->m_format = (GLMTexFormatDesc *)formatDesc;
// we know the mipcount from before
layout->m_mipCount = mipCount;
// we know the face count too
layout->m_faceCount = faceCount;
// slice count is the product
layout->m_sliceCount = mipCount * faceCount;
// we can now fill in the slices.
GLMTexLayoutSlice *slicePtr = &layout->m_slices[0];
int storageOffset = 0;
//bool compressed = (formatDesc->m_chunkSize > 1); // true if DXT
for( int mip = 0; mip < mipCount; mip ++ )
{
for( int face = 0; face < faceCount; face++ )
{
// note application of chunk size which is 1 for uncompressed, and 4 for compressed tex (DXT)
// note also that the *dimensions* must scale down to 1
// but that the *storage* cannot go below 4x4.
// we introduce the "storage sizes" which are clamped, to compute the storage footprint.
int storage_x,storage_y,storage_z;
slicePtr->m_xSize = layout->m_key.m_xSize >> mip;
slicePtr->m_xSize = MAX( slicePtr->m_xSize, 1 ); // dimension can't go to zero
storage_x = MAX( slicePtr->m_xSize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
slicePtr->m_ySize = layout->m_key.m_ySize >> mip;
slicePtr->m_ySize = MAX( slicePtr->m_ySize, 1 ); // dimension can't go to zero
storage_y = MAX( slicePtr->m_ySize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
slicePtr->m_zSize = layout->m_key.m_zSize >> mip;
slicePtr->m_zSize = MAX( slicePtr->m_zSize, 1 ); // dimension can't go to zero
storage_z = MAX( slicePtr->m_zSize, 1); // storage extent for Z cannot go below '1'.
//if (compressed) NO NO NO do not lie about the dimensionality, just fudge the storage.
//{
// // round up to multiple of 4 in X and Y axes
// slicePtr->m_xSize = (slicePtr->m_xSize+3) & (~3);
// slicePtr->m_ySize = (slicePtr->m_ySize+3) & (~3);
//}
int xchunks = (storage_x / formatDesc->m_chunkSize );
int ychunks = (storage_y / formatDesc->m_chunkSize );
slicePtr->m_storageSize = (xchunks * ychunks * formatDesc->m_bytesPerSquareChunk) * storage_z;
slicePtr->m_storageOffset = storageOffset;
storageOffset += slicePtr->m_storageSize;
storageOffset = ( (storageOffset+0x0F) & (~0x0F)); // keep each MIP starting on a 16 byte boundary.
slicePtr++;
}
}
layout->m_storageTotalSize = storageOffset;
//printf("\n size %08x for key (x=%d y=%d z=%d, fmt=%08x, bpsc=%d)", layout->m_storageTotalSize, key->m_xSize, key->m_ySize, key->m_zSize, key->m_texFormat, formatDesc->m_bytesPerSquareChunk );
// generate summary
// "target, format, +/- mips, base size"
char scratch[1024];
char *targetname = "?";
switch( key->m_texGLTarget )
{
case GL_TEXTURE_2D: targetname = "2D "; break;
case GL_TEXTURE_3D: targetname = "3D "; break;
case GL_TEXTURE_CUBE_MAP: targetname = "CUBE"; break;
}
sprintf( scratch, "[%s %s %dx%dx%d mips=%d slices=%d flags=%02lX%s]",
targetname,
formatDesc->m_formatSummary,
layout->m_key.m_xSize, layout->m_key.m_ySize, layout->m_key.m_zSize,
mipCount,
sliceCount,
layout->m_key.m_texFlags,
(layout->m_key.m_texFlags & kGLMTexSRGB) ? " SRGB" : ""
);
layout->m_layoutSummary = strdup( scratch );
//GLMPRINTF(("-D- new tex layout [ %s ]", scratch ));
// then insert into map. disregard returned index.
m_layoutMap.Insert( layout->m_key, layout );
return layout;
}
}
void CGLMTexLayoutTable::DelLayoutRef( GLMTexLayout *layout )
{
// locate layout in hash, drop refcount
// (some GC step later on will harvest expired layouts - not like it's any big challenge to re-generate them)
unsigned short index = m_layoutMap.Find( layout->m_key );
if (index != m_layoutMap.InvalidIndex())
{
// found it
GLMTexLayout *layout = m_layoutMap[ index ];
// drop ref count
layout->m_refCount --;
//assert( layout->m_refCount >= 0 );
}
else
{
// that's bad
GLMStop();
}
}
void CGLMTexLayoutTable::DumpStats( )
{
for (uint i=0; i<m_layoutMap.Count(); i++ )
{
GLMTexLayout *layout = m_layoutMap[ i ];
// print it out
printf("\n%05d instances %08d bytes %08d totbytes %s", layout->m_refCount, layout->m_storageTotalSize, (layout->m_refCount*layout->m_storageTotalSize), layout->m_layoutSummary );
}
}
ConVar gl_texmsaalog ( "gl_texmsaalog", "0");
ConVar gl_rt_forcergba ( "gl_rt_forcergba", "1" ); // on teximage of a renderable tex, pass GL_RGBA in place of GL_BGRA
ConVar gl_minimize_rt_tex ( "gl_minimize_rt_tex", "0" ); // if 1, set the GL_TEXTURE_MINIMIZE_STORAGE_APPLE texture parameter to cut off mipmaps for RT's
ConVar gl_minimize_all_tex ( "gl_minimize_all_tex", "1" ); // if 1, set the GL_TEXTURE_MINIMIZE_STORAGE_APPLE texture parameter to cut off mipmaps for textures which are unmipped
ConVar gl_minimize_tex_log ( "gl_minimize_tex_log", "0" ); // if 1, printf the names of the tex that got minimized
CGLMTex::CGLMTex( GLMContext *ctx, GLMTexLayout *layout, uint levels, const char *debugLabel )
{
#if GLMDEBUG
m_pPrevTex = NULL;
m_pNextTex = g_pFirstCGMLTex;
if ( m_pNextTex )
{
Assert( m_pNextTex->m_pPrevTex == NULL );
m_pNextTex->m_pPrevTex = this;
}
g_pFirstCGMLTex = this;
#endif
// caller has responsibility to make 'ctx' current, but we check to be sure.
ctx->CheckCurrent();
m_nLastResolvedBatchCounter = ctx->m_nBatchCounter;
// note layout requested
m_layout = layout;
m_texGLTarget = m_layout->m_key.m_texGLTarget;
m_nSamplerType = SAMPLER_TYPE_UNUSED;
switch ( m_texGLTarget )
{
case GL_TEXTURE_CUBE_MAP: m_nSamplerType = SAMPLER_TYPE_CUBE; break;
case GL_TEXTURE_2D: m_nSamplerType = SAMPLER_TYPE_2D; break;
case GL_TEXTURE_3D: m_nSamplerType = SAMPLER_TYPE_3D; break;
default:
Assert( 0 );
break;
}
m_maxActiveMip = -1; //index of highest mip that has been written - increase as each mip arrives
m_minActiveMip = 999; //index of lowest mip that has been written - lower it as each mip arrives
// note context owner
m_ctx = ctx;
// clear the bind point flags
//m_bindPoints.ClearAll();
// clear the RT attach count
m_rtAttachCount = 0;
// come up with a GL name for this texture.
m_texName = ctx->CreateTex( m_texGLTarget, m_layout->m_format->m_glIntFormat );
m_pBlitSrcFBO = NULL;
m_pBlitDstFBO = NULL;
// Sense whether to try and apply client storage upon teximage/subimage.
// This should only be true if we're running on OSX 10.6 or it was explicitly
// enabled with -gl_texclientstorage on the command line.
m_texClientStorage = ctx->m_bTexClientStorage;
// flag that we have not yet been explicitly kicked into VRAM..
m_texPreloaded = false;
// clone the debug label if there is one.
m_debugLabel = debugLabel ? strdup(debugLabel) : NULL;
// if tex is MSAA renderable, make an RBO, else zero the RBO name and dirty bit
if (layout->m_key.m_texFlags & kGLMTexMultisampled)
{
gGL->glGenRenderbuffersEXT( 1, &m_rboName );
// so we have enough info to go ahead and bind the RBO and put storage on it?
// try it.
gGL->glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, m_rboName );
// quietly clamp if sample count exceeds known limit for the device
int sampleCount = layout->m_key.m_texSamples;
if (sampleCount > ctx->Caps().m_maxSamples)
{
sampleCount = ctx->Caps().m_maxSamples; // clamp
}
GLenum msaaFormat = (layout->m_key.m_texFlags & kGLMTexSRGB) ? layout->m_format->m_glIntFormatSRGB : layout->m_format->m_glIntFormat;
gGL->glRenderbufferStorageMultisampleEXT( GL_RENDERBUFFER_EXT,
sampleCount, // not "layout->m_key.m_texSamples"
msaaFormat,
layout->m_key.m_xSize,
layout->m_key.m_ySize );
if (gl_texmsaalog.GetInt())
{
printf( "\n == MSAA Tex %p %s : MSAA RBO is intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, msaaFormat ), msaaFormat );
}
gGL->glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
}
else
{
m_rboName = 0;
}
// at this point we have the complete description of the texture, and a name for it, but no data and no actual GL object.
// we know this name has bever seen duty before, so we're going to hard-bind it to TMU 0, displacing any other tex that might have been bound there.
// any previously bound tex will be unbound and appropriately marked as a result.
// the active TMU will be set as a side effect.
CGLMTex *pPrevTex = ctx->m_samplers[0].m_pBoundTex;
ctx->BindTexToTMU( this, 0 );
m_SamplingParams.SetToDefaults();
m_SamplingParams.SetToTarget( m_texGLTarget );
// OK, our texture now exists and is bound on the active TMU. Not drawable yet though.
// Create backing storage and fill it
if ( !(layout->m_key.m_texFlags & kGLMTexRenderable) && m_texClientStorage )
{
m_backing = (char *)malloc( m_layout->m_storageTotalSize );
memset( m_backing, 0, m_layout->m_storageTotalSize );
// track bytes allocated for non-RT's
int formindex = sEncodeLayoutAsIndex( &layout->m_key );
g_texGlobalBytes[ formindex ] += m_layout->m_storageTotalSize;
#if TEXSPACE_LOGGING
printf( "\n Tex %s added %d bytes in form %d which is now %d bytes", m_debugLabel ? m_debugLabel : "-", m_layout->m_storageTotalSize, formindex, g_texGlobalBytes[ formindex ] );
printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
);
#endif
}
else
{
m_backing = NULL;
m_texClientStorage = false;
}
// init lock count
// lock reqs are tracked by the owning context
m_lockCount = 0;
m_sliceFlags.SetCount( m_layout->m_sliceCount );
for( int i=0; i< m_layout->m_sliceCount; i++)
{
m_sliceFlags[i] = 0;
// kSliceValid = false (we have not teximaged each slice yet)
// kSliceStorageValid = false (the storage allocated does not reflect what is in the tex)
// kSliceLocked = false (the slices are not locked)
// kSliceFullyDirty = false (this does not come true til first lock)
}
// texture minimize parameter keeps driver from allocing mips when it should not, by being explicit about the ones that have no mips.
bool setMinimizeParameter = false;
bool minimize_rt = (gl_minimize_rt_tex.GetInt()!=0);
bool minimize_all = (gl_minimize_all_tex.GetInt()!=0);
if (layout->m_key.m_texFlags & kGLMTexRenderable)
{
// it's an RT. if mips were not explicitly requested, and "gl_minimize_rt_tex" is true, set the minimize parameter.
if ( (minimize_rt || minimize_all) && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
{
setMinimizeParameter = true;
}
}
else
{
// not an RT. if mips were not requested, and "gl_minimize_all_tex" is true, set the minimize parameter.
if ( minimize_all && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
{
setMinimizeParameter = true;
}
}
if (setMinimizeParameter)
{
if (gl_minimize_tex_log.GetInt())
{
printf("\n minimizing storage for tex '%s' [%s] ", m_debugLabel?m_debugLabel:"-", m_layout->m_layoutSummary );
}
if (gGL->m_bHave_GL_APPLE_texture_range)
gGL->glTexParameteri( m_layout->m_key.m_texGLTarget, GL_TEXTURE_MINIMIZE_STORAGE_APPLE, 1 );
}
// after a lot of pain with texture completeness...
// always push black into all slices of all newly created textures.
#if 0
bool pushRenderableSlices = (m_layout->m_key.m_texFlags & kGLMTexRenderable) != 0;
bool pushTexSlices = true; // just do it everywhere (m_layout->m_mipCount>1) && (m_layout->m_format->m_chunkSize !=1) ;
if (pushTexSlices)
{
// fill storage with mostly-opaque purple
GLMGenTexelParams genp;
memset( &genp, 0, sizeof(genp) );
genp.m_format = m_layout->m_format->m_d3dFormat;
const GLMTexFormatDesc *format = GetFormatDesc( genp.m_format );
genp.m_dest = m_backing; // dest addr
genp.m_chunkCount = m_layout->m_storageTotalSize / format->m_bytesPerSquareChunk; // fill the whole slab
genp.m_byteCountLimit = m_layout->m_storageTotalSize; // limit writes to this amount
genp.r = 1.0;
genp.g = 0.0;
genp.b = 1.0;
genp.a = 0.75;
GLMGenTexels( &genp );
}
#endif
//if (pushRenderableSlices || pushTexSlices)
if ( !( ( layout->m_key.m_texFlags & kGLMTexMipped ) && ( levels == ( unsigned ) m_layout->m_mipCount ) ) )
{
for( int face=0; face <m_layout->m_faceCount; face++)
{
for( int mip=0; mip <m_layout->m_mipCount; mip++)
{
// we're not really going to lock, we're just going to write the blank data from the backing store we just made
GLMTexLockDesc desc;
desc.m_req.m_tex = this;
desc.m_req.m_face = face;
desc.m_req.m_mip = mip;
desc.m_sliceIndex = CalcSliceIndex( face, mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
desc.m_req.m_region.xmax = slice->m_xSize;
desc.m_req.m_region.ymax = slice->m_ySize;
desc.m_req.m_region.zmax = slice->m_zSize;
desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
desc.m_sliceRegionOffset = 0;
WriteTexels( &desc, true, (layout->m_key.m_texFlags & kGLMTexRenderable)!=0 ); // write whole slice - but disable data source if it's an RT, as there's no backing
}
}
}
GLMPRINTF(("-A- -**TEXNEW '%-60s' name=%06d size=%09d storage=%08x label=%s ", m_layout->m_layoutSummary, m_texName, m_layout->m_storageTotalSize, m_backing, m_debugLabel ? m_debugLabel : "-" ));
ctx->BindTexToTMU( pPrevTex, 0 );
}
CGLMTex::~CGLMTex( )
{
#if GLMDEBUG
if ( m_pPrevTex )
{
Assert( m_pPrevTex->m_pNextTex == this );
m_pPrevTex->m_pNextTex = m_pNextTex;
}
else
{
Assert( g_pFirstCGMLTex == this );
g_pFirstCGMLTex = m_pNextTex;
}
if ( m_pNextTex )
{
Assert( m_pNextTex->m_pPrevTex == this );
m_pNextTex->m_pPrevTex = m_pPrevTex;
}
m_pNextTex = m_pPrevTex = NULL;
#endif
if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) )
{
int formindex = sEncodeLayoutAsIndex( &m_layout->m_key );
g_texGlobalBytes[ formindex ] -= m_layout->m_storageTotalSize;
#if TEXSPACE_LOGGING
printf( "\n Tex %s freed %d bytes in form %d which is now %d bytes", m_debugLabel ? m_debugLabel : "-", m_layout->m_storageTotalSize, formindex, g_texGlobalBytes[ formindex ] );
printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
);
#endif
}
GLMPRINTF(("-A- -**TEXDEL '%-60s' name=%06d size=%09d storage=%08x label=%s ", m_layout->m_layoutSummary, m_texName, m_layout->m_storageTotalSize, m_backing, m_debugLabel ? m_debugLabel : "-" ));
// check first to see if we were still bound anywhere or locked... these should be failures.
if ( m_pBlitSrcFBO )
{
m_ctx->DelFBO( m_pBlitSrcFBO );
m_pBlitSrcFBO = NULL;
}
if ( m_pBlitDstFBO )
{
m_ctx->DelFBO( m_pBlitDstFBO );
m_pBlitDstFBO = NULL;
}
if ( m_rboName )
{
gGL->glDeleteRenderbuffersEXT( 1, &m_rboName );
m_rboName = 0;
}
// if all that is OK, then delete the underlying tex
if ( m_texName )
{
m_ctx->DestroyTex( m_texGLTarget, m_layout, m_texName );
m_texName = 0;
}
// release our usage of the layout
m_ctx->m_texLayoutTable->DelLayoutRef( m_layout );
m_layout = NULL;
if (m_backing)
{
free( m_backing );
m_backing = NULL;
}
if (m_debugLabel)
{
free( m_debugLabel );
m_debugLabel = NULL;
}
m_ctx = NULL;
}
int CGLMTex::CalcSliceIndex( int face, int mip )
{
// faces of the same mip level are adjacent. "face major" storage
int index = (mip * m_layout->m_faceCount) + face;
return index;
}
void CGLMTex::CalcTexelDataOffsetAndStrides( int sliceIndex, int x, int y, int z, int *offsetOut, int *yStrideOut, int *zStrideOut )
{
int offset = 0;
int yStride = 0;
int zStride = 0;
GLMTexFormatDesc *format = m_layout->m_format;
if (format->m_chunkSize==1)
{
// figure out row stride and layer stride
yStride = format->m_bytesPerSquareChunk * m_layout->m_slices[sliceIndex].m_xSize; // bytes per texel row (y stride)
zStride = yStride * m_layout->m_slices[sliceIndex].m_ySize; // bytes per texel layer (if 3D tex)
offset = x * format->m_bytesPerSquareChunk; // lateral offset
offset += (y * yStride); // scanline offset
offset += (z * zStride); // should be zero for 2D tex
}
else
{
yStride = format->m_bytesPerSquareChunk * (m_layout->m_slices[sliceIndex].m_xSize / format->m_chunkSize);
zStride = yStride * (m_layout->m_slices[sliceIndex].m_ySize / format->m_chunkSize);
// compressed format. scale the x,y,z values into chunks.
// assert if any of them are not multiples of a chunk.
int chunkx = x / format->m_chunkSize;
int chunky = y / format->m_chunkSize;
int chunkz = z / format->m_chunkSize;
if ( (chunkx * format->m_chunkSize) != x)
{
GLMStop();
}
if ( (chunky * format->m_chunkSize) != y)
{
GLMStop();
}
if ( (chunkz * format->m_chunkSize) != z)
{
GLMStop();
}
offset = chunkx * format->m_bytesPerSquareChunk; // lateral offset
offset += (chunky * yStride); // chunk row offset
offset += (chunkz * zStride); // should be zero for 2D tex
}
*offsetOut = offset;
*yStrideOut = yStride;
*zStrideOut = zStride;
}
void CGLMTex::ReadTexels( GLMTexLockDesc *desc, bool readWholeSlice )
{
GLMRegion readBox;
if (readWholeSlice)
{
readBox.xmin = readBox.ymin = readBox.zmin = 0;
readBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
readBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
readBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
}
else
{
readBox = desc->m_req.m_region;
}
CGLMTex *pPrevTex = m_ctx->m_samplers[0].m_pBoundTex;
m_ctx->BindTexToTMU( this, 0 ); // SelectTMU(n) is a side effect
if (readWholeSlice)
{
// make this work first.... then write the partial path
// (Hmmmm, I don't think we will ever actually need a partial path -
// since we have no notion of a partially valid slice of storage
GLMTexFormatDesc *format = m_layout->m_format;
GLenum target = m_layout->m_key.m_texGLTarget;
void *sliceAddress = m_backing + m_layout->m_slices[ desc->m_sliceIndex ].m_storageOffset; // this would change for PBO
//int sliceSize = m_layout->m_slices[ desc->m_sliceIndex ].m_storageSize;
// interestingly enough, we can use the same path for both 2D and 3D fetch
switch( target )
{
case GL_TEXTURE_CUBE_MAP:
// adjust target to steer to the proper face, then fall through to the 2D texture path.
target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
case GL_TEXTURE_2D:
case GL_TEXTURE_3D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glGetCompressedTexImage.xml
gGL->glGetCompressedTexImage( target, // target
desc->m_req.m_mip, // level
sliceAddress ); // destination
}
else
{
// uncompressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml
gGL->glGetTexImage( target, // target
desc->m_req.m_mip, // level
format->m_glDataFormat, // dataformat
format->m_glDataType, // datatype
sliceAddress ); // destination
}
}
break;
}
}
else
{
GLMStop();
}
m_ctx->BindTexToTMU( pPrevTex, 0 );
}
// TexSubImage should work properly on every driver stack and GPU--enabling by default.
ConVar gl_enabletexsubimage( "gl_enabletexsubimage", "1" );
void CGLMTex::WriteTexels( GLMTexLockDesc *desc, bool writeWholeSlice, bool noDataWrite )
{
//if ( m_nBindlessHashNumEntries )
// return;
GLMRegion writeBox;
bool needsExpand = false;
char *expandTemp = NULL;
switch( m_layout->m_format->m_d3dFormat)
{
case D3DFMT_V8U8:
{
needsExpand = true;
writeWholeSlice = true;
// shoot down client storage if we have to generate a new flavor of the data
m_texClientStorage = false;
}
break;
}
if (writeWholeSlice)
{
writeBox.xmin = writeBox.ymin = writeBox.zmin = 0;
writeBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
writeBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
writeBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
}
else
{
writeBox = desc->m_req.m_region;
}
// first thing is to get the GL texture bound to a TMU, or just select one if already bound
// to get this running we will just always slam TMU 0 and let the draw time code fix it back
// a later optimization would be to hoist the bind call to the caller, do it exactly once
CGLMTex *pPrevTex = m_ctx->m_samplers[0].m_pBoundTex;
m_ctx->BindTexToTMU( this, 0 ); // SelectTMU(n) is a side effect
GLMTexFormatDesc *format = m_layout->m_format;
GLenum target = m_layout->m_key.m_texGLTarget;
GLenum glDataFormat = format->m_glDataFormat; // this could change if expansion kicks in
GLenum glDataType = format->m_glDataType;
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc->m_sliceIndex ];
void *sliceAddress = m_backing ? (m_backing + slice->m_storageOffset) : NULL; // this would change for PBO
// allow use of subimage if the target is texture2D and it has already been teximage'd
bool mayUseSubImage = false;
if ( (target==GL_TEXTURE_2D) && (m_sliceFlags[ desc->m_sliceIndex ] & kSliceValid) )
{
mayUseSubImage = gl_enabletexsubimage.GetInt() != 0;
}
// check flavor, 2D, 3D, or cube map
// we also have the choice to use subimage if this is a tex already created. (open question as to benefit)
// SRGB select. At this level (writetexels) we firmly obey the m_texFlags.
// (mechanism not policy)
GLenum intformat = (m_layout->m_key.m_texFlags & kGLMTexSRGB) ? format->m_glIntFormatSRGB : format->m_glIntFormat;
if (CommandLine()->FindParm("-disable_srgbtex"))
{
// force non srgb flavor - experiment to make ATI r600 happy on 10.5.8 (maybe x1600 too!)
intformat = format->m_glIntFormat;
}
Assert( intformat != 0 );
if (m_layout->m_key.m_texFlags & kGLMTexSRGB)
{
Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_COMPONENT );
Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_STENCIL_EXT );
Assert( m_layout->m_format->m_glDataFormat != GL_ALPHA );
}
// adjust min and max mip written
if (desc->m_req.m_mip > m_maxActiveMip)
{
m_maxActiveMip = desc->m_req.m_mip;
gGL->glTexParameteri( target, GL_TEXTURE_MAX_LEVEL, desc->m_req.m_mip);
}
if (desc->m_req.m_mip < m_minActiveMip)
{
m_minActiveMip = desc->m_req.m_mip;
gGL->glTexParameteri( target, GL_TEXTURE_BASE_LEVEL, desc->m_req.m_mip);
}
if (needsExpand)
{
int expandSize = 0;
switch( m_layout->m_format->m_d3dFormat)
{
case D3DFMT_V8U8:
{
// figure out new size based on 3byte RGB format
// easy, just take the two byte size and grow it by 50%
expandSize = (slice->m_storageSize * 3) / 2;
expandTemp = (char*)malloc( expandSize );
char *src = (char*)sliceAddress;
char *dst = expandTemp;
// transfer RG's to RGB's
while(expandSize>0)
{
*dst = *src++; // move first byte
*dst = *src++; // move second byte
*reinterpret_cast<uint8*>(dst) = 0xBB; // pad third byte
expandSize -= 3;
}
// move the slice pointer
sliceAddress = expandTemp;
// change the data format we tell GL about
glDataFormat = GL_RGB;
}
break;
default: Assert(!"Don't know how to expand that format..");
}
}
// set up the client storage now, one way or another
// If this extension isn't supported, we just end up with two copies of the texture, one in the GL and one in app memory.
// So it's safe to just go on as if this extension existed and hold the possibly-unnecessary extra RAM.
if (gGL->m_bHave_GL_APPLE_client_storage)
{
gGL->glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, m_texClientStorage );
}
switch( target )
{
case GL_TEXTURE_CUBE_MAP:
// adjust target to steer to the proper face, then fall through to the 2D texture path.
target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
case GL_TEXTURE_2D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
Assert( writeWholeSlice ); //subimage not implemented in this path yet
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage2D.xml
gGL->glCompressedTexImage2D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
slice->m_xSize, // width
slice->m_ySize, // height
0, // border
slice->m_storageSize, // imageSize
sliceAddress ); // data
}
else
{
if (mayUseSubImage)
{
// go subimage2D if it's a replacement, not a creation
gGL->glPixelStorei( GL_UNPACK_ROW_LENGTH, slice->m_xSize ); // in pixels
gGL->glPixelStorei( GL_UNPACK_SKIP_PIXELS, writeBox.xmin ); // in pixels
gGL->glPixelStorei( GL_UNPACK_SKIP_ROWS, writeBox.ymin ); // in pixels
gGL->glTexSubImage2D( target,
desc->m_req.m_mip, // level
writeBox.xmin, // xoffset into dest
writeBox.ymin, // yoffset into dest
writeBox.xmax - writeBox.xmin, // width (was slice->m_xSize)
writeBox.ymax - writeBox.ymin, // height (was slice->m_ySize)
glDataFormat, // format
glDataType, // type
sliceAddress // data (will be offsetted by the SKIP_PIXELS and SKIP_ROWS - let GL do the math to find the first source texel)
);
gGL->glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
gGL->glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
gGL->glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
/*
//http://www.opengl.org/sdk/docs/man/xhtml/glTexSubImage2D.xml
glTexSubImage2D( target,
desc->m_req.m_mip, // level
0, // xoffset
0, // yoffset
slice->m_xSize, // width
slice->m_ySize, // height
glDataFormat, // format
glDataType, // type
sliceAddress // data
);
*/
}
else
{
if (m_layout->m_key.m_texFlags & kGLMTexRenderable)
{
if (gl_rt_forcergba.GetInt())
{
if (glDataFormat == GL_BGRA)
{
// change it
glDataFormat = GL_RGBA;
}
}
}
// uncompressed path
// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
gGL->glTexImage2D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
slice->m_xSize, // width
slice->m_ySize, // height
0, // border
glDataFormat, // dataformat
glDataType, // datatype
noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
if (m_layout->m_key.m_texFlags & kGLMTexMultisampled)
{
if (gl_texmsaalog.GetInt())
{
printf( "\n == MSAA Tex %p %s : glTexImage2D for flat tex using intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, intformat ), intformat );
printf( "\n" );
}
}
m_sliceFlags[ desc->m_sliceIndex ] |= kSliceValid; // for next time, we can subimage..
}
}
}
break;
case GL_TEXTURE_3D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage3D.xml
gGL->glCompressedTexImage3D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat
slice->m_xSize, // width
slice->m_ySize, // height
slice->m_zSize, // depth
0, // border
slice->m_storageSize, // imageSize
sliceAddress ); // data
}
else
{
// uncompressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glTexImage3D.xml
gGL->glTexImage3D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat
slice->m_xSize, // width
slice->m_ySize, // height
slice->m_zSize, // depth
0, // border
glDataFormat, // dataformat
glDataType, // datatype
noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
}
}
break;
}
if (gGL->m_bHave_GL_APPLE_client_storage)
{
gGL->glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE );
}
if ( expandTemp )
{
free( expandTemp );
}
m_ctx->BindTexToTMU( pPrevTex, 0 );
}
void CGLMTex::Lock( GLMTexLockParams *params, char** addressOut, int* yStrideOut, int *zStrideOut )
{
#if GL_TELEMETRY_GPU_ZONES
CScopedGLMPIXEvent glmPIXEvent( "CGLMTex::Lock" );
g_TelemetryGPUStats.m_nTotalTexLocksAndUnlocks++;
#endif
// locate appropriate slice in layout record
int sliceIndex = CalcSliceIndex( params->m_face, params->m_mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[sliceIndex];
// obtain offset
//int sliceBaseOffset = slice->m_storageOffset;
// cross check region req against slice bounds - figure out if it matches, exceeds, or is less than the whole slice.
char exceed = (params->m_region.xmin < 0) || (params->m_region.xmax > slice->m_xSize) ||
(params->m_region.ymin < 0) || (params->m_region.ymax > slice->m_ySize) ||
(params->m_region.zmin < 0) || (params->m_region.zmax > slice->m_zSize);
char partial = (params->m_region.xmin > 0) || (params->m_region.xmax < slice->m_xSize) ||
(params->m_region.ymin > 0) || (params->m_region.ymax < slice->m_ySize) ||
(params->m_region.zmin > 0) || (params->m_region.zmax < slice->m_zSize);
bool copyout = false; // set if a readback of the texture slice from GL is needed
if (exceed)
{
// illegal rect, out of bounds
GLMStop();
}
// on return, these things need to be true
// a - there needs to be storage allocated, which we will return an address within
// b - the region corresponding to the slice being locked, will have valid data there for the whole slice.
// c - the slice is marked as locked
// d - the params of the lock request have been saved in the lock table (in the context)
// so step 1 is unambiguous. If there's no backing storage, make some.
if (!m_backing)
{
if ( gl_pow2_tempmem.GetBool() )
{
uint32_t unStoragePow2 = m_layout->m_storageTotalSize;
// Round up to next power of 2
unStoragePow2--;
unStoragePow2 |= unStoragePow2 >> 1;
unStoragePow2 |= unStoragePow2 >> 2;
unStoragePow2 |= unStoragePow2 >> 4;
unStoragePow2 |= unStoragePow2 >> 8;
unStoragePow2 |= unStoragePow2 >> 16;
unStoragePow2++;
m_backing = (char *)calloc( unStoragePow2, 1 );
}
else
{
m_backing = (char *)calloc( m_layout->m_storageTotalSize, 1 );
}
// clear the kSliceStorageValid bit on all slices
for( int i=0; i<m_layout->m_sliceCount; i++)
{
m_sliceFlags[i] &= ~kSliceStorageValid;
}
}
// work on this slice now
// storage is known to exist at this point, but we need to check if its contents are valid for this slice.
// this is tracked per-slice so we don't hoist all the texels back out of GL across all slices if caller only
// wanted to lock some of them.
// (i.e. if we just alloced it, it's blank)
// if storage is invalid, but the texture itself is valid, hoist the texels back to the storage and mark it valid.
// if storage is invalid, and texture itself is also invalid, go ahead and mark storage as valid and fully dirty... to force teximage.
// ???????????? we need to go over this more carefully re "slice valid" (it has been teximaged) vs "storage valid" (it has been copied out).
unsigned char *sliceFlags = &m_sliceFlags[ sliceIndex ];
if (params->m_readback)
{
// caller is letting us know that it wants to readback the real texels.
*sliceFlags |= kSliceStorageValid;
*sliceFlags |= kSliceValid;
*sliceFlags &= ~(kSliceFullyDirty);
copyout = true;
}
else
{
// caller is pushing texels.
if (! (*sliceFlags & kSliceStorageValid) )
{
// storage is invalid. check texture state
if ( *sliceFlags & kSliceValid )
{
// kSliceValid set: the texture itself has a valid slice, but we don't have it in our backing copy, so copy it out.
copyout = true;
}
else
{
// kSliceValid not set: the texture does not have a valid slice to copy out - it hasn't been teximage'd yet.
// set the "full dirty" bit to make sure we teximage the whole thing on unlock.
*sliceFlags |= kSliceFullyDirty;
// assert if they did not ask to lock the full slice size on this go-round
if (partial)
{
// choice here -
// 1 - stop cold, we don't know how to subimage yet.
// 2 - grin and bear it, mark whole slice dirty (ah, we already did... so, do nothing).
// choice 2: // GLMStop();
}
}
// one way or another, upon reaching here the slice storage is valid for read.
*sliceFlags |= kSliceStorageValid;
}
}
// when we arrive here, there is storage, and the content of the storage for this slice is valid
// (or zeroes if it's the first lock)
// log the lock request in the context.
int newdesc = m_ctx->m_texLocks.AddToTail();
GLMTexLockDesc *desc = &m_ctx->m_texLocks[newdesc];
desc->m_req = *params;
desc->m_active = true;
desc->m_sliceIndex = sliceIndex;
desc->m_sliceBaseOffset = m_layout->m_slices[sliceIndex].m_storageOffset;
// to calculate the additional offset we need to look at the rect's min corner
// combined with the per-texel size and Y/Z stride
// also cross check it for 4x multiple if there is compression in play
int offsetInSlice = 0;
int yStride = 0;
int zStride = 0;
CalcTexelDataOffsetAndStrides( sliceIndex, params->m_region.xmin, params->m_region.ymin, params->m_region.zmin, &offsetInSlice, &yStride, &zStride );
// for compressed case...
// since there is presently no way to texsubimage a DXT when the rect does not cover the whole width,
// we will probably need to inflate the dirty rect in the recorded lock req so that the entire span is
// pushed across at unlock time.
desc->m_sliceRegionOffset = offsetInSlice + desc->m_sliceBaseOffset;
if (copyout)
{
// read the whole slice
// (odds are we'll never request anything but a whole slice to be read..)
ReadTexels( desc, true );
} // this would be a good place to fill with scrub value if in debug...
*addressOut = m_backing + desc->m_sliceRegionOffset;
*yStrideOut = yStride;
*zStrideOut = zStride;
m_lockCount++;
}
void CGLMTex::Unlock( GLMTexLockParams *params )
{
#if GL_TELEMETRY_GPU_ZONES
CScopedGLMPIXEvent glmPIXEvent( "CGLMTex::Unlock" );
g_TelemetryGPUStats.m_nTotalTexLocksAndUnlocks++;
#endif
// look for an active lock request on this face and mip (doesn't necessarily matter which one, if more than one)
// and mark it inactive.
// --> if you can't find one, fail. first line of defense against mismatched locks/unlocks..
int i=0;
bool found = false;
while( !found && (i<m_ctx->m_texLocks.Count()) )
{
GLMTexLockDesc *desc = &m_ctx->m_texLocks[i];
// is lock at index 'i' targeted at the texture/face/mip in question?
if ( (desc->m_req.m_tex == this) && (desc->m_req.m_face == params->m_face) & (desc->m_req.m_mip == params->m_mip) && (desc->m_active) )
{
// matched and active, so retire it
desc->m_active = false;
// stop searching
found = true;
}
i++;
}
if (!found)
{
GLMStop(); // bad news
}
// found - so drop lock count
m_lockCount--;
if (m_lockCount <0)
{
GLMStop(); // bad news
}
if (m_lockCount==0)
{
// there should not be any active locks remaining on this texture.
// motivation to defer all texel pushing til *all* open locks are closed out -
// if/when we back the texture with a PBO, we will need to unmap that PBO before teximaging from it;
// by waiting for all the locks to clear this gives us an unambiguous signal to act on.
// scan through all the retired locks for this texture and push the texels for each one.
// after each one is dispatched, remove it from the pile.
int j=0;
while( j<m_ctx->m_texLocks.Count() )
{
GLMTexLockDesc *desc = &m_ctx->m_texLocks[j];
if ( desc->m_req.m_tex == this )
{
// if it's active, something is wrong
if (desc->m_active)
{
GLMStop();
}
// write the texels
bool fullyDirty = false;
fullyDirty |= ((m_sliceFlags[ desc->m_sliceIndex ] & kSliceFullyDirty) != 0);
// this is not optimal and will result in full downloads on any dirty.
// we're papering over the fact that subimage isn't done yet.
// but this is safe if the slice of storage is all valid.
// at some point we'll need to actually compare the lock box against the slice bounds.
// fullyDirty |= (m_sliceFlags[ desc->m_sliceIndex ] & kSliceStorageValid);
WriteTexels( desc, fullyDirty );
// logical place to trigger preloading
// only do it for an RT tex, if it is not yet attached to any FBO.
// also, only do it if the slice number is the last slice in the tex.
if ( desc->m_sliceIndex == (m_layout->m_sliceCount-1) )
{
if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) || (m_rtAttachCount==0) )
{
m_ctx->PreloadTex( this );
// printf("( slice %d of %d )", desc->m_sliceIndex, m_layout->m_sliceCount );
}
}
m_ctx->m_texLocks.FastRemove( j ); // remove from the pile, don't advance index
}
else
{
j++; // move on to next one
}
}
// clear the locked and full-dirty flags for all slices
for( int slice=0; slice < m_layout->m_sliceCount; slice++)
{
m_sliceFlags[slice] &= ~( kSliceLocked | kSliceFullyDirty );
}
// The 3D texture upload code seems to rely on the host copy, probably
// because it reuploads the whole thing each slice; we only use 3D textures
// for the 32x32x32 colorpsace conversion lookups and debugging the problem
// would not save any more memory.
if ( !m_texClientStorage && ( m_texGLTarget == GL_TEXTURE_2D ) )
{
free(m_backing);
m_backing = NULL;
}
}
}
#if defined( OSX )
void CGLMTex::HandleSRGBMismatch( bool srgb, int &srgbFlipCount )
{
bool srgbCapableTex = false; // not yet known
bool renderableTex = false; // not yet known.
srgbCapableTex = m_layout->m_format->m_glIntFormatSRGB != 0;
renderableTex = ( m_layout->m_key.m_texFlags & kGLMTexRenderable ) != 0;
// we can fix it if it's not a renderable, and an sRGB enabled format variation is available.
if ( srgbCapableTex && !renderableTex )
{
char *texname = m_debugLabel;
if (!texname) texname = "-";
m_srgbFlipCount++;
#if GLMDEBUG
//policy: print the ones that have flipped 1 or N times
static bool print_allflips = CommandLine()->FindParm("-glmspewallsrgbflips");
static bool print_firstflips = CommandLine()->FindParm("-glmspewfirstsrgbflips");
static bool print_freqflips = CommandLine()->FindParm("-glmspewfreqsrgbflips");
static bool print_crawls = CommandLine()->FindParm("-glmspewsrgbcrawls");
static bool print_maxcrawls = CommandLine()->FindParm("-glmspewsrgbmaxcrawls");
bool print_it = false;
if (print_allflips)
{
print_it = true;
}
if (print_firstflips) // report on first flip
{
print_it |= m_srgbFlipCount==1;
}
if (print_freqflips) // report on 50th flip
{
print_it |= m_srgbFlipCount==50;
}
if ( print_it )
{
char *formatStr;
formatStr = "srgb change (samp=%d): tex '%-30s' %08x %s (srgb=%d, %d times)";
if (strlen(texname) >= 30)
{
formatStr = "srgb change (samp=%d): tex '%s' %08x %s (srgb=%d, %d times)";
}
printf( "\n" );
printf( formatStr, index, texname, m_layout->m_layoutSummary, (int)srgb, m_srgbFlipCount );
#ifdef POSIX
if (print_crawls)
{
static char *interesting_crawl_substrs[] = { "CShader::OnDrawElements", NULL }; // add more as needed
CStackCrawlParams cp;
memset( &cp, 0, sizeof(cp) );
cp.m_frameLimit = 20;
g_pLauncherMgr->GetStackCrawl(&cp);
for( int i=0; i< cp.m_frameCount; i++)
{
// for each row of crawl, decide if name is interesting
bool hit = print_maxcrawls;
for( char **match = interesting_crawl_substrs; (!hit) && (*match != NULL); match++)
{
if (strstr(cp.m_crawlNames[i], *match))
{
hit = true;
}
}
if (hit)
{
printf( "\n\t%s", cp.m_crawlNames[i] );
}
}
printf( "\n");
}
#endif
}
#endif // GLMDEBUG
#if GLMDEBUG && 0
//"toi" = texture of interest
static char s_toi[256] = "colorcorrection";
if (strstr( texname, s_toi ))
{
// breakpoint on this if you like
GLMPRINTF(( "srgb change %d for %s", m_srgbFlipCount, texname ));
}
#endif
// re-submit the tex unless we're stifling it
static bool s_nosrgbflips = CommandLine()->FindParm( "-glmnosrgbflips" );
if ( !s_nosrgbflips )
{
ResetSRGB( srgb, false );
}
}
else
{
//GLMPRINTF(("-Z- srgb sampling conflict: NOT fixing tex %08x [%s] (srgb req: %d) because (tex-srgb-capable=%d tex-renderable=%d)", m_textures[index], m_textures[index]->m_tex->m_layout->m_layoutSummary, (int)glsamp->m_srgb, (int)srgbCapableTex, (int)renderableTex ));
// we just leave the sampler state where it is, and that's life
}
}
void CGLMTex::ResetSRGB( bool srgb, bool noDataWrite )
{
// see if requested SRGB state differs from the known one
bool wasSRGB = (m_layout->m_key.m_texFlags & kGLMTexSRGB);
GLMTexLayout *oldLayout = m_layout; // need to m_ctx->m_texLayoutTable->DelLayoutRef on this one if we flip
if (srgb != wasSRGB)
{
// we're going to need a new layout (though the storage size should be the same - check it)
GLMTexLayoutKey newKey = m_layout->m_key;
newKey.m_texFlags &= (~kGLMTexSRGB); // turn off that bit
newKey.m_texFlags |= srgb ? kGLMTexSRGB : 0; // turn on that bit if it should be so
// get new layout
GLMTexLayout *newLayout = m_ctx->m_texLayoutTable->NewLayoutRef( &newKey );
// if SRGB requested, verify that the layout we just got can do it.
// if it can't, delete the new layout ref and bail.
if (srgb && (newLayout->m_format->m_glIntFormatSRGB == 0))
{
Assert( !"Can't enable SRGB mode on this format" );
m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
return;
}
// check sizes and fail if no match
if( newLayout->m_storageTotalSize != oldLayout->m_storageTotalSize )
{
Assert( !"Bug: layout sizes don't match on SRGB change" );
m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
return;
}
// commit to new layout
m_layout = newLayout;
m_texGLTarget = m_layout->m_key.m_texGLTarget;
// check same size
Assert( m_layout->m_storageTotalSize == oldLayout->m_storageTotalSize );
Assert( newLayout != oldLayout );
// release old
m_ctx->m_texLayoutTable->DelLayoutRef( oldLayout );
oldLayout = NULL;
// force texel re-DL
// note this messes with TMU 0 as side effect of WriteTexels
// so we save and restore the TMU 0 binding first
// since we're likely to be called in dxabstract when it is syncing sampler state, we can't go trampling the bindings.
// a refinement would be to have each texture make a note of which TMU they're bound on, and just use that active TMU for DL instead of 0.
CGLMTex *tmu0save = m_ctx->m_samplers[0].m_pBoundTex;
for( int face=0; face <m_layout->m_faceCount; face++)
{
for( int mip=0; mip <m_layout->m_mipCount; mip++)
{
// we're not really going to lock, we're just going to rewrite the orig data
GLMTexLockDesc desc;
desc.m_req.m_tex = this;
desc.m_req.m_face = face;
desc.m_req.m_mip = mip;
desc.m_sliceIndex = CalcSliceIndex( face, mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
desc.m_req.m_region.xmax = slice->m_xSize;
desc.m_req.m_region.ymax = slice->m_ySize;
desc.m_req.m_region.zmax = slice->m_zSize;
desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
desc.m_sliceRegionOffset = 0;
WriteTexels( &desc, true, noDataWrite ); // write whole slice. and avoid pushing real bits if the caller requests (RT's)
}
}
// put it back
m_ctx->BindTexToTMU( tmu0save, 0 );
}
}
#endif
bool CGLMTex::IsRBODirty() const
{
return m_nLastResolvedBatchCounter != m_ctx->m_nBatchCounter;
}
void CGLMTex::ForceRBONonDirty()
{
m_nLastResolvedBatchCounter = m_ctx->m_nBatchCounter;
}
void CGLMTex::ForceRBODirty()
{
m_nLastResolvedBatchCounter = m_ctx->m_nBatchCounter - 1;
}
|