TextureManager.cc 34 KB

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