TextureManager.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "graphics/TextureManager.h"
  23. #include "platform/platformAssert.h"
  24. #include "platform/platformGL.h"
  25. #include "platform/platform.h"
  26. #include "collection/vector.h"
  27. #include "io/resource/resourceManager.h"
  28. #include "graphics/gBitmap.h"
  29. #include "console/console.h"
  30. #include "console/consoleInternal.h"
  31. #include "console/consoleTypes.h"
  32. #include "memory/safeDelete.h"
  33. #include "math/mMath.h"
  34. #include "TextureManager_ScriptBinding.h"
  35. //---------------------------------------------------------------------------------------------------------------------
  36. S32 TextureManager::mMasterTextureKeyIndex = 0;
  37. TextureManager::ManagerState TextureManager::mManagerState = TextureManager::NotInitialized;
  38. bool TextureManager::mDGLRender = true;
  39. bool TextureManager::mForce16BitTexture = false;
  40. bool TextureManager::mAllowTextureCompression = false;
  41. bool TextureManager::mDisableTextureSubImageUpdates = false;
  42. GLenum TextureManager::mTextureCompressionHint = GL_FASTEST;
  43. S32 TextureManager::mBitmapResidentSize = 0;
  44. S32 TextureManager::mTextureResidentSize = 0;
  45. S32 TextureManager::mTextureResidentWasteSize = 0;
  46. S32 TextureManager::mTextureResidentCount = 0;
  47. //---------------------------------------------------------------------------------------------------------------------
  48. #ifdef TORQUE_OS_IOS
  49. #define EXT_ARRAY_SIZE 4
  50. static const char* extArray[EXT_ARRAY_SIZE] = { "", ".pvr", ".jpg", ".png"};
  51. #else
  52. struct Forced16BitMapping
  53. {
  54. GLenum wanted;
  55. GLenum forced;
  56. bool end;
  57. };
  58. Forced16BitMapping sg16BitMappings[] =
  59. {
  60. { GL_RGB, GL_RGB5, false },
  61. { GL_RGBA, GL_RGBA4, false },
  62. { 0, 0, true }
  63. };
  64. #define EXT_ARRAY_SIZE 3
  65. static const char* extArray[EXT_ARRAY_SIZE] = { "", ".jpg", ".png"};
  66. #endif
  67. //---------------------------------------------------------------------------------------------------------------------
  68. struct EventCallbackEntry
  69. {
  70. TextureManager::TextureEventCallback callback;
  71. void * userData;
  72. U32 key;
  73. };
  74. static U32 sgCurrCallbackKey = 0;
  75. static Vector<EventCallbackEntry> sgEventCallbacks(__FILE__, __LINE__);
  76. //--------------------------------------------------------------------------------------------------------------------
  77. U32 TextureManager::registerEventCallback(TextureEventCallback callback, void *userData)
  78. {
  79. sgEventCallbacks.increment();
  80. sgEventCallbacks.last().callback = callback;
  81. sgEventCallbacks.last().userData = userData;
  82. sgEventCallbacks.last().key = sgCurrCallbackKey++;
  83. return sgEventCallbacks.last().key;
  84. }
  85. //--------------------------------------------------------------------------------------------------------------------
  86. void TextureManager::unregisterEventCallback(const U32 callbackKey)
  87. {
  88. for (S32 i = 0; i < sgEventCallbacks.size(); i++)
  89. {
  90. if (sgEventCallbacks[i].key == callbackKey)
  91. {
  92. sgEventCallbacks.erase(i);
  93. return;
  94. }
  95. }
  96. }
  97. //--------------------------------------------------------------------------------------------------------------------
  98. void TextureManager::postTextureEvent(const TextureEventCode eventCode)
  99. {
  100. for (S32 i = 0; i < sgEventCallbacks.size(); i++)
  101. {
  102. (sgEventCallbacks[i].callback)(eventCode, sgEventCallbacks[i].userData);
  103. }
  104. }
  105. //--------------------------------------------------------------------------------------------------------------------
  106. void TextureManager::create()
  107. {
  108. AssertISV(mManagerState == NotInitialized, "TextureManager::create() - already created!");
  109. TextureDictionary::create();
  110. Con::addVariable("$pref::OpenGL::force16BitTexture", TypeBool, &TextureManager::mForce16BitTexture);
  111. Con::addVariable("$pref::OpenGL::allowTextureCompression", TypeBool, &TextureManager::mAllowTextureCompression);
  112. Con::addVariable("$pref::OpenGL::disableTextureSubImageUpdates", TypeBool, &TextureManager::mDisableTextureSubImageUpdates);
  113. // Flag as alive.
  114. mManagerState = Alive;
  115. }
  116. //--------------------------------------------------------------------------------------------------------------------
  117. void TextureManager::destroy()
  118. {
  119. AssertISV(mManagerState != NotInitialized, "TextureManager::destroy - nothing to destroy!");
  120. // Destroy the texture dictionary.
  121. TextureDictionary::destroy();
  122. // Reset state.
  123. mBitmapResidentSize = 0;
  124. mTextureResidentSize = 0;
  125. mTextureResidentWasteSize = 0;
  126. mTextureResidentCount = 0;
  127. mMasterTextureKeyIndex = 0;
  128. // Flag as not initialized.
  129. mManagerState = NotInitialized;
  130. }
  131. //--------------------------------------------------------------------------------------------------------------------
  132. void TextureManager::killManager()
  133. {
  134. // Finish if already dead.
  135. if ( mManagerState == Dead )
  136. return;
  137. // Flag as dead.
  138. mManagerState = Dead;
  139. // Post zombie event.
  140. postTextureEvent(BeginZombification);
  141. Vector<GLuint> deleteNames(4096);
  142. TextureObject* probe = TextureDictionary::TextureObjectChain;
  143. while (probe)
  144. {
  145. if (probe->mGLTextureName != 0)
  146. {
  147. deleteNames.push_back(probe->mGLTextureName);
  148. }
  149. probe->mGLTextureName = 0;
  150. // Adjust metrics.
  151. mTextureResidentCount--;
  152. mTextureResidentSize -= probe->mTextureResidentSize;
  153. probe->mTextureResidentSize = 0;
  154. mTextureResidentWasteSize -= probe->mTextureResidentWasteSize;
  155. probe->mTextureResidentWasteSize = 0;
  156. probe = probe->next;
  157. }
  158. // Delete all textures.
  159. glDeleteTextures(deleteNames.size(), deleteNames.address());
  160. }
  161. //--------------------------------------------------------------------------------------------------------------------
  162. void TextureManager::resurrectManager( void )
  163. {
  164. // Finish if not dead.
  165. if (mManagerState != Dead)
  166. return;
  167. // Flag as resurrecting.
  168. mManagerState = Resurrecting;
  169. // Post begin resurrection event.
  170. postTextureEvent(BeginResurrection);
  171. // Resurrect textures.
  172. TextureObject* probe = TextureDictionary::TextureObjectChain;
  173. while (probe)
  174. {
  175. switch( probe->mHandleType )
  176. {
  177. case TextureHandle::BitmapTexture:
  178. {
  179. // Sanity!
  180. AssertISV( probe->mTextureKey != NULL && probe->mTextureKey != StringTable->EmptyString, "Encountered a bitmap texture that didn't specify its bitmap." );
  181. // Load the bitmap.
  182. GBitmap* pBitmap = loadBitmap( probe->mTextureKey );
  183. // Sanity!
  184. AssertISV(pBitmap != NULL, "Error resurrecting the texture cache.\n""Possible cause: a bitmap was deleted during the course of gameplay.");
  185. // Register texture.
  186. TextureObject* pTextureObject = registerTexture(probe->mTextureKey, pBitmap, probe->mHandleType, probe->mClamp);
  187. // Sanity!
  188. AssertFatal(pTextureObject == probe, "A new texture was returned during resurrection.");
  189. } break;
  190. case TextureHandle::BitmapKeepTexture:
  191. {
  192. // Sanity!
  193. AssertISV( probe->mpBitmap != NULL, "Encountered no bitmap for a texture that should keep it." );
  194. // Create texture.
  195. createGLName(probe);
  196. } break;
  197. default:
  198. // Sanity!
  199. AssertISV( false, "Unknown texture type encountered during texture resurrection." );
  200. }
  201. // Next texture.
  202. probe = probe->next;
  203. }
  204. // Post end resurrection event.
  205. postTextureEvent(EndResurrection);
  206. // Flag as alive.
  207. mManagerState = Alive;
  208. }
  209. //--------------------------------------------------------------------------------------------------------------------
  210. void TextureManager::flush()
  211. {
  212. killManager();
  213. resurrectManager();
  214. }
  215. //--------------------------------------------------------------------------------------------------------------------
  216. StringTableEntry TextureManager::getUniqueTextureKey( void )
  217. {
  218. char textureKeyBuffer[32];
  219. dSprintf( textureKeyBuffer, sizeof(textureKeyBuffer), "GeneratedKey_%d", mMasterTextureKeyIndex++ );
  220. return StringTable->insert( textureKeyBuffer );
  221. }
  222. //--------------------------------------------------------------------------------------------------------------------
  223. GBitmap* TextureManager::createPowerOfTwoBitmap(GBitmap* pBitmap)
  224. {
  225. // Sanity!
  226. AssertISV( pBitmap->getFormat() != GBitmap::Palettized, "Paletted bitmaps are not supported." );
  227. // Finish if already a power-of-two in dimension.
  228. if (isPow2(pBitmap->getWidth()) && isPow2(pBitmap->getHeight()))
  229. return pBitmap;
  230. U32 width = pBitmap->getWidth();
  231. U32 height = pBitmap->getHeight();
  232. U32 newWidth = getNextPow2(pBitmap->getWidth());
  233. U32 newHeight = getNextPow2(pBitmap->getHeight());
  234. GBitmap* pReturn = new GBitmap(newWidth, newHeight, false, pBitmap->getFormat());
  235. for (U32 i = 0; i < height; i++)
  236. {
  237. U8* pDest = (U8*)pReturn->getAddress(0, i);
  238. const U8* pSrc = (const U8*)pBitmap->getAddress(0, i);
  239. dMemcpy(pDest, pSrc, width * pBitmap->bytesPerPixel);
  240. pDest += width * pBitmap->bytesPerPixel;
  241. // set the src pixel to the last pixel in the row
  242. const U8 *pSrcPixel = pDest - pBitmap->bytesPerPixel;
  243. for(U32 j = width; j < newWidth; j++)
  244. for(U32 k = 0; k < pBitmap->bytesPerPixel; k++)
  245. *pDest++ = pSrcPixel[k];
  246. }
  247. for(U32 i = height; i < newHeight; i++)
  248. {
  249. U8* pDest = (U8*)pReturn->getAddress(0, i);
  250. U8* pSrc = (U8*)pReturn->getAddress(0, height-1);
  251. dMemcpy(pDest, pSrc, newWidth * pBitmap->bytesPerPixel);
  252. }
  253. return pReturn;
  254. }
  255. //---------------------------------------------------------------------------------------------------------------------
  256. void TextureManager::freeTexture( TextureObject* pTextureObject )
  257. {
  258. if((mDGLRender || mManagerState == Resurrecting) && pTextureObject->mGLTextureName)
  259. {
  260. glDeleteTextures(1, (const GLuint*)&pTextureObject->mGLTextureName);
  261. // Adjust metrics.
  262. mTextureResidentCount--;
  263. mTextureResidentSize -= pTextureObject->mTextureResidentSize;
  264. pTextureObject->mTextureResidentSize = 0;
  265. mTextureResidentWasteSize -= pTextureObject->mTextureResidentWasteSize;
  266. pTextureObject->mTextureResidentWasteSize = 0;
  267. }
  268. if ( pTextureObject->mpBitmap != NULL )
  269. {
  270. SAFE_DELETE( pTextureObject->mpBitmap );
  271. mBitmapResidentSize -= pTextureObject->mBitmapResidentSize;
  272. pTextureObject->mBitmapResidentSize = 0;
  273. }
  274. TextureDictionary::remove(pTextureObject);
  275. SAFE_DELETE( pTextureObject );
  276. }
  277. //---------------------------------------------------------------------------------------------------------------------
  278. void TextureManager::getSourceDestByteFormat(GBitmap *pBitmap, U32 *sourceFormat, U32 *destFormat, U32 *byteFormat, U32* texelSize )
  279. {
  280. *byteFormat = GL_UNSIGNED_BYTE;
  281. U32 byteSize = 1;
  282. #if defined(TORQUE_OS_IOS)
  283. switch(pBitmap->getFormat())
  284. {
  285. case GBitmap::Intensity:
  286. AssertFatal( 0, "GBitmap::Intensity GL_INTENSITY format not supported" );
  287. break;
  288. case GBitmap::Palettized:
  289. AssertFatal( 0, "GBitmap::Palettized GL_COLOR_INDEX format not supported" );
  290. break;
  291. case GBitmap::Luminance:
  292. *sourceFormat = GL_LUMINANCE;
  293. break;
  294. case GBitmap::RGB:
  295. *sourceFormat = GL_RGB;
  296. break;
  297. case GBitmap::RGBA:
  298. *sourceFormat = GL_RGBA;
  299. break;
  300. case GBitmap::Alpha:
  301. *sourceFormat = GL_ALPHA;
  302. break;
  303. case GBitmap::RGB565:
  304. *sourceFormat = GL_RGB;
  305. *byteFormat = GL_UNSIGNED_SHORT_5_6_5;
  306. byteSize = 2;
  307. break;
  308. case GBitmap::RGB5551:
  309. *sourceFormat = GL_RGBA;
  310. *byteFormat = GL_UNSIGNED_SHORT_5_5_5_1;
  311. byteSize = 1; // Incorrect but assume worst case.
  312. break;
  313. case GBitmap::PVR2:
  314. *sourceFormat = GL_RGB;
  315. *byteFormat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  316. byteSize = 1; // Incorrect but assume worst case.
  317. break;
  318. case GBitmap::PVR2A:
  319. *sourceFormat = GL_RGBA;
  320. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  321. byteSize = 1; // Incorrect but assume worst case.
  322. break;
  323. case GBitmap::PVR4:
  324. *sourceFormat = GL_RGB;
  325. *byteFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  326. byteSize = 1; // Incorrect but assume worst case.
  327. break;
  328. case GBitmap::PVR4A:
  329. *sourceFormat = GL_RGBA;
  330. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  331. byteSize = 1; // Incorrect but assume worst case.
  332. break;
  333. }
  334. *destFormat = *sourceFormat;
  335. *texelSize = byteSize;
  336. return;
  337. #else
  338. switch(pBitmap->getFormat())
  339. {
  340. case GBitmap::Intensity:
  341. *sourceFormat = GL_INTENSITY;
  342. break;
  343. case GBitmap::Palettized:
  344. *sourceFormat = GL_COLOR_INDEX;
  345. break;
  346. case GBitmap::Luminance:
  347. *sourceFormat = GL_LUMINANCE;
  348. break;
  349. case GBitmap::RGB:
  350. *sourceFormat = GL_RGB;
  351. break;
  352. case GBitmap::RGBA:
  353. *sourceFormat = GL_RGBA;
  354. break;
  355. case GBitmap::Alpha:
  356. *sourceFormat = GL_ALPHA;
  357. break;
  358. case GBitmap::RGB565:
  359. case GBitmap::RGB5551:
  360. #if defined(TORQUE_BIG_ENDIAN)
  361. *sourceFormat = GL_BGRA_EXT;
  362. *byteFormat = GL_UNSIGNED_SHORT_1_5_5_5_REV;
  363. #else
  364. *sourceFormat = GL_RGBA;
  365. *byteFormat = GL_UNSIGNED_SHORT_5_5_5_1;
  366. #endif
  367. break;
  368. };
  369. if(*byteFormat == GL_UNSIGNED_BYTE)
  370. {
  371. if (*sourceFormat != GL_COLOR_INDEX)
  372. {
  373. *destFormat = *sourceFormat;
  374. }
  375. else
  376. {
  377. *destFormat = GL_COLOR_INDEX8_EXT;
  378. }
  379. byteSize = 1;
  380. *texelSize = byteSize;
  381. }
  382. else
  383. {
  384. *destFormat = GL_RGB5_A1;
  385. *texelSize = 2;
  386. }
  387. if (TextureManager::mForce16BitTexture)
  388. {
  389. for (U32 i = 0; sg16BitMappings[i].end != true; i++)
  390. {
  391. if (*destFormat == sg16BitMappings[i].wanted)
  392. {
  393. *destFormat = sg16BitMappings[i].forced;
  394. *texelSize = 2;
  395. return;
  396. }
  397. }
  398. }
  399. else
  400. {
  401. if(*destFormat == GL_RGB)
  402. {
  403. *destFormat = GL_RGB8;
  404. *texelSize = 3 * byteSize;
  405. }
  406. else if(*destFormat == GL_RGBA)
  407. {
  408. *destFormat = GL_RGBA8;
  409. *texelSize = 4 * byteSize;
  410. }
  411. }
  412. #endif // defined(TORQUE_OS_IOS)
  413. }
  414. //--------------------------------------------------------------------------------------------------------------------
  415. U16* TextureManager::create16BitBitmap( GBitmap *pDL, U8 *in_source8, GBitmap::BitmapFormat alpha_info, GLint *GLformat, GLint *GLdata_type, U32 width, U32 height )
  416. {
  417. //PUAP -Mat make 16 bit
  418. U16 *texture_data = new U16[width * height];
  419. U16 *dest = texture_data;
  420. U32 *source = (U32*)in_source8;
  421. //since the pointer is 4 bytes, multiply by the number of bytes per pixel over 4
  422. U32 spanInBytes = (U32)((width * height) * (pDL->bytesPerPixel / 4.0f));
  423. U32 *source_end = source + spanInBytes;
  424. switch (alpha_info) {
  425. case GBitmap::Alpha: //ALPHA_TRANSPARENT:
  426. while (source != source_end) {
  427. U32 color = *source++;
  428. *dest++ = ((color & 0xF8) << 8) | ((color & 0xF800) >> 5) | ((color & 0xF80000) >> 18) | (color >> 31);
  429. }
  430. *GLformat = GL_RGBA;
  431. *GLdata_type = GL_UNSIGNED_SHORT_5_5_5_1;
  432. break;
  433. case GBitmap::RGBA://ALPHA_BLEND
  434. while (source != source_end) {
  435. U32 color = *source++;
  436. *dest++ = ((color & 0xF0) << 8) | ((color & 0xF000) >> 4) | ((color & 0xF00000) >> 16) | ((color & 0xF0000000) >> 28);
  437. }
  438. *GLformat = GL_RGBA;
  439. *GLdata_type = GL_UNSIGNED_SHORT_4_4_4_4;
  440. break;
  441. default://ALPHA_NONE
  442. U8 *source8 = (U8*)source;
  443. //32 bytes per address, snce we are casting to U8 we need 4 times as many
  444. U8 *end8 = source8 + (U32)(spanInBytes*4);
  445. while (source8 < end8) {
  446. U16 red = (U16)*source8;
  447. source8++;
  448. U16 green = (U16)*source8;
  449. source8++;
  450. U16 blue = (U16)*source8;
  451. source8++;
  452. //now color should be == RR GG BB 00
  453. *dest = ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ((blue & 0xF8) >> 3);
  454. dest++;
  455. }
  456. *GLformat = GL_RGB;
  457. *GLdata_type = GL_UNSIGNED_SHORT_5_6_5;
  458. break;
  459. }
  460. return texture_data;
  461. }
  462. //-----------------------------------------------------------------------------
  463. void TextureManager::refresh( TextureObject* pTextureObject )
  464. {
  465. // Finish if refresh not appropriate.
  466. if (!(mDGLRender || mManagerState == Resurrecting))
  467. return;
  468. // Sanity!
  469. AssertISV( pTextureObject->mGLTextureName != 0, "Refreshing texture but no texture created." );
  470. AssertISV( pTextureObject->mpBitmap != 0, "Refreshing texture but no bitmap available." );
  471. // Fetch bitmaps.
  472. GBitmap* pSourceBitmap = pTextureObject->mpBitmap;
  473. GBitmap* pNewBitmap = createPowerOfTwoBitmap(pSourceBitmap);
  474. // Fetch source/dest formats.
  475. U32 sourceFormat, destFormat, byteFormat, texelSize;
  476. getSourceDestByteFormat(pSourceBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  477. #if defined(TORQUE_OS_IOS)
  478. bool isCompressed = (pNewBitmap->getFormat() >= GBitmap::PVR2) && (pNewBitmap->getFormat() <= GBitmap::PVR4A);
  479. #endif
  480. #if defined(TORQUE_OS_IOS)
  481. if (isCompressed) {
  482. switch (pNewBitmap->getFormat()) {
  483. case GBitmap::PVR2:
  484. case GBitmap::PVR2A:
  485. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  486. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),16) * getMax((int)pNewBitmap->getHeight(), 8) * 2 + 7) / 8, pNewBitmap->getBits() );
  487. break;
  488. case GBitmap::PVR4:
  489. case GBitmap::PVR4A:
  490. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  491. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),8) * getMax((int)pNewBitmap->getHeight(), 8) * 4 + 7) / 8, pNewBitmap->getBits() );
  492. break;
  493. default:
  494. // already tested for range of values, so default is just to keep the compiler happy!
  495. break;
  496. }
  497. } else
  498. #endif
  499. // Bind texture.
  500. glBindTexture( GL_TEXTURE_2D, pTextureObject->mGLTextureName );
  501. // Are we forcing to 16-bit?
  502. if( pSourceBitmap->mForce16Bit )
  503. {
  504. // Yes, so generate a 16-bit texture.
  505. GLint GLformat;
  506. GLint GLdata_type;
  507. U16* pBitmap16 = create16BitBitmap( pNewBitmap, pNewBitmap->getWritableBits(), pNewBitmap->getFormat(),
  508. &GLformat, &GLdata_type,
  509. pNewBitmap->getWidth(), pNewBitmap->getHeight() );
  510. glTexImage2D(GL_TEXTURE_2D,
  511. 0,
  512. GLformat,
  513. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  514. 0,
  515. GLformat,
  516. GLdata_type,
  517. pBitmap16
  518. );
  519. //copy new texture_data into pBits
  520. delete [] pBitmap16;
  521. }
  522. else
  523. {
  524. // No, so upload as-is.
  525. glTexImage2D(GL_TEXTURE_2D,
  526. 0,
  527. destFormat,
  528. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  529. 0,
  530. sourceFormat,
  531. byteFormat,
  532. pNewBitmap->getBits());
  533. }
  534. const GLuint filter = pTextureObject->getFilter();
  535. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
  536. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
  537. GLenum glClamp;
  538. if ( pTextureObject->getClamp() )
  539. glClamp = dglDoesSupportEdgeClamp() ? GL_CLAMP_TO_EDGE : GL_CLAMP;
  540. else
  541. glClamp = GL_REPEAT;
  542. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glClamp );
  543. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glClamp );
  544. if(pNewBitmap != pSourceBitmap)
  545. {
  546. delete pNewBitmap;
  547. }
  548. }
  549. //--------------------------------------------------------------------------------------------------------------------
  550. void TextureManager::refresh( const char *textureName )
  551. {
  552. // Finish if no texture name specified.
  553. AssertFatal( textureName != NULL, "Texture Manager: Cannot refresh a NULL texture name." );
  554. // Find the texture object.
  555. TextureObject* pTextureObject = TextureDictionary::find( textureName );
  556. // Finish if no texture for this texture name.
  557. if ( pTextureObject == NULL )
  558. return;
  559. // Finish if the texture object is a kept bitmap.
  560. if ( pTextureObject->getHandleType() == TextureHandle::BitmapKeepTexture )
  561. return;
  562. // Load the bitmap.
  563. GBitmap* pBitmap = loadBitmap( pTextureObject->mTextureKey );
  564. // Finish if bitmap could not be loaded.
  565. if ( pBitmap == NULL )
  566. return;
  567. // Register texture.
  568. TextureObject* pNewTextureObject = registerTexture(pTextureObject->mTextureKey, pBitmap, pTextureObject->mHandleType, pTextureObject->mClamp);
  569. // Sanity!
  570. AssertFatal(pNewTextureObject == pTextureObject, "A new texture was returned during refresh.");
  571. }
  572. //--------------------------------------------------------------------------------------------------------------------
  573. void TextureManager::createGLName( TextureObject* pTextureObject )
  574. {
  575. // Finish if not appropriate.
  576. if (!(mDGLRender || mManagerState == Resurrecting))
  577. return;
  578. // Sanity!
  579. AssertISV( pTextureObject->mHandleType != TextureHandle::InvalidTexture, "Invalid texture type." );
  580. AssertISV( pTextureObject->mpBitmap != NULL, "Bitmap cannot be NULL." );
  581. AssertISV( pTextureObject->mGLTextureName == 0, "GL texture name already exists." );
  582. // Generate texture name.
  583. glGenTextures(1, &pTextureObject->mGLTextureName);
  584. // Fetch source/dest formats.
  585. U32 sourceFormat, destFormat, byteFormat, texelSize;
  586. getSourceDestByteFormat(pTextureObject->mpBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  587. // Adjust metrics.
  588. mTextureResidentCount++;
  589. pTextureObject->mTextureResidentSize = pTextureObject->mTextureWidth * pTextureObject->mTextureHeight * texelSize;
  590. mTextureResidentSize += pTextureObject->mTextureResidentSize;
  591. pTextureObject->mTextureResidentWasteSize = ((pTextureObject->mTextureWidth * pTextureObject->mTextureHeight)-(pTextureObject->mBitmapWidth * pTextureObject->mBitmapHeight)) * texelSize;
  592. mTextureResidentWasteSize += pTextureObject->mTextureResidentWasteSize;
  593. // Refresh the texture.
  594. refresh( pTextureObject );
  595. }
  596. //--------------------------------------------------------------------------------------------------------------------
  597. TextureObject* TextureManager::registerTexture(const char* pTextureKey, GBitmap* pNewBitmap, TextureHandle::TextureHandleType type, bool clampToEdge)
  598. {
  599. // Sanity!
  600. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  601. TextureObject* pTextureObject = NULL;
  602. // Fetch texture key.
  603. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  604. if(pTextureKey)
  605. {
  606. pTextureObject = TextureDictionary::find(textureKey, type, clampToEdge);
  607. }
  608. if( pTextureObject )
  609. {
  610. // Remove bitmap if we have a different existing one.
  611. if ( pTextureObject->mpBitmap != NULL && pTextureObject->mpBitmap != pNewBitmap)
  612. {
  613. delete pTextureObject->mpBitmap;
  614. pTextureObject->mpBitmap = NULL;
  615. // Adjust metrics.
  616. mBitmapResidentSize -= pTextureObject->mBitmapResidentSize;
  617. pTextureObject->mBitmapResidentSize = 0;
  618. }
  619. // Remove any texture name.
  620. if ( pTextureObject->mGLTextureName != 0 )
  621. {
  622. glDeleteTextures(1, (const GLuint*)&pTextureObject->mGLTextureName);
  623. pTextureObject->mGLTextureName = 0;
  624. // Adjust metrics.
  625. mTextureResidentCount--;
  626. mTextureResidentSize -= pTextureObject->mTextureResidentSize;
  627. pTextureObject->mTextureResidentSize = 0;
  628. mTextureResidentWasteSize -= pTextureObject->mTextureResidentWasteSize;
  629. pTextureObject->mTextureResidentWasteSize = 0;
  630. }
  631. }
  632. else
  633. {
  634. // Create new texture object.
  635. pTextureObject = new TextureObject();
  636. pTextureObject->mTextureKey = textureKey;
  637. pTextureObject->mHandleType = type;
  638. TextureDictionary::insert(pTextureObject);
  639. }
  640. if ( pTextureObject->mHandleType == TextureHandle::BitmapKeepTexture && pTextureObject->mpBitmap != pNewBitmap )
  641. {
  642. // Adjust metrics.
  643. pTextureObject->mBitmapResidentSize = pNewBitmap->byteSize;
  644. mBitmapResidentSize += pTextureObject->mBitmapResidentSize;
  645. }
  646. pTextureObject->mpBitmap = pNewBitmap;
  647. pTextureObject->mBitmapWidth = pNewBitmap->getWidth();
  648. pTextureObject->mBitmapHeight = pNewBitmap->getHeight();
  649. pTextureObject->mTextureWidth = getNextPow2(pNewBitmap->getWidth());
  650. pTextureObject->mTextureHeight = getNextPow2(pNewBitmap->getHeight());
  651. pTextureObject->mClamp = clampToEdge;
  652. // Generate a GL texture name if one is not ready.
  653. if( pTextureObject->mGLTextureName == 0)
  654. {
  655. createGLName(pTextureObject);
  656. }
  657. // Delete bitmap if we're not keeping it.
  658. if ( pTextureObject->mHandleType != TextureHandle::BitmapKeepTexture )
  659. {
  660. delete pTextureObject->mpBitmap;
  661. pTextureObject->mpBitmap = NULL;
  662. }
  663. return pTextureObject;
  664. }
  665. //--------------------------------------------------------------------------------------------------------------------
  666. TextureObject *TextureManager::loadTexture(const char* pTextureKey, TextureHandle::TextureHandleType type, bool clampToEdge, bool checkOnly, bool force16Bit )
  667. {
  668. // Sanity!
  669. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  670. // Finish if texture key is invalid.
  671. if( pTextureKey == NULL || *pTextureKey == 0)
  672. return NULL;
  673. // Fetch texture key.
  674. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  675. TextureObject *ret = TextureDictionary::find(textureKey, type, clampToEdge);
  676. GBitmap *bmp = NULL;
  677. if( ret == NULL )
  678. {
  679. // Ok, no hit - is it in the current dir? If so then let's grab it
  680. // and use it.
  681. bmp = loadBitmap(textureKey, false);
  682. if(bmp)
  683. {
  684. bmp->mForce16Bit = force16Bit;
  685. return registerTexture(textureKey, bmp, type, clampToEdge);
  686. }
  687. }
  688. if(ret)
  689. return ret;
  690. // If we're just checking, fail out so we eventually get around to
  691. // loading a real bitmap.
  692. if(checkOnly)
  693. return NULL;
  694. // Ok, no success so let's try actually loading a texture.
  695. bmp = loadBitmap(textureKey);
  696. if(!bmp)
  697. {
  698. Con::warnf("Could not locate texture: %s", textureKey);
  699. return NULL;
  700. }
  701. bmp->mForce16Bit = force16Bit;
  702. return registerTexture(textureKey, bmp, type, clampToEdge);
  703. }
  704. //--------------------------------------------------------------------------------------------------------------------
  705. GBitmap *TextureManager::loadBitmap( const char* pTextureKey, bool recurse, bool nocompression )
  706. {
  707. char fileNameBuffer[512];
  708. Con::expandPath( fileNameBuffer, sizeof(fileNameBuffer), pTextureKey );
  709. GBitmap *bmp = NULL;
  710. // Loop through the supported extensions to find the file.
  711. U32 len = dStrlen(fileNameBuffer);
  712. for (U32 i = 0; i < EXT_ARRAY_SIZE && bmp == NULL; i++)
  713. {
  714. #if defined(TORQUE_OS_IOS)
  715. // check to see if requested no-compression...
  716. if (nocompression && (dStrncmp( extArray[i], ".pvr", 4 ) == 0)) {
  717. continue;
  718. }
  719. #endif
  720. dStrcpy(fileNameBuffer + len, extArray[i]);
  721. bmp = (GBitmap*)ResourceManager->loadInstance(fileNameBuffer);
  722. if ( bmp != NULL && (bmp->getWidth() > MaximumProductSupportedTextureWidth || bmp->getHeight() > MaximumProductSupportedTextureHeight) )
  723. {
  724. Con::warnf( "TextureManager::loadBitmap() - Cannot load bitmap '%s' as its dimensions exceed the maximum product-supported texture dimension.", fileNameBuffer );
  725. delete bmp;
  726. return NULL;
  727. }
  728. }
  729. return bmp;
  730. }
  731. //--------------------------------------------------------------------------------------------------------------------
  732. void TextureManager::dumpMetrics( void )
  733. {
  734. S32 textureResidentCount = 0;
  735. S32 textureResidentSize = 0;
  736. S32 textureResidentWasteSize = 0;
  737. S32 bitmapResidentSize = 0;
  738. Con::printSeparator();
  739. Con::printBlankLine();
  740. Con::printf( "Dumping texture manager metrics:" );
  741. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  742. while (pProbe != NULL)
  743. {
  744. GLboolean isTextureResident = false;
  745. if ( pProbe->mGLTextureName != 0 )
  746. {
  747. textureResidentCount++;
  748. glAreTexturesResident( 1, &pProbe->mGLTextureName, &isTextureResident );
  749. }
  750. textureResidentSize += pProbe->mTextureResidentSize;
  751. bitmapResidentSize += pProbe->mBitmapResidentSize;
  752. textureResidentWasteSize += pProbe->mTextureResidentWasteSize;
  753. // Info.
  754. Con::printf( "BitmapArea: (%d-%d), BitmapMemory: %d, TextureArea: (%d-%d), TextureMemory: %d, TextureMemoryWaste=%d, Refs=%d, Resident=%s, Name=%s",
  755. pProbe->mBitmapWidth,pProbe->mBitmapHeight, pProbe->mBitmapResidentSize,
  756. pProbe->mTextureWidth, pProbe->mTextureHeight, pProbe->mTextureResidentSize, pProbe->mTextureResidentWasteSize,
  757. pProbe->mRefCount,
  758. isTextureResident == 0 ? "NO" : "YES",
  759. pProbe->mTextureKey );
  760. pProbe = pProbe->next;
  761. }
  762. // Validate metrics.
  763. const bool textureCountSame = textureResidentCount == mTextureResidentCount;
  764. const bool textureSizeSame = textureResidentSize == mTextureResidentSize;
  765. const bool textureWasteSizeSame = textureResidentWasteSize == mTextureResidentWasteSize;
  766. const bool bitmapSizeSame = bitmapResidentSize == mBitmapResidentSize;
  767. const bool allMetricsValid = textureCountSame && textureSizeSame && textureWasteSizeSame && bitmapSizeSame;
  768. // Error if metrics are invalid.
  769. if ( !allMetricsValid )
  770. Con::errorf( "Metrics appear to be invalid." );
  771. // Info.
  772. Con::printf( "Metrics Totals:" );
  773. Con::printf( "TextureCount: %d, TextureSize: %d, TextureWasteSize: %d, BitmapSize: %d, ResidentFraction: %g",
  774. mTextureResidentCount,
  775. mTextureResidentSize,
  776. mTextureResidentWasteSize,
  777. mBitmapResidentSize,
  778. getResidentFraction() );
  779. Con::printBlankLine();
  780. Con::printSeparator();
  781. Con::printf( "All texture manager metrics are valid." );
  782. Con::printSeparator();
  783. }
  784. //--------------------------------------------------------------------------------------------------------------------
  785. F32 TextureManager::getResidentFraction()
  786. {
  787. U32 resident = 0;
  788. U32 total = 0;
  789. Vector<GLuint> names;
  790. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  791. while (pProbe != NULL)
  792. {
  793. if (pProbe->mGLTextureName != 0)
  794. {
  795. total++;
  796. names.push_back(pProbe->mGLTextureName);
  797. }
  798. pProbe = pProbe->next;
  799. }
  800. if (total == 0)
  801. return 1.0f;
  802. Vector<GLboolean> isResident;
  803. isResident.setSize(names.size());
  804. glAreTexturesResident(names.size(), names.address(), isResident.address());
  805. for (U32 i = 0; i < (U32)names.size(); i++)
  806. if (isResident[i] == GL_TRUE)
  807. resident++;
  808. return (F32(resident) / F32(total));
  809. }