TextureManager.cc 36 KB

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