TextureManager.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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) || defined(TORQUE_OS_ANDROID)
  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. #ifdef TORQUE_OS_IOS
  314. case GBitmap::PVR2:
  315. *sourceFormat = GL_RGB;
  316. *byteFormat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  317. byteSize = 1; // Incorrect but assume worst case.
  318. break;
  319. case GBitmap::PVR2A:
  320. *sourceFormat = GL_RGBA;
  321. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  322. byteSize = 1; // Incorrect but assume worst case.
  323. break;
  324. case GBitmap::PVR4:
  325. *sourceFormat = GL_RGB;
  326. *byteFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  327. byteSize = 1; // Incorrect but assume worst case.
  328. break;
  329. case GBitmap::PVR4A:
  330. *sourceFormat = GL_RGBA;
  331. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  332. byteSize = 1; // Incorrect but assume worst case.
  333. break;
  334. #endif
  335. }
  336. *destFormat = *sourceFormat;
  337. *texelSize = byteSize;
  338. return;
  339. #else
  340. switch(pBitmap->getFormat())
  341. {
  342. case GBitmap::Intensity:
  343. *sourceFormat = GL_INTENSITY;
  344. break;
  345. case GBitmap::Palettized:
  346. *sourceFormat = GL_COLOR_INDEX;
  347. break;
  348. case GBitmap::Luminance:
  349. *sourceFormat = GL_LUMINANCE;
  350. break;
  351. case GBitmap::RGB:
  352. *sourceFormat = GL_RGB;
  353. break;
  354. case GBitmap::RGBA:
  355. *sourceFormat = GL_RGBA;
  356. break;
  357. case GBitmap::Alpha:
  358. *sourceFormat = GL_ALPHA;
  359. break;
  360. case GBitmap::RGB565:
  361. case GBitmap::RGB5551:
  362. #if defined(TORQUE_BIG_ENDIAN)
  363. *sourceFormat = GL_BGRA_EXT;
  364. *byteFormat = GL_UNSIGNED_SHORT_1_5_5_5_REV;
  365. #else
  366. *sourceFormat = GL_RGBA;
  367. *byteFormat = GL_UNSIGNED_SHORT_5_5_5_1;
  368. #endif
  369. break;
  370. };
  371. if(*byteFormat == GL_UNSIGNED_BYTE)
  372. {
  373. if (*sourceFormat != GL_COLOR_INDEX)
  374. {
  375. *destFormat = *sourceFormat;
  376. }
  377. else
  378. {
  379. *destFormat = GL_COLOR_INDEX8_EXT;
  380. }
  381. byteSize = 1;
  382. *texelSize = byteSize;
  383. }
  384. else
  385. {
  386. *destFormat = GL_RGB5_A1;
  387. *texelSize = 2;
  388. }
  389. if (TextureManager::mForce16BitTexture)
  390. {
  391. for (U32 i = 0; sg16BitMappings[i].end != true; i++)
  392. {
  393. if (*destFormat == sg16BitMappings[i].wanted)
  394. {
  395. *destFormat = sg16BitMappings[i].forced;
  396. *texelSize = 2;
  397. return;
  398. }
  399. }
  400. }
  401. else
  402. {
  403. if(*destFormat == GL_RGB)
  404. {
  405. *destFormat = GL_RGB8;
  406. *texelSize = 3 * byteSize;
  407. }
  408. else if(*destFormat == GL_RGBA)
  409. {
  410. *destFormat = GL_RGBA8;
  411. *texelSize = 4 * byteSize;
  412. }
  413. }
  414. #endif // defined(TORQUE_OS_IOS)
  415. }
  416. //--------------------------------------------------------------------------------------------------------------------
  417. U16* TextureManager::create16BitBitmap( GBitmap *pDL, U8 *in_source8, GBitmap::BitmapFormat alpha_info, GLint *GLformat, GLint *GLdata_type, U32 width, U32 height )
  418. {
  419. //PUAP -Mat make 16 bit
  420. U16 *texture_data = new U16[width * height];
  421. U16 *dest = texture_data;
  422. U32 *source = (U32*)in_source8;
  423. //since the pointer is 4 bytes, multiply by the number of bytes per pixel over 4
  424. U32 spanInBytes = (U32)((width * height) * (pDL->bytesPerPixel / 4.0f));
  425. U32 *source_end = source + spanInBytes;
  426. switch (alpha_info) {
  427. case GBitmap::Alpha: //ALPHA_TRANSPARENT:
  428. while (source != source_end) {
  429. U32 color = *source++;
  430. *dest++ = ((color & 0xF8) << 8) | ((color & 0xF800) >> 5) | ((color & 0xF80000) >> 18) | (color >> 31);
  431. }
  432. *GLformat = GL_RGBA;
  433. *GLdata_type = GL_UNSIGNED_SHORT_5_5_5_1;
  434. break;
  435. case GBitmap::RGBA://ALPHA_BLEND
  436. while (source != source_end) {
  437. U32 color = *source++;
  438. *dest++ = ((color & 0xF0) << 8) | ((color & 0xF000) >> 4) | ((color & 0xF00000) >> 16) | ((color & 0xF0000000) >> 28);
  439. }
  440. *GLformat = GL_RGBA;
  441. *GLdata_type = GL_UNSIGNED_SHORT_4_4_4_4;
  442. break;
  443. default://ALPHA_NONE
  444. U8 *source8 = (U8*)source;
  445. //32 bytes per address, snce we are casting to U8 we need 4 times as many
  446. U8 *end8 = source8 + (U32)(spanInBytes*4);
  447. while (source8 < end8) {
  448. U16 red = (U16)*source8;
  449. source8++;
  450. U16 green = (U16)*source8;
  451. source8++;
  452. U16 blue = (U16)*source8;
  453. source8++;
  454. //now color should be == RR GG BB 00
  455. *dest = ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ((blue & 0xF8) >> 3);
  456. dest++;
  457. }
  458. *GLformat = GL_RGB;
  459. *GLdata_type = GL_UNSIGNED_SHORT_5_6_5;
  460. break;
  461. }
  462. return texture_data;
  463. }
  464. //-----------------------------------------------------------------------------
  465. void TextureManager::refresh( TextureObject* pTextureObject )
  466. {
  467. // Finish if refresh not appropriate.
  468. if (!(mDGLRender || mManagerState == Resurrecting))
  469. return;
  470. // Sanity!
  471. AssertISV( pTextureObject->mGLTextureName != 0, "Refreshing texture but no texture created." );
  472. AssertISV( pTextureObject->mpBitmap != 0, "Refreshing texture but no bitmap available." );
  473. // Fetch bitmaps.
  474. GBitmap* pSourceBitmap = pTextureObject->mpBitmap;
  475. GBitmap* pNewBitmap = createPowerOfTwoBitmap(pSourceBitmap);
  476. // Fetch source/dest formats.
  477. U32 sourceFormat, destFormat, byteFormat, texelSize;
  478. getSourceDestByteFormat(pSourceBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  479. #if defined(TORQUE_OS_IOS)
  480. bool isCompressed = (pNewBitmap->getFormat() >= GBitmap::PVR2) && (pNewBitmap->getFormat() <= GBitmap::PVR4A);
  481. #endif
  482. #if defined(TORQUE_OS_IOS)
  483. if (isCompressed) {
  484. switch (pNewBitmap->getFormat()) {
  485. case GBitmap::PVR2:
  486. case GBitmap::PVR2A:
  487. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  488. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),16) * getMax((int)pNewBitmap->getHeight(), 8) * 2 + 7) / 8, pNewBitmap->getBits() );
  489. break;
  490. case GBitmap::PVR4:
  491. case GBitmap::PVR4A:
  492. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  493. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),8) * getMax((int)pNewBitmap->getHeight(), 8) * 4 + 7) / 8, pNewBitmap->getBits() );
  494. break;
  495. default:
  496. // already tested for range of values, so default is just to keep the compiler happy!
  497. break;
  498. }
  499. } else
  500. #endif
  501. // Bind texture.
  502. glBindTexture( GL_TEXTURE_2D, pTextureObject->mGLTextureName );
  503. // Are we forcing to 16-bit?
  504. if( pSourceBitmap->mForce16Bit )
  505. {
  506. // Yes, so generate a 16-bit texture.
  507. GLint GLformat;
  508. GLint GLdata_type;
  509. U16* pBitmap16 = create16BitBitmap( pNewBitmap, pNewBitmap->getWritableBits(), pNewBitmap->getFormat(),
  510. &GLformat, &GLdata_type,
  511. pNewBitmap->getWidth(), pNewBitmap->getHeight() );
  512. glTexImage2D(GL_TEXTURE_2D,
  513. 0,
  514. GLformat,
  515. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  516. 0,
  517. GLformat,
  518. GLdata_type,
  519. pBitmap16
  520. );
  521. //copy new texture_data into pBits
  522. delete [] pBitmap16;
  523. }
  524. else
  525. {
  526. // No, so upload as-is.
  527. glTexImage2D(GL_TEXTURE_2D,
  528. 0,
  529. destFormat,
  530. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  531. 0,
  532. sourceFormat,
  533. byteFormat,
  534. pNewBitmap->getBits());
  535. }
  536. const GLuint filter = pTextureObject->getFilter();
  537. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
  538. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
  539. GLenum glClamp;
  540. if ( pTextureObject->getClamp() )
  541. glClamp = dglDoesSupportEdgeClamp() ? GL_CLAMP_TO_EDGE : GL_CLAMP;
  542. else
  543. glClamp = GL_REPEAT;
  544. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glClamp );
  545. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glClamp );
  546. if(pNewBitmap != pSourceBitmap)
  547. {
  548. delete pNewBitmap;
  549. }
  550. }
  551. //--------------------------------------------------------------------------------------------------------------------
  552. void TextureManager::refresh( const char *textureName )
  553. {
  554. // Finish if no texture name specified.
  555. AssertFatal( textureName != NULL, "Texture Manager: Cannot refresh a NULL texture name." );
  556. // Find the texture object.
  557. TextureObject* pTextureObject = TextureDictionary::find( textureName );
  558. // Finish if no texture for this texture name.
  559. if ( pTextureObject == NULL )
  560. return;
  561. // Finish if the texture object is a kept bitmap.
  562. if ( pTextureObject->getHandleType() == TextureHandle::BitmapKeepTexture )
  563. return;
  564. // Load the bitmap.
  565. GBitmap* pBitmap = loadBitmap( pTextureObject->mTextureKey );
  566. // Finish if bitmap could not be loaded.
  567. if ( pBitmap == NULL )
  568. return;
  569. // Register texture.
  570. TextureObject* pNewTextureObject = registerTexture(pTextureObject->mTextureKey, pBitmap, pTextureObject->mHandleType, pTextureObject->mClamp);
  571. // Sanity!
  572. AssertFatal(pNewTextureObject == pTextureObject, "A new texture was returned during refresh.");
  573. }
  574. //--------------------------------------------------------------------------------------------------------------------
  575. void TextureManager::createGLName( TextureObject* pTextureObject )
  576. {
  577. // Finish if not appropriate.
  578. if (!(mDGLRender || mManagerState == Resurrecting))
  579. return;
  580. // Sanity!
  581. AssertISV( pTextureObject->mHandleType != TextureHandle::InvalidTexture, "Invalid texture type." );
  582. AssertISV( pTextureObject->mpBitmap != NULL, "Bitmap cannot be NULL." );
  583. AssertISV( pTextureObject->mGLTextureName == 0, "GL texture name already exists." );
  584. // Generate texture name.
  585. glGenTextures(1, &pTextureObject->mGLTextureName);
  586. // Fetch source/dest formats.
  587. U32 sourceFormat, destFormat, byteFormat, texelSize;
  588. getSourceDestByteFormat(pTextureObject->mpBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  589. // Adjust metrics.
  590. mTextureResidentCount++;
  591. pTextureObject->mTextureResidentSize = pTextureObject->mTextureWidth * pTextureObject->mTextureHeight * texelSize;
  592. mTextureResidentSize += pTextureObject->mTextureResidentSize;
  593. pTextureObject->mTextureResidentWasteSize = ((pTextureObject->mTextureWidth * pTextureObject->mTextureHeight)-(pTextureObject->mBitmapWidth * pTextureObject->mBitmapHeight)) * texelSize;
  594. mTextureResidentWasteSize += pTextureObject->mTextureResidentWasteSize;
  595. // Refresh the texture.
  596. refresh( pTextureObject );
  597. }
  598. //--------------------------------------------------------------------------------------------------------------------
  599. TextureObject* TextureManager::registerTexture(const char* pTextureKey, GBitmap* pNewBitmap, TextureHandle::TextureHandleType type, bool clampToEdge)
  600. {
  601. // Sanity!
  602. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  603. TextureObject* pTextureObject = NULL;
  604. // Fetch texture key.
  605. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  606. if(pTextureKey)
  607. {
  608. pTextureObject = TextureDictionary::find(textureKey, type, clampToEdge);
  609. }
  610. if( pTextureObject )
  611. {
  612. // Remove bitmap if we have a different existing one.
  613. if ( pTextureObject->mpBitmap != NULL && pTextureObject->mpBitmap != pNewBitmap)
  614. {
  615. delete pTextureObject->mpBitmap;
  616. pTextureObject->mpBitmap = NULL;
  617. // Adjust metrics.
  618. mBitmapResidentSize -= pTextureObject->mBitmapResidentSize;
  619. pTextureObject->mBitmapResidentSize = 0;
  620. }
  621. // Remove any texture name.
  622. if ( pTextureObject->mGLTextureName != 0 )
  623. {
  624. glDeleteTextures(1, (const GLuint*)&pTextureObject->mGLTextureName);
  625. pTextureObject->mGLTextureName = 0;
  626. // Adjust metrics.
  627. mTextureResidentCount--;
  628. mTextureResidentSize -= pTextureObject->mTextureResidentSize;
  629. pTextureObject->mTextureResidentSize = 0;
  630. mTextureResidentWasteSize -= pTextureObject->mTextureResidentWasteSize;
  631. pTextureObject->mTextureResidentWasteSize = 0;
  632. }
  633. }
  634. else
  635. {
  636. // Create new texture object.
  637. pTextureObject = new TextureObject();
  638. pTextureObject->mTextureKey = textureKey;
  639. pTextureObject->mHandleType = type;
  640. TextureDictionary::insert(pTextureObject);
  641. }
  642. if ( pTextureObject->mHandleType == TextureHandle::BitmapKeepTexture && pTextureObject->mpBitmap != pNewBitmap )
  643. {
  644. // Adjust metrics.
  645. pTextureObject->mBitmapResidentSize = pNewBitmap->byteSize;
  646. mBitmapResidentSize += pTextureObject->mBitmapResidentSize;
  647. }
  648. pTextureObject->mpBitmap = pNewBitmap;
  649. pTextureObject->mBitmapWidth = pNewBitmap->getWidth();
  650. pTextureObject->mBitmapHeight = pNewBitmap->getHeight();
  651. pTextureObject->mTextureWidth = getNextPow2(pNewBitmap->getWidth());
  652. pTextureObject->mTextureHeight = getNextPow2(pNewBitmap->getHeight());
  653. pTextureObject->mClamp = clampToEdge;
  654. // Generate a GL texture name if one is not ready.
  655. if( pTextureObject->mGLTextureName == 0)
  656. {
  657. createGLName(pTextureObject);
  658. }
  659. // Delete bitmap if we're not keeping it.
  660. if ( pTextureObject->mHandleType != TextureHandle::BitmapKeepTexture )
  661. {
  662. delete pTextureObject->mpBitmap;
  663. pTextureObject->mpBitmap = NULL;
  664. }
  665. return pTextureObject;
  666. }
  667. //--------------------------------------------------------------------------------------------------------------------
  668. TextureObject *TextureManager::loadTexture(const char* pTextureKey, TextureHandle::TextureHandleType type, bool clampToEdge, bool checkOnly, bool force16Bit )
  669. {
  670. // Sanity!
  671. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  672. // Finish if texture key is invalid.
  673. if( pTextureKey == NULL || *pTextureKey == 0)
  674. return NULL;
  675. // Fetch texture key.
  676. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  677. TextureObject *ret = TextureDictionary::find(textureKey, type, clampToEdge);
  678. GBitmap *bmp = NULL;
  679. if( ret == NULL )
  680. {
  681. // Ok, no hit - is it in the current dir? If so then let's grab it
  682. // and use it.
  683. bmp = loadBitmap(textureKey, false);
  684. if(bmp)
  685. {
  686. bmp->mForce16Bit = force16Bit;
  687. return registerTexture(textureKey, bmp, type, clampToEdge);
  688. }
  689. }
  690. if(ret)
  691. return ret;
  692. // If we're just checking, fail out so we eventually get around to
  693. // loading a real bitmap.
  694. if(checkOnly)
  695. return NULL;
  696. // Ok, no success so let's try actually loading a texture.
  697. bmp = loadBitmap(textureKey);
  698. if(!bmp)
  699. {
  700. Con::warnf("Could not locate texture: %s", textureKey);
  701. return NULL;
  702. }
  703. bmp->mForce16Bit = force16Bit;
  704. return registerTexture(textureKey, bmp, type, clampToEdge);
  705. }
  706. //--------------------------------------------------------------------------------------------------------------------
  707. GBitmap *TextureManager::loadBitmap( const char* pTextureKey, bool recurse, bool nocompression )
  708. {
  709. char fileNameBuffer[512];
  710. Con::expandPath( fileNameBuffer, sizeof(fileNameBuffer), pTextureKey );
  711. GBitmap *bmp = NULL;
  712. // Loop through the supported extensions to find the file.
  713. U32 len = dStrlen(fileNameBuffer);
  714. for (U32 i = 0; i < EXT_ARRAY_SIZE && bmp == NULL; i++)
  715. {
  716. #if defined(TORQUE_OS_IOS)
  717. // check to see if requested no-compression...
  718. if (nocompression && (dStrncmp( extArray[i], ".pvr", 4 ) == 0)) {
  719. continue;
  720. }
  721. #endif
  722. dStrcpy(fileNameBuffer + len, extArray[i]);
  723. bmp = (GBitmap*)ResourceManager->loadInstance(fileNameBuffer);
  724. if ( bmp != NULL && (bmp->getWidth() > MaximumProductSupportedTextureWidth || bmp->getHeight() > MaximumProductSupportedTextureHeight) )
  725. {
  726. Con::warnf( "TextureManager::loadBitmap() - Cannot load bitmap '%s' as its dimensions exceed the maximum product-supported texture dimension.", fileNameBuffer );
  727. delete bmp;
  728. return NULL;
  729. }
  730. }
  731. return bmp;
  732. }
  733. //--------------------------------------------------------------------------------------------------------------------
  734. void TextureManager::dumpMetrics( void )
  735. {
  736. S32 textureResidentCount = 0;
  737. S32 textureResidentSize = 0;
  738. S32 textureResidentWasteSize = 0;
  739. S32 bitmapResidentSize = 0;
  740. Con::printSeparator();
  741. Con::printBlankLine();
  742. Con::printf( "Dumping texture manager metrics:" );
  743. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  744. while (pProbe != NULL)
  745. {
  746. GLboolean isTextureResident = false;
  747. if ( pProbe->mGLTextureName != 0 )
  748. {
  749. textureResidentCount++;
  750. glAreTexturesResident( 1, &pProbe->mGLTextureName, &isTextureResident );
  751. }
  752. textureResidentSize += pProbe->mTextureResidentSize;
  753. bitmapResidentSize += pProbe->mBitmapResidentSize;
  754. textureResidentWasteSize += pProbe->mTextureResidentWasteSize;
  755. // Info.
  756. Con::printf( "BitmapArea: (%d-%d), BitmapMemory: %d, TextureArea: (%d-%d), TextureMemory: %d, TextureMemoryWaste=%d, Refs=%d, Resident=%s, Name=%s",
  757. pProbe->mBitmapWidth,pProbe->mBitmapHeight, pProbe->mBitmapResidentSize,
  758. pProbe->mTextureWidth, pProbe->mTextureHeight, pProbe->mTextureResidentSize, pProbe->mTextureResidentWasteSize,
  759. pProbe->mRefCount,
  760. isTextureResident == 0 ? "NO" : "YES",
  761. pProbe->mTextureKey );
  762. pProbe = pProbe->next;
  763. }
  764. // Validate metrics.
  765. const bool textureCountSame = textureResidentCount == mTextureResidentCount;
  766. const bool textureSizeSame = textureResidentSize == mTextureResidentSize;
  767. const bool textureWasteSizeSame = textureResidentWasteSize == mTextureResidentWasteSize;
  768. const bool bitmapSizeSame = bitmapResidentSize == mBitmapResidentSize;
  769. const bool allMetricsValid = textureCountSame && textureSizeSame && textureWasteSizeSame && bitmapSizeSame;
  770. // Error if metrics are invalid.
  771. if ( !allMetricsValid )
  772. Con::errorf( "Metrics appear to be invalid." );
  773. // Info.
  774. Con::printf( "Metrics Totals:" );
  775. Con::printf( "TextureCount: %d, TextureSize: %d, TextureWasteSize: %d, BitmapSize: %d, ResidentFraction: %g",
  776. mTextureResidentCount,
  777. mTextureResidentSize,
  778. mTextureResidentWasteSize,
  779. mBitmapResidentSize,
  780. getResidentFraction() );
  781. Con::printBlankLine();
  782. Con::printSeparator();
  783. Con::printf( "All texture manager metrics are valid." );
  784. Con::printSeparator();
  785. }
  786. //--------------------------------------------------------------------------------------------------------------------
  787. F32 TextureManager::getResidentFraction()
  788. {
  789. U32 resident = 0;
  790. U32 total = 0;
  791. Vector<GLuint> names;
  792. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  793. while (pProbe != NULL)
  794. {
  795. if (pProbe->mGLTextureName != 0)
  796. {
  797. total++;
  798. names.push_back(pProbe->mGLTextureName);
  799. }
  800. pProbe = pProbe->next;
  801. }
  802. if (total == 0)
  803. return 1.0f;
  804. Vector<GLboolean> isResident;
  805. isResident.setSize(names.size());
  806. glAreTexturesResident(names.size(), names.address(), isResident.address());
  807. for (U32 i = 0; i < (U32)names.size(); i++)
  808. if (isResident[i] == GL_TRUE)
  809. resident++;
  810. return (F32(resident) / F32(total));
  811. }