TextureCacheBase.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. // Copyright 2010 Dolphin Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <string>
  6. #include "Common/FileUtil.h"
  7. #include "Common/MemoryUtil.h"
  8. #include "Common/StringUtil.h"
  9. #include "Core/ConfigManager.h"
  10. #include "Core/HW/Memmap.h"
  11. #include "VideoCommon/Debugger.h"
  12. #include "VideoCommon/FramebufferManagerBase.h"
  13. #include "VideoCommon/HiresTextures.h"
  14. #include "VideoCommon/RenderBase.h"
  15. #include "VideoCommon/Statistics.h"
  16. #include "VideoCommon/TextureCacheBase.h"
  17. #include "VideoCommon/VideoConfig.h"
  18. static const u64 TEXHASH_INVALID = 0;
  19. static const int TEXTURE_KILL_THRESHOLD = 60;
  20. static const int TEXTURE_POOL_KILL_THRESHOLD = 3;
  21. static const int FRAMECOUNT_INVALID = 0;
  22. TextureCache *g_texture_cache;
  23. GC_ALIGNED16(u8 *TextureCache::temp) = nullptr;
  24. size_t TextureCache::temp_size;
  25. TextureCache::TexCache TextureCache::textures_by_address;
  26. TextureCache::TexCache TextureCache::textures_by_hash;
  27. TextureCache::TexPool TextureCache::texture_pool;
  28. TextureCache::TCacheEntryBase* TextureCache::bound_textures[8];
  29. TextureCache::BackupConfig TextureCache::backup_config;
  30. static bool invalidate_texture_cache_requested;
  31. TextureCache::TCacheEntryBase::~TCacheEntryBase()
  32. {
  33. }
  34. void TextureCache::CheckTempSize(size_t required_size)
  35. {
  36. if (required_size <= temp_size)
  37. return;
  38. temp_size = required_size;
  39. FreeAlignedMemory(temp);
  40. temp = (u8*)AllocateAlignedMemory(temp_size, 16);
  41. }
  42. TextureCache::TextureCache()
  43. {
  44. temp_size = 2048 * 2048 * 4;
  45. if (!temp)
  46. temp = (u8*)AllocateAlignedMemory(temp_size, 16);
  47. TexDecoder_SetTexFmtOverlayOptions(g_ActiveConfig.bTexFmtOverlayEnable, g_ActiveConfig.bTexFmtOverlayCenter);
  48. HiresTexture::Init();
  49. SetHash64Function();
  50. invalidate_texture_cache_requested = false;
  51. }
  52. void TextureCache::RequestInvalidateTextureCache()
  53. {
  54. invalidate_texture_cache_requested = true;
  55. }
  56. void TextureCache::Invalidate()
  57. {
  58. UnbindTextures();
  59. for (auto& tex : textures_by_address)
  60. {
  61. delete tex.second;
  62. }
  63. textures_by_address.clear();
  64. textures_by_hash.clear();
  65. for (auto& rt : texture_pool)
  66. {
  67. delete rt.second;
  68. }
  69. texture_pool.clear();
  70. }
  71. TextureCache::~TextureCache()
  72. {
  73. HiresTexture::Shutdown();
  74. Invalidate();
  75. FreeAlignedMemory(temp);
  76. temp = nullptr;
  77. }
  78. void TextureCache::OnConfigChanged(VideoConfig& config)
  79. {
  80. if (g_texture_cache)
  81. {
  82. if (config.bHiresTextures != backup_config.s_hires_textures ||
  83. config.bCacheHiresTextures != backup_config.s_cache_hires_textures)
  84. {
  85. HiresTexture::Update();
  86. }
  87. // TODO: Invalidating texcache is really stupid in some of these cases
  88. if (config.iSafeTextureCache_ColorSamples != backup_config.s_colorsamples ||
  89. config.bTexFmtOverlayEnable != backup_config.s_texfmt_overlay ||
  90. config.bTexFmtOverlayCenter != backup_config.s_texfmt_overlay_center ||
  91. config.bHiresTextures != backup_config.s_hires_textures ||
  92. invalidate_texture_cache_requested)
  93. {
  94. g_texture_cache->Invalidate();
  95. TexDecoder_SetTexFmtOverlayOptions(g_ActiveConfig.bTexFmtOverlayEnable, g_ActiveConfig.bTexFmtOverlayCenter);
  96. invalidate_texture_cache_requested = false;
  97. }
  98. if ((config.iStereoMode > 0) != backup_config.s_stereo_3d ||
  99. config.bStereoEFBMonoDepth != backup_config.s_efb_mono_depth)
  100. {
  101. g_texture_cache->DeleteShaders();
  102. g_texture_cache->CompileShaders();
  103. }
  104. }
  105. backup_config.s_colorsamples = config.iSafeTextureCache_ColorSamples;
  106. backup_config.s_texfmt_overlay = config.bTexFmtOverlayEnable;
  107. backup_config.s_texfmt_overlay_center = config.bTexFmtOverlayCenter;
  108. backup_config.s_hires_textures = config.bHiresTextures;
  109. backup_config.s_cache_hires_textures = config.bCacheHiresTextures;
  110. backup_config.s_stereo_3d = config.iStereoMode > 0;
  111. backup_config.s_efb_mono_depth = config.bStereoEFBMonoDepth;
  112. }
  113. void TextureCache::Cleanup(int _frameCount)
  114. {
  115. TexCache::iterator iter = textures_by_address.begin();
  116. TexCache::iterator tcend = textures_by_address.end();
  117. while (iter != tcend)
  118. {
  119. if (iter->second->frameCount == FRAMECOUNT_INVALID)
  120. {
  121. iter->second->frameCount = _frameCount;
  122. }
  123. if (_frameCount > TEXTURE_KILL_THRESHOLD + iter->second->frameCount &&
  124. // EFB copies living on the host GPU are unrecoverable and thus shouldn't be deleted
  125. !iter->second->IsEfbCopy())
  126. {
  127. iter = RemoveTextureFromCache(iter);
  128. }
  129. else
  130. {
  131. ++iter;
  132. }
  133. }
  134. TexPool::iterator iter2 = texture_pool.begin();
  135. TexPool::iterator tcend2 = texture_pool.end();
  136. while (iter2 != tcend2)
  137. {
  138. if (iter2->second->frameCount == FRAMECOUNT_INVALID)
  139. {
  140. iter2->second->frameCount = _frameCount;
  141. }
  142. if (_frameCount > TEXTURE_POOL_KILL_THRESHOLD + iter2->second->frameCount)
  143. {
  144. delete iter2->second;
  145. iter2 = texture_pool.erase(iter2);
  146. }
  147. else
  148. {
  149. ++iter2;
  150. }
  151. }
  152. }
  153. void TextureCache::MakeRangeDynamic(u32 start_address, u32 size)
  154. {
  155. TexCache::iterator
  156. iter = textures_by_address.begin();
  157. while (iter != textures_by_address.end())
  158. {
  159. if (iter->second->OverlapsMemoryRange(start_address, size))
  160. {
  161. iter = RemoveTextureFromCache(iter);
  162. }
  163. else
  164. {
  165. ++iter;
  166. }
  167. }
  168. }
  169. bool TextureCache::TCacheEntryBase::OverlapsMemoryRange(u32 range_address, u32 range_size) const
  170. {
  171. if (addr + size_in_bytes <= range_address)
  172. return false;
  173. if (addr >= range_address + range_size)
  174. return false;
  175. return true;
  176. }
  177. void TextureCache::DumpTexture(TCacheEntryBase* entry, std::string basename, unsigned int level)
  178. {
  179. std::string szDir = File::GetUserPath(D_DUMPTEXTURES_IDX) +
  180. SConfig::GetInstance().m_LocalCoreStartupParameter.m_strUniqueID;
  181. // make sure that the directory exists
  182. if (!File::Exists(szDir) || !File::IsDirectory(szDir))
  183. File::CreateDir(szDir);
  184. if (level > 0)
  185. {
  186. basename += StringFromFormat("_mip%i", level);
  187. }
  188. std::string filename = szDir + "/" + basename + ".png";
  189. if (!File::Exists(filename))
  190. entry->Save(filename, level);
  191. }
  192. static u32 CalculateLevelSize(u32 level_0_size, u32 level)
  193. {
  194. return (level_0_size + ((1 << level) - 1)) >> level;
  195. }
  196. // Used by TextureCache::Load
  197. TextureCache::TCacheEntryBase* TextureCache::ReturnEntry(unsigned int stage, TCacheEntryBase* entry)
  198. {
  199. entry->frameCount = FRAMECOUNT_INVALID;
  200. bound_textures[stage] = entry;
  201. GFX_DEBUGGER_PAUSE_AT(NEXT_TEXTURE_CHANGE, true);
  202. return entry;
  203. }
  204. void TextureCache::BindTextures()
  205. {
  206. for (int i = 0; i < 8; ++i)
  207. {
  208. if (bound_textures[i])
  209. bound_textures[i]->Bind(i);
  210. }
  211. }
  212. void TextureCache::UnbindTextures()
  213. {
  214. std::fill(std::begin(bound_textures), std::end(bound_textures), nullptr);
  215. }
  216. TextureCache::TCacheEntryBase* TextureCache::Load(const u32 stage)
  217. {
  218. const FourTexUnits &tex = bpmem.tex[stage >> 2];
  219. const u32 id = stage & 3;
  220. const u32 address = (tex.texImage3[id].image_base/* & 0x1FFFFF*/) << 5;
  221. u32 width = tex.texImage0[id].width + 1;
  222. u32 height = tex.texImage0[id].height + 1;
  223. const int texformat = tex.texImage0[id].format;
  224. const u32 tlutaddr = tex.texTlut[id].tmem_offset << 9;
  225. const u32 tlutfmt = tex.texTlut[id].tlut_format;
  226. const bool use_mipmaps = (tex.texMode0[id].min_filter & 3) != 0;
  227. u32 tex_levels = use_mipmaps ? ((tex.texMode1[id].max_lod + 0xf) / 0x10 + 1) : 1;
  228. const bool from_tmem = tex.texImage1[id].image_type != 0;
  229. if (0 == address)
  230. return nullptr;
  231. // TexelSizeInNibbles(format) * width * height / 16;
  232. const unsigned int bsw = TexDecoder_GetBlockWidthInTexels(texformat) - 1;
  233. const unsigned int bsh = TexDecoder_GetBlockHeightInTexels(texformat) - 1;
  234. unsigned int expandedWidth = (width + bsw) & (~bsw);
  235. unsigned int expandedHeight = (height + bsh) & (~bsh);
  236. const unsigned int nativeW = width;
  237. const unsigned int nativeH = height;
  238. // Hash assigned to texcache entry (also used to generate filenames used for texture dumping and custom texture lookup)
  239. u64 tex_hash = TEXHASH_INVALID;
  240. u64 full_hash = TEXHASH_INVALID;
  241. u32 full_format = texformat;
  242. const bool isPaletteTexture = (texformat == GX_TF_C4 || texformat == GX_TF_C8 || texformat == GX_TF_C14X2);
  243. // Reject invalid tlut format.
  244. if (isPaletteTexture && tlutfmt > GX_TL_RGB5A3)
  245. return nullptr;
  246. if (isPaletteTexture)
  247. full_format = texformat | (tlutfmt << 16);
  248. const u32 texture_size = TexDecoder_GetTextureSizeInBytes(expandedWidth, expandedHeight, texformat);
  249. const u8* src_data;
  250. if (from_tmem)
  251. src_data = &texMem[bpmem.tex[stage / 4].texImage1[stage % 4].tmem_even * TMEM_LINE_SIZE];
  252. else
  253. src_data = Memory::GetPointer(address);
  254. // TODO: This doesn't hash GB tiles for preloaded RGBA8 textures (instead, it's hashing more data from the low tmem bank than it should)
  255. tex_hash = GetHash64(src_data, texture_size, g_ActiveConfig.iSafeTextureCache_ColorSamples);
  256. u32 palette_size = 0;
  257. if (isPaletteTexture)
  258. {
  259. palette_size = TexDecoder_GetPaletteSize(texformat);
  260. full_hash = tex_hash ^ GetHash64(&texMem[tlutaddr], palette_size, g_ActiveConfig.iSafeTextureCache_ColorSamples);
  261. }
  262. else
  263. {
  264. full_hash = tex_hash;
  265. }
  266. // GPUs don't like when the specified mipmap count would require more than one 1x1-sized LOD in the mipmap chain
  267. // e.g. 64x64 with 7 LODs would have the mipmap chain 64x64,32x32,16x16,8x8,4x4,2x2,1x1,0x0, so we limit the mipmap count to 6 there
  268. tex_levels = std::min<u32>(IntLog2(std::max(width, height)) + 1, tex_levels);
  269. // Search the texture cache for textures by address
  270. //
  271. // Find all texture cache entries for the current texture address, and decide whether to use one of
  272. // them, or to create a new one
  273. //
  274. // In most cases, the fastest way is to use only one texture cache entry for the same address. Usually,
  275. // when a texture changes, the old version of the texture is unlikely to be used again. If there were
  276. // new cache entries created for normal texture updates, there would be a slowdown due to a huge amount
  277. // of unused cache entries. Also thanks to texture pooling, overwriting an existing cache entry is
  278. // faster than creating a new one from scratch.
  279. //
  280. // Some games use the same address for different textures though. If the same cache entry was used in
  281. // this case, it would be constantly overwritten, and effectively there wouldn't be any caching for
  282. // those textures. Examples for this are Metroid Prime and Castlevania 3. Metroid Prime has multiple
  283. // sets of fonts on each other stored in a single texture and uses the palette to make different
  284. // characters visible or invisible. In Castlevania 3 some textures are used for 2 different things or
  285. // at least in 2 different ways(size 1024x1024 vs 1024x256).
  286. //
  287. // To determine whether to use multiple cache entries or a single entry, use the following heuristic:
  288. // If the same texture address is used several times during the same frame, assume the address is used
  289. // for different purposes and allow creating an additional cache entry. If there's at least one entry
  290. // that hasn't been used for the same frame, then overwrite it, in order to keep the cache as small as
  291. // possible. If the current texture is found in the cache, use that entry.
  292. //
  293. // For efb copies, the entry created in CopyRenderTargetToTexture always has to be used, or else it was
  294. // done in vain.
  295. std::pair<TexCache::iterator, TexCache::iterator> iter_range = textures_by_address.equal_range((u64)address);
  296. TexCache::iterator iter = iter_range.first;
  297. TexCache::iterator oldest_entry = iter;
  298. int temp_frameCount = 0x7fffffff;
  299. TexCache::iterator unconverted_copy = textures_by_address.end();
  300. while (iter != iter_range.second)
  301. {
  302. TCacheEntryBase* entry = iter->second;
  303. if (entry->IsEfbCopy())
  304. {
  305. // EFB copies have slightly different rules: the hash doesn't need to match
  306. // in EFB2Tex mode, and EFB copy formats have different meanings from texture
  307. // formats.
  308. if (g_ActiveConfig.bSkipEFBCopyToRam ||
  309. (tex_hash == entry->hash && (!isPaletteTexture || g_Config.backend_info.bSupportsPaletteConversion)))
  310. {
  311. // TODO: We should check format/width/height/levels for EFB copies. Checking
  312. // format is complicated because EFB copy formats don't exactly match
  313. // texture formats. I'm not sure what effect checking width/height/levels
  314. // would have.
  315. if (!isPaletteTexture || !g_Config.backend_info.bSupportsPaletteConversion)
  316. return ReturnEntry(stage, entry);
  317. // Note that we found an unconverted EFB copy, then continue. We'll
  318. // perform the conversion later. Currently, we only convert EFB copies to
  319. // palette textures; we could do other conversions if it proved to be
  320. // beneficial.
  321. unconverted_copy = iter;
  322. }
  323. else
  324. {
  325. // Aggressively prune EFB copies: if it isn't useful here, it will probably
  326. // never be useful again. It's theoretically possible for a game to do
  327. // something weird where the copy could become useful in the future, but in
  328. // practice it doesn't happen.
  329. FreeTexture(entry);
  330. iter = textures_by_address.erase(iter);
  331. continue;
  332. }
  333. }
  334. else
  335. {
  336. // For normal textures, all texture parameters need to match
  337. if (entry->hash == full_hash && entry->format == full_format && entry->native_levels >= tex_levels &&
  338. entry->native_width == nativeW && entry->native_height == nativeH)
  339. {
  340. return ReturnEntry(stage, entry);
  341. }
  342. }
  343. // Find the entry which hasn't been used for the longest time
  344. if (entry->frameCount != FRAMECOUNT_INVALID && entry->frameCount < temp_frameCount)
  345. {
  346. temp_frameCount = entry->frameCount;
  347. oldest_entry = iter;
  348. }
  349. ++iter;
  350. }
  351. if (unconverted_copy != textures_by_address.end())
  352. {
  353. // Perform palette decoding.
  354. TCacheEntryBase *entry = unconverted_copy->second;
  355. TCacheEntryConfig config;
  356. config.rendertarget = true;
  357. config.width = entry->config.width;
  358. config.height = entry->config.height;
  359. config.layers = FramebufferManagerBase::GetEFBLayers();
  360. TCacheEntryBase *decoded_entry = AllocateTexture(config);
  361. decoded_entry->SetGeneralParameters(address, texture_size, full_format);
  362. decoded_entry->SetDimensions(entry->native_width, entry->native_height, 1);
  363. decoded_entry->SetHashes(full_hash);
  364. decoded_entry->frameCount = FRAMECOUNT_INVALID;
  365. decoded_entry->is_efb_copy = false;
  366. g_texture_cache->ConvertTexture(decoded_entry, entry, &texMem[tlutaddr], (TlutFormat)tlutfmt);
  367. textures_by_address.insert(TexCache::value_type((u64)address, decoded_entry));
  368. return ReturnEntry(stage, decoded_entry);
  369. }
  370. // Search the texture cache for normal textures by hash
  371. //
  372. // If the texture was fully hashed, the address does not need to match. Identical duplicate textures cause unnecessary slowdowns
  373. // Example: Tales of Symphonia (GC) uses over 500 small textures in menus, but only around 70 different ones
  374. if (g_ActiveConfig.iSafeTextureCache_ColorSamples == 0 ||
  375. std::max(texture_size, palette_size) <= (u32)g_ActiveConfig.iSafeTextureCache_ColorSamples * 8)
  376. {
  377. iter_range = textures_by_hash.equal_range(full_hash);
  378. iter = iter_range.first;
  379. while (iter != iter_range.second)
  380. {
  381. TCacheEntryBase* entry = iter->second;
  382. // All parameters, except the address, need to match here
  383. if (entry->format == full_format && entry->native_levels >= tex_levels &&
  384. entry->native_width == nativeW && entry->native_height == nativeH)
  385. {
  386. return ReturnEntry(stage, entry);
  387. }
  388. ++iter;
  389. }
  390. }
  391. // If at least one entry was not used for the same frame, overwrite the oldest one
  392. if (temp_frameCount != 0x7fffffff)
  393. {
  394. // pool this texture and make a new one later
  395. RemoveTextureFromCache(oldest_entry);
  396. }
  397. std::shared_ptr<HiresTexture> hires_tex;
  398. if (g_ActiveConfig.bHiresTextures)
  399. {
  400. hires_tex = HiresTexture::Search(
  401. src_data, texture_size,
  402. &texMem[tlutaddr], palette_size,
  403. width, height,
  404. texformat, use_mipmaps
  405. );
  406. if (hires_tex)
  407. {
  408. auto& l = hires_tex->m_levels[0];
  409. if (l.width != width || l.height != height)
  410. {
  411. width = l.width;
  412. height = l.height;
  413. }
  414. expandedWidth = l.width;
  415. expandedHeight = l.height;
  416. CheckTempSize(l.data_size);
  417. memcpy(temp, l.data, l.data_size);
  418. }
  419. }
  420. if (!hires_tex)
  421. {
  422. if (!(texformat == GX_TF_RGBA8 && from_tmem))
  423. {
  424. const u8* tlut = &texMem[tlutaddr];
  425. TexDecoder_Decode(temp, src_data, expandedWidth, expandedHeight, texformat, tlut, (TlutFormat) tlutfmt);
  426. }
  427. else
  428. {
  429. u8* src_data_gb = &texMem[bpmem.tex[stage / 4].texImage2[stage % 4].tmem_odd * TMEM_LINE_SIZE];
  430. TexDecoder_DecodeRGBA8FromTmem(temp, src_data, src_data_gb, expandedWidth, expandedHeight);
  431. }
  432. }
  433. // how many levels the allocated texture shall have
  434. const u32 texLevels = hires_tex ? (u32)hires_tex->m_levels.size() : tex_levels;
  435. // create the entry/texture
  436. TCacheEntryConfig config;
  437. config.width = width;
  438. config.height = height;
  439. config.levels = texLevels;
  440. TCacheEntryBase* entry = AllocateTexture(config);
  441. GFX_DEBUGGER_PAUSE_AT(NEXT_NEW_TEXTURE, true);
  442. textures_by_address.insert(TexCache::value_type((u64)address, entry));
  443. if (g_ActiveConfig.iSafeTextureCache_ColorSamples == 0 ||
  444. std::max(texture_size, palette_size) <= (u32)g_ActiveConfig.iSafeTextureCache_ColorSamples * 8)
  445. {
  446. entry->textures_by_hash_iter = textures_by_hash.insert(TexCache::value_type(full_hash, entry));
  447. }
  448. entry->SetGeneralParameters(address, texture_size, full_format);
  449. entry->SetDimensions(nativeW, nativeH, tex_levels);
  450. entry->hash = full_hash;
  451. entry->is_efb_copy = false;
  452. entry->is_custom_tex = hires_tex != nullptr;
  453. // load texture
  454. entry->Load(width, height, expandedWidth, 0);
  455. std::string basename = "";
  456. if (g_ActiveConfig.bDumpTextures && !hires_tex)
  457. {
  458. basename = HiresTexture::GenBaseName(
  459. src_data, texture_size,
  460. &texMem[tlutaddr], palette_size,
  461. width, height,
  462. texformat, use_mipmaps,
  463. true
  464. );
  465. DumpTexture(entry, basename, 0);
  466. }
  467. if (hires_tex)
  468. {
  469. for (u32 level = 1; level != texLevels; ++level)
  470. {
  471. auto& l = hires_tex->m_levels[level];
  472. CheckTempSize(l.data_size);
  473. memcpy(temp, l.data, l.data_size);
  474. entry->Load(l.width, l.height, l.width, level);
  475. }
  476. }
  477. else
  478. {
  479. // load mips - TODO: Loading mipmaps from tmem is untested!
  480. src_data += texture_size;
  481. const u8* ptr_even = nullptr;
  482. const u8* ptr_odd = nullptr;
  483. if (from_tmem)
  484. {
  485. ptr_even = &texMem[bpmem.tex[stage / 4].texImage1[stage % 4].tmem_even * TMEM_LINE_SIZE + texture_size];
  486. ptr_odd = &texMem[bpmem.tex[stage / 4].texImage2[stage % 4].tmem_odd * TMEM_LINE_SIZE];
  487. }
  488. for (u32 level = 1; level != texLevels; ++level)
  489. {
  490. const u32 mip_width = CalculateLevelSize(width, level);
  491. const u32 mip_height = CalculateLevelSize(height, level);
  492. const u32 expanded_mip_width = (mip_width + bsw) & (~bsw);
  493. const u32 expanded_mip_height = (mip_height + bsh) & (~bsh);
  494. const u8*& mip_src_data = from_tmem
  495. ? ((level % 2) ? ptr_odd : ptr_even)
  496. : src_data;
  497. const u8* tlut = &texMem[tlutaddr];
  498. TexDecoder_Decode(temp, mip_src_data, expanded_mip_width, expanded_mip_height, texformat, tlut, (TlutFormat)tlutfmt);
  499. mip_src_data += TexDecoder_GetTextureSizeInBytes(expanded_mip_width, expanded_mip_height, texformat);
  500. entry->Load(mip_width, mip_height, expanded_mip_width, level);
  501. if (g_ActiveConfig.bDumpTextures)
  502. DumpTexture(entry, basename, level);
  503. }
  504. }
  505. INCSTAT(stats.numTexturesUploaded);
  506. SETSTAT(stats.numTexturesAlive, textures_by_address.size());
  507. return ReturnEntry(stage, entry);
  508. }
  509. void TextureCache::CopyRenderTargetToTexture(u32 dstAddr, unsigned int dstFormat, PEControl::PixelFormat srcFormat,
  510. const EFBRectangle& srcRect, bool isIntensity, bool scaleByHalf)
  511. {
  512. // Emulation methods:
  513. //
  514. // - EFB to RAM:
  515. // Encodes the requested EFB data at its native resolution to the emulated RAM using shaders.
  516. // Load() decodes the data from there again (using TextureDecoder) if the EFB copy is being used as a texture again.
  517. // Advantage: CPU can read data from the EFB copy and we don't lose any important updates to the texture
  518. // Disadvantage: Encoding+decoding steps often are redundant because only some games read or modify EFB copies before using them as textures.
  519. //
  520. // - EFB to texture:
  521. // Copies the requested EFB data to a texture object in VRAM, performing any color conversion using shaders.
  522. // Advantage: Works for many games, since in most cases EFB copies aren't read or modified at all before being used as a texture again.
  523. // Since we don't do any further encoding or decoding here, this method is much faster.
  524. // It also allows enhancing the visual quality by doing scaled EFB copies.
  525. //
  526. // - Hybrid EFB copies:
  527. // 1a) Whenever this function gets called, encode the requested EFB data to RAM (like EFB to RAM)
  528. // 1b) Set type to TCET_EC_DYNAMIC for all texture cache entries in the destination address range.
  529. // If EFB copy caching is enabled, further checks will (try to) prevent redundant EFB copies.
  530. // 2) Check if a texture cache entry for the specified dstAddr already exists (i.e. if an EFB copy was triggered to that address before):
  531. // 2a) Entry doesn't exist:
  532. // - Also copy the requested EFB data to a texture object in VRAM (like EFB to texture)
  533. // - Create a texture cache entry for the target (type = TCET_EC_VRAM)
  534. // - Store a hash of the encoded RAM data in the texcache entry.
  535. // 2b) Entry exists AND type is TCET_EC_VRAM:
  536. // - Like case 2a, but reuse the old texcache entry instead of creating a new one.
  537. // 2c) Entry exists AND type is TCET_EC_DYNAMIC:
  538. // - Only encode the texture to RAM (like EFB to RAM) and store a hash of the encoded data in the existing texcache entry.
  539. // - Do NOT copy the requested EFB data to a VRAM object. Reason: the texture is dynamic, i.e. the CPU is modifying it. Storing a VRAM copy is useless, because we'd always end up deleting it and reloading the data from RAM anyway.
  540. // 3) If the EFB copy gets used as a texture, compare the source RAM hash with the hash you stored when encoding the EFB data to RAM.
  541. // 3a) If the two hashes match AND type is TCET_EC_VRAM, reuse the VRAM copy you created
  542. // 3b) If the two hashes differ AND type is TCET_EC_VRAM, screw your existing VRAM copy. Set type to TCET_EC_DYNAMIC.
  543. // Redecode the source RAM data to a VRAM object. The entry basically behaves like a normal texture now.
  544. // 3c) If type is TCET_EC_DYNAMIC, treat the EFB copy like a normal texture.
  545. // Advantage: Non-dynamic EFB copies can be visually enhanced like with EFB to texture.
  546. // Compatibility is as good as EFB to RAM.
  547. // Disadvantage: Slower than EFB to texture and often even slower than EFB to RAM.
  548. // EFB copy cache depends on accurate texture hashing being enabled. However, with accurate hashing you end up being as slow as without a copy cache anyway.
  549. //
  550. // Disadvantage of all methods: Calling this function requires the GPU to perform a pipeline flush which stalls any further CPU processing.
  551. //
  552. // For historical reasons, Dolphin doesn't actually implement "pure" EFB to RAM emulation, but only EFB to texture and hybrid EFB copies.
  553. float colmat[28] = {0};
  554. float *const fConstAdd = colmat + 16;
  555. float *const ColorMask = colmat + 20;
  556. ColorMask[0] = ColorMask[1] = ColorMask[2] = ColorMask[3] = 255.0f;
  557. ColorMask[4] = ColorMask[5] = ColorMask[6] = ColorMask[7] = 1.0f / 255.0f;
  558. unsigned int cbufid = -1;
  559. bool efbHasAlpha = bpmem.zcontrol.pixel_format == PEControl::RGBA6_Z24;
  560. if (srcFormat == PEControl::Z24)
  561. {
  562. switch (dstFormat)
  563. {
  564. case 0: // Z4
  565. colmat[3] = colmat[7] = colmat[11] = colmat[15] = 1.0f;
  566. cbufid = 0;
  567. break;
  568. case 1: // Z8
  569. case 8: // Z8
  570. colmat[0] = colmat[4] = colmat[8] = colmat[12] = 1.0f;
  571. cbufid = 1;
  572. break;
  573. case 3: // Z16
  574. colmat[1] = colmat[5] = colmat[9] = colmat[12] = 1.0f;
  575. cbufid = 2;
  576. break;
  577. case 11: // Z16 (reverse order)
  578. colmat[0] = colmat[4] = colmat[8] = colmat[13] = 1.0f;
  579. cbufid = 3;
  580. break;
  581. case 6: // Z24X8
  582. colmat[0] = colmat[5] = colmat[10] = 1.0f;
  583. cbufid = 4;
  584. break;
  585. case 9: // Z8M
  586. colmat[1] = colmat[5] = colmat[9] = colmat[13] = 1.0f;
  587. cbufid = 5;
  588. break;
  589. case 10: // Z8L
  590. colmat[2] = colmat[6] = colmat[10] = colmat[14] = 1.0f;
  591. cbufid = 6;
  592. break;
  593. case 12: // Z16L - copy lower 16 depth bits
  594. // expected to be used as an IA8 texture (upper 8 bits stored as intensity, lower 8 bits stored as alpha)
  595. // Used e.g. in Zelda: Skyward Sword
  596. colmat[1] = colmat[5] = colmat[9] = colmat[14] = 1.0f;
  597. cbufid = 7;
  598. break;
  599. default:
  600. ERROR_LOG(VIDEO, "Unknown copy zbuf format: 0x%x", dstFormat);
  601. colmat[2] = colmat[5] = colmat[8] = 1.0f;
  602. cbufid = 8;
  603. break;
  604. }
  605. }
  606. else if (isIntensity)
  607. {
  608. fConstAdd[0] = fConstAdd[1] = fConstAdd[2] = 16.0f / 255.0f;
  609. switch (dstFormat)
  610. {
  611. case 0: // I4
  612. case 1: // I8
  613. case 2: // IA4
  614. case 3: // IA8
  615. case 8: // I8
  616. // TODO - verify these coefficients
  617. colmat[0] = 0.257f; colmat[1] = 0.504f; colmat[2] = 0.098f;
  618. colmat[4] = 0.257f; colmat[5] = 0.504f; colmat[6] = 0.098f;
  619. colmat[8] = 0.257f; colmat[9] = 0.504f; colmat[10] = 0.098f;
  620. if (dstFormat < 2 || dstFormat == 8)
  621. {
  622. colmat[12] = 0.257f; colmat[13] = 0.504f; colmat[14] = 0.098f;
  623. fConstAdd[3] = 16.0f / 255.0f;
  624. if (dstFormat == 0)
  625. {
  626. ColorMask[0] = ColorMask[1] = ColorMask[2] = 15.0f;
  627. ColorMask[4] = ColorMask[5] = ColorMask[6] = 1.0f / 15.0f;
  628. cbufid = 9;
  629. }
  630. else
  631. {
  632. cbufid = 10;
  633. }
  634. }
  635. else// alpha
  636. {
  637. colmat[15] = 1;
  638. if (dstFormat == 2)
  639. {
  640. ColorMask[0] = ColorMask[1] = ColorMask[2] = ColorMask[3] = 15.0f;
  641. ColorMask[4] = ColorMask[5] = ColorMask[6] = ColorMask[7] = 1.0f / 15.0f;
  642. cbufid = 11;
  643. }
  644. else
  645. {
  646. cbufid = 12;
  647. }
  648. }
  649. break;
  650. default:
  651. ERROR_LOG(VIDEO, "Unknown copy intensity format: 0x%x", dstFormat);
  652. colmat[0] = colmat[5] = colmat[10] = colmat[15] = 1.0f;
  653. cbufid = 13;
  654. break;
  655. }
  656. }
  657. else
  658. {
  659. switch (dstFormat)
  660. {
  661. case 0: // R4
  662. colmat[0] = colmat[4] = colmat[8] = colmat[12] = 1;
  663. ColorMask[0] = 15.0f;
  664. ColorMask[4] = 1.0f / 15.0f;
  665. cbufid = 14;
  666. break;
  667. case 1: // R8
  668. case 8: // R8
  669. colmat[0] = colmat[4] = colmat[8] = colmat[12] = 1;
  670. cbufid = 15;
  671. break;
  672. case 2: // RA4
  673. colmat[0] = colmat[4] = colmat[8] = colmat[15] = 1.0f;
  674. ColorMask[0] = ColorMask[3] = 15.0f;
  675. ColorMask[4] = ColorMask[7] = 1.0f / 15.0f;
  676. cbufid = 16;
  677. if (!efbHasAlpha)
  678. {
  679. ColorMask[3] = 0.0f;
  680. fConstAdd[3] = 1.0f;
  681. cbufid = 17;
  682. }
  683. break;
  684. case 3: // RA8
  685. colmat[0] = colmat[4] = colmat[8] = colmat[15] = 1.0f;
  686. cbufid = 18;
  687. if (!efbHasAlpha)
  688. {
  689. ColorMask[3] = 0.0f;
  690. fConstAdd[3] = 1.0f;
  691. cbufid = 19;
  692. }
  693. break;
  694. case 7: // A8
  695. colmat[3] = colmat[7] = colmat[11] = colmat[15] = 1.0f;
  696. cbufid = 20;
  697. if (!efbHasAlpha)
  698. {
  699. ColorMask[3] = 0.0f;
  700. fConstAdd[0] = 1.0f;
  701. fConstAdd[1] = 1.0f;
  702. fConstAdd[2] = 1.0f;
  703. fConstAdd[3] = 1.0f;
  704. cbufid = 21;
  705. }
  706. break;
  707. case 9: // G8
  708. colmat[1] = colmat[5] = colmat[9] = colmat[13] = 1.0f;
  709. cbufid = 22;
  710. break;
  711. case 10: // B8
  712. colmat[2] = colmat[6] = colmat[10] = colmat[14] = 1.0f;
  713. cbufid = 23;
  714. break;
  715. case 11: // RG8
  716. colmat[0] = colmat[4] = colmat[8] = colmat[13] = 1.0f;
  717. cbufid = 24;
  718. break;
  719. case 12: // GB8
  720. colmat[1] = colmat[5] = colmat[9] = colmat[14] = 1.0f;
  721. cbufid = 25;
  722. break;
  723. case 4: // RGB565
  724. colmat[0] = colmat[5] = colmat[10] = 1.0f;
  725. ColorMask[0] = ColorMask[2] = 31.0f;
  726. ColorMask[4] = ColorMask[6] = 1.0f / 31.0f;
  727. ColorMask[1] = 63.0f;
  728. ColorMask[5] = 1.0f / 63.0f;
  729. fConstAdd[3] = 1.0f; // set alpha to 1
  730. cbufid = 26;
  731. break;
  732. case 5: // RGB5A3
  733. colmat[0] = colmat[5] = colmat[10] = colmat[15] = 1.0f;
  734. ColorMask[0] = ColorMask[1] = ColorMask[2] = 31.0f;
  735. ColorMask[4] = ColorMask[5] = ColorMask[6] = 1.0f / 31.0f;
  736. ColorMask[3] = 7.0f;
  737. ColorMask[7] = 1.0f / 7.0f;
  738. cbufid = 27;
  739. if (!efbHasAlpha)
  740. {
  741. ColorMask[3] = 0.0f;
  742. fConstAdd[3] = 1.0f;
  743. cbufid = 28;
  744. }
  745. break;
  746. case 6: // RGBA8
  747. colmat[0] = colmat[5] = colmat[10] = colmat[15] = 1.0f;
  748. cbufid = 29;
  749. if (!efbHasAlpha)
  750. {
  751. ColorMask[3] = 0.0f;
  752. fConstAdd[3] = 1.0f;
  753. cbufid = 30;
  754. }
  755. break;
  756. default:
  757. ERROR_LOG(VIDEO, "Unknown copy color format: 0x%x", dstFormat);
  758. colmat[0] = colmat[5] = colmat[10] = colmat[15] = 1.0f;
  759. cbufid = 31;
  760. break;
  761. }
  762. }
  763. const unsigned int tex_w = scaleByHalf ? srcRect.GetWidth() / 2 : srcRect.GetWidth();
  764. const unsigned int tex_h = scaleByHalf ? srcRect.GetHeight() / 2 : srcRect.GetHeight();
  765. unsigned int scaled_tex_w = g_ActiveConfig.bCopyEFBScaled ? Renderer::EFBToScaledX(tex_w) : tex_w;
  766. unsigned int scaled_tex_h = g_ActiveConfig.bCopyEFBScaled ? Renderer::EFBToScaledY(tex_h) : tex_h;
  767. // remove all texture cache entries at dstAddr
  768. std::pair<TexCache::iterator, TexCache::iterator> iter_range = textures_by_address.equal_range((u64)dstAddr);
  769. TexCache::iterator iter = iter_range.first;
  770. while (iter != iter_range.second)
  771. {
  772. iter = RemoveTextureFromCache(iter);
  773. }
  774. // create the texture
  775. TCacheEntryConfig config;
  776. config.rendertarget = true;
  777. config.width = scaled_tex_w;
  778. config.height = scaled_tex_h;
  779. config.layers = FramebufferManagerBase::GetEFBLayers();
  780. TCacheEntryBase* entry = AllocateTexture(config);
  781. // TODO: Using the wrong dstFormat, dumb...
  782. entry->SetGeneralParameters(dstAddr, 0, dstFormat);
  783. entry->SetDimensions(tex_w, tex_h, 1);
  784. entry->SetHashes(TEXHASH_INVALID);
  785. entry->frameCount = FRAMECOUNT_INVALID;
  786. entry->is_efb_copy = true;
  787. entry->is_custom_tex = false;
  788. entry->FromRenderTarget(dstAddr, dstFormat, srcFormat, srcRect, isIntensity, scaleByHalf, cbufid, colmat);
  789. if (g_ActiveConfig.bDumpEFBTarget)
  790. {
  791. static int count = 0;
  792. entry->Save(StringFromFormat("%sefb_frame_%i.png", File::GetUserPath(D_DUMPTEXTURES_IDX).c_str(),
  793. count++), 0);
  794. }
  795. textures_by_address.insert(TexCache::value_type((u64)dstAddr, entry));
  796. }
  797. TextureCache::TCacheEntryBase* TextureCache::AllocateTexture(const TCacheEntryConfig& config)
  798. {
  799. TexPool::iterator iter = texture_pool.find(config);
  800. TextureCache::TCacheEntryBase* entry;
  801. if (iter != texture_pool.end())
  802. {
  803. entry = iter->second;
  804. texture_pool.erase(iter);
  805. }
  806. else
  807. {
  808. entry = g_texture_cache->CreateTexture(config);
  809. INCSTAT(stats.numTexturesCreated);
  810. }
  811. entry->textures_by_hash_iter = textures_by_hash.end();
  812. return entry;
  813. }
  814. TextureCache::TexCache::iterator TextureCache::RemoveTextureFromCache(TexCache::iterator iter)
  815. {
  816. if (iter->second->textures_by_hash_iter != textures_by_hash.end())
  817. {
  818. textures_by_hash.erase(iter->second->textures_by_hash_iter);
  819. iter->second->textures_by_hash_iter = textures_by_hash.end();
  820. }
  821. FreeTexture(iter->second);
  822. return textures_by_address.erase(iter);
  823. }
  824. void TextureCache::FreeTexture(TCacheEntryBase* entry)
  825. {
  826. entry->frameCount = FRAMECOUNT_INVALID;
  827. texture_pool.insert(TexPool::value_type(entry->config, entry));
  828. }