gfxTextureManager.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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/imageUtils.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. #include "renderInstance/renderProbeMgr.h"
  36. using namespace Torque;
  37. //#define DEBUG_SPEW
  38. S32 GFXTextureManager::smTextureReductionLevel = 0;
  39. String GFXTextureManager::smMissingTexturePath(Con::getVariable("$Core::MissingTexturePath"));
  40. String GFXTextureManager::smUnavailableTexturePath(Con::getVariable("$Core::UnAvailableTexturePath"));
  41. String GFXTextureManager::smWarningTexturePath(Con::getVariable("$Core::WarningTexturePath"));
  42. String GFXTextureManager::smDefaultIrradianceCubemapPath(Con::getVariable("$Core::DefaultIrradianceCubemap"));
  43. String GFXTextureManager::smDefaultPrefilterCubemapPath(Con::getVariable("$Core::DefaultPrefilterCubemap"));
  44. String GFXTextureManager::smBRDFTexturePath(Con::getVariable("$Core::BRDFTexture"));
  45. GFXTextureManager::EventSignal GFXTextureManager::smEventSignal;
  46. static const String sDDSExt( "dds" );
  47. void GFXTextureManager::init()
  48. {
  49. Con::addVariable( "$pref::Video::textureReductionLevel", TypeS32, &smTextureReductionLevel,
  50. "The number of mipmap levels to drop on loaded textures to reduce "
  51. "video memory usage. It will skip any textures that have been defined "
  52. "as not allowing down scaling.\n"
  53. "@ingroup GFX\n" );
  54. Con::addVariable( "$pref::Video::missingTexturePath", TypeRealString, &smMissingTexturePath,
  55. "The file path of the texture to display when the requested texture is missing.\n"
  56. "@ingroup GFX\n" );
  57. Con::addVariable( "$pref::Video::unavailableTexturePath", TypeRealString, &smUnavailableTexturePath,
  58. "@brief The file path of the texture to display when the requested texture is unavailable.\n\n"
  59. "Often this texture is used by GUI controls to indicate that the request image is unavailable.\n"
  60. "@ingroup GFX\n" );
  61. Con::addVariable( "$pref::Video::warningTexturePath", TypeRealString, &smWarningTexturePath,
  62. "The file path of the texture used to warn the developer.\n"
  63. "@ingroup GFX\n" );
  64. Con::addVariable("$Core::DefaultIrradianceCubemap", TypeRealString, &smDefaultIrradianceCubemapPath,
  65. "The file path of the texture used as the default irradiance cubemap for PBR.\n"
  66. "@ingroup GFX\n");
  67. Con::addVariable("$Core::DefaultPrefilterCubemap", TypeRealString, &smDefaultPrefilterCubemapPath,
  68. "The file path of the texture used as the default specular cubemap for PBR.\n"
  69. "@ingroup GFX\n");
  70. Con::addVariable("$Core::BRDFTexture", TypeRealString, &smBRDFTexturePath,
  71. "The file path of the texture used as the default irradiance cubemap for PBR.\n"
  72. "@ingroup GFX\n");
  73. }
  74. GFXTextureManager::GFXTextureManager()
  75. {
  76. mListHead = mListTail = NULL;
  77. mTextureManagerState = GFXTextureManager::Living;
  78. // Set up the hash table
  79. mHashCount = 1023;
  80. mHashTable = new GFXTextureObject *[mHashCount];
  81. for(U32 i = 0; i < mHashCount; i++)
  82. mHashTable[i] = NULL;
  83. }
  84. GFXTextureManager::~GFXTextureManager()
  85. {
  86. if( mHashTable )
  87. SAFE_DELETE_ARRAY( mHashTable );
  88. mCubemapTable.clear();
  89. }
  90. U32 GFXTextureManager::getTextureDownscalePower( GFXTextureProfile *profile )
  91. {
  92. if ( !profile || profile->canDownscale() )
  93. return smTextureReductionLevel;
  94. return 0;
  95. }
  96. bool GFXTextureManager::validateTextureQuality( GFXTextureProfile *profile, U32 &width, U32 &height )
  97. {
  98. U32 scaleFactor = getTextureDownscalePower( profile );
  99. if ( scaleFactor == 0 )
  100. return true;
  101. // Otherwise apply the appropriate scale...
  102. width >>= scaleFactor;
  103. height >>= scaleFactor;
  104. return true;
  105. }
  106. void GFXTextureManager::kill()
  107. {
  108. AssertFatal( mTextureManagerState != GFXTextureManager::Dead, "Texture Manager already killed!" );
  109. // Release everything in the cache we can
  110. // so we don't leak any textures.
  111. cleanupCache();
  112. GFXTextureObject *curr = mListHead;
  113. GFXTextureObject *temp;
  114. // Actually delete all the textures we know about.
  115. while( curr != NULL )
  116. {
  117. temp = curr->mNext;
  118. curr->kill();
  119. curr = temp;
  120. }
  121. mCubemapTable.clear();
  122. mTextureManagerState = GFXTextureManager::Dead;
  123. }
  124. void GFXTextureManager::zombify()
  125. {
  126. AssertFatal( mTextureManagerState != GFXTextureManager::Zombie, "Texture Manager already a zombie!" );
  127. // Notify everyone that cares about the zombification!
  128. smEventSignal.trigger( GFXZombify );
  129. // Release unused pool textures.
  130. cleanupPool();
  131. // Release everything in the cache we can.
  132. cleanupCache();
  133. // Free all the device copies of the textures.
  134. GFXTextureObject *temp = mListHead;
  135. while( temp != NULL )
  136. {
  137. freeTexture( temp, true );
  138. temp = temp->mNext;
  139. }
  140. // Finally, note our state.
  141. mTextureManagerState = GFXTextureManager::Zombie;
  142. }
  143. void GFXTextureManager::resurrect()
  144. {
  145. // Reupload all the device copies of the textures.
  146. GFXTextureObject *temp = mListHead;
  147. while( temp != NULL )
  148. {
  149. refreshTexture( temp );
  150. temp = temp->mNext;
  151. }
  152. // Notify callback registries.
  153. smEventSignal.trigger( GFXResurrect );
  154. // Update our state.
  155. mTextureManagerState = GFXTextureManager::Living;
  156. }
  157. void GFXTextureManager::cleanupPool()
  158. {
  159. PROFILE_SCOPE( GFXTextureManager_CleanupPool );
  160. TexturePoolMap::Iterator iter = mTexturePool.begin();
  161. for ( ; iter != mTexturePool.end(); )
  162. {
  163. if ( iter->value->getRefCount() == 1 )
  164. {
  165. // This texture is unreferenced, so take the time
  166. // now to completely remove it from the pool.
  167. TexturePoolMap::Iterator unref = iter;
  168. ++iter;
  169. unref->value = NULL;
  170. mTexturePool.erase( unref );
  171. continue;
  172. }
  173. ++iter;
  174. }
  175. }
  176. void GFXTextureManager::requestDeleteTexture( GFXTextureObject *texture )
  177. {
  178. // If this is a non-cached texture then just really delete it.
  179. if ( texture->mTextureLookupName.isEmpty() )
  180. {
  181. delete texture;
  182. return;
  183. }
  184. // Set the time and store it.
  185. texture->mDeleteTime = Platform::getTime();
  186. mToDelete.push_back_unique( texture );
  187. }
  188. void GFXTextureManager::cleanupCache( U32 secondsToLive )
  189. {
  190. PROFILE_SCOPE( GFXTextureManager_CleanupCache );
  191. U32 killTime = Platform::getTime() - secondsToLive;
  192. for ( U32 i=0; i < mToDelete.size(); )
  193. {
  194. GFXTextureObject *tex = mToDelete[i];
  195. // If the texture was picked back up by a user
  196. // then just remove it from the list.
  197. if ( tex->getRefCount() != 0 )
  198. {
  199. mToDelete.erase_fast( i );
  200. continue;
  201. }
  202. // If its time has expired delete it for real.
  203. if ( tex->mDeleteTime <= killTime )
  204. {
  205. //Con::errorf( "Killed texture: %s", tex->mTextureLookupName.c_str() );
  206. delete tex;
  207. mToDelete.erase_fast( i );
  208. continue;
  209. }
  210. i++;
  211. }
  212. }
  213. GFXTextureObject *GFXTextureManager::_lookupTexture( const char *hashName, const GFXTextureProfile *profile )
  214. {
  215. GFXTextureObject *ret = hashFind( hashName );
  216. //compare just the profile flags and not the entire profile, names could be different but otherwise identical flags
  217. if (ret && (ret->mProfile->compareFlags(*profile)))
  218. return ret;
  219. else if (ret)
  220. Con::warnf("GFXTextureManager::_lookupTexture: Cached texture %s has different profile flags: (%s,%s) ", hashName, ret->mProfile->getName().c_str(), profile->getName().c_str());
  221. return NULL;
  222. }
  223. GFXTextureObject *GFXTextureManager::_lookupTexture( const DDSFile *ddsFile, const GFXTextureProfile *profile )
  224. {
  225. if( ddsFile->getTextureCacheString().isNotEmpty() )
  226. {
  227. // Call _lookupTexture()
  228. return _lookupTexture( ddsFile->getTextureCacheString(), profile );
  229. }
  230. return NULL;
  231. }
  232. GFXTextureObject *GFXTextureManager::createTexture( GBitmap *bmp, const String &resourceName, GFXTextureProfile *profile, bool deleteBmp )
  233. {
  234. AssertFatal(bmp, "GFXTextureManager::createTexture() - Got NULL bitmap!");
  235. GFXTextureObject *cacheHit = _lookupTexture( resourceName, profile );
  236. if( cacheHit != NULL)
  237. {
  238. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  239. if (deleteBmp)
  240. delete bmp;
  241. return cacheHit;
  242. }
  243. return _createTexture( bmp, resourceName, profile, deleteBmp, NULL );
  244. }
  245. GFXTextureObject *GFXTextureManager::_createTexture( GBitmap *bmp,
  246. const String &resourceName,
  247. GFXTextureProfile *profile,
  248. bool deleteBmp,
  249. GFXTextureObject *inObj )
  250. {
  251. PROFILE_SCOPE( GFXTextureManager_CreateTexture_Bitmap );
  252. #ifdef DEBUG_SPEW
  253. Platform::outputDebugString( "[GFXTextureManager] _createTexture (GBitmap) '%s'",
  254. resourceName.c_str()
  255. );
  256. #endif
  257. // Massage the bitmap based on any resize rules.
  258. U32 scalePower = getTextureDownscalePower( profile );
  259. GBitmap *realBmp = bmp;
  260. U32 realWidth = bmp->getWidth();
  261. U32 realHeight = bmp->getHeight();
  262. if ( scalePower &&
  263. isPow2(bmp->getWidth()) &&
  264. isPow2(bmp->getHeight()) &&
  265. profile->canDownscale() )
  266. {
  267. // We only work with power of 2 textures for now, so we
  268. // don't have to worry about padding.
  269. // We downscale the bitmap on the CPU... this is the reason
  270. // you should be using DDS which already has good looking mips.
  271. GBitmap *padBmp = bmp;
  272. padBmp->extrudeMipLevels();
  273. scalePower = getMin( scalePower, padBmp->getNumMipLevels() - 1 );
  274. realWidth = getMax( (U32)1, padBmp->getWidth() >> scalePower );
  275. realHeight = getMax( (U32)1, padBmp->getHeight() >> scalePower );
  276. realBmp = new GBitmap( realWidth, realHeight, false, bmp->getFormat() );
  277. // Copy to the new bitmap...
  278. dMemcpy( realBmp->getWritableBits(),
  279. padBmp->getBits(scalePower),
  280. padBmp->getBytesPerPixel() * realWidth * realHeight );
  281. // This line is commented out because createPaddedBitmap is commented out.
  282. // If that line is added back in, this line should be added back in.
  283. // delete padBmp;
  284. }
  285. // Call the internal create... (use the real* variables now, as they
  286. // reflect the reality of the texture we are creating.)
  287. U32 numMips = 0;
  288. GFXFormat realFmt = realBmp->getFormat();
  289. _validateTexParams( realWidth, realHeight, profile, numMips, realFmt );
  290. GFXTextureObject *ret;
  291. if ( inObj )
  292. {
  293. // If the texture has changed in dimensions
  294. // then we need to recreate it.
  295. if ( inObj->getWidth() != realWidth ||
  296. inObj->getHeight() != realHeight ||
  297. inObj->getFormat() != realFmt )
  298. ret = _createTextureObject( realHeight, realWidth, 0, realFmt, profile, numMips, false, 0, inObj );
  299. else
  300. ret = inObj;
  301. }
  302. else
  303. ret = _createTextureObject(realHeight, realWidth, 0, realFmt, profile, numMips );
  304. if(!ret)
  305. {
  306. SAFE_DELETE(realBmp);
  307. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  308. return NULL;
  309. }
  310. // Extrude mip levels
  311. // Don't do this for fonts!
  312. if( ret->mMipLevels > 1 && ( realBmp->getNumMipLevels() == 1 ) && ( realBmp->getFormat() != GFXFormatA8 ) &&
  313. isPow2( realBmp->getHeight() ) && isPow2( realBmp->getWidth() ) && !profile->noMip() )
  314. {
  315. // NOTE: This should really be done by extruding mips INTO a DDS file instead
  316. // of modifying the gbitmap
  317. realBmp->extrudeMipLevels(false);
  318. }
  319. // If _validateTexParams kicked back a different format, than there needs to be
  320. // a conversion unless it's a sRGB format
  321. DDSFile *bmpDDS = NULL;
  322. if( realBmp->getFormat() != realFmt && !profile->isSRGB() )
  323. {
  324. const GFXFormat oldFmt = realBmp->getFormat();
  325. // TODO: Set it up so that ALL format conversions use DDSFile. Rip format
  326. // switching out of GBitmap entirely.
  327. if( !realBmp->setFormat( realFmt ) )
  328. {
  329. // This is not the ideal implementation...
  330. bmpDDS = DDSFile::createDDSFileFromGBitmap( realBmp );
  331. bool convSuccess = false;
  332. if( bmpDDS != NULL )
  333. {
  334. // This shouldn't live here, I don't think
  335. switch( realFmt )
  336. {
  337. case GFXFormatBC1:
  338. case GFXFormatBC2:
  339. case GFXFormatBC3:
  340. // If this is a Normal Map profile, than the data needs to be conditioned
  341. // to use the swizzle trick
  342. if( ret->mProfile->getType() == GFXTextureProfile::NormalMap )
  343. {
  344. PROFILE_START(DXT_DXTNMSwizzle);
  345. static DXT5nmSwizzle sDXT5nmSwizzle;
  346. ImageUtil::swizzleDDS( bmpDDS, sDXT5nmSwizzle );
  347. PROFILE_END();
  348. }
  349. convSuccess = ImageUtil::ddsCompress( bmpDDS, realFmt );
  350. break;
  351. default:
  352. AssertFatal(false, "Attempting to convert to a non-DXT format");
  353. break;
  354. }
  355. }
  356. if( !convSuccess )
  357. {
  358. Con::errorf( "[GFXTextureManager]: Failed to change source format from %s to %s. Cannot create texture.",
  359. GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  360. delete bmpDDS;
  361. return NULL;
  362. }
  363. }
  364. #ifdef TORQUE_DEBUG
  365. else
  366. {
  367. //Con::warnf( "[GFXTextureManager]: Changed bitmap format from %s to %s.",
  368. // GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  369. }
  370. #endif
  371. }
  372. // Call the internal load...
  373. if( ( bmpDDS == NULL && !_loadTexture( ret, realBmp ) ) || // If we aren't doing a DDS format change, use bitmap load
  374. ( bmpDDS != NULL && !_loadTexture( ret, bmpDDS ) ) ) // If there is a DDS, than load that instead. A format change took place.
  375. {
  376. Con::errorf("GFXTextureManager - failed to load GBitmap for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  377. return NULL;
  378. }
  379. // Do statistics and book-keeping...
  380. // - info for the texture...
  381. ret->mTextureLookupName = resourceName;
  382. ret->mBitmapSize.set(realWidth, realHeight,0);
  383. #ifdef TORQUE_DEBUG
  384. if (resourceName.isNotEmpty())
  385. ret->mDebugDescription = resourceName;
  386. else
  387. ret->mDebugDescription = "Anonymous Texture Object";
  388. #endif
  389. if(profile->doStoreBitmap())
  390. {
  391. // NOTE: may store a downscaled copy!
  392. SAFE_DELETE( ret->mBitmap );
  393. SAFE_DELETE( ret->mDDS );
  394. if( bmpDDS == NULL )
  395. ret->mBitmap = new GBitmap( *realBmp );
  396. else
  397. ret->mDDS = bmpDDS;
  398. }
  399. else
  400. {
  401. // Delete the DDS if we made one
  402. SAFE_DELETE( bmpDDS );
  403. }
  404. if ( !inObj )
  405. _linkTexture( ret );
  406. // - output debug info?
  407. // Save texture for debug purpose
  408. // static int texId = 0;
  409. // char buff[256];
  410. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  411. // bmp->writePNGDebug(buff);
  412. // texId++;
  413. // Before we delete the bitmap save our transparency flag
  414. ret->mHasTransparency = realBmp->getHasTransparency();
  415. // Some final cleanup...
  416. if(realBmp != bmp)
  417. SAFE_DELETE(realBmp);
  418. if (deleteBmp)
  419. SAFE_DELETE(bmp);
  420. // Return the new texture!
  421. return ret;
  422. }
  423. GFXTextureObject *GFXTextureManager::createTexture( DDSFile *dds, GFXTextureProfile *profile, bool deleteDDS )
  424. {
  425. AssertFatal(dds, "GFXTextureManager::createTexture() - Got NULL dds!");
  426. // Check the cache first...
  427. GFXTextureObject *cacheHit = _lookupTexture( dds, profile );
  428. if ( cacheHit )
  429. {
  430. // Con::errorf("Cached texture '%s'", (fileName.isNotEmpty() ? fileName.c_str() : "unknown"));
  431. if( deleteDDS )
  432. delete dds;
  433. return cacheHit;
  434. }
  435. return _createTexture( dds, profile, deleteDDS, NULL );
  436. }
  437. GFXTextureObject *GFXTextureManager::_createTexture( DDSFile *dds,
  438. GFXTextureProfile *profile,
  439. bool deleteDDS,
  440. GFXTextureObject *inObj )
  441. {
  442. PROFILE_SCOPE( GFXTextureManager_CreateTexture_DDS );
  443. const char *fileName = dds->getTextureCacheString();
  444. if( !fileName )
  445. fileName = "unknown";
  446. #ifdef DEBUG_SPEW
  447. Platform::outputDebugString( "[GFXTextureManager] _createTexture (DDS) '%s'",
  448. fileName
  449. );
  450. #endif
  451. // Ignore padding from the profile.
  452. U32 numMips = dds->mMipMapCount;
  453. GFXFormat fmt = dds->mFormat;
  454. _validateTexParams( dds->getHeight(), dds->getWidth(), profile, numMips, fmt );
  455. if( fmt != dds->mFormat && !profile->isSRGB())
  456. {
  457. Con::errorf( "GFXTextureManager - failed to validate texture parameters for DDS file '%s'", fileName );
  458. return NULL;
  459. }
  460. // Call the internal create... (use the real* variables now, as they
  461. // reflect the reality of the texture we are creating.)
  462. GFXTextureObject *ret;
  463. if ( inObj )
  464. {
  465. // If the texture has changed in dimensions
  466. // then we need to recreate it.
  467. if ( inObj->getWidth() != dds->getWidth() ||
  468. inObj->getHeight() != dds->getHeight() ||
  469. inObj->getFormat() != fmt ||
  470. inObj->getMipLevels() != numMips )
  471. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  472. fmt, profile, numMips,
  473. true, 0, inObj );
  474. else
  475. ret = inObj;
  476. }
  477. else
  478. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  479. fmt, profile, numMips, true );
  480. if(!ret)
  481. {
  482. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s' DDSFile.", fileName);
  483. return NULL;
  484. }
  485. // Call the internal load...
  486. if(!_loadTexture(ret, dds))
  487. {
  488. Con::errorf("GFXTextureManager - failed to load DDS for '%s'", fileName);
  489. return NULL;
  490. }
  491. // Do statistics and book-keeping...
  492. // - info for the texture...
  493. ret->mTextureLookupName = dds->getTextureCacheString();
  494. ret->mBitmapSize.set( dds->mWidth, dds->mHeight, 0 );
  495. #ifdef TORQUE_DEBUG
  496. ret->mDebugDescription = fileName;
  497. #endif
  498. if(profile->doStoreBitmap())
  499. {
  500. // NOTE: may store a downscaled copy!
  501. SAFE_DELETE( ret->mBitmap );
  502. SAFE_DELETE( ret->mDDS );
  503. ret->mDDS = new DDSFile( *dds );
  504. }
  505. if ( !inObj )
  506. _linkTexture( ret );
  507. // - output debug info?
  508. // Save texture for debug purpose
  509. // static int texId = 0;
  510. // char buff[256];
  511. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  512. // bmp->writePNGDebug(buff);
  513. // texId++;
  514. // Save our transparency flag
  515. ret->mHasTransparency = dds->getHasTransparency();
  516. if( deleteDDS )
  517. delete dds;
  518. // Return the new texture!
  519. return ret;
  520. }
  521. GFXTextureObject *GFXTextureManager::createTexture( const Torque::Path &path, GFXTextureProfile *profile )
  522. {
  523. PROFILE_SCOPE( GFXTextureManager_createTexture );
  524. // Resource handles used for loading. Hold on to them
  525. // throughout this function so that change notifications
  526. // don't get added, then removed, and then re-added.
  527. Resource< DDSFile > dds;
  528. Resource< GBitmap > bitmap;
  529. // We need to handle path's that have had "incorrect"
  530. // extensions parsed out of the file name
  531. Torque::Path correctPath = validatePath(path);
  532. // Check the cache first...
  533. String pathNoExt = Torque::Path::Join( correctPath.getRoot(), ':', correctPath.getPath() );
  534. pathNoExt = Torque::Path::Join( pathNoExt, '/', correctPath.getFileName() );
  535. GFXTextureObject *retTexObj = _lookupTexture( pathNoExt, profile );
  536. if( retTexObj )
  537. return retTexObj;
  538. const U32 scalePower = getTextureDownscalePower( profile );
  539. // If this is a valid file (has an extension) than load it
  540. Path realPath;
  541. if( Torque::FS::IsFile( correctPath ) )
  542. {
  543. // Check for DDS
  544. if( sDDSExt.equal(correctPath.getExtension(), String::NoCase ) )
  545. {
  546. dds = DDSFile::load( correctPath, scalePower );
  547. if( dds != NULL )
  548. {
  549. realPath = dds.getPath();
  550. retTexObj = createTexture( dds, profile, false );
  551. }
  552. }
  553. else // Let GBitmap take care of it
  554. {
  555. bitmap = GBitmap::load( correctPath );
  556. if( bitmap != NULL )
  557. {
  558. realPath = bitmap.getPath();
  559. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  560. }
  561. }
  562. }
  563. else
  564. {
  565. // NOTE -- We should probably remove the code from GBitmap that tries different
  566. // extensions for things GBitmap loads, and move it here. I think it should
  567. // be a bit more involved than just a list of extensions. Some kind of
  568. // extension registration thing, maybe.
  569. // Check to see if there is a .DDS file with this name (if no extension is provided)
  570. Torque::Path tryDDSPath = pathNoExt;
  571. if( tryDDSPath.getExtension().isNotEmpty() )
  572. tryDDSPath.setFileName( tryDDSPath.getFullFileName() );
  573. tryDDSPath.setExtension( sDDSExt );
  574. if( Torque::FS::IsFile( tryDDSPath ) )
  575. {
  576. dds = DDSFile::load( tryDDSPath, scalePower );
  577. if( dds != NULL )
  578. {
  579. realPath = dds.getPath();
  580. retTexObj = createTexture( dds, profile, false );
  581. }
  582. }
  583. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  584. // load.
  585. }
  586. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  587. // it will try a bunch of extensions
  588. if( retTexObj == NULL )
  589. {
  590. // Find and load the texture.
  591. bitmap = GBitmap::load( correctPath );
  592. if ( bitmap != NULL )
  593. {
  594. realPath = bitmap.getPath();
  595. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  596. }
  597. }
  598. if ( retTexObj )
  599. {
  600. // Store the path for later use.
  601. retTexObj->mPath = realPath;
  602. // Register the texture file for change notifications.
  603. FS::AddChangeNotification( retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged );
  604. }
  605. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  606. return retTexObj;
  607. }
  608. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, void *pixels, GFXFormat format, GFXTextureProfile *profile )
  609. {
  610. // For now, stuff everything into a GBitmap and pass it off... This may need to be revisited -- BJG
  611. GBitmap *bmp = new GBitmap(width, height, 0, format);
  612. dMemcpy(bmp->getWritableBits(), pixels, width * height * bmp->getBytesPerPixel());
  613. return createTexture( bmp, String::EmptyString, profile, true );
  614. }
  615. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, S32 antialiasLevel )
  616. {
  617. // Deal with sizing issues...
  618. U32 localWidth = width;
  619. U32 localHeight = height;
  620. // TODO: Format check HERE! -patw
  621. validateTextureQuality(profile, localWidth, localHeight);
  622. U32 numMips = numMipLevels;
  623. GFXFormat checkFmt = format;
  624. _validateTexParams( localWidth, localHeight, profile, numMips, checkFmt );
  625. //check to see if we've handled the mips just now, and if not, then handle them here
  626. if (numMips == numMipLevels && (localWidth != width || localHeight != height))
  627. {
  628. numMips = mFloor(mLog2(mMax(localWidth, localHeight))) + 1;
  629. }
  630. // AssertFatal( checkFmt == format, "Anonymous texture didn't get the format it wanted." );
  631. GFXTextureObject *outTex = NULL;
  632. // If this is a pooled profile then look there first.
  633. if ( profile->isPooled() )
  634. {
  635. outTex = _findPooledTexure( localWidth, localHeight, checkFmt,
  636. profile, numMips, antialiasLevel );
  637. // If we got a pooled texture then its
  638. // already setup... just return it.
  639. if ( outTex )
  640. return outTex;
  641. }
  642. // Create the texture if we didn't get one from the pool.
  643. if ( !outTex )
  644. {
  645. outTex = _createTextureObject( localHeight, localWidth, 0, format, profile, numMips, false, antialiasLevel );
  646. // Make sure we add it to the pool.
  647. if ( outTex && profile->isPooled() )
  648. mTexturePool.insertEqual( profile, outTex );
  649. }
  650. if ( !outTex )
  651. {
  652. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  653. return NULL;
  654. }
  655. // And do book-keeping...
  656. // - texture info
  657. outTex->mBitmapSize.set(localWidth, localHeight, 0);
  658. outTex->mAntialiasLevel = antialiasLevel;
  659. // PWTODO: Need to assign this a lookup name before _linkTexture() is called
  660. // otherwise it won't get a hash insert call
  661. _linkTexture( outTex );
  662. return outTex;
  663. }
  664. GFXTextureObject *GFXTextureManager::createTexture( U32 width,
  665. U32 height,
  666. U32 depth,
  667. GFXFormat format,
  668. GFXTextureProfile *profile,
  669. U32 numMipLevels)
  670. {
  671. PROFILE_SCOPE( GFXTextureManager_CreateTexture_3D );
  672. // Create texture...
  673. GFXTextureObject *ret = _createTextureObject( height, width, depth, format, profile, numMipLevels );
  674. if(!ret)
  675. {
  676. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  677. return NULL;
  678. }
  679. // And do book-keeping...
  680. // - texture info
  681. ret->mBitmapSize.set( width, height, depth );
  682. _linkTexture( ret );
  683. // Return the new texture!
  684. return ret;
  685. }
  686. Torque::Path GFXTextureManager::validatePath(const Torque::Path &path)
  687. {
  688. // We need to handle path's that have had "incorrect"
  689. // extensions parsed out of the file name
  690. Torque::Path correctPath = path;
  691. bool textureExt = false;
  692. // Easiest case to handle is when there isn't an extension
  693. if (path.getExtension().isEmpty())
  694. textureExt = true;
  695. // Since "dds" isn't registered with GBitmap currently we
  696. // have to test it separately
  697. if (sDDSExt.equal(path.getExtension(), String::NoCase))
  698. textureExt = true;
  699. // Now loop through the rest of the GBitmap extensions
  700. // to see if we have any matches
  701. for (U32 i = 0; i < GBitmap::sRegistrations.size(); i++)
  702. {
  703. // If we have gotten a match (either in this loop or before)
  704. // then we can exit
  705. if (textureExt)
  706. break;
  707. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  708. const Vector<String> &extensions = reg.extensions;
  709. for (U32 j = 0; j < extensions.size(); ++j)
  710. {
  711. if (extensions[j].equal(path.getExtension(), String::NoCase))
  712. {
  713. // Found a valid texture extension
  714. textureExt = true;
  715. break;
  716. }
  717. }
  718. }
  719. // If we didn't find a valid texture extension then assume that
  720. // the parsed out "extension" was actually intended to be part of
  721. // the texture name so add it back
  722. if (!textureExt)
  723. {
  724. correctPath.setFileName(Torque::Path::Join(path.getFileName(), '.', path.getExtension()));
  725. correctPath.setExtension(String::EmptyString);
  726. }
  727. return correctPath;
  728. }
  729. GBitmap *GFXTextureManager::loadUncompressedTexture(const Torque::Path &path, GFXTextureProfile *profile, U32 width, U32 height, bool genMips)
  730. {
  731. GBitmap* inBitmap = loadUncompressedTexture(path, &GFXTexturePersistentProfile);
  732. if (inBitmap == NULL)
  733. {
  734. Con::warnf("GFXTextureManager::loadUncompressedTexture unable to load texture: %s", path.getFullPath().c_str());
  735. return NULL;
  736. }
  737. // Set the format so we don't have to handle which channels are where.
  738. if (!inBitmap->setFormat(GFXFormatR8G8B8A8))
  739. {
  740. Con::warnf("GFXTextureManager::loadUncompressedTexture unable to handle texture format: %s", path.getFullPath().c_str());
  741. return NULL;
  742. }
  743. GBitmap* outBmp = new GBitmap(width, height, true, GFXFormatR8G8B8A8);
  744. U8* oBits = (U8*)outBmp->getWritableBits();
  745. for (S32 y = 0; y < width; y++)
  746. {
  747. for (S32 x = 0; x < height; x++)
  748. {
  749. ColorI texelColor = inBitmap->sampleTexel(x / F32(width), y / F32(height), true).toColorI(true);
  750. oBits[(y * width + x) * 4] = texelColor.red;
  751. oBits[(y * width + x) * 4 + 1] = texelColor.green;
  752. oBits[(y * width + x) * 4 + 2] = texelColor.blue;
  753. oBits[(y * width + x) * 4 + 3] = texelColor.alpha;
  754. }
  755. }
  756. if (genMips)
  757. outBmp->extrudeMipLevels();
  758. return outBmp;
  759. }
  760. GBitmap *GFXTextureManager::loadUncompressedTexture(const Torque::Path &path, GFXTextureProfile *profile)
  761. {
  762. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture);
  763. GBitmap *retBitmap = NULL;
  764. // Resource handles used for loading. Hold on to them
  765. // throughout this function so that change notifications
  766. // don't get added, then removed, and then re-added.
  767. Resource< DDSFile > dds;
  768. Resource< GBitmap > bitmap;
  769. // We need to handle path's that have had "incorrect"
  770. // extensions parsed out of the file name
  771. Torque::Path correctPath = validatePath(path);
  772. U32 scalePower = profile ? getTextureDownscalePower(profile) : 0;
  773. // Check the cache first...
  774. String pathNoExt = Torque::Path::Join(correctPath.getRoot(), ':', correctPath.getPath());
  775. pathNoExt = Torque::Path::Join(pathNoExt, '/', correctPath.getFileName());
  776. // If this is a valid file (has an extension) than load it
  777. Path realPath;
  778. if (Torque::FS::IsFile(correctPath))
  779. {
  780. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER1)
  781. // Check for DDS
  782. if (sDDSExt.equal(correctPath.getExtension(), String::NoCase))
  783. {
  784. dds = DDSFile::load(correctPath, scalePower);
  785. if (dds != NULL)
  786. {
  787. realPath = dds.getPath();
  788. retBitmap = new GBitmap();
  789. if (!dds->decompressToGBitmap(retBitmap))
  790. {
  791. delete retBitmap;
  792. retBitmap = NULL;
  793. }
  794. }
  795. }
  796. else // Let GBitmap take care of it
  797. {
  798. bitmap = GBitmap::load(correctPath);
  799. if (bitmap != NULL)
  800. {
  801. realPath = bitmap.getPath();
  802. retBitmap = new GBitmap(*bitmap);
  803. if (scalePower &&
  804. isPow2(retBitmap->getWidth()) &&
  805. isPow2(retBitmap->getHeight()) &&
  806. profile->canDownscale())
  807. {
  808. retBitmap->extrudeMipLevels();
  809. retBitmap->chopTopMips(scalePower);
  810. }
  811. }
  812. }
  813. }
  814. else
  815. {
  816. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER2)
  817. // NOTE -- We should probably remove the code from GBitmap that tries different
  818. // extensions for things GBitmap loads, and move it here. I think it should
  819. // be a bit more involved than just a list of extensions. Some kind of
  820. // extension registration thing, maybe.
  821. // Check to see if there is a .DDS file with this name (if no extension is provided)
  822. Torque::Path tryDDSPath = pathNoExt;
  823. if (tryDDSPath.getExtension().isNotEmpty())
  824. tryDDSPath.setFileName(tryDDSPath.getFullFileName());
  825. tryDDSPath.setExtension(sDDSExt);
  826. if (Torque::FS::IsFile(tryDDSPath))
  827. {
  828. dds = DDSFile::load(tryDDSPath, scalePower);
  829. if (dds != NULL)
  830. {
  831. realPath = dds.getPath();
  832. // Decompress dds into the GBitmap
  833. retBitmap = new GBitmap();
  834. if (!dds->decompressToGBitmap(retBitmap))
  835. {
  836. delete retBitmap;
  837. retBitmap = NULL;
  838. }
  839. }
  840. }
  841. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  842. // load.
  843. }
  844. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  845. // it will try a bunch of extensions
  846. if (retBitmap == NULL)
  847. {
  848. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER3)
  849. // Find and load the texture.
  850. bitmap = GBitmap::load(correctPath);
  851. if (bitmap != NULL)
  852. {
  853. retBitmap = new GBitmap(*bitmap);
  854. if (scalePower &&
  855. isPow2(retBitmap->getWidth()) &&
  856. isPow2(retBitmap->getHeight()) &&
  857. profile->canDownscale())
  858. {
  859. retBitmap->extrudeMipLevels();
  860. retBitmap->chopTopMips(scalePower);
  861. }
  862. }
  863. }
  864. return retBitmap;
  865. }
  866. GFXTextureObject *GFXTextureManager::createCompositeTexture(const Torque::Path &pathR, const Torque::Path &pathG, const Torque::Path &pathB, const Torque::Path &pathA, U32 inputKey[4],
  867. GFXTextureProfile *profile)
  868. {
  869. PROFILE_SCOPE(GFXTextureManager_createCompositeTexture);
  870. String inputKeyStr = String::ToString("%d%d%d%d", inputKey[0], inputKey[1], inputKey[2], inputKey[3]);
  871. String resourceTag = pathR.getFileName() + pathG.getFileName() + pathB.getFileName() + pathA.getFileName() + inputKeyStr; //associate texture object with a key combo
  872. GFXTextureObject *cacheHit = _lookupTexture(resourceTag, profile);
  873. if (cacheHit != NULL) return cacheHit;
  874. Torque::Path lastValidPath = "";
  875. GBitmap*bitmap[4];
  876. if (!pathR.isEmpty())
  877. {
  878. bitmap[0] = loadUncompressedTexture(pathR, profile);
  879. lastValidPath = pathR;
  880. }
  881. else
  882. bitmap[0] = NULL;
  883. if (!pathG.isEmpty())
  884. {
  885. bitmap[1] = loadUncompressedTexture(pathG, profile);
  886. lastValidPath = pathG;
  887. }
  888. else
  889. bitmap[1] = NULL;
  890. if (!pathB.isEmpty())
  891. {
  892. bitmap[2] = loadUncompressedTexture(pathB, profile);
  893. lastValidPath = pathB;
  894. }
  895. else
  896. bitmap[2] = NULL;
  897. if (!pathA.isEmpty())
  898. {
  899. bitmap[3] = loadUncompressedTexture(pathA, profile);
  900. lastValidPath = pathA;
  901. }
  902. else
  903. bitmap[3] = NULL;
  904. Path realPath;
  905. GFXTextureObject *retTexObj = NULL;
  906. realPath = validatePath(lastValidPath); //associate path with last valid channel texture in.
  907. retTexObj = createCompositeTexture(bitmap, inputKey, resourceTag, profile, false);
  908. if (retTexObj)
  909. {
  910. // Store the path for later use.
  911. retTexObj->mPath = resourceTag;
  912. // Register the texture file for change notifications.
  913. FS::AddChangeNotification(retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged);
  914. }
  915. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  916. for (U32 i = 0; i < 4; i++)
  917. {
  918. if (bitmap[i])
  919. {
  920. bitmap[i]->deleteImage();
  921. delete bitmap[i];
  922. }
  923. }
  924. return retTexObj;
  925. }
  926. void GFXTextureManager::saveCompositeTexture(const Torque::Path &pathR, const Torque::Path &pathG, const Torque::Path &pathB, const Torque::Path &pathA, U32 inputKey[4],
  927. const Torque::Path &saveAs,GFXTextureProfile *profile)
  928. {
  929. PROFILE_SCOPE(GFXTextureManager_saveCompositeTexture);
  930. String inputKeyStr = String::ToString("%d%d%d%d", inputKey[0], inputKey[1], inputKey[2], inputKey[3]);
  931. String resourceTag = pathR.getFileName() + pathG.getFileName() + pathB.getFileName() + pathA.getFileName() + inputKeyStr; //associate texture object with a key combo
  932. GFXTextureObject *cacheHit = _lookupTexture(resourceTag, profile);
  933. if (cacheHit != NULL)
  934. {
  935. cacheHit->dumpToDisk("png", saveAs.getFullPath());
  936. return;
  937. }
  938. Torque::Path lastValidPath = "";
  939. GBitmap* bitmap[4];
  940. if (!pathR.isEmpty())
  941. {
  942. bitmap[0] = loadUncompressedTexture(pathR, profile);
  943. lastValidPath = pathR;
  944. }
  945. else
  946. bitmap[0] = NULL;
  947. if (!pathG.isEmpty())
  948. {
  949. bitmap[1] = loadUncompressedTexture(pathG, profile);
  950. lastValidPath = pathG;
  951. }
  952. else
  953. bitmap[1] = NULL;
  954. if (!pathB.isEmpty())
  955. {
  956. bitmap[2] = loadUncompressedTexture(pathB, profile);
  957. lastValidPath = pathB;
  958. }
  959. else
  960. bitmap[2] = NULL;
  961. if (!pathA.isEmpty())
  962. {
  963. bitmap[3] = loadUncompressedTexture(pathA, profile);
  964. lastValidPath = pathA;
  965. }
  966. else
  967. bitmap[3] = NULL;
  968. Path realPath;
  969. GFXTextureObject *retTexObj = NULL;
  970. realPath = validatePath(lastValidPath); //associate path with last valid channel texture in.
  971. retTexObj = createCompositeTexture(bitmap, inputKey, resourceTag, profile, false);
  972. if (retTexObj != NULL)
  973. retTexObj->dumpToDisk("png", saveAs.getFullPath());
  974. return;
  975. }
  976. DefineEngineFunction(saveCompositeTexture, void, (const char* pathR, const char* pathG, const char* pathB, const char* pathA,
  977. const char * inputKeyString, const char* saveAs),
  978. ("", "", "", "", "", ""), "File1,file2,file3,file4,[chanels for r g b and a locations],saveAs")
  979. {
  980. U32 inputKey[4] = {0,0,0,0};
  981. if (String::compare(inputKeyString, "") != 0)
  982. {
  983. dSscanf(inputKeyString, "%i %i %i %i", &inputKey[0], &inputKey[1], &inputKey[2], &inputKey[3]);
  984. }
  985. GFX->getTextureManager()->saveCompositeTexture(pathR, pathG, pathB, pathA, inputKey, saveAs, &GFXTexturePersistentProfile);
  986. }
  987. GFXTextureObject *GFXTextureManager::createCompositeTexture(GBitmap*bmp[4], U32 inputKey[4],
  988. const String &resourceName, GFXTextureProfile *profile, bool deleteBmp)
  989. {
  990. S32 lastValidTex = -1;
  991. for (U32 i = 0; i < 4; i++)
  992. {
  993. if (bmp[i])
  994. lastValidTex = i;
  995. }
  996. if (lastValidTex == -1)
  997. {
  998. Con::errorf(ConsoleLogEntry::General, "GFXTextureManager::createCompositeTexture() - Got all NULL bitmaps!");
  999. return NULL;
  1000. }
  1001. GFXTextureObject* cacheHit = _lookupTexture(resourceName, profile);
  1002. if (cacheHit != NULL)
  1003. {
  1004. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  1005. return cacheHit;
  1006. }
  1007. U8 rChan, gChan, bChan, aChan;
  1008. GBitmap *outBitmap = new GBitmap();
  1009. outBitmap->allocateBitmap(bmp[lastValidTex]->getWidth(), bmp[lastValidTex]->getHeight(),false, GFXFormatR8G8B8A8);
  1010. //pack additional bitmaps into the origional
  1011. for (U32 x = 0; x < bmp[lastValidTex]->getWidth(); x++)
  1012. {
  1013. for (U32 y = 0; y < bmp[lastValidTex]->getHeight(); y++)
  1014. {
  1015. if (bmp[0])
  1016. rChan = bmp[0]->getChanelValueAt(x, y, inputKey[0]);
  1017. else
  1018. rChan = 255;
  1019. if (bmp[1])
  1020. gChan = bmp[1]->getChanelValueAt(x, y, inputKey[1]);
  1021. else
  1022. gChan = 255;
  1023. if (bmp[2])
  1024. bChan = bmp[2]->getChanelValueAt(x, y, inputKey[2]);
  1025. else
  1026. bChan = 255;
  1027. if (bmp[3])
  1028. aChan = bmp[3]->getChanelValueAt(x, y, inputKey[3]);
  1029. else
  1030. aChan = 255;
  1031. outBitmap->setColor(x, y, ColorI(rChan, gChan, bChan, aChan));
  1032. }
  1033. }
  1034. if (deleteBmp)
  1035. {
  1036. delete[] bmp;
  1037. }
  1038. GFXTextureObject * ret= _createTexture(outBitmap, resourceName, profile, deleteBmp, NULL);
  1039. delete outBitmap;
  1040. return ret;
  1041. }
  1042. GFXTextureObject* GFXTextureManager::_findPooledTexure( U32 width,
  1043. U32 height,
  1044. GFXFormat format,
  1045. GFXTextureProfile *profile,
  1046. U32 numMipLevels,
  1047. S32 antialiasLevel )
  1048. {
  1049. PROFILE_SCOPE( GFXTextureManager_FindPooledTexure );
  1050. GFXTextureObject *outTex;
  1051. // First see if we have a free one in the pool.
  1052. TexturePoolMap::Iterator iter = mTexturePool.find( profile );
  1053. for ( ; iter != mTexturePool.end() && iter->key == profile; iter++ )
  1054. {
  1055. outTex = iter->value;
  1056. // If the reference count is 1 then we're the only
  1057. // ones holding on to this texture and we can hand
  1058. // it out if the size matches... else its in use.
  1059. if ( outTex->getRefCount() != 1 )
  1060. continue;
  1061. // Check for a match... if so return it. The assignment
  1062. // to a GFXTexHandle will take care of incrementing the
  1063. // reference count and keeping it from being handed out
  1064. // to anyone else.
  1065. if ( outTex->getFormat() == format &&
  1066. outTex->getWidth() == width &&
  1067. outTex->getHeight() == height &&
  1068. outTex->getMipLevels() == numMipLevels &&
  1069. outTex->mAntialiasLevel == antialiasLevel )
  1070. return outTex;
  1071. }
  1072. return NULL;
  1073. }
  1074. void GFXTextureManager::hashInsert( GFXTextureObject *object )
  1075. {
  1076. if ( object->mTextureLookupName.isEmpty() )
  1077. return;
  1078. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  1079. object->mHashNext = mHashTable[key];
  1080. mHashTable[key] = object;
  1081. }
  1082. void GFXTextureManager::hashRemove( GFXTextureObject *object )
  1083. {
  1084. if ( object->mTextureLookupName.isEmpty() )
  1085. return;
  1086. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  1087. GFXTextureObject **walk = &mHashTable[key];
  1088. while(*walk)
  1089. {
  1090. if(*walk == object)
  1091. {
  1092. *walk = object->mHashNext;
  1093. break;
  1094. }
  1095. walk = &((*walk)->mHashNext);
  1096. }
  1097. }
  1098. GFXTextureObject* GFXTextureManager::hashFind( const String &name )
  1099. {
  1100. if ( name.isEmpty() )
  1101. return NULL;
  1102. U32 key = name.getHashCaseInsensitive() % mHashCount;
  1103. GFXTextureObject *walk = mHashTable[key];
  1104. for(; walk; walk = walk->mHashNext)
  1105. {
  1106. if( walk->mTextureLookupName.equal( name, String::NoCase ) )
  1107. break;
  1108. }
  1109. return walk;
  1110. }
  1111. void GFXTextureManager::freeTexture(GFXTextureObject *texture, bool zombify)
  1112. {
  1113. // Ok, let the backend deal with it.
  1114. _freeTexture(texture, zombify);
  1115. }
  1116. void GFXTextureManager::refreshTexture(GFXTextureObject *texture)
  1117. {
  1118. _refreshTexture(texture);
  1119. }
  1120. void GFXTextureManager::_linkTexture( GFXTextureObject *obj )
  1121. {
  1122. // info for the profile
  1123. GFXTextureProfile::updateStatsForCreation(obj);
  1124. // info for the cache
  1125. hashInsert(obj);
  1126. // info for the master list
  1127. if( mListHead == NULL )
  1128. mListHead = obj;
  1129. if( mListTail != NULL )
  1130. mListTail->mNext = obj;
  1131. obj->mPrev = mListTail;
  1132. mListTail = obj;
  1133. }
  1134. void GFXTextureManager::deleteTexture( GFXTextureObject *texture )
  1135. {
  1136. if ( mTextureManagerState == GFXTextureManager::Dead )
  1137. return;
  1138. #ifdef DEBUG_SPEW
  1139. Platform::outputDebugString( "[GFXTextureManager] deleteTexture '%s'",
  1140. texture->mTextureLookupName.c_str()
  1141. );
  1142. #endif
  1143. if( mListHead == texture )
  1144. mListHead = texture->mNext;
  1145. if( mListTail == texture )
  1146. mListTail = texture->mPrev;
  1147. hashRemove( texture );
  1148. // If we have a path for the texture then
  1149. // remove change notifications for it.
  1150. Path texPath = texture->getPath();
  1151. if ( !texPath.isEmpty() )
  1152. FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  1153. GFXTextureProfile::updateStatsForDeletion(texture);
  1154. freeTexture( texture );
  1155. }
  1156. void GFXTextureManager::_validateTexParams( const U32 width, const U32 height,
  1157. const GFXTextureProfile *profile,
  1158. U32 &inOutNumMips, GFXFormat &inOutFormat )
  1159. {
  1160. // Validate mipmap parameter. If this profile requests no mips, set mips to 1.
  1161. if( profile->noMip() )
  1162. {
  1163. inOutNumMips = 1;
  1164. }
  1165. else if( !isPow2( width ) || !isPow2( height ) )
  1166. {
  1167. // If a texture is not power-of-2 in size for both dimensions, it must
  1168. // have only 1 mip level.
  1169. inOutNumMips = 1;
  1170. }
  1171. // Check format, and compatibility with texture profile requirements
  1172. bool autoGenSupp = ( inOutNumMips == 0 );
  1173. // If the format is non-compressed, and the profile requests a compressed format
  1174. // than change the format.
  1175. GFXFormat testingFormat = inOutFormat;
  1176. if( profile->getCompression() != GFXTextureProfile::NONE )
  1177. {
  1178. const S32 offset = profile->getCompression() - GFXTextureProfile::BC1;
  1179. testingFormat = GFXFormat( GFXFormatBC1 + offset );
  1180. // No auto-gen mips on compressed textures
  1181. autoGenSupp = false;
  1182. }
  1183. if (profile->isSRGB())
  1184. testingFormat = ImageUtil::toSRGBFormat(testingFormat);
  1185. // inOutFormat is not modified by this method
  1186. GFXCardProfiler* cardProfiler = GFX->getCardProfiler();
  1187. bool chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1188. if( !chekFmt )
  1189. {
  1190. // It tested for a compressed format, and didn't like it
  1191. if( testingFormat != inOutFormat && profile->getCompression() )
  1192. testingFormat = inOutFormat; // Reset to requested format, and try again
  1193. // Trying again here, so reset autogen mip
  1194. autoGenSupp = ( inOutNumMips == 0 );
  1195. // Wow more weak sauce. There should be a better way to do this.
  1196. switch( inOutFormat )
  1197. {
  1198. case GFXFormatR8G8B8:
  1199. testingFormat = GFXFormatR8G8B8X8;
  1200. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1201. break;
  1202. case GFXFormatA8:
  1203. testingFormat = GFXFormatR8G8B8A8;
  1204. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1205. break;
  1206. default:
  1207. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1208. break;
  1209. }
  1210. }
  1211. // Write back num mips that need to be generated by GBitmap
  1212. if( !chekFmt )
  1213. Con::errorf( "Format %s not supported with specified profile.", GFXStringTextureFormat[inOutFormat] );
  1214. else
  1215. {
  1216. inOutFormat = testingFormat;
  1217. // If auto gen mipmaps were requested, and they aren't supported for whatever
  1218. // reason, than write out the number of mips that need to be generated.
  1219. //
  1220. // NOTE: Does this belong here?
  1221. if( inOutNumMips == 0 && !autoGenSupp )
  1222. {
  1223. inOutNumMips = mFloor(mLog2(mMax(width, height))) + 1;
  1224. }
  1225. }
  1226. }
  1227. GFXCubemap* GFXTextureManager::createCubemap( const Torque::Path &path )
  1228. {
  1229. // Very first thing... check the cache.
  1230. CubemapTable::Iterator iter = mCubemapTable.find( path.getFullPath() );
  1231. if ( iter != mCubemapTable.end() )
  1232. return iter->value;
  1233. // Not in the cache... we have to load it ourselves.
  1234. // First check for a DDS file.
  1235. if ( !sDDSExt.equal( path.getExtension(), String::NoCase ) )
  1236. {
  1237. // At the moment we only support DDS cubemaps.
  1238. return NULL;
  1239. }
  1240. const U32 scalePower = getTextureDownscalePower( NULL );
  1241. // Ok... load the DDS file then.
  1242. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1243. if ( !dds || !dds->isCubemap() )
  1244. {
  1245. // This wasn't a cubemap... give up too.
  1246. return NULL;
  1247. }
  1248. // We loaded the cubemap dds, so now we create the GFXCubemap from it.
  1249. GFXCubemap *cubemap = GFX->createCubemap();
  1250. cubemap->initStatic( dds );
  1251. cubemap->_setPath( path.getFullPath() );
  1252. // Store the cubemap into the cache.
  1253. mCubemapTable.insertUnique( path.getFullPath(), cubemap );
  1254. return cubemap;
  1255. }
  1256. void GFXTextureManager::releaseCubemap( GFXCubemap *cubemap )
  1257. {
  1258. if ( mTextureManagerState == GFXTextureManager::Dead )
  1259. return;
  1260. const String &path = cubemap->getPath();
  1261. CubemapTable::Iterator iter = mCubemapTable.find( path );
  1262. if ( iter != mCubemapTable.end() && iter->value == cubemap )
  1263. mCubemapTable.erase( iter );
  1264. // If we have a path for the texture then
  1265. // remove change notifications for it.
  1266. //Path texPath = texture->getPath();
  1267. //if ( !texPath.isEmpty() )
  1268. //FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  1269. }
  1270. void GFXTextureManager::_onFileChanged( const Torque::Path &path )
  1271. {
  1272. String pathNoExt = Torque::Path::Join( path.getRoot(), ':', path.getPath() );
  1273. pathNoExt = Torque::Path::Join( pathNoExt, '/', path.getFileName() );
  1274. // See if we've got it loaded.
  1275. GFXTextureObject *obj = hashFind( pathNoExt );
  1276. if ( !obj || path != obj->getPath() )
  1277. return;
  1278. Con::errorf( "[GFXTextureManager::_onFileChanged] : File changed [%s]", path.getFullPath().c_str() );
  1279. const U32 scalePower = getTextureDownscalePower( obj->mProfile );
  1280. if ( sDDSExt.equal( path.getExtension(), String::NoCase) )
  1281. {
  1282. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1283. if ( dds )
  1284. _createTexture( dds, obj->mProfile, false, obj );
  1285. }
  1286. else
  1287. {
  1288. Resource<GBitmap> bmp = GBitmap::load( path );
  1289. if( bmp )
  1290. _createTexture( bmp, obj->mTextureLookupName, obj->mProfile, false, obj );
  1291. }
  1292. }
  1293. void GFXTextureManager::reloadTextures()
  1294. {
  1295. GFXTextureObject *tex = mListHead;
  1296. while ( tex != NULL )
  1297. {
  1298. const Torque::Path path( tex->mPath );
  1299. if ( !path.isEmpty() )
  1300. {
  1301. const U32 scalePower = getTextureDownscalePower( tex->mProfile );
  1302. if ( sDDSExt.equal( path.getExtension(), String::NoCase ) )
  1303. {
  1304. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1305. if ( dds )
  1306. _createTexture( dds, tex->mProfile, false, tex );
  1307. }
  1308. else
  1309. {
  1310. Resource<GBitmap> bmp = GBitmap::load( path );
  1311. if( bmp )
  1312. _createTexture( bmp, tex->mTextureLookupName, tex->mProfile, false, tex );
  1313. }
  1314. }
  1315. tex = tex->mNext;
  1316. }
  1317. }
  1318. DefineEngineFunction( flushTextureCache, void, (),,
  1319. "Releases all textures and resurrects the texture manager.\n"
  1320. "@ingroup GFX\n" )
  1321. {
  1322. if ( !GFX || !TEXMGR )
  1323. return;
  1324. TEXMGR->zombify();
  1325. TEXMGR->resurrect();
  1326. }
  1327. DefineEngineFunction( cleanupTexturePool, void, (),,
  1328. "Release the unused pooled textures in texture manager freeing up video memory.\n"
  1329. "@ingroup GFX\n" )
  1330. {
  1331. if ( !GFX || !TEXMGR )
  1332. return;
  1333. TEXMGR->cleanupPool();
  1334. }
  1335. DefineEngineFunction( reloadTextures, void, (),,
  1336. "Reload all the textures from disk.\n"
  1337. "@ingroup GFX\n" )
  1338. {
  1339. if ( !GFX || !TEXMGR )
  1340. return;
  1341. TEXMGR->reloadTextures();
  1342. PROBEMGR->reloadTextures();
  1343. }