gfxTextureManager.cpp 54 KB

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