TextureManager.cc 36 KB

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