gfxTextureManager.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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 "platform/platform.h"
  23. #include "gfx/gfxTextureManager.h"
  24. #include "gfx/gfxDevice.h"
  25. #include "gfx/gfxCardProfile.h"
  26. #include "gfx/gfxStringEnumTranslate.h"
  27. #include "gfx/bitmap/ddsUtils.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "core/util/safeDelete.h"
  30. #include "core/resourceManager.h"
  31. #include "core/volume.h"
  32. #include "core/util/dxt5nmSwizzle.h"
  33. #include "console/consoleTypes.h"
  34. #include "console/engineAPI.h"
  35. //#define DEBUG_SPEW
  36. S32 GFXTextureManager::smTextureReductionLevel = 0;
  37. GFXTextureManager::EventSignal GFXTextureManager::smEventSignal;
  38. static const String sDDSExt( "dds" );
  39. void GFXTextureManager::init()
  40. {
  41. Con::addVariable( "$pref::Video::textureReductionLevel", TypeS32, &smTextureReductionLevel,
  42. "The number of mipmap levels to drop on loaded textures to reduce "
  43. "video memory usage. It will skip any textures that have been defined "
  44. "as not allowing down scaling.\n"
  45. "@ingroup GFX\n" );
  46. }
  47. GFXTextureManager::GFXTextureManager()
  48. {
  49. mListHead = mListTail = NULL;
  50. mTextureManagerState = GFXTextureManager::Living;
  51. // Set up the hash table
  52. mHashCount = 1023;
  53. mHashTable = new GFXTextureObject *[mHashCount];
  54. for(U32 i = 0; i < mHashCount; i++)
  55. mHashTable[i] = NULL;
  56. }
  57. GFXTextureManager::~GFXTextureManager()
  58. {
  59. if( mHashTable )
  60. SAFE_DELETE_ARRAY( mHashTable );
  61. mCubemapTable.clear();
  62. }
  63. U32 GFXTextureManager::getTextureDownscalePower( GFXTextureProfile *profile )
  64. {
  65. if ( !profile || profile->canDownscale() )
  66. return smTextureReductionLevel;
  67. return 0;
  68. }
  69. bool GFXTextureManager::validateTextureQuality( GFXTextureProfile *profile, U32 &width, U32 &height )
  70. {
  71. U32 scaleFactor = getTextureDownscalePower( profile );
  72. if ( scaleFactor == 0 )
  73. return true;
  74. // Otherwise apply the appropriate scale...
  75. width >>= scaleFactor;
  76. height >>= scaleFactor;
  77. return true;
  78. }
  79. void GFXTextureManager::kill()
  80. {
  81. AssertFatal( mTextureManagerState != GFXTextureManager::Dead, "Texture Manager already killed!" );
  82. // Release everything in the cache we can
  83. // so we don't leak any textures.
  84. cleanupCache();
  85. GFXTextureObject *curr = mListHead;
  86. GFXTextureObject *temp;
  87. // Actually delete all the textures we know about.
  88. while( curr != NULL )
  89. {
  90. temp = curr->mNext;
  91. curr->kill();
  92. curr = temp;
  93. }
  94. mCubemapTable.clear();
  95. mTextureManagerState = GFXTextureManager::Dead;
  96. }
  97. void GFXTextureManager::zombify()
  98. {
  99. AssertFatal( mTextureManagerState != GFXTextureManager::Zombie, "Texture Manager already a zombie!" );
  100. // Notify everyone that cares about the zombification!
  101. smEventSignal.trigger( GFXZombify );
  102. // Release unused pool textures.
  103. cleanupPool();
  104. // Release everything in the cache we can.
  105. cleanupCache();
  106. // Free all the device copies of the textures.
  107. GFXTextureObject *temp = mListHead;
  108. while( temp != NULL )
  109. {
  110. freeTexture( temp, true );
  111. temp = temp->mNext;
  112. }
  113. // Finally, note our state.
  114. mTextureManagerState = GFXTextureManager::Zombie;
  115. }
  116. void GFXTextureManager::resurrect()
  117. {
  118. // Reupload all the device copies of the textures.
  119. GFXTextureObject *temp = mListHead;
  120. while( temp != NULL )
  121. {
  122. refreshTexture( temp );
  123. temp = temp->mNext;
  124. }
  125. // Notify callback registries.
  126. smEventSignal.trigger( GFXResurrect );
  127. // Update our state.
  128. mTextureManagerState = GFXTextureManager::Living;
  129. }
  130. void GFXTextureManager::cleanupPool()
  131. {
  132. PROFILE_SCOPE( GFXTextureManager_CleanupPool );
  133. TexturePoolMap::Iterator iter = mTexturePool.begin();
  134. for ( ; iter != mTexturePool.end(); )
  135. {
  136. if ( iter->value->getRefCount() == 1 )
  137. {
  138. // This texture is unreferenced, so take the time
  139. // now to completely remove it from the pool.
  140. TexturePoolMap::Iterator unref = iter;
  141. iter++;
  142. unref->value = NULL;
  143. mTexturePool.erase( unref );
  144. continue;
  145. }
  146. iter++;
  147. }
  148. }
  149. void GFXTextureManager::requestDeleteTexture( GFXTextureObject *texture )
  150. {
  151. // If this is a non-cached texture then just really delete it.
  152. if ( texture->mTextureLookupName.isEmpty() )
  153. {
  154. delete texture;
  155. return;
  156. }
  157. // Set the time and store it.
  158. texture->mDeleteTime = Platform::getTime();
  159. mToDelete.push_back_unique( texture );
  160. }
  161. void GFXTextureManager::cleanupCache( U32 secondsToLive )
  162. {
  163. PROFILE_SCOPE( GFXTextureManager_CleanupCache );
  164. U32 killTime = Platform::getTime() - secondsToLive;
  165. for ( U32 i=0; i < mToDelete.size(); )
  166. {
  167. GFXTextureObject *tex = mToDelete[i];
  168. // If the texture was picked back up by a user
  169. // then just remove it from the list.
  170. if ( tex->getRefCount() != 0 )
  171. {
  172. mToDelete.erase_fast( i );
  173. continue;
  174. }
  175. // If its time has expired delete it for real.
  176. if ( tex->mDeleteTime <= killTime )
  177. {
  178. //Con::errorf( "Killed texture: %s", tex->mTextureLookupName.c_str() );
  179. delete tex;
  180. mToDelete.erase_fast( i );
  181. continue;
  182. }
  183. i++;
  184. }
  185. }
  186. GFXTextureObject *GFXTextureManager::_lookupTexture( const char *hashName, const GFXTextureProfile *profile )
  187. {
  188. GFXTextureObject *ret = hashFind( hashName );
  189. // TODO: Profile checking HERE
  190. return ret;
  191. }
  192. GFXTextureObject *GFXTextureManager::_lookupTexture( const DDSFile *ddsFile, const GFXTextureProfile *profile )
  193. {
  194. if( ddsFile->getTextureCacheString().isNotEmpty() )
  195. {
  196. // Call _lookupTexture()
  197. return _lookupTexture( ddsFile->getTextureCacheString(), profile );
  198. }
  199. return NULL;
  200. }
  201. GFXTextureObject *GFXTextureManager::createTexture( GBitmap *bmp, const String &resourceName, GFXTextureProfile *profile, bool deleteBmp )
  202. {
  203. AssertFatal(bmp, "GFXTextureManager::createTexture() - Got NULL bitmap!");
  204. GFXTextureObject *cacheHit = _lookupTexture( resourceName, profile );
  205. if( cacheHit != NULL)
  206. {
  207. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  208. if (deleteBmp)
  209. delete bmp;
  210. return cacheHit;
  211. }
  212. return _createTexture( bmp, resourceName, profile, deleteBmp, NULL );
  213. }
  214. GFXTextureObject *GFXTextureManager::_createTexture( GBitmap *bmp,
  215. const String &resourceName,
  216. GFXTextureProfile *profile,
  217. bool deleteBmp,
  218. GFXTextureObject *inObj )
  219. {
  220. PROFILE_SCOPE( GFXTextureManager_CreateTexture_Bitmap );
  221. #ifdef DEBUG_SPEW
  222. Platform::outputDebugString( "[GFXTextureManager] _createTexture (GBitmap) '%s'",
  223. resourceName.c_str()
  224. );
  225. #endif
  226. // Massage the bitmap based on any resize rules.
  227. U32 scalePower = getTextureDownscalePower( profile );
  228. GBitmap *realBmp = bmp;
  229. U32 realWidth = bmp->getWidth();
  230. U32 realHeight = bmp->getHeight();
  231. if ( scalePower &&
  232. isPow2(bmp->getWidth()) &&
  233. isPow2(bmp->getHeight()) &&
  234. profile->canDownscale() )
  235. {
  236. // We only work with power of 2 textures for now, so we
  237. // don't have to worry about padding.
  238. // We downscale the bitmap on the CPU... this is the reason
  239. // you should be using DDS which already has good looking mips.
  240. GBitmap *padBmp = bmp;
  241. padBmp->extrudeMipLevels();
  242. scalePower = getMin( scalePower, padBmp->getNumMipLevels() - 1 );
  243. realWidth = getMax( (U32)1, padBmp->getWidth() >> scalePower );
  244. realHeight = getMax( (U32)1, padBmp->getHeight() >> scalePower );
  245. realBmp = new GBitmap( realWidth, realHeight, false, bmp->getFormat() );
  246. // Copy to the new bitmap...
  247. dMemcpy( realBmp->getWritableBits(),
  248. padBmp->getBits(scalePower),
  249. padBmp->getBytesPerPixel() * realWidth * realHeight );
  250. // This line is commented out because createPaddedBitmap is commented out.
  251. // If that line is added back in, this line should be added back in.
  252. // delete padBmp;
  253. }
  254. // Call the internal create... (use the real* variables now, as they
  255. // reflect the reality of the texture we are creating.)
  256. U32 numMips = 0;
  257. GFXFormat realFmt = realBmp->getFormat();
  258. _validateTexParams( realWidth, realHeight, profile, numMips, realFmt );
  259. GFXTextureObject *ret;
  260. if ( inObj )
  261. {
  262. // If the texture has changed in dimensions
  263. // then we need to recreate it.
  264. if ( inObj->getWidth() != realWidth ||
  265. inObj->getHeight() != realHeight ||
  266. inObj->getFormat() != realFmt )
  267. ret = _createTextureObject( realHeight, realWidth, 0, realFmt, profile, numMips, false, 0, inObj );
  268. else
  269. ret = inObj;
  270. }
  271. else
  272. ret = _createTextureObject(realHeight, realWidth, 0, realFmt, profile, numMips );
  273. if(!ret)
  274. {
  275. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  276. return NULL;
  277. }
  278. // Extrude mip levels
  279. // Don't do this for fonts!
  280. if( ret->mMipLevels > 1 && ( realBmp->getNumMipLevels() == 1 ) && ( realBmp->getFormat() != GFXFormatA8 ) &&
  281. isPow2( realBmp->getHeight() ) && isPow2( realBmp->getWidth() ) && !profile->noMip() )
  282. {
  283. // NOTE: This should really be done by extruding mips INTO a DDS file instead
  284. // of modifying the gbitmap
  285. realBmp->extrudeMipLevels(false);
  286. }
  287. // If _validateTexParams kicked back a different format, than there needs to be
  288. // a conversion
  289. DDSFile *bmpDDS = NULL;
  290. if( realBmp->getFormat() != realFmt )
  291. {
  292. const GFXFormat oldFmt = realBmp->getFormat();
  293. // TODO: Set it up so that ALL format conversions use DDSFile. Rip format
  294. // switching out of GBitmap entirely.
  295. if( !realBmp->setFormat( realFmt ) )
  296. {
  297. // This is not the ideal implementation...
  298. bmpDDS = DDSFile::createDDSFileFromGBitmap( realBmp );
  299. bool convSuccess = false;
  300. if( bmpDDS != NULL )
  301. {
  302. // This shouldn't live here, I don't think
  303. switch( realFmt )
  304. {
  305. case GFXFormatDXT1:
  306. case GFXFormatDXT2:
  307. case GFXFormatDXT3:
  308. case GFXFormatDXT4:
  309. case GFXFormatDXT5:
  310. // If this is a Normal Map profile, than the data needs to be conditioned
  311. // to use the swizzle trick
  312. if( ret->mProfile->getType() == GFXTextureProfile::NormalMap )
  313. {
  314. PROFILE_START(DXT_DXTNMSwizzle);
  315. static DXT5nmSwizzle sDXT5nmSwizzle;
  316. DDSUtil::swizzleDDS( bmpDDS, sDXT5nmSwizzle );
  317. PROFILE_END();
  318. }
  319. convSuccess = DDSUtil::squishDDS( bmpDDS, realFmt );
  320. break;
  321. default:
  322. AssertFatal(false, "Attempting to convert to a non-DXT format");
  323. break;
  324. }
  325. }
  326. if( !convSuccess )
  327. {
  328. Con::errorf( "[GFXTextureManager]: Failed to change source format from %s to %s. Cannot create texture.",
  329. GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  330. delete bmpDDS;
  331. return NULL;
  332. }
  333. }
  334. #ifdef TORQUE_DEBUG
  335. else
  336. {
  337. //Con::warnf( "[GFXTextureManager]: Changed bitmap format from %s to %s.",
  338. // GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  339. }
  340. #endif
  341. }
  342. // Call the internal load...
  343. if( ( bmpDDS == NULL && !_loadTexture( ret, realBmp ) ) || // If we aren't doing a DDS format change, use bitmap load
  344. ( bmpDDS != NULL && !_loadTexture( ret, bmpDDS ) ) ) // If there is a DDS, than load that instead. A format change took place.
  345. {
  346. Con::errorf("GFXTextureManager - failed to load GBitmap for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  347. return NULL;
  348. }
  349. // Do statistics and book-keeping...
  350. // - info for the texture...
  351. ret->mTextureLookupName = resourceName;
  352. ret->mBitmapSize.set(realWidth, realHeight,0);
  353. #ifdef TORQUE_DEBUG
  354. if (resourceName.isNotEmpty())
  355. ret->mDebugDescription = resourceName;
  356. else
  357. ret->mDebugDescription = "Anonymous Texture Object";
  358. #endif
  359. if(profile->doStoreBitmap())
  360. {
  361. // NOTE: may store a downscaled copy!
  362. SAFE_DELETE( ret->mBitmap );
  363. SAFE_DELETE( ret->mDDS );
  364. if( bmpDDS == NULL )
  365. ret->mBitmap = new GBitmap( *realBmp );
  366. else
  367. ret->mDDS = bmpDDS;
  368. }
  369. else
  370. {
  371. // Delete the DDS if we made one
  372. SAFE_DELETE( bmpDDS );
  373. }
  374. if ( !inObj )
  375. _linkTexture( ret );
  376. // - output debug info?
  377. // Save texture for debug purpose
  378. // static int texId = 0;
  379. // char buff[256];
  380. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  381. // bmp->writePNGDebug(buff);
  382. // texId++;
  383. // Before we delete the bitmap save our transparency flag
  384. ret->mHasTransparency = realBmp->getHasTransparency();
  385. // Some final cleanup...
  386. if(realBmp != bmp)
  387. SAFE_DELETE(realBmp);
  388. if (deleteBmp)
  389. SAFE_DELETE(bmp);
  390. // Return the new texture!
  391. return ret;
  392. }
  393. GFXTextureObject *GFXTextureManager::createTexture( DDSFile *dds, GFXTextureProfile *profile, bool deleteDDS )
  394. {
  395. AssertFatal(dds, "GFXTextureManager::createTexture() - Got NULL dds!");
  396. // Check the cache first...
  397. GFXTextureObject *cacheHit = _lookupTexture( dds, profile );
  398. if ( cacheHit )
  399. {
  400. // Con::errorf("Cached texture '%s'", (fileName.isNotEmpty() ? fileName.c_str() : "unknown"));
  401. if( deleteDDS )
  402. delete dds;
  403. return cacheHit;
  404. }
  405. return _createTexture( dds, profile, deleteDDS, NULL );
  406. }
  407. GFXTextureObject *GFXTextureManager::_createTexture( DDSFile *dds,
  408. GFXTextureProfile *profile,
  409. bool deleteDDS,
  410. GFXTextureObject *inObj )
  411. {
  412. PROFILE_SCOPE( GFXTextureManager_CreateTexture_DDS );
  413. const char *fileName = dds->getTextureCacheString();
  414. if( !fileName )
  415. fileName = "unknown";
  416. #ifdef DEBUG_SPEW
  417. Platform::outputDebugString( "[GFXTextureManager] _createTexture (DDS) '%s'",
  418. fileName
  419. );
  420. #endif
  421. // Ignore padding from the profile.
  422. U32 numMips = dds->mMipMapCount;
  423. GFXFormat fmt = dds->mFormat;
  424. _validateTexParams( dds->getHeight(), dds->getWidth(), profile, numMips, fmt );
  425. if( fmt != dds->mFormat )
  426. {
  427. Con::errorf( "GFXTextureManager - failed to validate texture parameters for DDS file '%s'", fileName );
  428. return NULL;
  429. }
  430. // Call the internal create... (use the real* variables now, as they
  431. // reflect the reality of the texture we are creating.)
  432. GFXTextureObject *ret;
  433. if ( inObj )
  434. {
  435. // If the texture has changed in dimensions
  436. // then we need to recreate it.
  437. if ( inObj->getWidth() != dds->getWidth() ||
  438. inObj->getHeight() != dds->getHeight() ||
  439. inObj->getFormat() != fmt ||
  440. inObj->getMipLevels() != numMips )
  441. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  442. fmt, profile, numMips,
  443. true, 0, inObj );
  444. else
  445. ret = inObj;
  446. }
  447. else
  448. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  449. fmt, profile, numMips, true );
  450. if(!ret)
  451. {
  452. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s' DDSFile.", fileName);
  453. return NULL;
  454. }
  455. // Call the internal load...
  456. if(!_loadTexture(ret, dds))
  457. {
  458. Con::errorf("GFXTextureManager - failed to load DDS for '%s'", fileName);
  459. return NULL;
  460. }
  461. // Do statistics and book-keeping...
  462. // - info for the texture...
  463. ret->mTextureLookupName = dds->getTextureCacheString();
  464. ret->mBitmapSize.set( dds->mWidth, dds->mHeight, 0 );
  465. #ifdef TORQUE_DEBUG
  466. ret->mDebugDescription = fileName;
  467. #endif
  468. if(profile->doStoreBitmap())
  469. {
  470. // NOTE: may store a downscaled copy!
  471. SAFE_DELETE( ret->mBitmap );
  472. SAFE_DELETE( ret->mDDS );
  473. ret->mDDS = new DDSFile( *dds );
  474. }
  475. if ( !inObj )
  476. _linkTexture( ret );
  477. // - output debug info?
  478. // Save texture for debug purpose
  479. // static int texId = 0;
  480. // char buff[256];
  481. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  482. // bmp->writePNGDebug(buff);
  483. // texId++;
  484. // Save our transparency flag
  485. ret->mHasTransparency = dds->getHasTransparency();
  486. if( deleteDDS )
  487. delete dds;
  488. // Return the new texture!
  489. return ret;
  490. }
  491. GFXTextureObject *GFXTextureManager::createTexture( const Torque::Path &path, GFXTextureProfile *profile )
  492. {
  493. PROFILE_SCOPE( GFXTextureManager_createTexture );
  494. // Resource handles used for loading. Hold on to them
  495. // throughout this function so that change notifications
  496. // don't get added, then removed, and then re-added.
  497. Resource< DDSFile > dds;
  498. Resource< GBitmap > bitmap;
  499. // We need to handle path's that have had "incorrect"
  500. // extensions parsed out of the file name
  501. Torque::Path correctPath = path;
  502. bool textureExt = false;
  503. // Easiest case to handle is when there isn't an extension
  504. if (path.getExtension().isEmpty())
  505. textureExt = true;
  506. // Since "dds" isn't registered with GBitmap currently we
  507. // have to test it separately
  508. if (sDDSExt.equal( path.getExtension(), String::NoCase ) )
  509. textureExt = true;
  510. // Now loop through the rest of the GBitmap extensions
  511. // to see if we have any matches
  512. for ( U32 i = 0; i < GBitmap::sRegistrations.size(); i++ )
  513. {
  514. // If we have gotten a match (either in this loop or before)
  515. // then we can exit
  516. if (textureExt)
  517. break;
  518. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  519. const Vector<String> &extensions = reg.extensions;
  520. for ( U32 j = 0; j < extensions.size(); ++j )
  521. {
  522. if ( extensions[j].equal( path.getExtension(), String::NoCase ) )
  523. {
  524. // Found a valid texture extension
  525. textureExt = true;
  526. break;
  527. }
  528. }
  529. }
  530. // If we didn't find a valid texture extension then assume that
  531. // the parsed out "extension" was actually intended to be part of
  532. // the texture name so add it back
  533. if (!textureExt)
  534. {
  535. correctPath.setFileName( Torque::Path::Join( path.getFileName(), '.', path.getExtension() ) );
  536. correctPath.setExtension( String::EmptyString );
  537. }
  538. // Check the cache first...
  539. String pathNoExt = Torque::Path::Join( correctPath.getRoot(), ':', correctPath.getPath() );
  540. pathNoExt = Torque::Path::Join( pathNoExt, '/', correctPath.getFileName() );
  541. GFXTextureObject *retTexObj = _lookupTexture( pathNoExt, profile );
  542. if( retTexObj )
  543. return retTexObj;
  544. const U32 scalePower = getTextureDownscalePower( profile );
  545. // If this is a valid file (has an extension) than load it
  546. Path realPath;
  547. if( Torque::FS::IsFile( correctPath ) )
  548. {
  549. // Check for DDS
  550. if( sDDSExt.equal(correctPath.getExtension(), String::NoCase ) )
  551. {
  552. dds = DDSFile::load( correctPath, scalePower );
  553. if( dds != NULL )
  554. {
  555. realPath = dds.getPath();
  556. retTexObj = createTexture( dds, profile, false );
  557. }
  558. }
  559. else // Let GBitmap take care of it
  560. {
  561. bitmap = GBitmap::load( correctPath );
  562. if( bitmap != NULL )
  563. {
  564. realPath = bitmap.getPath();
  565. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  566. }
  567. }
  568. }
  569. else
  570. {
  571. // NOTE -- We should probably remove the code from GBitmap that tries different
  572. // extensions for things GBitmap loads, and move it here. I think it should
  573. // be a bit more involved than just a list of extensions. Some kind of
  574. // extension registration thing, maybe.
  575. // Check to see if there is a .DDS file with this name (if no extension is provided)
  576. Torque::Path tryDDSPath = pathNoExt;
  577. if( tryDDSPath.getExtension().isNotEmpty() )
  578. tryDDSPath.setFileName( tryDDSPath.getFullFileName() );
  579. tryDDSPath.setExtension( sDDSExt );
  580. if( Torque::FS::IsFile( tryDDSPath ) )
  581. {
  582. dds = DDSFile::load( tryDDSPath, scalePower );
  583. if( dds != NULL )
  584. {
  585. realPath = dds.getPath();
  586. retTexObj = createTexture( dds, profile, false );
  587. }
  588. }
  589. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  590. // load.
  591. }
  592. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  593. // it will try a bunch of extensions
  594. if( retTexObj == NULL )
  595. {
  596. // Find and load the texture.
  597. bitmap = GBitmap::load( correctPath );
  598. if ( bitmap != NULL )
  599. {
  600. realPath = bitmap.getPath();
  601. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  602. }
  603. }
  604. if ( retTexObj )
  605. {
  606. // Store the path for later use.
  607. retTexObj->mPath = realPath;
  608. // Register the texture file for change notifications.
  609. FS::AddChangeNotification( retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged );
  610. }
  611. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  612. return retTexObj;
  613. }
  614. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, void *pixels, GFXFormat format, GFXTextureProfile *profile )
  615. {
  616. // For now, stuff everything into a GBitmap and pass it off... This may need to be revisited -- BJG
  617. GBitmap *bmp = new GBitmap(width, height, 0, format);
  618. dMemcpy(bmp->getWritableBits(), pixels, width * height * bmp->getBytesPerPixel());
  619. return createTexture( bmp, String::EmptyString, profile, true );
  620. }
  621. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, S32 antialiasLevel )
  622. {
  623. // Deal with sizing issues...
  624. U32 localWidth = width;
  625. U32 localHeight = height;
  626. // TODO: Format check HERE! -patw
  627. validateTextureQuality(profile, localWidth, localHeight);
  628. U32 numMips = numMipLevels;
  629. GFXFormat checkFmt = format;
  630. _validateTexParams( localWidth, localHeight, profile, numMips, checkFmt );
  631. AssertFatal( checkFmt == format, "Anonymous texture didn't get the format it wanted." );
  632. GFXTextureObject *outTex = NULL;
  633. // If this is a pooled profile then look there first.
  634. if ( profile->isPooled() )
  635. {
  636. outTex = _findPooledTexure( localWidth, localHeight, checkFmt,
  637. profile, numMips, antialiasLevel );
  638. // If we got a pooled texture then its
  639. // already setup... just return it.
  640. if ( outTex )
  641. return outTex;
  642. }
  643. // Create the texture if we didn't get one from the pool.
  644. if ( !outTex )
  645. {
  646. outTex = _createTextureObject( localHeight, localWidth, 0, format, profile, numMips, false, antialiasLevel );
  647. // Make sure we add it to the pool.
  648. if ( outTex && profile->isPooled() )
  649. mTexturePool.insertEqual( profile, outTex );
  650. }
  651. if ( !outTex )
  652. {
  653. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  654. return NULL;
  655. }
  656. // And do book-keeping...
  657. // - texture info
  658. outTex->mBitmapSize.set(localWidth, localHeight, 0);
  659. outTex->mAntialiasLevel = antialiasLevel;
  660. // PWTODO: Need to assign this a lookup name before _linkTexture() is called
  661. // otherwise it won't get a hash insert call
  662. _linkTexture( outTex );
  663. return outTex;
  664. }
  665. GFXTextureObject *GFXTextureManager::createTexture( U32 width,
  666. U32 height,
  667. U32 depth,
  668. void *pixels,
  669. GFXFormat format,
  670. GFXTextureProfile *profile )
  671. {
  672. PROFILE_SCOPE( GFXTextureManager_CreateTexture_3D );
  673. // Create texture...
  674. GFXTextureObject *ret = _createTextureObject( height, width, depth, format, profile, 1 );
  675. if(!ret)
  676. {
  677. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  678. return NULL;
  679. }
  680. // Call the internal load...
  681. if( !_loadTexture( ret, pixels ) )
  682. {
  683. Con::errorf("GFXTextureManager - failed to load volume texture" );
  684. return NULL;
  685. }
  686. // And do book-keeping...
  687. // - texture info
  688. ret->mBitmapSize.set( width, height, depth );
  689. _linkTexture( ret );
  690. // Return the new texture!
  691. return ret;
  692. }
  693. GFXTextureObject* GFXTextureManager::_findPooledTexure( U32 width,
  694. U32 height,
  695. GFXFormat format,
  696. GFXTextureProfile *profile,
  697. U32 numMipLevels,
  698. S32 antialiasLevel )
  699. {
  700. PROFILE_SCOPE( GFXTextureManager_FindPooledTexure );
  701. GFXTextureObject *outTex;
  702. // First see if we have a free one in the pool.
  703. TexturePoolMap::Iterator iter = mTexturePool.find( profile );
  704. for ( ; iter != mTexturePool.end() && iter->key == profile; iter++ )
  705. {
  706. outTex = iter->value;
  707. // If the reference count is 1 then we're the only
  708. // ones holding on to this texture and we can hand
  709. // it out if the size matches... else its in use.
  710. if ( outTex->getRefCount() != 1 )
  711. continue;
  712. // Check for a match... if so return it. The assignment
  713. // to a GFXTexHandle will take care of incrementing the
  714. // reference count and keeping it from being handed out
  715. // to anyone else.
  716. if ( outTex->getFormat() == format &&
  717. outTex->getWidth() == width &&
  718. outTex->getHeight() == height &&
  719. outTex->getMipLevels() == numMipLevels &&
  720. outTex->mAntialiasLevel == antialiasLevel )
  721. return outTex;
  722. }
  723. return NULL;
  724. }
  725. void GFXTextureManager::hashInsert( GFXTextureObject *object )
  726. {
  727. if ( object->mTextureLookupName.isEmpty() )
  728. return;
  729. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  730. object->mHashNext = mHashTable[key];
  731. mHashTable[key] = object;
  732. }
  733. void GFXTextureManager::hashRemove( GFXTextureObject *object )
  734. {
  735. if ( object->mTextureLookupName.isEmpty() )
  736. return;
  737. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  738. GFXTextureObject **walk = &mHashTable[key];
  739. while(*walk)
  740. {
  741. if(*walk == object)
  742. {
  743. *walk = object->mHashNext;
  744. break;
  745. }
  746. walk = &((*walk)->mHashNext);
  747. }
  748. }
  749. GFXTextureObject* GFXTextureManager::hashFind( const String &name )
  750. {
  751. if ( name.isEmpty() )
  752. return NULL;
  753. U32 key = name.getHashCaseInsensitive() % mHashCount;
  754. GFXTextureObject *walk = mHashTable[key];
  755. for(; walk; walk = walk->mHashNext)
  756. {
  757. if( walk->mTextureLookupName.equal( name, String::NoCase ) )
  758. break;
  759. }
  760. return walk;
  761. }
  762. void GFXTextureManager::freeTexture(GFXTextureObject *texture, bool zombify)
  763. {
  764. // Ok, let the backend deal with it.
  765. _freeTexture(texture, zombify);
  766. }
  767. void GFXTextureManager::refreshTexture(GFXTextureObject *texture)
  768. {
  769. _refreshTexture(texture);
  770. }
  771. void GFXTextureManager::_linkTexture( GFXTextureObject *obj )
  772. {
  773. // info for the profile
  774. GFXTextureProfile::updateStatsForCreation(obj);
  775. // info for the cache
  776. hashInsert(obj);
  777. // info for the master list
  778. if( mListHead == NULL )
  779. mListHead = obj;
  780. if( mListTail != NULL )
  781. mListTail->mNext = obj;
  782. obj->mPrev = mListTail;
  783. mListTail = obj;
  784. }
  785. void GFXTextureManager::deleteTexture( GFXTextureObject *texture )
  786. {
  787. if ( mTextureManagerState == GFXTextureManager::Dead )
  788. return;
  789. #ifdef DEBUG_SPEW
  790. Platform::outputDebugString( "[GFXTextureManager] deleteTexture '%s'",
  791. texture->mTextureLookupName.c_str()
  792. );
  793. #endif
  794. if( mListHead == texture )
  795. mListHead = texture->mNext;
  796. if( mListTail == texture )
  797. mListTail = texture->mPrev;
  798. hashRemove( texture );
  799. // If we have a path for the texture then
  800. // remove change notifications for it.
  801. Path texPath = texture->getPath();
  802. if ( !texPath.isEmpty() )
  803. FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  804. GFXTextureProfile::updateStatsForDeletion(texture);
  805. freeTexture( texture );
  806. }
  807. void GFXTextureManager::_validateTexParams( const U32 width, const U32 height,
  808. const GFXTextureProfile *profile,
  809. U32 &inOutNumMips, GFXFormat &inOutFormat )
  810. {
  811. // Validate mipmap parameter. If this profile requests no mips, set mips to 1.
  812. if( profile->noMip() )
  813. {
  814. inOutNumMips = 1;
  815. }
  816. else if( !isPow2( width ) || !isPow2( height ) )
  817. {
  818. // If a texture is not power-of-2 in size for both dimensions, it must
  819. // have only 1 mip level.
  820. inOutNumMips = 1;
  821. }
  822. // Check format, and compatibility with texture profile requirements
  823. bool autoGenSupp = ( inOutNumMips == 0 );
  824. // If the format is non-compressed, and the profile requests a compressed format
  825. // than change the format.
  826. GFXFormat testingFormat = inOutFormat;
  827. if( profile->getCompression() != GFXTextureProfile::None )
  828. {
  829. const int offset = profile->getCompression() - GFXTextureProfile::DXT1;
  830. testingFormat = GFXFormat( GFXFormatDXT1 + offset );
  831. // No auto-gen mips on compressed textures
  832. autoGenSupp = false;
  833. }
  834. // inOutFormat is not modified by this method
  835. bool chekFmt = GFX->getCardProfiler()->checkFormat( testingFormat, profile, autoGenSupp );
  836. if( !chekFmt )
  837. {
  838. // It tested for a compressed format, and didn't like it
  839. if( testingFormat != inOutFormat && profile->getCompression() )
  840. testingFormat = inOutFormat; // Reset to requested format, and try again
  841. // Trying again here, so reset autogen mip
  842. autoGenSupp = ( inOutNumMips == 0 );
  843. // Wow more weak sauce. There should be a better way to do this.
  844. switch( inOutFormat )
  845. {
  846. case GFXFormatR8G8B8:
  847. testingFormat = GFXFormatR8G8B8X8;
  848. chekFmt = GFX->getCardProfiler()->checkFormat( testingFormat, profile, autoGenSupp );
  849. break;
  850. case GFXFormatA8:
  851. testingFormat = GFXFormatR8G8B8A8;
  852. chekFmt = GFX->getCardProfiler()->checkFormat( testingFormat, profile, autoGenSupp );
  853. break;
  854. default:
  855. chekFmt = GFX->getCardProfiler()->checkFormat( testingFormat, profile, autoGenSupp );
  856. break;
  857. }
  858. }
  859. // Write back num mips that need to be generated by GBitmap
  860. if( !chekFmt )
  861. Con::errorf( "Format %s not supported with specified profile.", GFXStringTextureFormat[inOutFormat] );
  862. else
  863. {
  864. inOutFormat = testingFormat;
  865. // If auto gen mipmaps were requested, and they aren't supported for whatever
  866. // reason, than write out the number of mips that need to be generated.
  867. //
  868. // NOTE: Does this belong here?
  869. if( inOutNumMips == 0 && !autoGenSupp )
  870. {
  871. U32 currWidth = width;
  872. U32 currHeight = height;
  873. inOutNumMips = 1;
  874. do
  875. {
  876. currWidth >>= 1;
  877. currHeight >>= 1;
  878. if( currWidth == 0 )
  879. currWidth = 1;
  880. if( currHeight == 0 )
  881. currHeight = 1;
  882. inOutNumMips++;
  883. } while ( currWidth != 1 || currHeight != 1 );
  884. }
  885. }
  886. }
  887. GFXCubemap* GFXTextureManager::createCubemap( const Torque::Path &path )
  888. {
  889. // Very first thing... check the cache.
  890. CubemapTable::Iterator iter = mCubemapTable.find( path.getFullPath() );
  891. if ( iter != mCubemapTable.end() )
  892. return iter->value;
  893. // Not in the cache... we have to load it ourselves.
  894. // First check for a DDS file.
  895. if ( !sDDSExt.equal( path.getExtension(), String::NoCase ) )
  896. {
  897. // At the moment we only support DDS cubemaps.
  898. return NULL;
  899. }
  900. const U32 scalePower = getTextureDownscalePower( NULL );
  901. // Ok... load the DDS file then.
  902. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  903. if ( !dds || !dds->isCubemap() )
  904. {
  905. // This wasn't a cubemap... give up too.
  906. return NULL;
  907. }
  908. // We loaded the cubemap dds, so now we create the GFXCubemap from it.
  909. GFXCubemap *cubemap = GFX->createCubemap();
  910. cubemap->initStatic( dds );
  911. cubemap->_setPath( path.getFullPath() );
  912. // Store the cubemap into the cache.
  913. mCubemapTable.insertUnique( path.getFullPath(), cubemap );
  914. return cubemap;
  915. }
  916. void GFXTextureManager::releaseCubemap( GFXCubemap *cubemap )
  917. {
  918. if ( mTextureManagerState == GFXTextureManager::Dead )
  919. return;
  920. const String &path = cubemap->getPath();
  921. CubemapTable::Iterator iter = mCubemapTable.find( path );
  922. if ( iter != mCubemapTable.end() && iter->value == cubemap )
  923. mCubemapTable.erase( iter );
  924. // If we have a path for the texture then
  925. // remove change notifications for it.
  926. //Path texPath = texture->getPath();
  927. //if ( !texPath.isEmpty() )
  928. //FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  929. }
  930. void GFXTextureManager::_onFileChanged( const Torque::Path &path )
  931. {
  932. String pathNoExt = Torque::Path::Join( path.getRoot(), ':', path.getPath() );
  933. pathNoExt = Torque::Path::Join( pathNoExt, '/', path.getFileName() );
  934. // See if we've got it loaded.
  935. GFXTextureObject *obj = hashFind( pathNoExt );
  936. if ( !obj || path != obj->getPath() )
  937. return;
  938. Con::errorf( "[GFXTextureManager::_onFileChanged] : File changed [%s]", path.getFullPath().c_str() );
  939. const U32 scalePower = getTextureDownscalePower( obj->mProfile );
  940. if ( sDDSExt.equal( path.getExtension(), String::NoCase) )
  941. {
  942. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  943. if ( dds )
  944. _createTexture( dds, obj->mProfile, false, obj );
  945. }
  946. else
  947. {
  948. Resource<GBitmap> bmp = GBitmap::load( path );
  949. if( bmp )
  950. _createTexture( bmp, obj->mTextureLookupName, obj->mProfile, false, obj );
  951. }
  952. }
  953. void GFXTextureManager::reloadTextures()
  954. {
  955. GFXTextureObject *tex = mListHead;
  956. while ( tex != NULL )
  957. {
  958. const Torque::Path path( tex->mPath );
  959. if ( !path.isEmpty() )
  960. {
  961. const U32 scalePower = getTextureDownscalePower( tex->mProfile );
  962. if ( sDDSExt.equal( path.getExtension(), String::NoCase ) )
  963. {
  964. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  965. if ( dds )
  966. _createTexture( dds, tex->mProfile, false, tex );
  967. }
  968. else
  969. {
  970. Resource<GBitmap> bmp = GBitmap::load( path );
  971. if( bmp )
  972. _createTexture( bmp, tex->mTextureLookupName, tex->mProfile, false, tex );
  973. }
  974. }
  975. tex = tex->mNext;
  976. }
  977. }
  978. DefineEngineFunction( flushTextureCache, void, (),,
  979. "Releases all textures and resurrects the texture manager.\n"
  980. "@ingroup GFX\n" )
  981. {
  982. if ( !GFX || !TEXMGR )
  983. return;
  984. TEXMGR->zombify();
  985. TEXMGR->resurrect();
  986. }
  987. DefineEngineFunction( cleanupTexturePool, void, (),,
  988. "Release the unused pooled textures in texture manager freeing up video memory.\n"
  989. "@ingroup GFX\n" )
  990. {
  991. if ( !GFX || !TEXMGR )
  992. return;
  993. TEXMGR->cleanupPool();
  994. }
  995. DefineEngineFunction( reloadTextures, void, (),,
  996. "Reload all the textures from disk.\n"
  997. "@ingroup GFX\n" )
  998. {
  999. if ( !GFX || !TEXMGR )
  1000. return;
  1001. TEXMGR->reloadTextures();
  1002. }