Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1939 lines
61 KiB

  1. //============ Copyright (c) Valve Corporation, All rights reserved. ============
  2. //
  3. // cglmtex.cpp
  4. //
  5. //===============================================================================
  6. #include "togl/rendermechanism.h"
  7. #include "tier0/icommandline.h"
  8. #include "glmtexinlines.h"
  9. // memdbgon -must- be the last include file in a .cpp file.
  10. #include "tier0/memdbgon.h"
  11. #if defined(OSX)
  12. #include "appframework/ilaunchermgr.h"
  13. extern ILauncherMgr *g_pLauncherMgr;
  14. #endif
  15. //===============================================================================
  16. #if GLMDEBUG
  17. CGLMTex *g_pFirstCGMLTex;
  18. #endif
  19. #define TEXSPACE_LOGGING 0
  20. // encoding layout to an index where the bits read
  21. // 4 : 1 if compressed
  22. // 2 : 1 if not power of two
  23. // 1 : 1 if mipmapped
  24. bool pwroftwo (int val )
  25. {
  26. return (val & (val-1)) == 0;
  27. }
  28. int sEncodeLayoutAsIndex( GLMTexLayoutKey *key )
  29. {
  30. int index = 0;
  31. if (key->m_texFlags & kGLMTexMipped)
  32. {
  33. index |= 1;
  34. }
  35. if ( ! ( pwroftwo(key->m_xSize) && pwroftwo(key->m_ySize) && pwroftwo(key->m_zSize) ) )
  36. {
  37. // if not all power of two
  38. index |= 2;
  39. }
  40. if (GetFormatDesc( key->m_texFormat )->m_chunkSize >1 )
  41. {
  42. index |= 4;
  43. }
  44. return index;
  45. }
  46. static unsigned long g_texGlobalBytes[8];
  47. //===============================================================================
  48. const GLMTexFormatDesc g_formatDescTable[] =
  49. {
  50. // not yet handled by this table:
  51. // D3DFMT_INDEX16, D3DFMT_VERTEXDATA // D3DFMT_INDEX32,
  52. // WTF { D3DFMT_R5G6R5 ???, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
  53. // WTF { D3DFMT_A ???, GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
  54. // ??? D3DFMT_V8U8,
  55. // ??? D3DFMT_Q8W8V8U8,
  56. // ??? D3DFMT_X8L8V8U8,
  57. // ??? D3DFMT_R32F,
  58. // ??? D3DFMT_D24X4S4 unsure how to handle or if it is ever used..
  59. // ??? D3DFMT_D15S1 ever used ?
  60. // ??? D3DFMT_D24X8 ever used?
  61. // summ-name d3d-format gl-int-format gl-int-format-srgb gl-data-format gl-data-type chunksize, bytes-per-sqchunk
  62. { "_D16", D3DFMT_D16, GL_DEPTH_COMPONENT16, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 1, 2 },
  63. { "_D24X8", D3DFMT_D24X8, GL_DEPTH_COMPONENT24, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 1, 4 }, // ??? unsure on this one
  64. { "_D24S8", D3DFMT_D24S8, GL_DEPTH24_STENCIL8_EXT, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, 1, 4 },
  65. { "_A8R8G8B8", D3DFMT_A8R8G8B8, GL_RGBA8, GL_SRGB8_ALPHA8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
  66. { "_A4R4G4B4", D3DFMT_A4R4G4B4, GL_RGBA4, 0, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, 1, 2 },
  67. { "_X8R8G8B8", D3DFMT_X8R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
  68. { "_X1R5G5B5", D3DFMT_X1R5G5B5, GL_RGB5, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
  69. { "_A1R5G5B5", D3DFMT_A1R5G5B5, GL_RGB5_A1, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
  70. { "_L8", D3DFMT_L8, GL_LUMINANCE8, GL_SLUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 1 },
  71. { "_A8L8", D3DFMT_A8L8, GL_LUMINANCE8_ALPHA8, GL_SLUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 1, 2 },
  72. { "_DXT1", D3DFMT_DXT1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, GL_RGB, GL_UNSIGNED_BYTE, 4, 8 },
  73. { "_DXT3", D3DFMT_DXT3, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
  74. { "_DXT5", D3DFMT_DXT5, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
  75. { "_A16B16G16R16F", D3DFMT_A16B16G16R16F, GL_RGBA16F_ARB, 0, GL_RGBA, GL_HALF_FLOAT_ARB, 1, 8 },
  76. { "_A16B16G16R16", D3DFMT_A16B16G16R16, GL_RGBA16, 0, GL_RGBA, GL_UNSIGNED_SHORT, 1, 8 }, // 16bpc integer tex
  77. { "_A32B32G32R32F", D3DFMT_A32B32G32R32F, GL_RGBA32F_ARB, 0, GL_RGBA, GL_FLOAT, 1, 16 },
  78. { "_R8G8B8", D3DFMT_R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGR, GL_UNSIGNED_BYTE, 1, 3 },
  79. { "_A8", D3DFMT_A8, GL_ALPHA8, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
  80. { "_R5G6B5", D3DFMT_R5G6B5, GL_RGB, GL_SRGB_EXT, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
  81. // fakey tex formats: the stated GL format and the memory layout may not agree (U8V8 for example)
  82. // _Q8W8V8U8 we just pass through as RGBA bytes. Shader does scale/bias fix
  83. { "_Q8W8V8U8", D3DFMT_Q8W8V8U8, GL_RGBA8, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 }, // straight ripoff of D3DFMT_A8R8G8B8
  84. // U8V8 is exposed to the client as 2-bytes per texel, but we download it as 3-byte RGB.
  85. // WriteTexels needs to do that conversion from rg8 to rgb8 in order to be able to download it correctly
  86. { "_V8U8", D3DFMT_V8U8, GL_RGB8, 0, GL_RG, GL_BYTE, 1, 2 },
  87. { "_R32F", D3DFMT_R32F, GL_R32F, GL_R32F, GL_RED, GL_FLOAT, 1, 4 },
  88. { "_A2R10G10B10", D3DFMT_A2R10G10B10, GL_RGB10_A2, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_10_10_10_2, 1, 4 },
  89. { "_A2B10G10R10", D3DFMT_A2B10G10R10, GL_RGB10_A2, GL_RGB10_A2, GL_BGRA, GL_UNSIGNED_INT_10_10_10_2, 1, 4 },
  90. /*
  91. // NV shadow depth tex
  92. D3DFMT_NV_INTZ = 0x5a544e49, // MAKEFOURCC('I','N','T','Z')
  93. D3DFMT_NV_RAWZ = 0x5a574152, // MAKEFOURCC('R','A','W','Z')
  94. // NV null tex
  95. D3DFMT_NV_NULL = 0x4c4c554e, // MAKEFOURCC('N','U','L','L')
  96. // ATI shadow depth tex
  97. D3DFMT_ATI_D16 = 0x36314644, // MAKEFOURCC('D','F','1','6')
  98. D3DFMT_ATI_D24S8 = 0x34324644, // MAKEFOURCC('D','F','2','4')
  99. // ATI 1N and 2N compressed tex
  100. D3DFMT_ATI_2N = 0x32495441, // MAKEFOURCC('A', 'T', 'I', '2')
  101. D3DFMT_ATI_1N = 0x31495441, // MAKEFOURCC('A', 'T', 'I', '1')
  102. */
  103. };
  104. int g_formatDescTableCount = sizeof(g_formatDescTable) / sizeof( g_formatDescTable[0] );
  105. const GLMTexFormatDesc *GetFormatDesc( D3DFORMAT format )
  106. {
  107. for( int i=0; i<g_formatDescTableCount; i++)
  108. {
  109. if (g_formatDescTable[i].m_d3dFormat == format)
  110. {
  111. return &g_formatDescTable[i];
  112. }
  113. }
  114. return (const GLMTexFormatDesc *)NULL; // not found
  115. }
  116. //===============================================================================
  117. void InsertTexelComponentFixed( float value, int width, unsigned long *valuebuf )
  118. {
  119. unsigned long range = (1<<width);
  120. unsigned long scaled = (value * (float) range) * (range-1) / (range);
  121. if (scaled >= range) DebuggerBreak();
  122. *valuebuf = (*valuebuf << width) | scaled;
  123. }
  124. // return true if successful
  125. bool GLMGenTexels( GLMGenTexelParams *params )
  126. {
  127. unsigned char chunkbuf[256]; // can't think of any chunk this big..
  128. const GLMTexFormatDesc *format = GetFormatDesc( params->m_format );
  129. if (!format)
  130. {
  131. return FALSE; // fail
  132. }
  133. // this section just generates one square chunk in the desired format
  134. unsigned long *temp32 = (unsigned long*)chunkbuf;
  135. unsigned int chunksize = 0; // we can sanity check against the format table with this
  136. switch( params->m_format )
  137. {
  138. // comment shows byte order in RAM
  139. // lowercase is bit arrangement in a byte
  140. case D3DFMT_A8R8G8B8: // B G R A
  141. InsertTexelComponentFixed( params->a, 8, temp32 ); // A is inserted first and winds up at most significant bits after insertions follow
  142. InsertTexelComponentFixed( params->r, 8, temp32 );
  143. InsertTexelComponentFixed( params->g, 8, temp32 );
  144. InsertTexelComponentFixed( params->b, 8, temp32 );
  145. chunksize = 4;
  146. break;
  147. case D3DFMT_A4R4G4B4: // [ggggbbbb] [aaaarrrr] RA (nibbles)
  148. InsertTexelComponentFixed( params->a, 4, temp32 );
  149. InsertTexelComponentFixed( params->r, 4, temp32 );
  150. InsertTexelComponentFixed( params->g, 4, temp32 );
  151. InsertTexelComponentFixed( params->b, 4, temp32 );
  152. chunksize = 2;
  153. break;
  154. case D3DFMT_X8R8G8B8: // B G R X
  155. InsertTexelComponentFixed( 0.0, 8, temp32 );
  156. InsertTexelComponentFixed( params->r, 8, temp32 );
  157. InsertTexelComponentFixed( params->g, 8, temp32 );
  158. InsertTexelComponentFixed( params->b, 8, temp32 );
  159. chunksize = 4;
  160. break;
  161. case D3DFMT_X1R5G5B5: // [gggbbbbb] [xrrrrrgg]
  162. InsertTexelComponentFixed( 0.0, 1, temp32 );
  163. InsertTexelComponentFixed( params->r, 5, temp32 );
  164. InsertTexelComponentFixed( params->g, 5, temp32 );
  165. InsertTexelComponentFixed( params->b, 5, temp32 );
  166. chunksize = 2;
  167. break;
  168. case D3DFMT_A1R5G5B5: // [gggbbbbb] [arrrrrgg]
  169. InsertTexelComponentFixed( params->a, 1, temp32 );
  170. InsertTexelComponentFixed( params->r, 5, temp32 );
  171. InsertTexelComponentFixed( params->g, 5, temp32 );
  172. InsertTexelComponentFixed( params->b, 5, temp32 );
  173. chunksize = 2;
  174. break;
  175. case D3DFMT_L8: // L // caller, use R for L
  176. InsertTexelComponentFixed( params->r, 8, temp32 );
  177. chunksize = 1;
  178. break;
  179. case D3DFMT_A8L8: // L A // caller, use R for L and A for A
  180. InsertTexelComponentFixed( params->a, 8, temp32 );
  181. InsertTexelComponentFixed( params->r, 8, temp32 );
  182. chunksize = 2;
  183. break;
  184. case D3DFMT_R8G8B8: // B G R
  185. InsertTexelComponentFixed( params->r, 8, temp32 );
  186. InsertTexelComponentFixed( params->g, 8, temp32 );
  187. InsertTexelComponentFixed( params->b, 8, temp32 );
  188. chunksize = 3;
  189. break;
  190. case D3DFMT_A8: // A
  191. InsertTexelComponentFixed( params->a, 8, temp32 );
  192. chunksize = 1;
  193. break;
  194. case D3DFMT_R5G6B5: // [gggbbbbb] [rrrrrggg]
  195. InsertTexelComponentFixed( params->r, 5, temp32 );
  196. InsertTexelComponentFixed( params->g, 6, temp32 );
  197. InsertTexelComponentFixed( params->b, 5, temp32 );
  198. chunksize = 2;
  199. break;
  200. case D3DFMT_DXT1:
  201. {
  202. memset( temp32, 0, 8 ); // zap 8 bytes
  203. // two 565 RGB words followed by 32 bits of 2-bit interp values for a 4x4 block
  204. // we write the same color to both slots and all zeroes for the mask (one color total)
  205. unsigned long dxt1_color = 0;
  206. // generate one such word and clone it
  207. InsertTexelComponentFixed( params->r, 5, &dxt1_color );
  208. InsertTexelComponentFixed( params->g, 6, &dxt1_color );
  209. InsertTexelComponentFixed( params->b, 5, &dxt1_color );
  210. // dupe
  211. dxt1_color = dxt1_color | (dxt1_color<<16);
  212. // write into chunkbuf
  213. *(unsigned long*)&chunkbuf[0] = dxt1_color;
  214. // color mask bits after that are already set to all zeroes. chunk is done.
  215. chunksize = 8;
  216. }
  217. break;
  218. case D3DFMT_DXT3:
  219. {
  220. memset( temp32, 0, 16 ); // zap 16 bytes
  221. // eight bytes of alpha (16 4-bit alpha nibbles)
  222. // followed by a DXT1 block
  223. unsigned long dxt3_alpha = 0;
  224. for( int i=0; i<8; i++)
  225. {
  226. // splat same alpha through block
  227. InsertTexelComponentFixed( params->a, 4, &dxt3_alpha );
  228. }
  229. unsigned long dxt3_color = 0;
  230. // generate one such word and clone it
  231. InsertTexelComponentFixed( params->r, 5, &dxt3_color );
  232. InsertTexelComponentFixed( params->g, 6, &dxt3_color );
  233. InsertTexelComponentFixed( params->b, 5, &dxt3_color );
  234. // dupe
  235. dxt3_color = dxt3_color | (dxt3_color<<16);
  236. // write into chunkbuf
  237. *(unsigned long*)&chunkbuf[0] = dxt3_alpha;
  238. *(unsigned long*)&chunkbuf[4] = dxt3_alpha;
  239. *(unsigned long*)&chunkbuf[8] = dxt3_color;
  240. *(unsigned long*)&chunkbuf[12] = dxt3_color;
  241. chunksize = 16;
  242. }
  243. break;
  244. case D3DFMT_DXT5:
  245. {
  246. memset( temp32, 0, 16 ); // zap 16 bytes
  247. // DXT5 has 8 bytes of compressed alpha, then 8 bytes of compressed RGB like DXT1.
  248. // the 8 alpha bytes are 2 bytes of endpoint alpha values, then 16x3 bits of interpolants.
  249. // so to write a single alpha value, just figure out the value, store it in both the first two bytes then store zeroes.
  250. InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
  251. InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
  252. // rest of the alpha mask was already zeroed.
  253. // now do colors
  254. unsigned long dxt5_color = 0;
  255. // generate one such word and clone it
  256. InsertTexelComponentFixed( params->r, 5, &dxt5_color );
  257. InsertTexelComponentFixed( params->g, 6, &dxt5_color );
  258. InsertTexelComponentFixed( params->b, 5, &dxt5_color );
  259. // dupe
  260. dxt5_color = dxt5_color | (dxt5_color<<16);
  261. // write into chunkbuf
  262. *(unsigned long*)&chunkbuf[8] = dxt5_color;
  263. *(unsigned long*)&chunkbuf[12] = dxt5_color;
  264. chunksize = 16;
  265. }
  266. break;
  267. case D3DFMT_A32B32G32R32F:
  268. {
  269. *(float*)&chunkbuf[0] = params->r;
  270. *(float*)&chunkbuf[4] = params->g;
  271. *(float*)&chunkbuf[8] = params->b;
  272. *(float*)&chunkbuf[12] = params->a;
  273. chunksize = 16;
  274. }
  275. break;
  276. case D3DFMT_A16B16G16R16:
  277. memset( chunkbuf, 0, 8 );
  278. // R and G wind up in the first 32 bits
  279. // B and A wind up in the second 32 bits
  280. InsertTexelComponentFixed( params->a, 16, (unsigned long*)&chunkbuf[4] ); // winds up as MSW of second word (note [4]) - thus last in RAM
  281. InsertTexelComponentFixed( params->b, 16, (unsigned long*)&chunkbuf[4] );
  282. InsertTexelComponentFixed( params->g, 16, (unsigned long*)&chunkbuf[0] );
  283. InsertTexelComponentFixed( params->r, 16, (unsigned long*)&chunkbuf[0] ); // winds up as LSW of first word, thus first in RAM
  284. chunksize = 8;
  285. break;
  286. // not done yet
  287. //case D3DFMT_D16:
  288. //case D3DFMT_D24X8:
  289. //case D3DFMT_D24S8:
  290. //case D3DFMT_A16B16G16R16F:
  291. default:
  292. return FALSE; // fail
  293. break;
  294. }
  295. // once the chunk buffer is filled..
  296. // sanity check the reported chunk size.
  297. if (static_cast<int>(chunksize) != format->m_bytesPerSquareChunk)
  298. {
  299. DebuggerBreak();
  300. return FALSE;
  301. }
  302. // verify that the amount you want to write will not exceed the limit byte count
  303. unsigned long destByteCount = chunksize * params->m_chunkCount;
  304. if (static_cast<int>(destByteCount) > params->m_byteCountLimit)
  305. {
  306. DebuggerBreak();
  307. return FALSE;
  308. }
  309. // write the bytes.
  310. unsigned char *destP = (unsigned char*)params->m_dest;
  311. for( int chunk=0; chunk < params->m_chunkCount; chunk++)
  312. {
  313. for( uint byteindex = 0; byteindex < chunksize; byteindex++)
  314. {
  315. *destP++ = chunkbuf[byteindex];
  316. }
  317. }
  318. params->m_bytesWritten = destP - (unsigned char*)params->m_dest;
  319. return TRUE;
  320. }
  321. //===============================================================================
  322. bool LessFunc_GLMTexLayoutKey( const GLMTexLayoutKey &a, const GLMTexLayoutKey &b )
  323. {
  324. #define DO_LESS(fff) if (a.fff != b.fff) { return (a.fff< b.fff); }
  325. DO_LESS(m_texGLTarget);
  326. DO_LESS(m_texFormat);
  327. DO_LESS(m_texFlags);
  328. DO_LESS(m_texSamples);
  329. DO_LESS(m_xSize);
  330. DO_LESS(m_ySize)
  331. DO_LESS(m_zSize);
  332. #undef DO_LESS
  333. return false; // they are equal
  334. }
  335. CGLMTexLayoutTable::CGLMTexLayoutTable()
  336. {
  337. m_layoutMap.SetLessFunc( LessFunc_GLMTexLayoutKey );
  338. }
  339. GLMTexLayout *CGLMTexLayoutTable::NewLayoutRef( GLMTexLayoutKey *pDesiredKey )
  340. {
  341. GLMTexLayoutKey tempKey;
  342. GLMTexLayoutKey *key = pDesiredKey;
  343. // look up 'key' in the map and see if it's a hit, if so, bump the refcount and return
  344. // if not, generate a completed layout based on the key, add to map, set refcount to 1, return that
  345. const GLMTexFormatDesc *formatDesc = GetFormatDesc( key->m_texFormat );
  346. //bool compression = (formatDesc->m_chunkSize > 1) != 0;
  347. if (!formatDesc)
  348. {
  349. GLMStop(); // bad news
  350. }
  351. if ( gGL->m_bHave_GL_EXT_texture_sRGB_decode )
  352. {
  353. if ( ( formatDesc->m_glIntFormatSRGB != 0 ) && ( ( key->m_texFlags & kGLMTexSRGB ) == 0 ) )
  354. {
  355. tempKey = *pDesiredKey;
  356. key = &tempKey;
  357. // Slam on SRGB texture flag, and we'll use GL_EXT_texture_sRGB_decode to selectively turn it off in the samplers
  358. key->m_texFlags |= kGLMTexSRGB;
  359. }
  360. }
  361. unsigned short index = m_layoutMap.Find( *key );
  362. if (index != m_layoutMap.InvalidIndex())
  363. {
  364. // found it
  365. //printf(" -hit- ");
  366. GLMTexLayout *layout = m_layoutMap[ index ];
  367. // bump ref count
  368. layout->m_refCount ++;
  369. return layout;
  370. }
  371. else
  372. {
  373. //printf(" -miss- ");
  374. // need to make a new one
  375. // to allocate it, we need to know how big to make it (slice count)
  376. // figure out how many mip levels are in play
  377. int mipCount = 1;
  378. if (key->m_texFlags & kGLMTexMipped)
  379. {
  380. int largestAxis = key->m_xSize;
  381. if (key->m_ySize > largestAxis)
  382. largestAxis = key->m_ySize;
  383. if (key->m_zSize > largestAxis)
  384. largestAxis = key->m_zSize;
  385. mipCount = 0;
  386. while( largestAxis > 0 )
  387. {
  388. mipCount ++;
  389. largestAxis >>= 1;
  390. }
  391. }
  392. int faceCount = 1;
  393. if (key->m_texGLTarget == GL_TEXTURE_CUBE_MAP)
  394. {
  395. faceCount = 6;
  396. }
  397. int sliceCount = mipCount * faceCount;
  398. if (key->m_texFlags & kGLMTexMultisampled)
  399. {
  400. Assert( (key->m_texGLTarget == GL_TEXTURE_2D) );
  401. Assert( sliceCount == 1 );
  402. // assume non mipped
  403. Assert( (key->m_texFlags & kGLMTexMipped) == 0 );
  404. Assert( (key->m_texFlags & kGLMTexMippedAuto) == 0 );
  405. // assume renderable and srgb
  406. Assert( (key->m_texFlags & kGLMTexRenderable) !=0 );
  407. //Assert( (key->m_texFlags & kGLMTexSRGB) !=0 ); //FIXME don't assert on making depthstencil surfaces which are non srgb
  408. // double check sample count (FIXME need real limit check here against device/driver)
  409. Assert( (key->m_texSamples==2) || (key->m_texSamples==4) || (key->m_texSamples==6) || (key->m_texSamples==8) );
  410. }
  411. // now we know enough to allocate and populate the new tex layout.
  412. // malloc the new layout
  413. int layoutSize = sizeof( GLMTexLayout ) + (sliceCount * sizeof( GLMTexLayoutSlice ));
  414. GLMTexLayout *layout = (GLMTexLayout *)malloc( layoutSize );
  415. memset( layout, 0, layoutSize );
  416. // clone the key in there
  417. memset( &layout->m_key, 0x00, sizeof(layout->m_key) );
  418. layout->m_key = *key;
  419. // set refcount
  420. layout->m_refCount = 1;
  421. // save the format desc
  422. layout->m_format = (GLMTexFormatDesc *)formatDesc;
  423. // we know the mipcount from before
  424. layout->m_mipCount = mipCount;
  425. // we know the face count too
  426. layout->m_faceCount = faceCount;
  427. // slice count is the product
  428. layout->m_sliceCount = mipCount * faceCount;
  429. // we can now fill in the slices.
  430. GLMTexLayoutSlice *slicePtr = &layout->m_slices[0];
  431. int storageOffset = 0;
  432. //bool compressed = (formatDesc->m_chunkSize > 1); // true if DXT
  433. for( int mip = 0; mip < mipCount; mip ++ )
  434. {
  435. for( int face = 0; face < faceCount; face++ )
  436. {
  437. // note application of chunk size which is 1 for uncompressed, and 4 for compressed tex (DXT)
  438. // note also that the *dimensions* must scale down to 1
  439. // but that the *storage* cannot go below 4x4.
  440. // we introduce the "storage sizes" which are clamped, to compute the storage footprint.
  441. int storage_x,storage_y,storage_z;
  442. slicePtr->m_xSize = layout->m_key.m_xSize >> mip;
  443. slicePtr->m_xSize = MAX( slicePtr->m_xSize, 1 ); // dimension can't go to zero
  444. storage_x = MAX( slicePtr->m_xSize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
  445. slicePtr->m_ySize = layout->m_key.m_ySize >> mip;
  446. slicePtr->m_ySize = MAX( slicePtr->m_ySize, 1 ); // dimension can't go to zero
  447. storage_y = MAX( slicePtr->m_ySize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
  448. slicePtr->m_zSize = layout->m_key.m_zSize >> mip;
  449. slicePtr->m_zSize = MAX( slicePtr->m_zSize, 1 ); // dimension can't go to zero
  450. storage_z = MAX( slicePtr->m_zSize, 1); // storage extent for Z cannot go below '1'.
  451. //if (compressed) NO NO NO do not lie about the dimensionality, just fudge the storage.
  452. //{
  453. // // round up to multiple of 4 in X and Y axes
  454. // slicePtr->m_xSize = (slicePtr->m_xSize+3) & (~3);
  455. // slicePtr->m_ySize = (slicePtr->m_ySize+3) & (~3);
  456. //}
  457. int xchunks = (storage_x / formatDesc->m_chunkSize );
  458. int ychunks = (storage_y / formatDesc->m_chunkSize );
  459. slicePtr->m_storageSize = (xchunks * ychunks * formatDesc->m_bytesPerSquareChunk) * storage_z;
  460. slicePtr->m_storageOffset = storageOffset;
  461. storageOffset += slicePtr->m_storageSize;
  462. storageOffset = ( (storageOffset+0x0F) & (~0x0F)); // keep each MIP starting on a 16 byte boundary.
  463. slicePtr++;
  464. }
  465. }
  466. layout->m_storageTotalSize = storageOffset;
  467. //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 );
  468. // generate summary
  469. // "target, format, +/- mips, base size"
  470. char scratch[1024];
  471. char *targetname = "?";
  472. switch( key->m_texGLTarget )
  473. {
  474. case GL_TEXTURE_2D: targetname = "2D "; break;
  475. case GL_TEXTURE_3D: targetname = "3D "; break;
  476. case GL_TEXTURE_CUBE_MAP: targetname = "CUBE"; break;
  477. }
  478. sprintf( scratch, "[%s %s %dx%dx%d mips=%d slices=%d flags=%02lX%s]",
  479. targetname,
  480. formatDesc->m_formatSummary,
  481. layout->m_key.m_xSize, layout->m_key.m_ySize, layout->m_key.m_zSize,
  482. mipCount,
  483. sliceCount,
  484. layout->m_key.m_texFlags,
  485. (layout->m_key.m_texFlags & kGLMTexSRGB) ? " SRGB" : ""
  486. );
  487. layout->m_layoutSummary = strdup( scratch );
  488. //GLMPRINTF(("-D- new tex layout [ %s ]", scratch ));
  489. // then insert into map. disregard returned index.
  490. m_layoutMap.Insert( layout->m_key, layout );
  491. return layout;
  492. }
  493. }
  494. void CGLMTexLayoutTable::DelLayoutRef( GLMTexLayout *layout )
  495. {
  496. // locate layout in hash, drop refcount
  497. // (some GC step later on will harvest expired layouts - not like it's any big challenge to re-generate them)
  498. unsigned short index = m_layoutMap.Find( layout->m_key );
  499. if (index != m_layoutMap.InvalidIndex())
  500. {
  501. // found it
  502. GLMTexLayout *layout = m_layoutMap[ index ];
  503. // drop ref count
  504. layout->m_refCount --;
  505. //assert( layout->m_refCount >= 0 );
  506. }
  507. else
  508. {
  509. // that's bad
  510. GLMStop();
  511. }
  512. }
  513. void CGLMTexLayoutTable::DumpStats( )
  514. {
  515. for (uint i=0; i<m_layoutMap.Count(); i++ )
  516. {
  517. GLMTexLayout *layout = m_layoutMap[ i ];
  518. // print it out
  519. printf("\n%05d instances %08d bytes %08d totbytes %s", layout->m_refCount, layout->m_storageTotalSize, (layout->m_refCount*layout->m_storageTotalSize), layout->m_layoutSummary );
  520. }
  521. }
  522. ConVar gl_texmsaalog ( "gl_texmsaalog", "0");
  523. ConVar gl_rt_forcergba ( "gl_rt_forcergba", "1" ); // on teximage of a renderable tex, pass GL_RGBA in place of GL_BGRA
  524. 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
  525. 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
  526. ConVar gl_minimize_tex_log ( "gl_minimize_tex_log", "0" ); // if 1, printf the names of the tex that got minimized
  527. CGLMTex::CGLMTex( GLMContext *ctx, GLMTexLayout *layout, uint levels, const char *debugLabel )
  528. {
  529. #if GLMDEBUG
  530. m_pPrevTex = NULL;
  531. m_pNextTex = g_pFirstCGMLTex;
  532. if ( m_pNextTex )
  533. {
  534. Assert( m_pNextTex->m_pPrevTex == NULL );
  535. m_pNextTex->m_pPrevTex = this;
  536. }
  537. g_pFirstCGMLTex = this;
  538. #endif
  539. // caller has responsibility to make 'ctx' current, but we check to be sure.
  540. ctx->CheckCurrent();
  541. m_nLastResolvedBatchCounter = ctx->m_nBatchCounter;
  542. // note layout requested
  543. m_layout = layout;
  544. m_texGLTarget = m_layout->m_key.m_texGLTarget;
  545. m_nSamplerType = SAMPLER_TYPE_UNUSED;
  546. switch ( m_texGLTarget )
  547. {
  548. case GL_TEXTURE_CUBE_MAP: m_nSamplerType = SAMPLER_TYPE_CUBE; break;
  549. case GL_TEXTURE_2D: m_nSamplerType = SAMPLER_TYPE_2D; break;
  550. case GL_TEXTURE_3D: m_nSamplerType = SAMPLER_TYPE_3D; break;
  551. default:
  552. Assert( 0 );
  553. break;
  554. }
  555. m_maxActiveMip = -1; //index of highest mip that has been written - increase as each mip arrives
  556. m_minActiveMip = 999; //index of lowest mip that has been written - lower it as each mip arrives
  557. // note context owner
  558. m_ctx = ctx;
  559. // clear the bind point flags
  560. //m_bindPoints.ClearAll();
  561. // clear the RT attach count
  562. m_rtAttachCount = 0;
  563. // come up with a GL name for this texture.
  564. // for MTGL friendliness, we should generate our own names at some point..
  565. gGL->glGenTextures( 1, &m_texName );
  566. m_pBlitSrcFBO = NULL;
  567. m_pBlitDstFBO = NULL;
  568. // Sense whether to try and apply client storage upon teximage/subimage.
  569. // This should only be true if we're running on OSX 10.6 or it was explicitly
  570. // enabled with -gl_texclientstorage on the command line.
  571. m_texClientStorage = ctx->m_bTexClientStorage;
  572. // flag that we have not yet been explicitly kicked into VRAM..
  573. m_texPreloaded = false;
  574. // clone the debug label if there is one.
  575. m_debugLabel = debugLabel ? strdup(debugLabel) : NULL;
  576. // if tex is MSAA renderable, make an RBO, else zero the RBO name and dirty bit
  577. if (layout->m_key.m_texFlags & kGLMTexMultisampled)
  578. {
  579. gGL->glGenRenderbuffersEXT( 1, &m_rboName );
  580. // so we have enough info to go ahead and bind the RBO and put storage on it?
  581. // try it.
  582. gGL->glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, m_rboName );
  583. // quietly clamp if sample count exceeds known limit for the device
  584. int sampleCount = layout->m_key.m_texSamples;
  585. if (sampleCount > ctx->Caps().m_maxSamples)
  586. {
  587. sampleCount = ctx->Caps().m_maxSamples; // clamp
  588. }
  589. GLenum msaaFormat = (layout->m_key.m_texFlags & kGLMTexSRGB) ? layout->m_format->m_glIntFormatSRGB : layout->m_format->m_glIntFormat;
  590. gGL->glRenderbufferStorageMultisampleEXT( GL_RENDERBUFFER_EXT,
  591. sampleCount, // not "layout->m_key.m_texSamples"
  592. msaaFormat,
  593. layout->m_key.m_xSize,
  594. layout->m_key.m_ySize );
  595. if (gl_texmsaalog.GetInt())
  596. {
  597. printf( "\n == MSAA Tex %p %s : MSAA RBO is intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, msaaFormat ), msaaFormat );
  598. }
  599. gGL->glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
  600. }
  601. else
  602. {
  603. m_rboName = 0;
  604. }
  605. // at this point we have the complete description of the texture, and a name for it, but no data and no actual GL object.
  606. // 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.
  607. // any previously bound tex will be unbound and appropriately marked as a result.
  608. // the active TMU will be set as a side effect.
  609. CGLMTex *pPrevTex = ctx->m_samplers[0].m_pBoundTex;
  610. ctx->BindTexToTMU( this, 0 );
  611. m_SamplingParams.SetToDefaults();
  612. m_SamplingParams.SetToTarget( m_texGLTarget );
  613. // OK, our texture now exists and is bound on the active TMU. Not drawable yet though.
  614. // if not an RT, create backing storage and fill it
  615. if ( !(layout->m_key.m_texFlags & kGLMTexRenderable) )
  616. {
  617. m_backing = (char *)malloc( m_layout->m_storageTotalSize );
  618. memset( m_backing, 0, m_layout->m_storageTotalSize );
  619. // track bytes allocated for non-RT's
  620. int formindex = sEncodeLayoutAsIndex( &layout->m_key );
  621. g_texGlobalBytes[ formindex ] += m_layout->m_storageTotalSize;
  622. #if TEXSPACE_LOGGING
  623. 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 ] );
  624. printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
  625. g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
  626. g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
  627. );
  628. #endif
  629. }
  630. else
  631. {
  632. m_backing = NULL;
  633. m_texClientStorage = false;
  634. }
  635. // init lock count
  636. // lock reqs are tracked by the owning context
  637. m_lockCount = 0;
  638. m_sliceFlags.SetCount( m_layout->m_sliceCount );
  639. for( int i=0; i< m_layout->m_sliceCount; i++)
  640. {
  641. m_sliceFlags[i] = 0;
  642. // kSliceValid = false (we have not teximaged each slice yet)
  643. // kSliceStorageValid = false (the storage allocated does not reflect what is in the tex)
  644. // kSliceLocked = false (the slices are not locked)
  645. // kSliceFullyDirty = false (this does not come true til first lock)
  646. }
  647. // texture minimize parameter keeps driver from allocing mips when it should not, by being explicit about the ones that have no mips.
  648. bool setMinimizeParameter = false;
  649. bool minimize_rt = (gl_minimize_rt_tex.GetInt()!=0);
  650. bool minimize_all = (gl_minimize_all_tex.GetInt()!=0);
  651. if (layout->m_key.m_texFlags & kGLMTexRenderable)
  652. {
  653. // it's an RT. if mips were not explicitly requested, and "gl_minimize_rt_tex" is true, set the minimize parameter.
  654. if ( (minimize_rt || minimize_all) && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
  655. {
  656. setMinimizeParameter = true;
  657. }
  658. }
  659. else
  660. {
  661. // not an RT. if mips were not requested, and "gl_minimize_all_tex" is true, set the minimize parameter.
  662. if ( minimize_all && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
  663. {
  664. setMinimizeParameter = true;
  665. }
  666. }
  667. if (setMinimizeParameter)
  668. {
  669. if (gl_minimize_tex_log.GetInt())
  670. {
  671. printf("\n minimizing storage for tex '%s' [%s] ", m_debugLabel?m_debugLabel:"-", m_layout->m_layoutSummary );
  672. }
  673. if (gGL->m_bHave_GL_APPLE_texture_range)
  674. gGL->glTexParameteri( m_layout->m_key.m_texGLTarget, GL_TEXTURE_MINIMIZE_STORAGE_APPLE, 1 );
  675. }
  676. // after a lot of pain with texture completeness...
  677. // always push black into all slices of all newly created textures.
  678. #if 0
  679. bool pushRenderableSlices = (m_layout->m_key.m_texFlags & kGLMTexRenderable) != 0;
  680. bool pushTexSlices = true; // just do it everywhere (m_layout->m_mipCount>1) && (m_layout->m_format->m_chunkSize !=1) ;
  681. if (pushTexSlices)
  682. {
  683. // fill storage with mostly-opaque purple
  684. GLMGenTexelParams genp;
  685. memset( &genp, 0, sizeof(genp) );
  686. genp.m_format = m_layout->m_format->m_d3dFormat;
  687. const GLMTexFormatDesc *format = GetFormatDesc( genp.m_format );
  688. genp.m_dest = m_backing; // dest addr
  689. genp.m_chunkCount = m_layout->m_storageTotalSize / format->m_bytesPerSquareChunk; // fill the whole slab
  690. genp.m_byteCountLimit = m_layout->m_storageTotalSize; // limit writes to this amount
  691. genp.r = 1.0;
  692. genp.g = 0.0;
  693. genp.b = 1.0;
  694. genp.a = 0.75;
  695. GLMGenTexels( &genp );
  696. }
  697. #endif
  698. //if (pushRenderableSlices || pushTexSlices)
  699. if ( !( ( layout->m_key.m_texFlags & kGLMTexMipped ) && ( levels == m_layout->m_mipCount ) ) )
  700. {
  701. for( int face=0; face <m_layout->m_faceCount; face++)
  702. {
  703. for( int mip=0; mip <m_layout->m_mipCount; mip++)
  704. {
  705. // we're not really going to lock, we're just going to write the blank data from the backing store we just made
  706. GLMTexLockDesc desc;
  707. desc.m_req.m_tex = this;
  708. desc.m_req.m_face = face;
  709. desc.m_req.m_mip = mip;
  710. desc.m_sliceIndex = CalcSliceIndex( face, mip );
  711. GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
  712. desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
  713. desc.m_req.m_region.xmax = slice->m_xSize;
  714. desc.m_req.m_region.ymax = slice->m_ySize;
  715. desc.m_req.m_region.zmax = slice->m_zSize;
  716. desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
  717. desc.m_sliceRegionOffset = 0;
  718. 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
  719. }
  720. }
  721. }
  722. 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 : "-" ));
  723. ctx->BindTexToTMU( pPrevTex, 0 );
  724. }
  725. CGLMTex::~CGLMTex( )
  726. {
  727. #if GLMDEBUG
  728. if ( m_pPrevTex )
  729. {
  730. Assert( m_pPrevTex->m_pNextTex == this );
  731. m_pPrevTex->m_pNextTex = m_pNextTex;
  732. }
  733. else
  734. {
  735. Assert( g_pFirstCGMLTex == this );
  736. g_pFirstCGMLTex = m_pNextTex;
  737. }
  738. if ( m_pNextTex )
  739. {
  740. Assert( m_pNextTex->m_pPrevTex == this );
  741. m_pNextTex->m_pPrevTex = m_pPrevTex;
  742. }
  743. m_pNextTex = m_pPrevTex = NULL;
  744. #endif
  745. if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) )
  746. {
  747. int formindex = sEncodeLayoutAsIndex( &m_layout->m_key );
  748. g_texGlobalBytes[ formindex ] -= m_layout->m_storageTotalSize;
  749. #if TEXSPACE_LOGGING
  750. 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 ] );
  751. printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
  752. g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
  753. g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
  754. );
  755. #endif
  756. }
  757. 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 : "-" ));
  758. // check first to see if we were still bound anywhere or locked... these should be failures.
  759. if ( m_pBlitSrcFBO )
  760. {
  761. m_ctx->DelFBO( m_pBlitSrcFBO );
  762. m_pBlitSrcFBO = NULL;
  763. }
  764. if ( m_pBlitDstFBO )
  765. {
  766. m_ctx->DelFBO( m_pBlitDstFBO );
  767. m_pBlitDstFBO = NULL;
  768. }
  769. if ( m_rboName )
  770. {
  771. gGL->glDeleteRenderbuffersEXT( 1, &m_rboName );
  772. m_rboName = 0;
  773. }
  774. // if all that is OK, then delete the underlying tex
  775. if ( m_texName )
  776. {
  777. gGL->glDeleteTextures( 1, &m_texName );
  778. m_texName = 0;
  779. }
  780. // release our usage of the layout
  781. m_ctx->m_texLayoutTable->DelLayoutRef( m_layout );
  782. m_layout = NULL;
  783. if (m_backing)
  784. {
  785. free( m_backing );
  786. m_backing = NULL;
  787. }
  788. if (m_debugLabel)
  789. {
  790. free( m_debugLabel );
  791. m_debugLabel = NULL;
  792. }
  793. m_ctx = NULL;
  794. }
  795. int CGLMTex::CalcSliceIndex( int face, int mip )
  796. {
  797. // faces of the same mip level are adjacent. "face major" storage
  798. int index = (mip * m_layout->m_faceCount) + face;
  799. return index;
  800. }
  801. void CGLMTex::CalcTexelDataOffsetAndStrides( int sliceIndex, int x, int y, int z, int *offsetOut, int *yStrideOut, int *zStrideOut )
  802. {
  803. int offset = 0;
  804. int yStride = 0;
  805. int zStride = 0;
  806. GLMTexFormatDesc *format = m_layout->m_format;
  807. if (format->m_chunkSize==1)
  808. {
  809. // figure out row stride and layer stride
  810. yStride = format->m_bytesPerSquareChunk * m_layout->m_slices[sliceIndex].m_xSize; // bytes per texel row (y stride)
  811. zStride = yStride * m_layout->m_slices[sliceIndex].m_ySize; // bytes per texel layer (if 3D tex)
  812. offset = x * format->m_bytesPerSquareChunk; // lateral offset
  813. offset += (y * yStride); // scanline offset
  814. offset += (z * zStride); // should be zero for 2D tex
  815. }
  816. else
  817. {
  818. yStride = format->m_bytesPerSquareChunk * (m_layout->m_slices[sliceIndex].m_xSize / format->m_chunkSize);
  819. zStride = yStride * (m_layout->m_slices[sliceIndex].m_ySize / format->m_chunkSize);
  820. // compressed format. scale the x,y values into chunks. Z isn't chunked.
  821. // assert if any of them are not multiples of a chunk.
  822. int chunkx = x / format->m_chunkSize;
  823. int chunky = y / format->m_chunkSize;
  824. if ( (chunkx * format->m_chunkSize) != x)
  825. {
  826. GLMStop();
  827. }
  828. if ( (chunky * format->m_chunkSize) != y)
  829. {
  830. GLMStop();
  831. }
  832. offset = chunkx * format->m_bytesPerSquareChunk; // lateral offset
  833. offset += (chunky * yStride); // chunk row offset
  834. offset += (z * zStride); // should be zero for 2D tex
  835. }
  836. *offsetOut = offset;
  837. *yStrideOut = yStride;
  838. *zStrideOut = zStride;
  839. }
  840. void CGLMTex::ReadTexels( GLMTexLockDesc *desc, bool readWholeSlice )
  841. {
  842. GLMRegion readBox;
  843. if (readWholeSlice)
  844. {
  845. readBox.xmin = readBox.ymin = readBox.zmin = 0;
  846. readBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
  847. readBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
  848. readBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
  849. }
  850. else
  851. {
  852. readBox = desc->m_req.m_region;
  853. }
  854. CGLMTex *pPrevTex = m_ctx->m_samplers[0].m_pBoundTex;
  855. m_ctx->BindTexToTMU( this, 0 ); // SelectTMU(n) is a side effect
  856. if (readWholeSlice)
  857. {
  858. // make this work first.... then write the partial path
  859. // (Hmmmm, I don't think we will ever actually need a partial path -
  860. // since we have no notion of a partially valid slice of storage
  861. GLMTexFormatDesc *format = m_layout->m_format;
  862. GLenum target = m_layout->m_key.m_texGLTarget;
  863. void *sliceAddress = m_backing + m_layout->m_slices[ desc->m_sliceIndex ].m_storageOffset; // this would change for PBO
  864. //int sliceSize = m_layout->m_slices[ desc->m_sliceIndex ].m_storageSize;
  865. // interestingly enough, we can use the same path for both 2D and 3D fetch
  866. switch( target )
  867. {
  868. case GL_TEXTURE_CUBE_MAP:
  869. // adjust target to steer to the proper face, then fall through to the 2D texture path.
  870. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
  871. case GL_TEXTURE_2D:
  872. case GL_TEXTURE_3D:
  873. {
  874. // check compressed or not
  875. if (format->m_chunkSize != 1)
  876. {
  877. // compressed path
  878. // http://www.opengl.org/sdk/docs/man/xhtml/glGetCompressedTexImage.xml
  879. gGL->glGetCompressedTexImage( target, // target
  880. desc->m_req.m_mip, // level
  881. sliceAddress ); // destination
  882. }
  883. else
  884. {
  885. // uncompressed path
  886. // http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml
  887. gGL->glGetTexImage( target, // target
  888. desc->m_req.m_mip, // level
  889. format->m_glDataFormat, // dataformat
  890. format->m_glDataType, // datatype
  891. sliceAddress ); // destination
  892. }
  893. }
  894. break;
  895. }
  896. }
  897. else
  898. {
  899. GLMStop();
  900. }
  901. m_ctx->BindTexToTMU( pPrevTex, 0 );
  902. }
  903. // TexSubImage should work properly on every driver stack and GPU--enabling by default.
  904. ConVar gl_enabletexsubimage( "gl_enabletexsubimage", "1" );
  905. void CGLMTex::WriteTexels( GLMTexLockDesc *desc, bool writeWholeSlice, bool noDataWrite )
  906. {
  907. //if ( m_nBindlessHashNumEntries )
  908. // return;
  909. GLMRegion writeBox;
  910. bool needsExpand = false;
  911. char *expandTemp = NULL;
  912. switch( m_layout->m_format->m_d3dFormat)
  913. {
  914. case D3DFMT_V8U8:
  915. {
  916. needsExpand = true;
  917. writeWholeSlice = true;
  918. // shoot down client storage if we have to generate a new flavor of the data
  919. m_texClientStorage = false;
  920. }
  921. break;
  922. }
  923. if (writeWholeSlice)
  924. {
  925. writeBox.xmin = writeBox.ymin = writeBox.zmin = 0;
  926. writeBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
  927. writeBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
  928. writeBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
  929. }
  930. else
  931. {
  932. writeBox = desc->m_req.m_region;
  933. }
  934. // first thing is to get the GL texture bound to a TMU, or just select one if already bound
  935. // to get this running we will just always slam TMU 0 and let the draw time code fix it back
  936. // a later optimization would be to hoist the bind call to the caller, do it exactly once
  937. CGLMTex *pPrevTex = m_ctx->m_samplers[0].m_pBoundTex;
  938. m_ctx->BindTexToTMU( this, 0 ); // SelectTMU(n) is a side effect
  939. GLMTexFormatDesc *format = m_layout->m_format;
  940. GLenum target = m_layout->m_key.m_texGLTarget;
  941. GLenum glDataFormat = format->m_glDataFormat; // this could change if expansion kicks in
  942. GLenum glDataType = format->m_glDataType;
  943. GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc->m_sliceIndex ];
  944. void *sliceAddress = m_backing ? (m_backing + slice->m_storageOffset) : NULL; // this would change for PBO
  945. // allow use of subimage if the target is texture2D and it has already been teximage'd
  946. bool mayUseSubImage = false;
  947. if ( (target==GL_TEXTURE_2D) && (m_sliceFlags[ desc->m_sliceIndex ] & kSliceValid) )
  948. {
  949. mayUseSubImage = gl_enabletexsubimage.GetInt() != 0;
  950. }
  951. // check flavor, 2D, 3D, or cube map
  952. // we also have the choice to use subimage if this is a tex already created. (open question as to benefit)
  953. // SRGB select. At this level (writetexels) we firmly obey the m_texFlags.
  954. // (mechanism not policy)
  955. GLenum intformat = (m_layout->m_key.m_texFlags & kGLMTexSRGB) ? format->m_glIntFormatSRGB : format->m_glIntFormat;
  956. if (CommandLine()->FindParm("-disable_srgbtex"))
  957. {
  958. // force non srgb flavor - experiment to make ATI r600 happy on 10.5.8 (maybe x1600 too!)
  959. intformat = format->m_glIntFormat;
  960. }
  961. Assert( intformat != 0 );
  962. if (m_layout->m_key.m_texFlags & kGLMTexSRGB)
  963. {
  964. Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_COMPONENT );
  965. Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_STENCIL_EXT );
  966. Assert( m_layout->m_format->m_glDataFormat != GL_ALPHA );
  967. }
  968. // adjust min and max mip written
  969. if (desc->m_req.m_mip > m_maxActiveMip)
  970. {
  971. m_maxActiveMip = desc->m_req.m_mip;
  972. //gGL->glTexParameteri( target, GL_TEXTURE_MAX_LEVEL, desc->m_req.m_mip);
  973. }
  974. if (desc->m_req.m_mip < m_minActiveMip)
  975. {
  976. m_minActiveMip = desc->m_req.m_mip;
  977. //gGL->glTexParameteri( target, GL_TEXTURE_BASE_LEVEL, desc->m_req.m_mip);
  978. }
  979. if (needsExpand)
  980. {
  981. int expandSize = 0;
  982. switch( m_layout->m_format->m_d3dFormat)
  983. {
  984. case D3DFMT_V8U8:
  985. {
  986. // figure out new size based on 3byte RGB format
  987. // easy, just take the two byte size and grow it by 50%
  988. expandSize = (slice->m_storageSize * 3) / 2;
  989. expandTemp = (char*)malloc( expandSize );
  990. char *src = (char*)sliceAddress;
  991. char *dst = expandTemp;
  992. // transfer RG's to RGB's
  993. while(expandSize>0)
  994. {
  995. *dst = *src++; // move first byte
  996. *dst = *src++; // move second byte
  997. *reinterpret_cast<uint8*>(dst) = 0xBB; // pad third byte
  998. expandSize -= 3;
  999. }
  1000. // move the slice pointer
  1001. sliceAddress = expandTemp;
  1002. // change the data format we tell GL about
  1003. glDataFormat = GL_RGB;
  1004. }
  1005. break;
  1006. default: Assert(!"Don't know how to expand that format..");
  1007. }
  1008. }
  1009. // set up the client storage now, one way or another
  1010. // 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.
  1011. // So it's safe to just go on as if this extension existed and hold the possibly-unnecessary extra RAM.
  1012. if (gGL->m_bHave_GL_APPLE_client_storage)
  1013. {
  1014. gGL->glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, m_texClientStorage );
  1015. }
  1016. switch( target )
  1017. {
  1018. case GL_TEXTURE_CUBE_MAP:
  1019. // adjust target to steer to the proper face, then fall through to the 2D texture path.
  1020. target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
  1021. case GL_TEXTURE_2D:
  1022. {
  1023. // check compressed or not
  1024. if (format->m_chunkSize != 1)
  1025. {
  1026. Assert( writeWholeSlice ); //subimage not implemented in this path yet
  1027. // compressed path
  1028. // http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage2D.xml
  1029. gGL->glCompressedTexImage2D( target, // target
  1030. desc->m_req.m_mip, // level
  1031. intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
  1032. slice->m_xSize, // width
  1033. slice->m_ySize, // height
  1034. 0, // border
  1035. slice->m_storageSize, // imageSize
  1036. sliceAddress ); // data
  1037. }
  1038. else
  1039. {
  1040. if (mayUseSubImage)
  1041. {
  1042. // go subimage2D if it's a replacement, not a creation
  1043. gGL->glPixelStorei( GL_UNPACK_ROW_LENGTH, slice->m_xSize ); // in pixels
  1044. gGL->glPixelStorei( GL_UNPACK_SKIP_PIXELS, writeBox.xmin ); // in pixels
  1045. gGL->glPixelStorei( GL_UNPACK_SKIP_ROWS, writeBox.ymin ); // in pixels
  1046. gGL->glTexSubImage2D( target,
  1047. desc->m_req.m_mip, // level
  1048. writeBox.xmin, // xoffset into dest
  1049. writeBox.ymin, // yoffset into dest
  1050. writeBox.xmax - writeBox.xmin, // width (was slice->m_xSize)
  1051. writeBox.ymax - writeBox.ymin, // height (was slice->m_ySize)
  1052. glDataFormat, // format
  1053. glDataType, // type
  1054. sliceAddress // data (will be offsetted by the SKIP_PIXELS and SKIP_ROWS - let GL do the math to find the first source texel)
  1055. );
  1056. gGL->glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
  1057. gGL->glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
  1058. gGL->glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
  1059. /*
  1060. //http://www.opengl.org/sdk/docs/man/xhtml/glTexSubImage2D.xml
  1061. glTexSubImage2D( target,
  1062. desc->m_req.m_mip, // level
  1063. 0, // xoffset
  1064. 0, // yoffset
  1065. slice->m_xSize, // width
  1066. slice->m_ySize, // height
  1067. glDataFormat, // format
  1068. glDataType, // type
  1069. sliceAddress // data
  1070. );
  1071. */
  1072. }
  1073. else
  1074. {
  1075. if (m_layout->m_key.m_texFlags & kGLMTexRenderable)
  1076. {
  1077. if (gl_rt_forcergba.GetInt())
  1078. {
  1079. if (glDataFormat == GL_BGRA)
  1080. {
  1081. // change it
  1082. glDataFormat = GL_RGBA;
  1083. }
  1084. }
  1085. }
  1086. // uncompressed path
  1087. // http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
  1088. gGL->glTexImage2D( target, // target
  1089. desc->m_req.m_mip, // level
  1090. intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
  1091. slice->m_xSize, // width
  1092. slice->m_ySize, // height
  1093. 0, // border
  1094. glDataFormat, // dataformat
  1095. glDataType, // datatype
  1096. noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
  1097. if (m_layout->m_key.m_texFlags & kGLMTexMultisampled)
  1098. {
  1099. if (gl_texmsaalog.GetInt())
  1100. {
  1101. printf( "\n == MSAA Tex %p %s : glTexImage2D for flat tex using intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, intformat ), intformat );
  1102. printf( "\n" );
  1103. }
  1104. }
  1105. m_sliceFlags[ desc->m_sliceIndex ] |= kSliceValid; // for next time, we can subimage..
  1106. }
  1107. }
  1108. }
  1109. break;
  1110. case GL_TEXTURE_3D:
  1111. {
  1112. // check compressed or not
  1113. if (format->m_chunkSize != 1)
  1114. {
  1115. // compressed path
  1116. // http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage3D.xml
  1117. gGL->glCompressedTexImage3D( target, // target
  1118. desc->m_req.m_mip, // level
  1119. intformat, // internalformat
  1120. slice->m_xSize, // width
  1121. slice->m_ySize, // height
  1122. slice->m_zSize, // depth
  1123. 0, // border
  1124. slice->m_storageSize, // imageSize
  1125. sliceAddress ); // data
  1126. }
  1127. else
  1128. {
  1129. // uncompressed path
  1130. // http://www.opengl.org/sdk/docs/man/xhtml/glTexImage3D.xml
  1131. gGL->glTexImage3D( target, // target
  1132. desc->m_req.m_mip, // level
  1133. intformat, // internalformat
  1134. slice->m_xSize, // width
  1135. slice->m_ySize, // height
  1136. slice->m_zSize, // depth
  1137. 0, // border
  1138. glDataFormat, // dataformat
  1139. glDataType, // datatype
  1140. noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
  1141. }
  1142. }
  1143. break;
  1144. }
  1145. if (gGL->m_bHave_GL_APPLE_client_storage)
  1146. {
  1147. gGL->glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE );
  1148. }
  1149. if ( expandTemp )
  1150. {
  1151. free( expandTemp );
  1152. }
  1153. m_ctx->BindTexToTMU( pPrevTex, 0 );
  1154. }
  1155. void CGLMTex::Lock( GLMTexLockParams *params, char** addressOut, int* yStrideOut, int *zStrideOut )
  1156. {
  1157. #if GL_TELEMETRY_GPU_ZONES
  1158. CScopedGLMPIXEvent glmPIXEvent( "CGLMTex::Lock" );
  1159. g_TelemetryGPUStats.m_nTotalTexLocksAndUnlocks++;
  1160. #endif
  1161. // locate appropriate slice in layout record
  1162. int sliceIndex = CalcSliceIndex( params->m_face, params->m_mip );
  1163. GLMTexLayoutSlice *slice = &m_layout->m_slices[sliceIndex];
  1164. // obtain offset
  1165. //int sliceBaseOffset = slice->m_storageOffset;
  1166. // cross check region req against slice bounds - figure out if it matches, exceeds, or is less than the whole slice.
  1167. char exceed = (params->m_region.xmin < 0) || (params->m_region.xmax > slice->m_xSize) ||
  1168. (params->m_region.ymin < 0) || (params->m_region.ymax > slice->m_ySize) ||
  1169. (params->m_region.zmin < 0) || (params->m_region.zmax > slice->m_zSize);
  1170. char partial = (params->m_region.xmin > 0) || (params->m_region.xmax < slice->m_xSize) ||
  1171. (params->m_region.ymin > 0) || (params->m_region.ymax < slice->m_ySize) ||
  1172. (params->m_region.zmin > 0) || (params->m_region.zmax < slice->m_zSize);
  1173. bool copyout = false; // set if a readback of the texture slice from GL is needed
  1174. if (exceed)
  1175. {
  1176. // illegal rect, out of bounds
  1177. GLMStop();
  1178. }
  1179. // on return, these things need to be true
  1180. // a - there needs to be storage allocated, which we will return an address within
  1181. // b - the region corresponding to the slice being locked, will have valid data there for the whole slice.
  1182. // c - the slice is marked as locked
  1183. // d - the params of the lock request have been saved in the lock table (in the context)
  1184. // so step 1 is unambiguous. If there's no backing storage, make some.
  1185. if (!m_backing)
  1186. {
  1187. m_backing = (char *)malloc( m_layout->m_storageTotalSize );
  1188. memset( m_backing, 0, m_layout->m_storageTotalSize );
  1189. // clear the kSliceStorageValid bit on all slices
  1190. for( int i=0; i<m_layout->m_sliceCount; i++)
  1191. {
  1192. m_sliceFlags[i] &= ~kSliceStorageValid;
  1193. }
  1194. }
  1195. // work on this slice now
  1196. // storage is known to exist at this point, but we need to check if its contents are valid for this slice.
  1197. // this is tracked per-slice so we don't hoist all the texels back out of GL across all slices if caller only
  1198. // wanted to lock some of them.
  1199. // (i.e. if we just alloced it, it's blank)
  1200. // if storage is invalid, but the texture itself is valid, hoist the texels back to the storage and mark it valid.
  1201. // if storage is invalid, and texture itself is also invalid, go ahead and mark storage as valid and fully dirty... to force teximage.
  1202. // ???????????? we need to go over this more carefully re "slice valid" (it has been teximaged) vs "storage valid" (it has been copied out).
  1203. unsigned char *sliceFlags = &m_sliceFlags[ sliceIndex ];
  1204. if (params->m_readback)
  1205. {
  1206. // caller is letting us know that it wants to readback the real texels.
  1207. *sliceFlags |= kSliceStorageValid;
  1208. *sliceFlags |= kSliceValid;
  1209. *sliceFlags &= ~(kSliceFullyDirty);
  1210. copyout = true;
  1211. }
  1212. else
  1213. {
  1214. // caller is pushing texels.
  1215. if (! (*sliceFlags & kSliceStorageValid) )
  1216. {
  1217. // storage is invalid. check texture state
  1218. if ( *sliceFlags & kSliceValid )
  1219. {
  1220. // kSliceValid set: the texture itself has a valid slice, but we don't have it in our backing copy, so copy it out.
  1221. copyout = true;
  1222. }
  1223. else
  1224. {
  1225. // kSliceValid not set: the texture does not have a valid slice to copy out - it hasn't been teximage'd yet.
  1226. // set the "full dirty" bit to make sure we teximage the whole thing on unlock.
  1227. *sliceFlags |= kSliceFullyDirty;
  1228. // assert if they did not ask to lock the full slice size on this go-round
  1229. if (partial)
  1230. {
  1231. // choice here -
  1232. // 1 - stop cold, we don't know how to subimage yet.
  1233. // 2 - grin and bear it, mark whole slice dirty (ah, we already did... so, do nothing).
  1234. // choice 2: // GLMStop();
  1235. }
  1236. }
  1237. // one way or another, upon reaching here the slice storage is valid for read.
  1238. *sliceFlags |= kSliceStorageValid;
  1239. }
  1240. }
  1241. // when we arrive here, there is storage, and the content of the storage for this slice is valid
  1242. // (or zeroes if it's the first lock)
  1243. // log the lock request in the context.
  1244. int newdesc = m_ctx->m_texLocks.AddToTail();
  1245. GLMTexLockDesc *desc = &m_ctx->m_texLocks[newdesc];
  1246. desc->m_req = *params;
  1247. desc->m_active = true;
  1248. desc->m_sliceIndex = sliceIndex;
  1249. desc->m_sliceBaseOffset = m_layout->m_slices[sliceIndex].m_storageOffset;
  1250. // to calculate the additional offset we need to look at the rect's min corner
  1251. // combined with the per-texel size and Y/Z stride
  1252. // also cross check it for 4x multiple if there is compression in play
  1253. int offsetInSlice = 0;
  1254. int yStride = 0;
  1255. int zStride = 0;
  1256. CalcTexelDataOffsetAndStrides( sliceIndex, params->m_region.xmin, params->m_region.ymin, params->m_region.zmin, &offsetInSlice, &yStride, &zStride );
  1257. // for compressed case...
  1258. // since there is presently no way to texsubimage a DXT when the rect does not cover the whole width,
  1259. // we will probably need to inflate the dirty rect in the recorded lock req so that the entire span is
  1260. // pushed across at unlock time.
  1261. desc->m_sliceRegionOffset = offsetInSlice + desc->m_sliceBaseOffset;
  1262. if (copyout)
  1263. {
  1264. // read the whole slice
  1265. // (odds are we'll never request anything but a whole slice to be read..)
  1266. ReadTexels( desc, true );
  1267. } // this would be a good place to fill with scrub value if in debug...
  1268. *addressOut = m_backing + desc->m_sliceRegionOffset;
  1269. *yStrideOut = yStride;
  1270. *zStrideOut = zStride;
  1271. m_lockCount++;
  1272. }
  1273. void CGLMTex::Unlock( GLMTexLockParams *params )
  1274. {
  1275. #if GL_TELEMETRY_GPU_ZONES
  1276. CScopedGLMPIXEvent glmPIXEvent( "CGLMTex::Unlock" );
  1277. g_TelemetryGPUStats.m_nTotalTexLocksAndUnlocks++;
  1278. #endif
  1279. // look for an active lock request on this face and mip (doesn't necessarily matter which one, if more than one)
  1280. // and mark it inactive.
  1281. // --> if you can't find one, fail. first line of defense against mismatched locks/unlocks..
  1282. int i=0;
  1283. bool found = false;
  1284. while( !found && (i<m_ctx->m_texLocks.Count()) )
  1285. {
  1286. GLMTexLockDesc *desc = &m_ctx->m_texLocks[i];
  1287. // is lock at index 'i' targeted at the texture/face/mip in question?
  1288. 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) )
  1289. {
  1290. // matched and active, so retire it
  1291. desc->m_active = false;
  1292. // stop searching
  1293. found = true;
  1294. }
  1295. i++;
  1296. }
  1297. if (!found)
  1298. {
  1299. GLMStop(); // bad news
  1300. }
  1301. // found - so drop lock count
  1302. m_lockCount--;
  1303. if (m_lockCount <0)
  1304. {
  1305. GLMStop(); // bad news
  1306. }
  1307. if (m_lockCount==0)
  1308. {
  1309. // there should not be any active locks remaining on this texture.
  1310. // motivation to defer all texel pushing til *all* open locks are closed out -
  1311. // if/when we back the texture with a PBO, we will need to unmap that PBO before teximaging from it;
  1312. // by waiting for all the locks to clear this gives us an unambiguous signal to act on.
  1313. // scan through all the retired locks for this texture and push the texels for each one.
  1314. // after each one is dispatched, remove it from the pile.
  1315. int j=0;
  1316. while( j<m_ctx->m_texLocks.Count() )
  1317. {
  1318. GLMTexLockDesc *desc = &m_ctx->m_texLocks[j];
  1319. if ( desc->m_req.m_tex == this )
  1320. {
  1321. // if it's active, something is wrong
  1322. if (desc->m_active)
  1323. {
  1324. GLMStop();
  1325. }
  1326. // write the texels
  1327. bool fullyDirty = false;
  1328. fullyDirty |= ((m_sliceFlags[ desc->m_sliceIndex ] & kSliceFullyDirty) != 0);
  1329. // this is not optimal and will result in full downloads on any dirty.
  1330. // we're papering over the fact that subimage isn't done yet.
  1331. // but this is safe if the slice of storage is all valid.
  1332. // at some point we'll need to actually compare the lock box against the slice bounds.
  1333. // fullyDirty |= (m_sliceFlags[ desc->m_sliceIndex ] & kSliceStorageValid);
  1334. WriteTexels( desc, fullyDirty );
  1335. // logical place to trigger preloading
  1336. // only do it for an RT tex, if it is not yet attached to any FBO.
  1337. // also, only do it if the slice number is the last slice in the tex.
  1338. if ( desc->m_sliceIndex == (m_layout->m_sliceCount-1) )
  1339. {
  1340. if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) || (m_rtAttachCount==0) )
  1341. {
  1342. m_ctx->PreloadTex( this );
  1343. // printf("( slice %d of %d )", desc->m_sliceIndex, m_layout->m_sliceCount );
  1344. }
  1345. }
  1346. m_ctx->m_texLocks.FastRemove( j ); // remove from the pile, don't advance index
  1347. }
  1348. else
  1349. {
  1350. j++; // move on to next one
  1351. }
  1352. }
  1353. // clear the locked and full-dirty flags for all slices
  1354. for( int slice=0; slice < m_layout->m_sliceCount; slice++)
  1355. {
  1356. m_sliceFlags[slice] &= ~( kSliceLocked | kSliceFullyDirty );
  1357. }
  1358. // The 3D texture upload code seems to rely on the host copy, probably
  1359. // because it reuploads the whole thing each slice; we only use 3D textures
  1360. // for the 32x32x32 colorpsace conversion lookups and debugging the problem
  1361. // would not save any more memory.
  1362. if ( !m_texClientStorage && ( m_texGLTarget == GL_TEXTURE_2D ) )
  1363. {
  1364. free(m_backing);
  1365. m_backing = NULL;
  1366. }
  1367. }
  1368. }
  1369. #if defined( OSX )
  1370. void CGLMTex::HandleSRGBMismatch( bool srgb, int &srgbFlipCount )
  1371. {
  1372. bool srgbCapableTex = false; // not yet known
  1373. bool renderableTex = false; // not yet known.
  1374. srgbCapableTex = m_layout->m_format->m_glIntFormatSRGB != 0;
  1375. renderableTex = ( m_layout->m_key.m_texFlags & kGLMTexRenderable ) != 0;
  1376. // we can fix it if it's not a renderable, and an sRGB enabled format variation is available.
  1377. if ( srgbCapableTex && !renderableTex )
  1378. {
  1379. char *texname = m_debugLabel;
  1380. if (!texname) texname = "-";
  1381. m_srgbFlipCount++;
  1382. //policy: print the ones that have flipped 1 or N times
  1383. bool print_allflips = CommandLine()->FindParm("-glmspewallsrgbflips");
  1384. bool print_firstflips = CommandLine()->FindParm("-glmspewfirstsrgbflips");
  1385. bool print_freqflips = CommandLine()->FindParm("-glmspewfreqsrgbflips");
  1386. bool print_crawls = CommandLine()->FindParm("-glmspewsrgbcrawls");
  1387. bool print_maxcrawls = CommandLine()->FindParm("-glmspewsrgbmaxcrawls");
  1388. bool print_it = false;
  1389. if (print_allflips)
  1390. {
  1391. print_it = true;
  1392. }
  1393. if (print_firstflips) // report on first flip
  1394. {
  1395. print_it |= m_srgbFlipCount==1;
  1396. }
  1397. if (print_freqflips) // report on 50th flip
  1398. {
  1399. print_it |= m_srgbFlipCount==50;
  1400. }
  1401. if ( print_it )
  1402. {
  1403. char *formatStr;
  1404. formatStr = "srgb change (samp=%d): tex '%-30s' %08x %s (srgb=%d, %d times)";
  1405. if (strlen(texname) >= 30)
  1406. {
  1407. formatStr = "srgb change (samp=%d): tex '%s' %08x %s (srgb=%d, %d times)";
  1408. }
  1409. printf( "\n" );
  1410. printf( formatStr, index, texname, m_layout->m_layoutSummary, (int)srgb, m_srgbFlipCount );
  1411. #ifdef POSIX
  1412. if (print_crawls)
  1413. {
  1414. static char *interesting_crawl_substrs[] = { "CShader::OnDrawElements", NULL }; // add more as needed
  1415. CStackCrawlParams cp;
  1416. memset( &cp, 0, sizeof(cp) );
  1417. cp.m_frameLimit = 20;
  1418. g_pLauncherMgr->GetStackCrawl(&cp);
  1419. for( int i=0; i< cp.m_frameCount; i++)
  1420. {
  1421. // for each row of crawl, decide if name is interesting
  1422. bool hit = print_maxcrawls;
  1423. for( char **match = interesting_crawl_substrs; (!hit) && (*match != NULL); match++)
  1424. {
  1425. if (strstr(cp.m_crawlNames[i], *match))
  1426. {
  1427. hit = true;
  1428. }
  1429. }
  1430. if (hit)
  1431. {
  1432. printf( "\n\t%s", cp.m_crawlNames[i] );
  1433. }
  1434. }
  1435. printf( "\n");
  1436. }
  1437. #endif
  1438. }
  1439. #if GLMDEBUG && 0
  1440. //"toi" = texture of interest
  1441. static char s_toi[256] = "colorcorrection";
  1442. if (strstr( texname, s_toi ))
  1443. {
  1444. // breakpoint on this if you like
  1445. GLMPRINTF(( "srgb change %d for %s", m_srgbFlipCount, texname ));
  1446. }
  1447. #endif
  1448. // re-submit the tex unless we're stifling it
  1449. if (!CommandLine()->FindParm( "-glmnosrgbflips" ))
  1450. {
  1451. ResetSRGB( srgb, false );
  1452. }
  1453. }
  1454. else
  1455. {
  1456. //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 ));
  1457. // we just leave the sampler state where it is, and that's life
  1458. }
  1459. }
  1460. void CGLMTex::ResetSRGB( bool srgb, bool noDataWrite )
  1461. {
  1462. // see if requested SRGB state differs from the known one
  1463. bool wasSRGB = (m_layout->m_key.m_texFlags & kGLMTexSRGB);
  1464. GLMTexLayout *oldLayout = m_layout; // need to m_ctx->m_texLayoutTable->DelLayoutRef on this one if we flip
  1465. if (srgb != wasSRGB)
  1466. {
  1467. // we're going to need a new layout (though the storage size should be the same - check it)
  1468. GLMTexLayoutKey newKey = m_layout->m_key;
  1469. newKey.m_texFlags &= (~kGLMTexSRGB); // turn off that bit
  1470. newKey.m_texFlags |= srgb ? kGLMTexSRGB : 0; // turn on that bit if it should be so
  1471. // get new layout
  1472. GLMTexLayout *newLayout = m_ctx->m_texLayoutTable->NewLayoutRef( &newKey );
  1473. // if SRGB requested, verify that the layout we just got can do it.
  1474. // if it can't, delete the new layout ref and bail.
  1475. if (srgb && (newLayout->m_format->m_glIntFormatSRGB == 0))
  1476. {
  1477. Assert( !"Can't enable SRGB mode on this format" );
  1478. m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
  1479. return;
  1480. }
  1481. // check sizes and fail if no match
  1482. if( newLayout->m_storageTotalSize != oldLayout->m_storageTotalSize )
  1483. {
  1484. Assert( !"Bug: layout sizes don't match on SRGB change" );
  1485. m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
  1486. return;
  1487. }
  1488. // commit to new layout
  1489. m_layout = newLayout;
  1490. m_texGLTarget = m_layout->m_key.m_texGLTarget;
  1491. // check same size
  1492. Assert( m_layout->m_storageTotalSize == oldLayout->m_storageTotalSize );
  1493. Assert( newLayout != oldLayout );
  1494. // release old
  1495. m_ctx->m_texLayoutTable->DelLayoutRef( oldLayout );
  1496. oldLayout = NULL;
  1497. // force texel re-DL
  1498. // note this messes with TMU 0 as side effect of WriteTexels
  1499. // so we save and restore the TMU 0 binding first
  1500. // since we're likely to be called in dxabstract when it is syncing sampler state, we can't go trampling the bindings.
  1501. // 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.
  1502. CGLMTex *tmu0save = m_ctx->m_samplers[0].m_pBoundTex;
  1503. for( int face=0; face <m_layout->m_faceCount; face++)
  1504. {
  1505. for( int mip=0; mip <m_layout->m_mipCount; mip++)
  1506. {
  1507. // we're not really going to lock, we're just going to rewrite the orig data
  1508. GLMTexLockDesc desc;
  1509. desc.m_req.m_tex = this;
  1510. desc.m_req.m_face = face;
  1511. desc.m_req.m_mip = mip;
  1512. desc.m_sliceIndex = CalcSliceIndex( face, mip );
  1513. GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
  1514. desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
  1515. desc.m_req.m_region.xmax = slice->m_xSize;
  1516. desc.m_req.m_region.ymax = slice->m_ySize;
  1517. desc.m_req.m_region.zmax = slice->m_zSize;
  1518. desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
  1519. desc.m_sliceRegionOffset = 0;
  1520. WriteTexels( &desc, true, noDataWrite ); // write whole slice. and avoid pushing real bits if the caller requests (RT's)
  1521. }
  1522. }
  1523. // put it back
  1524. m_ctx->BindTexToTMU( tmu0save, 0 );
  1525. }
  1526. }
  1527. #endif
  1528. bool CGLMTex::IsRBODirty() const
  1529. {
  1530. return m_nLastResolvedBatchCounter != m_ctx->m_nBatchCounter;
  1531. }
  1532. void CGLMTex::ForceRBONonDirty()
  1533. {
  1534. m_nLastResolvedBatchCounter = m_ctx->m_nBatchCounter;
  1535. }
  1536. void CGLMTex::ForceRBODirty()
  1537. {
  1538. m_nLastResolvedBatchCounter = m_ctx->m_nBatchCounter - 1;
  1539. }