Debian Codegraph @

Source/Core/VideoCommon/TextureCacheBase.cpp

raw symbols SCIP
1 // Copyright 2010 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/TextureCacheBase.h"
5
6 #include <algorithm>
7 #include <chrono>
8 #include <cmath>
9 #include <cstring>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 #include <vector>
14 #if defined(_M_X86_64)
15 #include <pmmintrin.h>
16 #endif
17
18 #include <fmt/format.h>
19
20 #include "Common/Align.h"
21 #include "Common/Assert.h"
22 #include "Common/ChunkFile.h"
23 #include "Common/CommonTypes.h"
24 #include "Common/FileUtil.h"
25 #include "Common/Hash.h"
26 #include "Common/Logging/Log.h"
27 #include "Common/MathUtil.h"
28 #include "Common/MemoryUtil.h"
29
30 #include "Core/Config/GraphicsSettings.h"
31 #include "Core/ConfigManager.h"
32 #include "Core/FifoPlayer/FifoPlayer.h"
33 #include "Core/FifoPlayer/FifoRecorder.h"
34 #include "Core/HW/Memmap.h"
35 #include "Core/System.h"
36
37 #include "VideoCommon/AbstractFramebuffer.h"
38 #include "VideoCommon/AbstractGfx.h"
39 #include "VideoCommon/AbstractStagingTexture.h"
40 #include "VideoCommon/Assets/CustomTextureData.h"
41 #include "VideoCommon/Assets/TextureAssetUtils.h"
42 #include "VideoCommon/BPMemory.h"
43 #include "VideoCommon/FramebufferManager.h"
44 #include "VideoCommon/GraphicsModSystem/Runtime/FBInfo.h"
45 #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModActionData.h"
46 #include "VideoCommon/GraphicsModSystem/Runtime/GraphicsModManager.h"
47 #include "VideoCommon/OpcodeDecoding.h"
48 #include "VideoCommon/PixelShaderManager.h"
49 #include "VideoCommon/Present.h"
50 #include "VideoCommon/Resources/CustomResourceManager.h"
51 #include "VideoCommon/ShaderCache.h"
52 #include "VideoCommon/Statistics.h"
53 #include "VideoCommon/TMEM.h"
54 #include "VideoCommon/TextureConversionShader.h"
55 #include "VideoCommon/TextureConverterShaderGen.h"
56 #include "VideoCommon/TextureDecoder.h"
57 #include "VideoCommon/VertexManagerBase.h"
58 #include "VideoCommon/VideoCommon.h"
59 #include "VideoCommon/VideoConfig.h"
60
61 static const u64 TEXHASH_INVALID = 0;
62 // Sonic the Fighters (inside Sonic Gems Collection) loops a 64 frames animation
63 static const int TEXTURE_KILL_THRESHOLD = 64;
64 static const int TEXTURE_POOL_KILL_THRESHOLD = 3;
65
66 static int xfb_count = 0;
67
68 std::unique_ptr<TextureCacheBase> g_texture_cache;
69
70 TCacheEntry::TCacheEntry(std::unique_ptr<AbstractTexture> tex,
71 std::unique_ptr<AbstractFramebuffer> fb)
72 : texture(std::move(tex)), framebuffer(std::move(fb))
73 {
74 }
75
76 TCacheEntry::~TCacheEntry()
77 {
78 for (auto& reference : references)
79 reference->references.erase(this);
80 ASSERT_MSG(VIDEO, g_texture_cache, "Texture cache destroyed before TCacheEntry was destroyed");
81 g_texture_cache->ReleaseToPool(this);
82 }
83
84 void TextureCacheBase::CheckTempSize(size_t required_size)
85 {
86 if (required_size <= m_temp_size)
87 return;
88
89 m_temp_size = required_size;
90 Common::FreeAlignedMemory(m_temp);
91 m_temp = static_cast<u8*>(Common::AllocateAlignedMemory(m_temp_size, 16));
92 }
93
94 TextureCacheBase::TextureCacheBase()
95 {
96 SetBackupConfig(g_ActiveConfig);
97
98 m_temp_size = 2048 * 2048 * 4;
99 m_temp = static_cast<u8*>(Common::AllocateAlignedMemory(m_temp_size, 16));
100
101 TexDecoder_SetTexFmtOverlayOptions(m_backup_config.texfmt_overlay,
102 m_backup_config.texfmt_overlay_center);
103
104 TMEM::InvalidateAll();
105 }
106
107 void TextureCacheBase::Shutdown()
108 {
109 // Clear pending EFB copies first, so we don't try to flush them.
110 m_pending_efb_copies.clear();
111
112 HiresTexture::Shutdown();
113
114 // For correctness, we need to invalidate textures before the gpu context starts shutting down.
115 Invalidate();
116 }
117
118 TextureCacheBase::~TextureCacheBase()
119 {
120 Common::FreeAlignedMemory(m_temp);
121 m_temp = nullptr;
122 }
123
124 bool TextureCacheBase::Initialize()
125 {
126 if (!CreateUtilityTextures())
127 {
128 PanicAlertFmt("Failed to create utility textures.");
129 return false;
130 }
131
132 return true;
133 }
134
135 void TextureCacheBase::Invalidate()
136 {
137 FlushEFBCopies();
138 TMEM::InvalidateAll();
139
140 for (auto& bind : m_bound_textures)
141 bind.reset();
142 m_textures_by_hash.clear();
143 m_textures_by_address.clear();
144
145 m_texture_pool.clear();
146 }
147
148 void TextureCacheBase::OnConfigChanged(const VideoConfig& config)
149 {
150 if (config.bHiresTextures != m_backup_config.hires_textures ||
151 config.bCacheHiresTextures != m_backup_config.cache_hires_textures)
152 {
153 HiresTexture::Update();
154 }
155
156 const u32 change_count =
157 config.graphics_mod_config ? config.graphics_mod_config->GetChangeCount() : 0;
158
159 // TODO: Invalidating texcache is really stupid in some of these cases
160 if (config.iSafeTextureCache_ColorSamples != m_backup_config.color_samples ||
161 config.bTexFmtOverlayEnable != m_backup_config.texfmt_overlay ||
162 config.bTexFmtOverlayCenter != m_backup_config.texfmt_overlay_center ||
163 config.bHiresTextures != m_backup_config.hires_textures ||
164 config.bEnableGPUTextureDecoding != m_backup_config.gpu_texture_decoding ||
165 config.bDisableCopyToVRAM != m_backup_config.disable_vram_copies ||
166 config.bArbitraryMipmapDetection != m_backup_config.arbitrary_mipmap_detection ||
167 config.bGraphicMods != m_backup_config.graphics_mods ||
168 change_count != m_backup_config.graphics_mod_change_count)
169 {
170 Invalidate();
171 TexDecoder_SetTexFmtOverlayOptions(config.bTexFmtOverlayEnable, config.bTexFmtOverlayCenter);
172 }
173
174 SetBackupConfig(config);
175 }
176
177 void TextureCacheBase::Cleanup(int _frameCount)
178 {
179 TexAddrCache::iterator iter = m_textures_by_address.begin();
180 TexAddrCache::iterator tcend = m_textures_by_address.end();
181 while (iter != tcend)
182 {
183 if (iter->second->frameCount == FRAMECOUNT_INVALID)
184 {
185 iter->second->frameCount = _frameCount;
186 ++iter;
187 }
188 else if (_frameCount > TEXTURE_KILL_THRESHOLD + iter->second->frameCount)
189 {
190 if (iter->second->IsCopy())
191 {
192 // Only remove EFB copies when they wouldn't be used anymore(changed hash), because EFB
193 // copies living on the
194 // host GPU are unrecoverable. Perform this check only every TEXTURE_KILL_THRESHOLD for
195 // performance reasons
196 if ((_frameCount - iter->second->frameCount) % TEXTURE_KILL_THRESHOLD == 1 &&
197 iter->second->hash != iter->second->CalculateHash())
198 {
199 iter = InvalidateTexture(iter);
200 }
201 else
202 {
203 ++iter;
204 }
205 }
206 else
207 {
208 iter = InvalidateTexture(iter);
209 }
210 }
211 else
212 {
213 ++iter;
214 }
215 }
216
217 TexPool::iterator iter2 = m_texture_pool.begin();
218 TexPool::iterator tcend2 = m_texture_pool.end();
219 while (iter2 != tcend2)
220 {
221 if (iter2->second.frameCount == FRAMECOUNT_INVALID)
222 {
223 iter2->second.frameCount = _frameCount;
224 }
225 if (_frameCount > TEXTURE_POOL_KILL_THRESHOLD + iter2->second.frameCount)
226 {
227 iter2 = m_texture_pool.erase(iter2);
228 }
229 else
230 {
231 ++iter2;
232 }
233 }
234 }
235
236 bool TCacheEntry::OverlapsMemoryRange(u32 range_address, u32 range_size) const
237 {
238 if (addr + size_in_bytes <= range_address)
239 return false;
240
241 if (addr >= range_address + range_size)
242 return false;
243
244 return true;
245 }
246
247 void TextureCacheBase::SetBackupConfig(const VideoConfig& config)
248 {
249 m_backup_config.color_samples = config.iSafeTextureCache_ColorSamples;
250 m_backup_config.texfmt_overlay = config.bTexFmtOverlayEnable;
251 m_backup_config.texfmt_overlay_center = config.bTexFmtOverlayCenter;
252 m_backup_config.hires_textures = config.bHiresTextures;
253 m_backup_config.cache_hires_textures = config.bCacheHiresTextures;
254 m_backup_config.stereo_3d = config.stereo_mode != StereoMode::Off;
255 m_backup_config.efb_mono_depth = config.bStereoEFBMonoDepth;
256 m_backup_config.gpu_texture_decoding = config.bEnableGPUTextureDecoding;
257 m_backup_config.disable_vram_copies = config.bDisableCopyToVRAM;
258 m_backup_config.arbitrary_mipmap_detection = config.bArbitraryMipmapDetection;
259 m_backup_config.graphics_mods = config.bGraphicMods;
260 m_backup_config.graphics_mod_change_count =
261 config.graphics_mod_config ? config.graphics_mod_config->GetChangeCount() : 0;
262 }
263
264 bool TextureCacheBase::DidLinkedAssetsChange(const TCacheEntry& entry)
265 {
266 if (!entry.hires_texture)
267 return false;
268
269 const auto* resource = entry.hires_texture->LoadTexture();
270
271 return resource->GetLoadTime() > entry.last_load_time;
272 }
273
274 RcTcacheEntry TextureCacheBase::ApplyPaletteToEntry(RcTcacheEntry& entry, const u8* palette,
275 TLUTFormat tlutfmt)
276 {
277 DEBUG_ASSERT(g_backend_info.bSupportsPaletteConversion);
278
279 const AbstractPipeline* pipeline = g_shader_cache->GetPaletteConversionPipeline(tlutfmt);
280 if (!pipeline)
281 {
282 ERROR_LOG_FMT(VIDEO, "Failed to get conversion pipeline for format {}", tlutfmt);
283 return {};
284 }
285
286 TextureConfig new_config = entry->texture->GetConfig();
287 new_config.levels = 1;
288 new_config.flags |= AbstractTextureFlag_RenderTarget;
289
290 RcTcacheEntry decoded_entry = AllocateCacheEntry(new_config);
291 if (!decoded_entry)
292 return decoded_entry;
293
294 decoded_entry->SetGeneralParameters(entry->addr, entry->size_in_bytes, entry->format,
295 entry->should_force_safe_hashing);
296 decoded_entry->SetDimensions(entry->native_width, entry->native_height, 1);
297 decoded_entry->SetHashes(entry->base_hash, entry->hash);
298 decoded_entry->frameCount = FRAMECOUNT_INVALID;
299 decoded_entry->should_force_safe_hashing = false;
300 decoded_entry->SetNotCopy();
301 decoded_entry->may_have_overlapping_textures = entry->may_have_overlapping_textures;
302
303 g_gfx->BeginUtilityDrawing();
304
305 const u32 palette_size = entry->format == TextureFormat::I4 ? 32 : 512;
306 u32 texel_buffer_offset;
307 if (g_vertex_manager->UploadTexelBuffer(palette, palette_size,
308 TexelBufferFormat::TEXEL_BUFFER_FORMAT_R16_UINT,
309 &texel_buffer_offset))
310 {
311 struct Uniforms
312 {
313 float multiplier;
314 u32 texel_buffer_offset;
315 u32 pad[2];
316 };
317 static_assert(std::is_standard_layout<Uniforms>::value);
318 Uniforms uniforms = {};
319 uniforms.multiplier = entry->format == TextureFormat::I4 ? 15.0f : 255.0f;
320 uniforms.texel_buffer_offset = texel_buffer_offset;
321 g_vertex_manager->UploadUtilityUniforms(&uniforms, sizeof(uniforms));
322
323 g_gfx->SetAndDiscardFramebuffer(decoded_entry->framebuffer.get());
324 g_gfx->SetViewportAndScissor(decoded_entry->texture->GetRect());
325 g_gfx->SetPipeline(pipeline);
326 g_gfx->SetTexture(1, entry->texture.get());
327 g_gfx->SetSamplerState(1, RenderState::GetPointSamplerState());
328 g_gfx->Draw(0, 3);
329 g_gfx->EndUtilityDrawing();
330 decoded_entry->texture->FinishedRendering();
331 }
332 else
333 {
334 ERROR_LOG_FMT(VIDEO, "Texel buffer upload of {} bytes failed", palette_size);
335 g_gfx->EndUtilityDrawing();
336 }
337
338 m_textures_by_address.emplace(decoded_entry->addr, decoded_entry);
339
340 return decoded_entry;
341 }
342
343 RcTcacheEntry TextureCacheBase::ReinterpretEntry(const RcTcacheEntry& existing_entry,
344 TextureFormat new_format)
345 {
346 const AbstractPipeline* pipeline =
347 g_shader_cache->GetTextureReinterpretPipeline(existing_entry->format.texfmt, new_format);
348 if (!pipeline)
349 {
350 ERROR_LOG_FMT(VIDEO, "Failed to obtain texture reinterpreting pipeline from format {} to {}",
351 existing_entry->format.texfmt, new_format);
352 return {};
353 }
354
355 TextureConfig new_config = existing_entry->texture->GetConfig();
356 new_config.levels = 1;
357 new_config.flags |= AbstractTextureFlag_RenderTarget;
358
359 RcTcacheEntry reinterpreted_entry = AllocateCacheEntry(new_config);
360 if (!reinterpreted_entry)
361 return {};
362
363 reinterpreted_entry->SetGeneralParameters(existing_entry->addr, existing_entry->size_in_bytes,
364 new_format, existing_entry->should_force_safe_hashing);
365 reinterpreted_entry->SetDimensions(existing_entry->native_width, existing_entry->native_height,
366 1);
367 reinterpreted_entry->SetHashes(existing_entry->base_hash, existing_entry->hash);
368 reinterpreted_entry->frameCount = existing_entry->frameCount;
369 reinterpreted_entry->SetNotCopy();
370 reinterpreted_entry->is_efb_copy = existing_entry->is_efb_copy;
371 reinterpreted_entry->may_have_overlapping_textures =
372 existing_entry->may_have_overlapping_textures;
373
374 g_gfx->BeginUtilityDrawing();
375 g_gfx->SetAndDiscardFramebuffer(reinterpreted_entry->framebuffer.get());
376 g_gfx->SetViewportAndScissor(reinterpreted_entry->texture->GetRect());
377 g_gfx->SetPipeline(pipeline);
378 g_gfx->SetTexture(0, existing_entry->texture.get());
379 g_gfx->SetSamplerState(1, RenderState::GetPointSamplerState());
380 g_gfx->Draw(0, 3);
381 g_gfx->EndUtilityDrawing();
382 reinterpreted_entry->texture->FinishedRendering();
383
384 m_textures_by_address.emplace(reinterpreted_entry->addr, reinterpreted_entry);
385
386 return reinterpreted_entry;
387 }
388
389 void TextureCacheBase::ScaleTextureCacheEntryTo(RcTcacheEntry& entry, u32 new_width, u32 new_height)
390 {
391 if (entry->GetWidth() == new_width && entry->GetHeight() == new_height)
392 {
393 return;
394 }
395
396 const u32 max = g_backend_info.MaxTextureSize;
397 if (max < new_width || max < new_height)
398 {
399 ERROR_LOG_FMT(VIDEO, "Texture too big, width = {}, height = {}", new_width, new_height);
400 return;
401 }
402
403 const TextureConfig newconfig(new_width, new_height, 1, entry->GetNumLayers(), 1,
404 AbstractTextureFormat::RGBA8, AbstractTextureFlag_RenderTarget,
405 AbstractTextureType::Texture_2DArray);
406 std::optional<TexPoolEntry> new_texture = AllocateTexture(newconfig);
407 if (!new_texture)
408 {
409 ERROR_LOG_FMT(VIDEO, "Scaling failed due to texture allocation failure");
410 return;
411 }
412
413 // No need to convert the coordinates here since they'll be the same.
414 g_gfx->ScaleTexture(new_texture->framebuffer.get(), new_texture->texture->GetConfig().GetRect(),
415 entry->texture.get(), entry->texture->GetConfig().GetRect());
416 entry->texture.swap(new_texture->texture);
417 entry->framebuffer.swap(new_texture->framebuffer);
418
419 // At this point new_texture has the old texture in it,
420 // we can potentially reuse this, so let's move it back to the pool
421 auto config = new_texture->texture->GetConfig();
422 m_texture_pool.emplace(
423 config, TexPoolEntry(std::move(new_texture->texture), std::move(new_texture->framebuffer)));
424 }
425
426 bool TextureCacheBase::CheckReadbackTexture(u32 width, u32 height, AbstractTextureFormat format)
427 {
428 if (m_readback_texture && m_readback_texture->GetConfig().width >= width &&
429 m_readback_texture->GetConfig().height >= height &&
430 m_readback_texture->GetConfig().format == format)
431 {
432 return true;
433 }
434
435 TextureConfig staging_config(std::max(width, 128u), std::max(height, 128u), 1, 1, 1, format, 0,
436 AbstractTextureType::Texture_2DArray);
437 m_readback_texture.reset();
438 m_readback_texture = g_gfx->CreateStagingTexture(StagingTextureType::Readback, staging_config);
439 return m_readback_texture != nullptr;
440 }
441
442 void TextureCacheBase::SerializeTexture(AbstractTexture* tex, const TextureConfig& config,
443 PointerWrap& p)
444 {
445 // If we're in measure mode, skip the actual readback to save some time.
446 const bool skip_readback = p.IsMeasureMode();
447 p.Do(config);
448
449 if (skip_readback || CheckReadbackTexture(config.width, config.height, config.format))
450 {
451 // First, measure the amount of memory needed.
452 u32 total_size = 0;
453 for (u32 layer = 0; layer < config.layers; layer++)
454 {
455 for (u32 level = 0; level < config.levels; level++)
456 {
457 u32 level_width = std::max(config.width >> level, 1u);
458 u32 level_height = std::max(config.height >> level, 1u);
459
460 u32 stride = AbstractTexture::CalculateStrideForFormat(config.format, level_width);
461 u32 size = stride * level_height;
462
463 total_size += size;
464 }
465 }
466
467 // Set aside total_size bytes of space for the textures.
468 // When measuring, this will be set aside and not written to,
469 // but when writing we'll use this pointer directly to avoid
470 // needing to allocate/free an extra buffer.
471 u8* texture_data = p.DoExternal(total_size);
472
473 if (!skip_readback && p.IsMeasureMode())
474 {
475 ERROR_LOG_FMT(VIDEO, "Couldn't acquire {} bytes for serializing texture.", total_size);
476 return;
477 }
478
479 if (!skip_readback)
480 {
481 // Save out each layer of the texture to the pointer.
482 for (u32 layer = 0; layer < config.layers; layer++)
483 {
484 for (u32 level = 0; level < config.levels; level++)
485 {
486 u32 level_width = std::max(config.width >> level, 1u);
487 u32 level_height = std::max(config.height >> level, 1u);
488 auto rect = tex->GetConfig().GetMipRect(level);
489 m_readback_texture->CopyFromTexture(tex, rect, layer, level, rect);
490
491 u32 stride = AbstractTexture::CalculateStrideForFormat(config.format, level_width);
492 u32 size = stride * level_height;
493 m_readback_texture->ReadTexels(rect, texture_data, stride);
494
495 texture_data += size;
496 }
497 }
498 }
499 }
500 else
501 {
502 PanicAlertFmt("Failed to create staging texture for serialization");
503 }
504 }
505
506 std::optional<TextureCacheBase::TexPoolEntry> TextureCacheBase::DeserializeTexture(PointerWrap& p)
507 {
508 TextureConfig config;
509 p.Do(config);
510
511 // Read in the size from the save state, then texture data will point to
512 // a region of size total_size where textures are stored.
513 u32 total_size = 0;
514 u8* texture_data = p.DoExternal(total_size);
515
516 if (!p.IsReadMode() || total_size == 0)
517 return std::nullopt;
518
519 auto tex = AllocateTexture(config);
520 if (!tex)
521 {
522 PanicAlertFmt("Failed to create texture for deserialization");
523 return std::nullopt;
524 }
525
526 size_t start = 0;
527 for (u32 layer = 0; layer < config.layers; layer++)
528 {
529 for (u32 level = 0; level < config.levels; level++)
530 {
531 const u32 level_width = std::max(config.width >> level, 1u);
532 const u32 level_height = std::max(config.height >> level, 1u);
533 const size_t stride = AbstractTexture::CalculateStrideForFormat(config.format, level_width);
534 const size_t size = stride * level_height;
535 if ((start + size) > total_size)
536 {
537 ERROR_LOG_FMT(VIDEO, "Insufficient texture data for layer {} level {}", layer, level);
538 return tex;
539 }
540
541 tex->texture->Load(level, level_width, level_height, level_width, &texture_data[start], size);
542 start += size;
543 }
544 }
545
546 return tex;
547 }
548
549 void TextureCacheBase::DoState(PointerWrap& p)
550 {
551 // Flush all pending XFB copies before either loading or saving.
552 FlushEFBCopies();
553
554 p.Do(m_last_entry_id);
555
556 if (p.IsWriteMode() || p.IsMeasureMode())
557 DoSaveState(p);
558 else
559 DoLoadState(p);
560 }
561
562 void TextureCacheBase::DoSaveState(PointerWrap& p)
563 {
564 // Flush all stale binds
565 FlushStaleBinds();
566
567 std::map<const TCacheEntry*, u32> entry_map;
568 std::vector<TCacheEntry*> entries_to_save;
569 auto ShouldSaveEntry = [](const RcTcacheEntry& entry) {
570 // We skip non-copies as they can be decoded from RAM when the state is loaded.
571 // Storing them would duplicate data in the save state file, adding to decompression time.
572 // We also need to store invalidated entries, as they can't be restored from RAM.
573 return entry->IsCopy() || entry->invalidated;
574 };
575 auto AddCacheEntryToMap = [&entry_map, &entries_to_save](const RcTcacheEntry& entry) -> u32 {
576 auto iter = entry_map.find(entry.get());
577 if (iter != entry_map.end())
578 return iter->second;
579
580 // Since we are sequentially allocating texture entries, we need to save the textures in the
581 // same order they were collected. This is because of iterating both the address and hash maps.
582 // Therefore, the map is used for fast lookup, and the vector for ordering.
583 u32 id = static_cast<u32>(entry_map.size());
584 entry_map.emplace(entry.get(), id);
585 entries_to_save.push_back(entry.get());
586 return id;
587 };
588 auto GetCacheEntryId = [&entry_map](const TCacheEntry* entry) -> std::optional<u32> {
589 auto iter = entry_map.find(entry);
590 return iter != entry_map.end() ? std::make_optional(iter->second) : std::nullopt;
591 };
592
593 // Transform the m_textures_by_address and m_textures_by_hash maps to a mapping
594 // of address/hash to entry ID.
595 std::vector<std::pair<u32, u32>> textures_by_address_list;
596 std::vector<std::pair<u64, u32>> textures_by_hash_list;
597 std::vector<std::pair<u32, u32>> bound_textures_list;
598 if (Config::Get(Config::GFX_SAVE_TEXTURE_CACHE_TO_STATE))
599 {
600 for (const auto& it : m_textures_by_address)
601 {
602 if (ShouldSaveEntry(it.second))
603 {
604 const u32 id = AddCacheEntryToMap(it.second);
605 textures_by_address_list.emplace_back(it.first, id);
606 }
607 }
608 for (const auto& it : m_textures_by_hash)
609 {
610 if (ShouldSaveEntry(it.second))
611 {
612 const u32 id = AddCacheEntryToMap(it.second);
613 textures_by_hash_list.emplace_back(it.first, id);
614 }
615 }
616 for (u32 i = 0; i < m_bound_textures.size(); i++)
617 {
618 const auto& tentry = m_bound_textures[i];
619 if (m_bound_textures[i] && ShouldSaveEntry(tentry))
620 {
621 const u32 id = AddCacheEntryToMap(tentry);
622 bound_textures_list.emplace_back(i, id);
623 }
624 }
625 }
626
627 // Save the texture cache entries out in the order the were referenced.
628 u32 size = static_cast<u32>(entries_to_save.size());
629 p.Do(size);
630 for (TCacheEntry* entry : entries_to_save)
631 {
632 SerializeTexture(entry->texture.get(), entry->texture->GetConfig(), p);
633 entry->DoState(p);
634 }
635 p.DoMarker("TextureCacheEntries");
636
637 // Save references for each cache entry.
638 // As references are circular, we need to have everything created before linking entries.
639 std::set<std::pair<u32, u32>> reference_pairs;
640 for (const auto& it : entry_map)
641 {
642 const TCacheEntry* entry = it.first;
643 auto id1 = GetCacheEntryId(entry);
644 if (!id1)
645 continue;
646
647 for (const TCacheEntry* referenced_entry : entry->references)
648 {
649 auto id2 = GetCacheEntryId(referenced_entry);
650 if (!id2)
651 continue;
652
653 auto refpair1 = std::make_pair(*id1, *id2);
654 auto refpair2 = std::make_pair(*id2, *id1);
655 if (!reference_pairs.contains(refpair2))
656 reference_pairs.insert(std::move(refpair1));
657 }
658 }
659
660 auto doList = [&p](const auto& list) {
661 u32 list_size = static_cast<u32>(list.size());
662 p.Do(list_size);
663 for (const auto& it : list)
664 {
665 p.Do(it.first);
666 p.Do(it.second);
667 }
668 };
669
670 doList(reference_pairs);
671 doList(textures_by_address_list);
672 doList(textures_by_hash_list);
673 doList(bound_textures_list);
674
675 // Free the readback texture to potentially save host-mapped GPU memory, depending on where
676 // the driver mapped the staging buffer.
677 m_readback_texture.reset();
678 }
679
680 void TextureCacheBase::DoLoadState(PointerWrap& p)
681 {
682 // Helper for getting a cache entry from an ID.
683 std::map<u32, RcTcacheEntry> id_map;
684 RcTcacheEntry null_entry;
685 auto GetEntry = [&id_map, &null_entry](u32 id) -> RcTcacheEntry& {
686 auto iter = id_map.find(id);
687 return iter == id_map.end() ? null_entry : iter->second;
688 };
689
690 // Only clear out state when actually restoring/loading.
691 // Since we throw away entries when not in loading mode now, we don't need to check
692 // before inserting entries into the cache, as GetEntry will always return null.
693 const bool commit_state = p.IsReadMode();
694 if (commit_state)
695 Invalidate();
696
697 // Preload all cache entries.
698 u32 size = 0;
699 p.Do(size);
700 for (u32 i = 0; i < size; i++)
701 {
702 // Even if the texture isn't valid, we still need to create the cache entry object
703 // to update the point in the state state. We'll just throw it away if it's invalid.
704 auto tex = DeserializeTexture(p);
705 auto entry =
706 std::make_shared<TCacheEntry>(std::move(tex->texture), std::move(tex->framebuffer));
707 entry->textures_by_hash_iter = m_textures_by_hash.end();
708 entry->DoState(p);
709 if (entry->texture && commit_state)
710 id_map.emplace(i, entry);
711 }
712 p.DoMarker("TextureCacheEntries");
713
714 // Link all cache entry references.
715 p.Do(size);
716 for (u32 i = 0; i < size; i++)
717 {
718 u32 id1 = 0, id2 = 0;
719 p.Do(id1);
720 p.Do(id2);
721 auto e1 = GetEntry(id1);
722 auto e2 = GetEntry(id2);
723 if (e1 && e2)
724 e1->CreateReference(e2.get());
725 }
726
727 // Fill in address map.
728 p.Do(size);
729 for (u32 i = 0; i < size; i++)
730 {
731 u32 addr = 0;
732 u32 id = 0;
733 p.Do(addr);
734 p.Do(id);
735
736 auto& entry = GetEntry(id);
737 if (entry)
738 m_textures_by_address.emplace(addr, entry);
739 }
740
741 // Fill in hash map.
742 p.Do(size);
743 for (u32 i = 0; i < size; i++)
744 {
745 u64 hash = 0;
746 u32 id = 0;
747 p.Do(hash);
748 p.Do(id);
749
750 auto& entry = GetEntry(id);
751 if (entry)
752 entry->textures_by_hash_iter = m_textures_by_hash.emplace(hash, entry);
753 }
754
755 // Clear bound textures
756 for (u32 i = 0; i < m_bound_textures.size(); i++)
757 m_bound_textures[i].reset();
758
759 // Fill in bound textures
760 p.Do(size);
761 for (u32 i = 0; i < size; i++)
762 {
763 u32 index = 0;
764 u32 id = 0;
765 p.Do(index);
766 p.Do(id);
767
768 auto& entry = GetEntry(id);
769 if (entry)
770 m_bound_textures[index] = entry;
771 }
772 }
773
774 void TextureCacheBase::OnFrameEnd()
775 {
776 // Flush any outstanding EFB copies to RAM, in case the game is running at an uncapped frame
777 // rate and not waiting for vblank. Otherwise, we'd end up with a huge list of pending
778 // copies.
779 FlushEFBCopies();
780
781 Cleanup(g_presenter->FrameCount());
782 }
783
784 void TCacheEntry::DoState(PointerWrap& p)
785 {
786 p.Do(addr);
787 p.Do(size_in_bytes);
788 p.Do(base_hash);
789 p.Do(hash);
790 p.Do(format);
791 p.Do(memory_stride);
792 p.Do(is_efb_copy);
793 p.Do(is_custom_tex);
794 p.Do(may_have_overlapping_textures);
795 p.Do(invalidated);
796 p.Do(has_arbitrary_mips);
797 p.Do(should_force_safe_hashing);
798 p.Do(is_xfb_copy);
799 p.Do(is_xfb_container);
800 p.Do(id);
801 p.Do(reference_changed);
802 p.Do(native_width);
803 p.Do(native_height);
804 p.Do(native_levels);
805 p.Do(frameCount);
806 }
807
808 RcTcacheEntry TextureCacheBase::DoPartialTextureUpdates(RcTcacheEntry& entry_to_update,
809 const u8* palette, TLUTFormat tlutfmt)
810 {
811 // If the flag may_have_overlapping_textures is cleared, there are no overlapping EFB copies,
812 // which aren't applied already. It is set for new textures, and for the affected range
813 // on each EFB copy.
814 if (!entry_to_update->may_have_overlapping_textures)
815 return entry_to_update;
816 entry_to_update->may_have_overlapping_textures = false;
817
818 const bool isPaletteTexture = IsColorIndexed(entry_to_update->format.texfmt);
819
820 // EFB copies are excluded from these updates, until there's an example where a game would
821 // benefit from updating. This would require more work to be done.
822 if (entry_to_update->IsCopy())
823 return entry_to_update;
824
825 if (entry_to_update->IsLocked())
826 {
827 // TODO: Shouldn't be too hard, just need to clone the texture entry + texture contents.
828 PanicAlertFmt("TextureCache: PartialTextureUpdates of locked textures is not implemented");
829 return {};
830 }
831
832 u32 block_width = TexDecoder_GetBlockWidthInTexels(entry_to_update->format.texfmt);
833 u32 block_height = TexDecoder_GetBlockHeightInTexels(entry_to_update->format.texfmt);
834 u32 block_size = block_width * block_height *
835 TexDecoder_GetTexelSizeInNibbles(entry_to_update->format.texfmt) / 2;
836
837 u32 numBlocksX = (entry_to_update->native_width + block_width - 1) / block_width;
838
839 auto iter = FindOverlappingTextures(entry_to_update->addr, entry_to_update->size_in_bytes);
840 while (iter.first != iter.second)
841 {
842 auto& entry = iter.first->second;
843 if (entry != entry_to_update && entry->IsCopy() &&
844 !entry->references.contains(entry_to_update.get()) &&
845 entry->OverlapsMemoryRange(entry_to_update->addr, entry_to_update->size_in_bytes) &&
846 entry->memory_stride == numBlocksX * block_size)
847 {
848 if (entry->hash == entry->CalculateHash())
849 {
850 // If the texture formats are not compatible or convertible, skip it.
851 if (!IsCompatibleTextureFormat(entry_to_update->format.texfmt, entry->format.texfmt))
852 {
853 if (!CanReinterpretTextureOnGPU(entry_to_update->format.texfmt, entry->format.texfmt))
854 {
855 ++iter.first;
856 continue;
857 }
858
859 auto reinterpreted_entry = ReinterpretEntry(entry, entry_to_update->format.texfmt);
860 if (reinterpreted_entry)
861 entry = reinterpreted_entry;
862 }
863
864 if (isPaletteTexture)
865 {
866 auto decoded_entry = ApplyPaletteToEntry(entry, palette, tlutfmt);
867 if (decoded_entry)
868 {
869 // Link the efb copy with the partially updated texture, so we won't apply this partial
870 // update again
871 entry->CreateReference(entry_to_update.get());
872 // Mark the texture update as used, as if it was loaded directly
873 entry->frameCount = FRAMECOUNT_INVALID;
874 entry = decoded_entry;
875 }
876 else
877 {
878 ++iter.first;
879 continue;
880 }
881 }
882
883 u32 src_x, src_y, dst_x, dst_y;
884
885 // Note for understanding the math:
886 // Normal textures can't be strided, so the 2 missing cases with src_x > 0 don't exist
887 if (entry->addr >= entry_to_update->addr)
888 {
889 u32 block_offset = (entry->addr - entry_to_update->addr) / block_size;
890 u32 block_x = block_offset % numBlocksX;
891 u32 block_y = block_offset / numBlocksX;
892 src_x = 0;
893 src_y = 0;
894 dst_x = block_x * block_width;
895 dst_y = block_y * block_height;
896 }
897 else
898 {
899 u32 block_offset = (entry_to_update->addr - entry->addr) / block_size;
900 u32 block_x = (~block_offset + 1) % numBlocksX;
901 u32 block_y = (block_offset + block_x) / numBlocksX;
902 src_x = 0;
903 src_y = block_y * block_height;
904 dst_x = block_x * block_width;
905 dst_y = 0;
906 }
907
908 u32 copy_width =
909 std::min(entry->native_width - src_x, entry_to_update->native_width - dst_x);
910 u32 copy_height =
911 std::min(entry->native_height - src_y, entry_to_update->native_height - dst_y);
912
913 // If one of the textures is scaled, scale both with the current efb scaling factor
914 if (entry_to_update->native_width != entry_to_update->GetWidth() ||
915 entry_to_update->native_height != entry_to_update->GetHeight() ||
916 entry->native_width != entry->GetWidth() || entry->native_height != entry->GetHeight())
917 {
918 ScaleTextureCacheEntryTo(
919 entry_to_update, g_framebuffer_manager->EFBToScaledX(entry_to_update->native_width),
920 g_framebuffer_manager->EFBToScaledY(entry_to_update->native_height));
921 ScaleTextureCacheEntryTo(entry, g_framebuffer_manager->EFBToScaledX(entry->native_width),
922 g_framebuffer_manager->EFBToScaledY(entry->native_height));
923
924 src_x = g_framebuffer_manager->EFBToScaledX(src_x);
925 src_y = g_framebuffer_manager->EFBToScaledY(src_y);
926 dst_x = g_framebuffer_manager->EFBToScaledX(dst_x);
927 dst_y = g_framebuffer_manager->EFBToScaledY(dst_y);
928 copy_width = g_framebuffer_manager->EFBToScaledX(copy_width);
929 copy_height = g_framebuffer_manager->EFBToScaledY(copy_height);
930 }
931
932 // If the source rectangle is outside of what we actually have in VRAM, skip the copy.
933 // The backend doesn't do any clamping, so if we don't, we'd pass out-of-range coordinates
934 // to the graphics driver, which can cause GPU resets.
935 if (static_cast<u32>(src_x + copy_width) > entry->GetWidth() ||
936 static_cast<u32>(src_y + copy_height) > entry->GetHeight() ||
937 static_cast<u32>(dst_x + copy_width) > entry_to_update->GetWidth() ||
938 static_cast<u32>(dst_y + copy_height) > entry_to_update->GetHeight())
939 {
940 ++iter.first;
941 continue;
942 }
943
944 MathUtil::Rectangle<int> srcrect, dstrect;
945 srcrect.left = src_x;
946 srcrect.top = src_y;
947 srcrect.right = (src_x + copy_width);
948 srcrect.bottom = (src_y + copy_height);
949 dstrect.left = dst_x;
950 dstrect.top = dst_y;
951 dstrect.right = (dst_x + copy_width);
952 dstrect.bottom = (dst_y + copy_height);
953
954 // If one copy is stereo, and the other isn't... not much we can do here :/
955 const u32 layers_to_copy = std::min(entry->GetNumLayers(), entry_to_update->GetNumLayers());
956 for (u32 layer = 0; layer < layers_to_copy; layer++)
957 {
958 entry_to_update->texture->CopyRectangleFromTexture(entry->texture.get(), srcrect, layer,
959 0, dstrect, layer, 0);
960 }
961
962 if (isPaletteTexture)
963 {
964 // Remove the temporary converted texture, it won't be used anywhere else
965 // TODO: It would be nice to convert and copy in one step, but this code path isn't common
966 iter.first = InvalidateTexture(iter.first);
967 continue;
968 }
969 else
970 {
971 // Link the two textures together, so we won't apply this partial update again
972 entry->CreateReference(entry_to_update.get());
973 // Mark the texture update as used, as if it was loaded directly
974 entry->frameCount = FRAMECOUNT_INVALID;
975 }
976 }
977 else
978 {
979 // If the hash does not match, this EFB copy will not be used for anything, so remove it
980 iter.first = InvalidateTexture(iter.first);
981 continue;
982 }
983 }
984 ++iter.first;
985 }
986
987 return entry_to_update;
988 }
989
990 // Helper for checking if a BPMemory TexMode0 register is set to Point
991 // Filtering modes. This is used to decide whether Anisotropic enhancements
992 // are (mostly) safe in the VideoBackends.
993 // If both the minification and magnification filters are set to POINT modes
994 // then applying anisotropic filtering is equivalent to forced filtering. Point
995 // mode textures are usually some sort of 2D UI billboard which will end up
996 // misaligned from the correct pixels when filtered anisotropically.
997 static bool IsAnisotropicEnhancementSafe(const TexMode0& tm0)
998 {
999 return !(tm0.min_filter == FilterMode::Near && tm0.mag_filter == FilterMode::Near);
1000 }
1001
1002 SamplerState TextureCacheBase::GetSamplerState(u32 index, float custom_tex_scale, bool custom_tex,
1003 bool has_arbitrary_mips)
1004 {
1005 const TexMode0& tm0 = bpmem.tex.GetUnit(index).texMode0;
1006
1007 SamplerState state = {};
1008 state.Generate(bpmem, index);
1009
1010 // Force texture filtering config option.
1011 if (g_ActiveConfig.texture_filtering_mode == TextureFilteringMode::Nearest)
1012 {
1013 state.tm0.min_filter = FilterMode::Near;
1014 state.tm0.mag_filter = FilterMode::Near;
1015 state.tm0.mipmap_filter = FilterMode::Near;
1016 }
1017 else if (g_ActiveConfig.texture_filtering_mode == TextureFilteringMode::Linear)
1018 {
1019 state.tm0.min_filter = FilterMode::Linear;
1020 state.tm0.mag_filter = FilterMode::Linear;
1021 state.tm0.mipmap_filter =
1022 tm0.mipmap_filter != MipMode::None ? FilterMode::Linear : FilterMode::Near;
1023 }
1024
1025 // Custom textures may have a greater number of mips
1026 if (custom_tex)
1027 state.tm1.max_lod = 255;
1028
1029 // Anisotropic filtering option.
1030 if (g_ActiveConfig.iMaxAnisotropy != AnisotropicFilteringMode::Default &&
1031 IsAnisotropicEnhancementSafe(tm0))
1032 {
1033 state.tm0.anisotropic_filtering = std::to_underlying(g_ActiveConfig.iMaxAnisotropy);
1034 }
1035
1036 if (state.tm0.anisotropic_filtering != 0)
1037 {
1038 // https://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt
1039 // For predictable results on all hardware/drivers, only use one of:
1040 // GL_LINEAR + GL_LINEAR (No Mipmaps [Bilinear])
1041 // GL_LINEAR + GL_LINEAR_MIPMAP_LINEAR (w/ Mipmaps [Trilinear])
1042 // Letting the game set other combinations will have varying arbitrary results;
1043 // possibly being interpreted as equal to bilinear/trilinear, implicitly
1044 // disabling anisotropy, or changing the anisotropic algorithm employed.
1045 state.tm0.min_filter = FilterMode::Linear;
1046 state.tm0.mag_filter = FilterMode::Linear;
1047 if (tm0.mipmap_filter != MipMode::None)
1048 state.tm0.mipmap_filter = FilterMode::Linear;
1049 }
1050
1051 if (has_arbitrary_mips && tm0.mipmap_filter != MipMode::None)
1052 {
1053 // Apply a secondary bias calculated from the IR scale to pull inwards mipmaps
1054 // that have arbitrary contents, eg. are used for fog effects where the
1055 // distance they kick in at is important to preserve at any resolution.
1056 // Correct this with the upscaling factor of custom textures.
1057 s32 lod_offset = std::log2(g_framebuffer_manager->GetEFBScale() / custom_tex_scale) * 256.f;
1058 state.tm0.lod_bias = std::clamp<s32>(state.tm0.lod_bias + lod_offset, -32768, 32767);
1059
1060 // Anisotropic also pushes mips farther away so it cannot be used either
1061 state.tm0.anisotropic_filtering = 0;
1062 }
1063
1064 return state;
1065 }
1066
1067 void TextureCacheBase::BindTextures(BitSet32 used_textures,
1068 const std::array<SamplerState, 8>& samplers)
1069 {
1070 auto& system = Core::System::GetInstance();
1071 auto& pixel_shader_manager = system.GetPixelShaderManager();
1072 for (u32 i = 0; i < m_bound_textures.size(); i++)
1073 {
1074 const RcTcacheEntry& tentry = m_bound_textures[i];
1075 if (used_textures[i] && tentry)
1076 {
1077 g_gfx->SetTexture(i, tentry->texture.get());
1078 pixel_shader_manager.SetTexDims(i, tentry->native_width, tentry->native_height);
1079
1080 auto& state = samplers[i];
1081 g_gfx->SetSamplerState(i, state);
1082 pixel_shader_manager.SetSamplerState(i, state.tm0.hex, state.tm1.hex);
1083 }
1084 }
1085
1086 TMEM::FinalizeBinds(used_textures);
1087 }
1088
1089 class ArbitraryMipmapDetector
1090 {
1091 private:
1092 using PixelRGBAf = std::array<float, 4>;
1093 using PixelRGBAu8 = std::array<u8, 4>;
1094
1095 public:
1096 explicit ArbitraryMipmapDetector() = default;
1097
1098 void AddLevel(u32 width, u32 height, u32 row_length, const u8* buffer)
1099 {
1100 levels.push_back({{width, height, row_length}, buffer});
1101 }
1102
1103 bool HasArbitraryMipmaps(u8* downsample_buffer) const
1104 {
1105 if (levels.size() < 2)
1106 return false;
1107
1108 if (!g_ActiveConfig.bArbitraryMipmapDetection)
1109 return false;
1110
1111 // This is the average per-pixel, per-channel difference in percent between what we
1112 // expect a normal blurred mipmap to look like and what we actually received
1113 // 4.5% was chosen because it's just below the lowest clearly-arbitrary texture
1114 // I found in my tests, the background clouds in Mario Galaxy's Observatory lobby.
1115 const auto threshold = g_ActiveConfig.fArbitraryMipmapDetectionThreshold;
1116
1117 auto* src = downsample_buffer;
1118 auto* dst = downsample_buffer + levels[1].shape.row_length * levels[1].shape.height * 4;
1119
1120 float total_diff = 0.f;
1121
1122 for (std::size_t i = 0; i < levels.size() - 1; ++i)
1123 {
1124 const auto& level = levels[i];
1125 const auto& mip = levels[i + 1];
1126
1127 u64 level_pixel_count = level.shape.width;
1128 level_pixel_count *= level.shape.height;
1129
1130 // AverageDiff stores the difference sum in a u64, so make sure we can't overflow
1131 ASSERT(level_pixel_count < (std::numeric_limits<u64>::max() / (255 * 255 * 4)));
1132
1133 // Manually downsample the past downsample with a simple box blur
1134 // This is not necessarily close to whatever the original artists used, however
1135 // It should still be closer than a thing that's not a downscale at all
1136 Level::Downsample(i ? src : level.pixels, level.shape, dst, mip.shape);
1137
1138 // Find the average difference between pixels in this level but downsampled
1139 // and the next level
1140 auto diff = mip.AverageDiff(dst);
1141 total_diff += diff;
1142
1143 std::swap(src, dst);
1144 }
1145
1146 auto all_levels = total_diff / (levels.size() - 1);
1147 return all_levels > threshold;
1148 }
1149
1150 private:
1151 struct Shape
1152 {
1153 u32 width;
1154 u32 height;
1155 u32 row_length;
1156 };
1157
1158 struct Level
1159 {
1160 Shape shape;
1161 const u8* pixels;
1162
1163 static PixelRGBAu8 SampleLinear(const u8* src, const Shape& src_shape, u32 x, u32 y)
1164 {
1165 const auto* p = src + (x + y * src_shape.row_length) * 4;
1166 return {{p[0], p[1], p[2], p[3]}};
1167 }
1168
1169 // Puts a downsampled image in dst. dst must be at least width*height*4
1170 static void Downsample(const u8* src, const Shape& src_shape, u8* dst, const Shape& dst_shape)
1171 {
1172 for (u32 i = 0; i < dst_shape.height; ++i)
1173 {
1174 for (u32 j = 0; j < dst_shape.width; ++j)
1175 {
1176 auto x = j * 2;
1177 auto y = i * 2;
1178 const std::array<PixelRGBAu8, 4> samples{{
1179 SampleLinear(src, src_shape, x, y),
1180 SampleLinear(src, src_shape, x + 1, y),
1181 SampleLinear(src, src_shape, x, y + 1),
1182 SampleLinear(src, src_shape, x + 1, y + 1),
1183 }};
1184
1185 auto* dst_pixel = dst + (j + i * dst_shape.row_length) * 4;
1186 for (int channel = 0; channel < 4; channel++)
1187 {
1188 uint32_t channel_value = samples[0][channel] + samples[1][channel] +
1189 samples[2][channel] + samples[3][channel];
1190 dst_pixel[channel] = (channel_value + 2) / 4;
1191 }
1192 }
1193 }
1194 }
1195
1196 float AverageDiff(const u8* other) const
1197 {
1198 // As textures are stored in (at most) 8 bit precision, each channel can
1199 // have a max diff of (2^8)^2, multiply by 4 channels = 2^18 per pixel.
1200 // That means to overflow, we must have a texture with more than 2^46
1201 // pixels - which is way beyond anything the original hardware could do,
1202 // and likely a sane assumption going forward for some significant time.
1203 u64 current_diff_sum = 0;
1204 const auto* ptr1 = pixels;
1205 const auto* ptr2 = other;
1206 for (u32 i = 0; i < shape.height; ++i)
1207 {
1208 const auto* row1 = ptr1;
1209 const auto* row2 = ptr2;
1210 for (u32 j = 0; j < shape.width; ++j, row1 += 4, row2 += 4)
1211 {
1212 int pixel_diff = 0;
1213 for (int channel = 0; channel < 4; channel++)
1214 {
1215 const int diff = static_cast<int>(row1[channel]) - static_cast<int>(row2[channel]);
1216 const int diff_squared = diff * diff;
1217 pixel_diff += diff_squared;
1218 }
1219 current_diff_sum += pixel_diff;
1220 }
1221 ptr1 += shape.row_length;
1222 ptr2 += shape.row_length;
1223 }
1224 // calculate the MSE over all pixels, divide by 2.56 to make it a percent
1225 // (IE scale to 0..100 instead of 0..256)
1226
1227 return std::sqrt(static_cast<float>(current_diff_sum) / (shape.width * shape.height * 4)) /
1228 2.56f;
1229 }
1230 };
1231 std::vector<Level> levels;
1232 };
1233
1234 TCacheEntry* TextureCacheBase::Load(u32 stage)
1235 {
1236 if (auto entry = LoadImpl(stage, false))
1237 {
1238 if (!DidLinkedAssetsChange(*entry))
1239 {
1240 return entry;
1241 }
1242
1243 InvalidateTexture(GetTexCacheIter(entry));
1244 return LoadImpl(stage, true);
1245 }
1246
1247 return nullptr;
1248 }
1249
1250 TCacheEntry* TextureCacheBase::LoadImpl(u32 stage, bool force_reload)
1251 {
1252 // if this stage was not invalidated by changes to texture registers, keep the current texture
1253 if (!force_reload && TMEM::IsValid(stage) && m_bound_textures[stage])
1254 {
1255 TCacheEntry* entry = m_bound_textures[stage].get();
1256 // If the TMEM configuration is such that this texture is more or less guaranteed to still
1257 // be in TMEM, then we know we can reuse the old entry without even hashing the memory
1258 //
1259 // It's possible this texture has already been overwritten in emulated memory and therefore
1260 // invalidated from our texture cache, but we want to use it anyway to approximate the
1261 // result of the game using an overwritten texture cached in TMEM.
1262 //
1263 // Spyro: A Hero's Tail is known for (deliberately?) using such overwritten textures
1264 // in it's bloom effect, which breaks without giving it the invalidated texture.
1265 if (TMEM::IsCached(stage))
1266 {
1267 return entry;
1268 }
1269
1270 // Otherwise, hash the backing memory and check it's unchanged.
1271 // FIXME: this doesn't correctly handle textures from tmem.
1272 if (!entry->invalidated && entry->base_hash == entry->CalculateHash())
1273 {
1274 return entry;
1275 }
1276 }
1277
1278 const TextureInfo texture_info = TextureInfo::FromStage(stage);
1279 auto entry = GetTexture(g_ActiveConfig.iSafeTextureCache_ColorSamples, texture_info);
1280
1281 if (!entry)
1282 return nullptr;
1283
1284 entry->frameCount = FRAMECOUNT_INVALID;
1285 if (entry->texture_info_name.empty() && g_ActiveConfig.bGraphicMods)
1286 {
1287 entry->texture_info_name = texture_info.CalculateTextureName().GetFullName();
1288
1289 GraphicsModActionData::TextureLoad texture_load{entry->texture_info_name};
1290 for (const auto& action :
1291 g_graphics_mod_manager->GetTextureLoadActions(entry->texture_info_name))
1292 {
1293 action->OnTextureLoad(&texture_load);
1294 }
1295 }
1296 m_bound_textures[texture_info.GetStage()] = entry;
1297
1298 // We need to keep track of invalided textures until they have actually been replaced or
1299 // re-loaded
1300 TMEM::Bind(texture_info.GetStage(), entry->NumBlocksX(), entry->NumBlocksY(),
1301 entry->GetNumLevels() > 1, entry->format == TextureFormat::RGBA8);
1302
1303 return entry.get();
1304 }
1305
1306 RcTcacheEntry TextureCacheBase::GetTexture(const int textureCacheSafetyColorSampleSize,
1307 const TextureInfo& texture_info)
1308 {
1309 if (!texture_info.IsDataValid())
1310 return {};
1311
1312 // Hash assigned to texcache entry (also used to generate filenames used for texture dumping and
1313 // custom texture lookup)
1314 u64 base_hash = TEXHASH_INVALID;
1315 u64 full_hash = TEXHASH_INVALID;
1316
1317 TextureAndTLUTFormat full_format(texture_info.GetTextureFormat(), texture_info.GetTlutFormat());
1318
1319 // Reject invalid tlut format.
1320 if (texture_info.GetPaletteSize() && !IsValidTLUTFormat(texture_info.GetTlutFormat()))
1321 return {};
1322
1323 u32 bytes_per_block = (texture_info.GetBlockWidth() * texture_info.GetBlockHeight() *
1324 TexDecoder_GetTexelSizeInNibbles(texture_info.GetTextureFormat())) /
1325 2;
1326
1327 // TODO: the texture cache lookup is based on address, but a texture from tmem has no reason
1328 // to have a unique and valid address. This could result in a regular texture and a tmem
1329 // texture aliasing onto the same texture cache entry.
1330
1331 // If we are recording a FifoLog, keep track of what memory we read. FifoRecorder does
1332 // its own memory modification tracking independent of the texture hashing below.
1333 if (OpcodeDecoder::g_record_fifo_data && !texture_info.IsFromTmem())
1334 {
1335 Core::System::GetInstance().GetFifoRecorder().UseMemory(texture_info.GetRawAddress(),
1336 texture_info.GetFullLevelSize(),
1337 MemoryUpdate::Type::TextureMap);
1338 }
1339
1340 // TODO: This doesn't hash GB tiles for preloaded RGBA8 textures (instead, it's hashing more data
1341 // from the low tmem bank than it should)
1342 base_hash = Common::GetHash64(texture_info.GetData(), texture_info.GetTextureSize(),
1343 textureCacheSafetyColorSampleSize);
1344 u32 palette_size = 0;
1345 if (texture_info.GetPaletteSize())
1346 {
1347 palette_size = *texture_info.GetPaletteSize();
1348 full_hash =
1349 base_hash ^ Common::GetHash64(texture_info.GetTlutAddress(), *texture_info.GetPaletteSize(),
1350 textureCacheSafetyColorSampleSize);
1351 }
1352 else
1353 {
1354 full_hash = base_hash;
1355 }
1356
1357 // Search the texture cache for textures by address
1358 //
1359 // Find all texture cache entries for the current texture address, and decide whether to use one
1360 // of them, or to create a new one
1361 //
1362 // In most cases, the fastest way is to use only one texture cache entry for the same address.
1363 // Usually, when a texture changes, the old version of the texture is unlikely to be used again.
1364 // If there were new cache entries created for normal texture updates, there would be a slowdown
1365 // due to a huge amount of unused cache entries. Also thanks to texture pooling, overwriting an
1366 // existing cache entry is faster than creating a new one from scratch.
1367 //
1368 // Some games use the same address for different textures though. If the same cache entry was used
1369 // in this case, it would be constantly overwritten, and effectively there wouldn't be any caching
1370 // for those textures. Examples for this are Metroid Prime and Castlevania 3. Metroid Prime has
1371 // multiple sets of fonts on each other stored in a single texture and uses the palette to make
1372 // different characters visible or invisible. In Castlevania 3 some textures are used for 2
1373 // different things or at least in 2 different ways (size 1024x1024 vs 1024x256).
1374 //
1375 // To determine whether to use multiple cache entries or a single entry, use the following
1376 // heuristic: If the same texture address is used several times during the same frame, assume the
1377 // address is used for different purposes and allow creating an additional cache entry. If there's
1378 // at least one entry that hasn't been used for the same frame, then overwrite it, in order to
1379 // keep the cache as small as possible. If the current texture is found in the cache, use that
1380 // entry.
1381 //
1382 // For efb copies, the entry created in CopyRenderTargetToTexture always has to be used, or else
1383 // it was done in vain.
1384 auto iter_range = m_textures_by_address.equal_range(texture_info.GetRawAddress());
1385 TexAddrCache::iterator iter = iter_range.first;
1386 TexAddrCache::iterator oldest_entry = iter;
1387 int temp_frameCount = 0x7fffffff;
1388 TexAddrCache::iterator unconverted_copy = m_textures_by_address.end();
1389 TexAddrCache::iterator unreinterpreted_copy = m_textures_by_address.end();
1390
1391 while (iter != iter_range.second)
1392 {
1393 RcTcacheEntry& entry = iter->second;
1394
1395 // TODO: Some games (Rogue Squadron 3, Twin Snakes) seem to load a previously made XFB
1396 // copy as a regular texture. You can see this particularly well in RS3 whenever the
1397 // game freezes the image and fades it out to black on screen transitions, which fades
1398 // out a purple screen in XFB2Tex. Check for this here and convert them if necessary.
1399
1400 // Do not load strided EFB copies, they are not meant to be used directly.
1401 // Also do not directly load EFB copies, which were partly overwritten.
1402 if (entry->IsEfbCopy() && entry->native_width == texture_info.GetRawWidth() &&
1403 entry->native_height == texture_info.GetRawHeight() &&
1404 entry->memory_stride == entry->BytesPerRow() && !entry->may_have_overlapping_textures)
1405 {
1406 // EFB copies have slightly different rules as EFB copy formats have different
1407 // meanings from texture formats.
1408 if ((base_hash == entry->hash &&
1409 (!texture_info.GetPaletteSize() || g_backend_info.bSupportsPaletteConversion)) ||
1410 IsPlayingBackFifologWithBrokenEFBCopies)
1411 {
1412 // The texture format in VRAM must match the format that the copy was created with. Some
1413 // formats are inherently compatible, as the channel and bit layout is identical (e.g.
1414 // I8/C8). Others have the same number of bits per texel, and can be reinterpreted on the
1415 // GPU (e.g. IA4 and I8 or RGB565 and RGBA5). The only known game which reinteprets texels
1416 // in this manner is Spiderman Shattered Dimensions, where it creates a copy in B8 format,
1417 // and sets it up as a IA4 texture.
1418 if (!IsCompatibleTextureFormat(entry->format.texfmt, texture_info.GetTextureFormat()))
1419 {
1420 // Can we reinterpret this in VRAM?
1421 if (CanReinterpretTextureOnGPU(entry->format.texfmt, texture_info.GetTextureFormat()))
1422 {
1423 // Delay the conversion until afterwards, it's possible this texture has already been
1424 // converted.
1425 unreinterpreted_copy = iter++;
1426 continue;
1427 }
1428 else
1429 {
1430 // If the EFB copies are in a different format and are not reinterpretable, use the RAM
1431 // copy.
1432 ++iter;
1433 continue;
1434 }
1435 }
1436 else
1437 {
1438 // Prefer the already-converted copy.
1439 unconverted_copy = m_textures_by_address.end();
1440 }
1441
1442 // TODO: We should check width/height/levels for EFB copies. I'm not sure what effect
1443 // checking width/height/levels would have.
1444 if (!texture_info.GetPaletteSize() || !g_backend_info.bSupportsPaletteConversion)
1445 return entry;
1446
1447 // Note that we found an unconverted EFB copy, then continue. We'll
1448 // perform the conversion later. Currently, we only convert EFB copies to
1449 // palette textures; we could do other conversions if it proved to be
1450 // beneficial.
1451 unconverted_copy = iter;
1452 }
1453 else
1454 {
1455 // Aggressively prune EFB copies: if it isn't useful here, it will probably
1456 // never be useful again. It's theoretically possible for a game to do
1457 // something weird where the copy could become useful in the future, but in
1458 // practice it doesn't happen.
1459 iter = InvalidateTexture(iter);
1460 continue;
1461 }
1462 }
1463 else
1464 {
1465 // For normal textures, all texture parameters need to match
1466 if (!entry->IsEfbCopy() && entry->hash == full_hash && entry->format == full_format &&
1467 entry->native_levels >= texture_info.GetLevelCount() &&
1468 entry->native_width == texture_info.GetRawWidth() &&
1469 entry->native_height == texture_info.GetRawHeight())
1470 {
1471 entry = DoPartialTextureUpdates(iter->second, texture_info.GetTlutAddress(),
1472 texture_info.GetTlutFormat());
1473 if (entry)
1474 {
1475 entry->texture->FinishedRendering();
1476 return entry;
1477 }
1478 }
1479 }
1480
1481 // Find the texture which hasn't been used for the longest time. Count paletted
1482 // textures as the same texture here, when the texture itself is the same. This
1483 // improves the performance a lot in some games that use paletted textures.
1484 // Example: Sonic the Fighters (inside Sonic Gems Collection)
1485 // Skip EFB copies here, so they can be used for partial texture updates
1486 // Also skip XFB copies, we might need to still scan them out
1487 // or load them as regular textures later.
1488 if (entry->frameCount != FRAMECOUNT_INVALID && entry->frameCount < temp_frameCount &&
1489 !entry->IsCopy() && !(texture_info.GetPaletteSize() && entry->base_hash == base_hash))
1490 {
1491 temp_frameCount = entry->frameCount;
1492 oldest_entry = iter;
1493 }
1494 ++iter;
1495 }
1496
1497 if (unreinterpreted_copy != m_textures_by_address.end())
1498 {
1499 auto decoded_entry =
1500 ReinterpretEntry(unreinterpreted_copy->second, texture_info.GetTextureFormat());
1501
1502 // It's possible to combine reinterpreted textures + palettes.
1503 if (unreinterpreted_copy == unconverted_copy && decoded_entry)
1504 decoded_entry = ApplyPaletteToEntry(decoded_entry, texture_info.GetTlutAddress(),
1505 texture_info.GetTlutFormat());
1506
1507 if (decoded_entry)
1508 return decoded_entry;
1509 }
1510
1511 if (unconverted_copy != m_textures_by_address.end())
1512 {
1513 auto decoded_entry = ApplyPaletteToEntry(
1514 unconverted_copy->second, texture_info.GetTlutAddress(), texture_info.GetTlutFormat());
1515
1516 if (decoded_entry)
1517 {
1518 return decoded_entry;
1519 }
1520 }
1521
1522 // Search the texture cache for normal textures by hash
1523 //
1524 // If the texture was fully hashed, the address does not need to match. Identical duplicate
1525 // textures cause unnecessary slowdowns
1526 // Example: Tales of Symphonia (GC) uses over 500 small textures in menus, but only around 70
1527 // different ones
1528 if (textureCacheSafetyColorSampleSize == 0 ||
1529 std::max(texture_info.GetTextureSize(), palette_size) <=
1530 (u32)textureCacheSafetyColorSampleSize * 8)
1531 {
1532 auto hash_range = m_textures_by_hash.equal_range(full_hash);
1533 TexHashCache::iterator hash_iter = hash_range.first;
1534 while (hash_iter != hash_range.second)
1535 {
1536 RcTcacheEntry& entry = hash_iter->second;
1537 // All parameters, except the address, need to match here
1538 if (entry->format == full_format && entry->native_levels >= texture_info.GetLevelCount() &&
1539 entry->native_width == texture_info.GetRawWidth() &&
1540 entry->native_height == texture_info.GetRawHeight())
1541 {
1542 entry = DoPartialTextureUpdates(hash_iter->second, texture_info.GetTlutAddress(),
1543 texture_info.GetTlutFormat());
1544 if (entry)
1545 {
1546 entry->texture->FinishedRendering();
1547 return entry;
1548 }
1549 }
1550 ++hash_iter;
1551 }
1552 }
1553
1554 // If at least one entry was not used for the same frame, overwrite the oldest one
1555 if (temp_frameCount != 0x7fffffff)
1556 {
1557 // pool this texture and make a new one later
1558 InvalidateTexture(oldest_entry);
1559 }
1560
1561 std::shared_ptr<HiresTexture> hires_texture;
1562 bool has_arbitrary_mipmaps = false;
1563 bool skip_texture_dump = false;
1564 std::shared_ptr<VideoCommon::CustomTextureData> custom_texture_data = nullptr;
1565 VideoCommon::CustomAsset::TimeType load_time = {};
1566 if (g_ActiveConfig.bHiresTextures)
1567 {
1568 hires_texture = HiresTexture::Search(texture_info);
1569 if (hires_texture)
1570 {
1571 has_arbitrary_mipmaps = hires_texture->HasArbitraryMipmaps();
1572 const auto resource = hires_texture->LoadTexture();
1573 load_time = resource->GetLoadTime();
1574 custom_texture_data = resource->GetData();
1575 if (custom_texture_data && !VideoCommon::ValidateTextureData(
1576 hires_texture->GetId(), *custom_texture_data,
1577 texture_info.GetRawWidth(), texture_info.GetRawHeight()))
1578 {
1579 custom_texture_data = nullptr;
1580 load_time = {};
1581 }
1582 skip_texture_dump = true;
1583 }
1584 }
1585
1586 std::string texture_name = "";
1587
1588 if (g_ActiveConfig.bGraphicMods)
1589 {
1590 u32 height = texture_info.GetRawHeight();
1591 u32 width = texture_info.GetRawWidth();
1592 texture_name = texture_info.CalculateTextureName().GetFullName();
1593 GraphicsModActionData::TextureCreate texture_create{texture_name, width, height, nullptr,
1594 nullptr};
1595 for (const auto& action : g_graphics_mod_manager->GetTextureCreateActions(texture_name))
1596 {
1597 action->OnTextureCreate(&texture_create);
1598 }
1599 }
1600
1601 auto entry =
1602 CreateTextureEntry(TextureCreationInfo{base_hash, full_hash, bytes_per_block, palette_size},
1603 texture_info, textureCacheSafetyColorSampleSize, custom_texture_data.get(),
1604 has_arbitrary_mipmaps, skip_texture_dump);
1605 entry->hires_texture = std::move(hires_texture);
1606 entry->last_load_time = load_time;
1607 entry->texture_info_name = std::move(texture_name);
1608 return entry;
1609 }
1610
1611 // Note: the following function assumes all CustomTextureData has a single slice. This is verified
1612 // with the 'GameTexture::Validate' function after the data is loaded. Only a single slice is
1613 // expected because each texture is loaded into a texture array
1614 RcTcacheEntry TextureCacheBase::CreateTextureEntry(
1615 const TextureCreationInfo& creation_info, const TextureInfo& texture_info,
1616 const int safety_color_sample_size, VideoCommon::CustomTextureData* custom_texture_data,
1617 const bool custom_arbitrary_mipmaps, bool skip_texture_dump)
1618 {
1619 #ifdef __APPLE__
1620 const bool no_mips = g_ActiveConfig.bNoMipmapping;
1621 #else
1622 const bool no_mips = false;
1623 #endif
1624
1625 RcTcacheEntry entry;
1626 if (custom_texture_data)
1627 {
1628 const u32 texLevels = no_mips ? 1 : (u32)custom_texture_data->m_slices[0].m_levels.size();
1629 const auto& first_level = custom_texture_data->m_slices[0].m_levels[0];
1630 const TextureConfig config(first_level.width, first_level.height, texLevels, 1, 1,
1631 first_level.format, 0, AbstractTextureType::Texture_2DArray);
1632 entry = AllocateCacheEntry(config);
1633 if (!entry) [[unlikely]]
1634 return entry;
1635 const auto& slice = custom_texture_data->m_slices[0];
1636 for (u32 level_index = 0;
1637 level_index < std::min(texLevels, static_cast<u32>(slice.m_levels.size())); ++level_index)
1638 {
1639 const auto& level = slice.m_levels[level_index];
1640 entry->texture->Load(level_index, level.width, level.height, level.row_length,
1641 level.data.data(), level.data.size());
1642 }
1643
1644 entry->has_arbitrary_mips = custom_arbitrary_mipmaps;
1645 entry->is_custom_tex = true;
1646 }
1647 else
1648 {
1649 const u32 texLevels = no_mips ? 1 : texture_info.GetLevelCount();
1650 const u32 expanded_width = texture_info.GetExpandedWidth();
1651 const u32 expanded_height = texture_info.GetExpandedHeight();
1652
1653 const u32 width = texture_info.GetRawWidth();
1654 const u32 height = texture_info.GetRawHeight();
1655
1656 const TextureConfig config(width, height, texLevels, 1, 1, AbstractTextureFormat::RGBA8, 0,
1657 AbstractTextureType::Texture_2DArray);
1658 entry = AllocateCacheEntry(config);
1659 if (!entry) [[unlikely]]
1660 return entry;
1661
1662 // We can decode on the GPU if it is a supported format and the flag is enabled.
1663 // Currently we don't decode RGBA8 textures from TMEM, as that would require copying from both
1664 // banks, and if we're doing an copy we may as well just do the whole thing on the CPU, since
1665 // there's no conversion between formats. In the future this could be extended with a separate
1666 // shader, however.
1667 const bool decode_on_gpu =
1668 g_ActiveConfig.UseGPUTextureDecoding() &&
1669 !(texture_info.IsFromTmem() && texture_info.GetTextureFormat() == TextureFormat::RGBA8);
1670
1671 ArbitraryMipmapDetector arbitrary_mip_detector;
1672
1673 // Initialized to null because only software loading uses this buffer
1674 u8* dst_buffer = nullptr;
1675
1676 if (!decode_on_gpu ||
1677 !DecodeTextureOnGPU(
1678 entry, 0, texture_info.GetData(), texture_info.GetTextureSize(),
1679 texture_info.GetTextureFormat(), width, height, expanded_width, expanded_height,
1680 creation_info.bytes_per_block * (expanded_width / texture_info.GetBlockWidth()),
1681 texture_info.GetTlutAddress(), texture_info.GetTlutFormat()))
1682 {
1683 size_t decoded_texture_size = expanded_width * sizeof(u32) * expanded_height;
1684
1685 // Allocate memory for all levels at once
1686 size_t total_texture_size = decoded_texture_size;
1687
1688 // For the downsample, we need 2 buffers; 1 is 1/4 of the original texture, the other 1/16
1689 size_t mip_downsample_buffer_size = decoded_texture_size * 5 / 16;
1690
1691 size_t prev_level_size = decoded_texture_size;
1692 for (u32 i = 1; i < texture_info.GetLevelCount(); ++i)
1693 {
1694 prev_level_size /= 4;
1695 total_texture_size += prev_level_size;
1696 }
1697
1698 // Add space for the downsampling at the end
1699 total_texture_size += mip_downsample_buffer_size;
1700
1701 CheckTempSize(total_texture_size);
1702 dst_buffer = m_temp;
1703 if (!(texture_info.GetTextureFormat() == TextureFormat::RGBA8 && texture_info.IsFromTmem()))
1704 {
1705 TexDecoder_Decode(dst_buffer, texture_info.GetData(), expanded_width, expanded_height,
1706 texture_info.GetTextureFormat(), texture_info.GetTlutAddress(),
1707 texture_info.GetTlutFormat());
1708 }
1709 else
1710 {
1711 TexDecoder_DecodeRGBA8FromTmem(dst_buffer, texture_info.GetData(),
1712 texture_info.GetTmemOddAddress(), expanded_width,
1713 expanded_height);
1714 }
1715
1716 entry->texture->Load(0, width, height, expanded_width, dst_buffer, decoded_texture_size);
1717
1718 arbitrary_mip_detector.AddLevel(width, height, expanded_width, dst_buffer);
1719
1720 dst_buffer += decoded_texture_size;
1721 }
1722
1723 for (const auto& mip_level : texture_info.GetMipMapLevels())
1724 {
1725 if (no_mips)
1726 break;
1727 if (!mip_level.IsDataValid())
1728 {
1729 ERROR_LOG_FMT(VIDEO, "Trying to use an invalid mipmap address {:#010x}",
1730 texture_info.GetRawAddress());
1731 continue;
1732 }
1733
1734 if (!decode_on_gpu ||
1735 !DecodeTextureOnGPU(entry, mip_level.GetLevel(), mip_level.GetData(),
1736 mip_level.GetTextureSize(), texture_info.GetTextureFormat(),
1737 mip_level.GetRawWidth(), mip_level.GetRawHeight(),
1738 mip_level.GetExpandedWidth(), mip_level.GetExpandedHeight(),
1739 creation_info.bytes_per_block *
1740 (mip_level.GetExpandedWidth() / texture_info.GetBlockWidth()),
1741 texture_info.GetTlutAddress(), texture_info.GetTlutFormat()))
1742 {
1743 // No need to call CheckTempSize here, as the whole buffer is preallocated at the beginning
1744 const u32 decoded_mip_size =
1745 mip_level.GetExpandedWidth() * sizeof(u32) * mip_level.GetExpandedHeight();
1746 TexDecoder_Decode(dst_buffer, mip_level.GetData(), mip_level.GetExpandedWidth(),
1747 mip_level.GetExpandedHeight(), texture_info.GetTextureFormat(),
1748 texture_info.GetTlutAddress(), texture_info.GetTlutFormat());
1749 entry->texture->Load(mip_level.GetLevel(), mip_level.GetRawWidth(),
1750 mip_level.GetRawHeight(), mip_level.GetExpandedWidth(), dst_buffer,
1751 decoded_mip_size);
1752
1753 arbitrary_mip_detector.AddLevel(mip_level.GetRawWidth(), mip_level.GetRawHeight(),
1754 mip_level.GetExpandedWidth(), dst_buffer);
1755
1756 dst_buffer += decoded_mip_size;
1757 }
1758 }
1759
1760 entry->has_arbitrary_mips = arbitrary_mip_detector.HasArbitraryMipmaps(dst_buffer);
1761
1762 if (g_ActiveConfig.bDumpTextures && !skip_texture_dump && texLevels > 0)
1763 {
1764 const std::string basename = texture_info.CalculateTextureName().GetFullName();
1765 if (g_ActiveConfig.bDumpBaseTextures)
1766 {
1767 m_texture_dumper.DumpTexture(*entry->texture, basename, 0, entry->has_arbitrary_mips);
1768 }
1769 if (g_ActiveConfig.bDumpMipmapTextures)
1770 {
1771 for (u32 level = 1; level < texLevels; ++level)
1772 {
1773 m_texture_dumper.DumpTexture(*entry->texture, basename, level, entry->has_arbitrary_mips);
1774 }
1775 }
1776 }
1777 }
1778
1779 const auto iter = m_textures_by_address.emplace(texture_info.GetRawAddress(), entry);
1780 if (safety_color_sample_size == 0 ||
1781 std::max(texture_info.GetTextureSize(), creation_info.palette_size) <=
1782 (u32)safety_color_sample_size * 8)
1783 {
1784 entry->textures_by_hash_iter = m_textures_by_hash.emplace(creation_info.full_hash, entry);
1785 }
1786
1787 const TextureAndTLUTFormat full_format(texture_info.GetTextureFormat(),
1788 texture_info.GetTlutFormat());
1789 entry->SetGeneralParameters(texture_info.GetRawAddress(), texture_info.GetTextureSize(),
1790 full_format, false);
1791 entry->SetDimensions(texture_info.GetRawWidth(), texture_info.GetRawHeight(),
1792 texture_info.GetLevelCount());
1793 entry->SetHashes(creation_info.base_hash, creation_info.full_hash);
1794 entry->memory_stride = entry->BytesPerRow();
1795 entry->SetNotCopy();
1796
1797 INCSTAT(g_stats.num_textures_uploaded);
1798 SETSTAT(g_stats.num_textures_alive, static_cast<int>(m_textures_by_address.size()));
1799
1800 entry = DoPartialTextureUpdates(iter->second, texture_info.GetTlutAddress(),
1801 texture_info.GetTlutFormat());
1802
1803 // This should only be needed if the texture was updated, or used GPU decoding.
1804 entry->texture->FinishedRendering();
1805
1806 return entry;
1807 }
1808
1809 static void GetDisplayRectForXFBEntry(TCacheEntry* entry, u32 width, u32 height,
1810 MathUtil::Rectangle<int>* display_rect)
1811 {
1812 // Scale the sub-rectangle to the full resolution of the texture.
1813 display_rect->left = 0;
1814 display_rect->top = 0;
1815 display_rect->right = static_cast<int>(width * entry->GetWidth() / entry->native_width);
1816 display_rect->bottom = static_cast<int>(height * entry->GetHeight() / entry->native_height);
1817 }
1818
1819 RcTcacheEntry TextureCacheBase::GetXFBTexture(u32 address, u32 width, u32 height, u32 stride,
1820 MathUtil::Rectangle<int>* display_rect)
1821 {
1822 // Compute total texture size. XFB textures aren't tiled, so this is simple.
1823 const u32 total_size = height * stride;
1824
1825 auto& system = Core::System::GetInstance();
1826 auto& memory = system.GetMemory();
1827 const u8* src_data = memory.GetPointerForRange(address, total_size);
1828 if (!src_data)
1829 {
1830 ERROR_LOG_FMT(VIDEO, "Trying to load XFB texture from invalid address {:#010x}", address);
1831 return {};
1832 }
1833
1834 // Do we currently have a mutable version of this XFB copy in VRAM?
1835 RcTcacheEntry entry = GetXFBFromCache(address, width, height, stride);
1836 if (entry && !entry->IsLocked())
1837 {
1838 if (entry->is_xfb_container)
1839 {
1840 StitchXFBCopy(entry);
1841 entry->texture->FinishedRendering();
1842 }
1843
1844 GetDisplayRectForXFBEntry(entry.get(), width, height, display_rect);
1845 return entry;
1846 }
1847
1848 // Create a new VRAM texture, and fill it with the data from guest RAM.
1849 entry = AllocateCacheEntry(TextureConfig(width, height, 1, 1, 1, AbstractTextureFormat::RGBA8,
1850 AbstractTextureFlag_RenderTarget,
1851 AbstractTextureType::Texture_2DArray));
1852
1853 entry->SetGeneralParameters(address, total_size,
1854 TextureAndTLUTFormat(TextureFormat::XFB, TLUTFormat::IA8), true);
1855 entry->SetDimensions(width, height, 1);
1856 entry->SetXfbCopy(stride);
1857
1858 const u64 hash = entry->CalculateHash();
1859 entry->SetHashes(hash, hash);
1860 entry->is_xfb_container = true;
1861 entry->is_custom_tex = false;
1862 entry->may_have_overlapping_textures = false;
1863 entry->frameCount = FRAMECOUNT_INVALID;
1864 if (!g_ActiveConfig.UseGPUTextureDecoding() ||
1865 !DecodeTextureOnGPU(entry, 0, src_data, total_size, entry->format.texfmt, width, height,
1866 width, height, stride, s_tex_mem.data(), entry->format.tlutfmt))
1867 {
1868 const u32 decoded_size = width * height * sizeof(u32);
1869 CheckTempSize(decoded_size);
1870 TexDecoder_DecodeXFB(m_temp, src_data, width, height, stride);
1871 entry->texture->Load(0, width, height, width, m_temp, decoded_size);
1872 }
1873
1874 // Stitch any VRAM copies into the new RAM copy.
1875 StitchXFBCopy(entry);
1876 entry->texture->FinishedRendering();
1877
1878 // Insert into the texture cache so we can re-use it next frame, if needed.
1879 m_textures_by_address.emplace(entry->addr, entry);
1880 SETSTAT(g_stats.num_textures_alive, static_cast<int>(m_textures_by_address.size()));
1881 INCSTAT(g_stats.num_textures_uploaded);
1882
1883 if (g_ActiveConfig.bDumpXFBTarget || g_ActiveConfig.bGraphicMods)
1884 {
1885 const std::string id = fmt::format("{}x{}", width, height);
1886 if (g_ActiveConfig.bGraphicMods)
1887 {
1888 entry->texture_info_name = fmt::format("{}_{}", XFB_DUMP_PREFIX, id);
1889 }
1890
1891 if (g_ActiveConfig.bDumpXFBTarget)
1892 {
1893 entry->texture->Save(fmt::format("{}{}_n{:06}_{}.png", File::GetUserPath(D_DUMPTEXTURES_IDX),
1894 XFB_DUMP_PREFIX, xfb_count++, id),
1895 0);
1896 }
1897 }
1898
1899 GetDisplayRectForXFBEntry(entry.get(), width, height, display_rect);
1900 return entry;
1901 }
1902
1903 RcTcacheEntry TextureCacheBase::GetXFBFromCache(u32 address, u32 width, u32 height, u32 stride)
1904 {
1905 auto iter_range = m_textures_by_address.equal_range(address);
1906 TexAddrCache::iterator iter = iter_range.first;
1907
1908 while (iter != iter_range.second)
1909 {
1910 auto& entry = iter->second;
1911
1912 // The only thing which has to match exactly is the stride. We can use a partial rectangle if
1913 // the VI width/height differs from that of the XFB copy.
1914 if (entry->is_xfb_copy && entry->memory_stride == stride && entry->native_width >= width &&
1915 entry->native_height >= height && !entry->may_have_overlapping_textures)
1916 {
1917 if (entry->hash == entry->CalculateHash() && !entry->reference_changed)
1918 {
1919 return entry;
1920 }
1921 else
1922 {
1923 // At this point, we either have an xfb copy that has changed its hash
1924 // or an xfb created by stitching or from memory that has been changed
1925 // we are safe to invalidate this
1926 iter = InvalidateTexture(iter);
1927 continue;
1928 }
1929 }
1930
1931 ++iter;
1932 }
1933
1934 return {};
1935 }
1936
1937 void TextureCacheBase::StitchXFBCopy(RcTcacheEntry& stitched_entry)
1938 {
1939 // It is possible that some of the overlapping textures overlap each other. This behavior has been
1940 // seen with XFB copies in Rogue Leader. To get the correct result, we apply the texture updates
1941 // in the order the textures were originally loaded. This ensures that the parts of the texture
1942 // that would have been overwritten in memory on real hardware get overwritten the same way here
1943 // too. This should work, but it may be a better idea to keep track of partial XFB copy
1944 // invalidations instead, which would reduce the amount of copying work here.
1945 std::vector<TCacheEntry*> candidates;
1946 bool create_upscaled_copy = false;
1947
1948 auto iter = FindOverlappingTextures(stitched_entry->addr, stitched_entry->size_in_bytes);
1949 while (iter.first != iter.second)
1950 {
1951 // Currently, this checks the stride of the VRAM copy against the VI request. Therefore, for
1952 // interlaced modes, VRAM copies won't be considered candidates. This is okay for now, because
1953 // our force progressive hack means that an XFB copy should always have a matching stride. If
1954 // the hack is disabled, XFB2RAM should also be enabled. Should we wish to implement interlaced
1955 // stitching in the future, this would require a shader which grabs every second line.
1956 auto& entry = iter.first->second;
1957 if (entry != stitched_entry && entry->IsCopy() &&
1958 entry->OverlapsMemoryRange(stitched_entry->addr, stitched_entry->size_in_bytes) &&
1959 entry->memory_stride == stitched_entry->memory_stride)
1960 {
1961 if (entry->hash == entry->CalculateHash())
1962 {
1963 // Can't check the height here because of Y scaling.
1964 if (entry->native_width != entry->GetWidth())
1965 create_upscaled_copy = true;
1966
1967 candidates.emplace_back(entry.get());
1968 }
1969 else
1970 {
1971 // If the hash does not match, this EFB copy will not be used for anything, so remove it
1972 iter.first = InvalidateTexture(iter.first);
1973 continue;
1974 }
1975 }
1976 ++iter.first;
1977 }
1978
1979 if (candidates.empty())
1980 return;
1981
1982 std::ranges::sort(candidates, {}, &TCacheEntry::id);
1983
1984 // We only upscale when necessary to preserve resolution. i.e. when there are upscaled partial
1985 // copies to be stitched together.
1986 if (create_upscaled_copy)
1987 {
1988 ScaleTextureCacheEntryTo(stitched_entry,
1989 g_framebuffer_manager->EFBToScaledX(stitched_entry->native_width),
1990 g_framebuffer_manager->EFBToScaledY(stitched_entry->native_height));
1991 }
1992
1993 for (TCacheEntry* entry : candidates)
1994 {
1995 int src_x, src_y, dst_x, dst_y;
1996 if (entry->addr >= stitched_entry->addr)
1997 {
1998 int pixel_offset = (entry->addr - stitched_entry->addr) / 2;
1999 src_x = 0;
2000 src_y = 0;
2001 dst_x = pixel_offset % stitched_entry->native_width;
2002 dst_y = pixel_offset / stitched_entry->native_width;
2003 }
2004 else
2005 {
2006 int pixel_offset = (stitched_entry->addr - entry->addr) / 2;
2007 src_x = pixel_offset % entry->native_width;
2008 src_y = pixel_offset / entry->native_width;
2009 dst_x = 0;
2010 dst_y = 0;
2011 }
2012
2013 const int native_width =
2014 std::min(entry->native_width - src_x, stitched_entry->native_width - dst_x);
2015 const int native_height =
2016 std::min(entry->native_height - src_y, stitched_entry->native_height - dst_y);
2017 int src_width = native_width;
2018 int src_height = native_height;
2019 int dst_width = native_width;
2020 int dst_height = native_height;
2021
2022 // Scale to internal resolution.
2023 if (entry->native_width != entry->GetWidth())
2024 {
2025 src_x = g_framebuffer_manager->EFBToScaledX(src_x);
2026 src_y = g_framebuffer_manager->EFBToScaledY(src_y);
2027 src_width = g_framebuffer_manager->EFBToScaledX(src_width);
2028 src_height = g_framebuffer_manager->EFBToScaledY(src_height);
2029 }
2030 if (create_upscaled_copy)
2031 {
2032 dst_x = g_framebuffer_manager->EFBToScaledX(dst_x);
2033 dst_y = g_framebuffer_manager->EFBToScaledY(dst_y);
2034 dst_width = g_framebuffer_manager->EFBToScaledX(dst_width);
2035 dst_height = g_framebuffer_manager->EFBToScaledY(dst_height);
2036 }
2037
2038 // If the source rectangle is outside of what we actually have in VRAM, skip the copy.
2039 // The backend doesn't do any clamping, so if we don't, we'd pass out-of-range coordinates
2040 // to the graphics driver, which can cause GPU resets.
2041 if (static_cast<u32>(src_x + src_width) > entry->GetWidth() ||
2042 static_cast<u32>(src_y + src_height) > entry->GetHeight() ||
2043 static_cast<u32>(dst_x + dst_width) > stitched_entry->GetWidth() ||
2044 static_cast<u32>(dst_y + dst_height) > stitched_entry->GetHeight())
2045 {
2046 continue;
2047 }
2048
2049 MathUtil::Rectangle<int> srcrect, dstrect;
2050 srcrect.left = src_x;
2051 srcrect.top = src_y;
2052 srcrect.right = (src_x + src_width);
2053 srcrect.bottom = (src_y + src_height);
2054 dstrect.left = dst_x;
2055 dstrect.top = dst_y;
2056 dstrect.right = (dst_x + dst_width);
2057 dstrect.bottom = (dst_y + dst_height);
2058
2059 // We may have to scale if one of the copies is not internal resolution.
2060 if (srcrect.GetWidth() != dstrect.GetWidth() || srcrect.GetHeight() != dstrect.GetHeight())
2061 {
2062 g_gfx->ScaleTexture(stitched_entry->framebuffer.get(), dstrect, entry->texture.get(),
2063 srcrect);
2064 }
2065 else
2066 {
2067 // If one copy is stereo, and the other isn't... not much we can do here :/
2068 const u32 layers_to_copy = std::min(entry->GetNumLayers(), stitched_entry->GetNumLayers());
2069 for (u32 layer = 0; layer < layers_to_copy; layer++)
2070 {
2071 stitched_entry->texture->CopyRectangleFromTexture(entry->texture.get(), srcrect, layer, 0,
2072 dstrect, layer, 0);
2073 }
2074 }
2075
2076 // Link the two textures together, so we won't apply this partial update again
2077 entry->CreateReference(stitched_entry.get());
2078
2079 // Mark the texture update as used, as if it was loaded directly
2080 entry->frameCount = FRAMECOUNT_INVALID;
2081 }
2082 }
2083
2084 std::array<u32, 3>
2085 TextureCacheBase::GetRAMCopyFilterCoefficients(const CopyFilterCoefficients::Values& coefficients)
2086 {
2087 // To simplify the backend, we precalculate the three coefficients in common. Coefficients 0, 1
2088 // are for the row above, 2, 3, 4 are for the current pixel, and 5, 6 are for the row below.
2089 return {
2090 static_cast<u32>(coefficients[0]) + static_cast<u32>(coefficients[1]),
2091 static_cast<u32>(coefficients[2]) + static_cast<u32>(coefficients[3]) +
2092 static_cast<u32>(coefficients[4]),
2093 static_cast<u32>(coefficients[5]) + static_cast<u32>(coefficients[6]),
2094 };
2095 }
2096
2097 std::array<u32, 3>
2098 TextureCacheBase::GetVRAMCopyFilterCoefficients(const CopyFilterCoefficients::Values& coefficients)
2099 {
2100 // If the user disables the copy filter, only apply it to the VRAM copy.
2101 // This way games which are sensitive to changes to the RAM copy of the XFB will be unaffected.
2102 std::array<u32, 3> res = GetRAMCopyFilterCoefficients(coefficients);
2103 if (!g_ActiveConfig.bDisableCopyFilter)
2104 return res;
2105
2106 // Disabling the copy filter in options should not ignore the values the game sets completely,
2107 // as some games use the filter coefficients to control the brightness of the screen. Instead,
2108 // add all coefficients to the middle sample, so the deflicker/vertical filter has no effect.
2109 res[1] = res[0] + res[1] + res[2];
2110 res[0] = 0;
2111 res[2] = 0;
2112 return res;
2113 }
2114
2115 bool TextureCacheBase::AllCopyFilterCoefsNeeded(const std::array<u32, 3>& coefficients)
2116 {
2117 // If the top/bottom coefficients are zero, no point sampling/blending from these rows.
2118 return coefficients[0] != 0 || coefficients[2] != 0;
2119 }
2120
2121 bool TextureCacheBase::CopyFilterCanOverflow(const std::array<u32, 3>& coefficients)
2122 {
2123 // Normally, the copy filter coefficients will sum to at most 64. If the sum is higher than that,
2124 // colors are clamped to the range [0, 255], but if the sum is higher than 128, that clamping
2125 // breaks (as colors end up >= 512, which wraps back to 0).
2126 return coefficients[0] + coefficients[1] + coefficients[2] >= 128;
2127 }
2128
2129 void TextureCacheBase::CopyRenderTargetToTexture(
2130 u32 dstAddr, EFBCopyFormat dstFormat, u32 width, u32 height, u32 dstStride, bool is_depth_copy,
2131 const MathUtil::Rectangle<int>& srcRect, bool isIntensity, bool scaleByHalf, float y_scale,
2132 float gamma, bool clamp_top, bool clamp_bottom,
2133 const CopyFilterCoefficients::Values& filter_coefficients)
2134 {
2135 // Emulation methods:
2136 //
2137 // - EFB to RAM:
2138 // Encodes the requested EFB data at its native resolution to the emulated RAM using shaders.
2139 // Load() decodes the data from there again (using TextureDecoder) if the EFB copy is being
2140 // used as a texture again.
2141 // Advantage: CPU can read data from the EFB copy and we don't lose any important updates to
2142 // the texture
2143 // Disadvantage: Encoding+decoding steps often are redundant because only some games read or
2144 // modify EFB copies before using them as textures.
2145 //
2146 // - EFB to texture:
2147 // Copies the requested EFB data to a texture object in VRAM, performing any color conversion
2148 // using shaders.
2149 // Advantage: Works for many games, since in most cases EFB copies aren't read or modified at
2150 // all before being used as a texture again.
2151 // Since we don't do any further encoding or decoding here, this method is much
2152 // faster.
2153 // It also allows enhancing the visual quality by doing scaled EFB copies.
2154 //
2155 // - Hybrid EFB copies:
2156 // 1a) Whenever this function gets called, encode the requested EFB data to RAM (like EFB to
2157 // RAM)
2158 // 1b) Set type to TCET_EC_DYNAMIC for all texture cache entries in the destination address
2159 // range.
2160 // If EFB copy caching is enabled, further checks will (try to) prevent redundant EFB
2161 // copies.
2162 // 2) Check if a texture cache entry for the specified dstAddr already exists (i.e. if an EFB
2163 // copy was triggered to that address before):
2164 // 2a) Entry doesn't exist:
2165 // - Also copy the requested EFB data to a texture object in VRAM (like EFB to texture)
2166 // - Create a texture cache entry for the target (type = TCET_EC_VRAM)
2167 // - Store a hash of the encoded RAM data in the texcache entry.
2168 // 2b) Entry exists AND type is TCET_EC_VRAM:
2169 // - Like case 2a, but reuse the old texcache entry instead of creating a new one.
2170 // 2c) Entry exists AND type is TCET_EC_DYNAMIC:
2171 // - Only encode the texture to RAM (like EFB to RAM) and store a hash of the encoded
2172 // data in the existing texcache entry.
2173 // - Do NOT copy the requested EFB data to a VRAM object. Reason: the texture is dynamic,
2174 // i.e. the CPU is modifying it. Storing a VRAM copy is useless, because we'd always end
2175 // up deleting it and reloading the data from RAM anyway.
2176 // 3) If the EFB copy gets used as a texture, compare the source RAM hash with the hash you
2177 // stored when encoding the EFB data to RAM.
2178 // 3a) If the two hashes match AND type is TCET_EC_VRAM, reuse the VRAM copy you created
2179 // 3b) If the two hashes differ AND type is TCET_EC_VRAM, screw your existing VRAM copy. Set
2180 // type to TCET_EC_DYNAMIC.
2181 // Redecode the source RAM data to a VRAM object. The entry basically behaves like a
2182 // normal texture now.
2183 // 3c) If type is TCET_EC_DYNAMIC, treat the EFB copy like a normal texture.
2184 // Advantage: Non-dynamic EFB copies can be visually enhanced like with EFB to texture.
2185 // Compatibility is as good as EFB to RAM.
2186 // Disadvantage: Slower than EFB to texture and often even slower than EFB to RAM.
2187 // EFB copy cache depends on accurate texture hashing being enabled. However,
2188 // with accurate hashing you end up being as slow as without a copy cache
2189 // anyway.
2190 //
2191 // Disadvantage of all methods: Calling this function requires the GPU to perform a pipeline flush
2192 // which stalls any further CPU processing.
2193 const bool is_xfb_copy = !is_depth_copy && !isIntensity && dstFormat == EFBCopyFormat::XFB;
2194 bool copy_to_vram = g_backend_info.bSupportsCopyToVram && !g_ActiveConfig.bDisableCopyToVRAM;
2195 bool copy_to_ram =
2196 !(is_xfb_copy ? g_ActiveConfig.bSkipXFBCopyToRam : g_ActiveConfig.bSkipEFBCopyToRam) ||
2197 !copy_to_vram;
2198
2199 // tex_w and tex_h are the native size of the texture in the GC memory.
2200 // The size scaled_* represents the emulated texture. Those differ
2201 // because of upscaling and because of yscaling of XFB copies.
2202 // For the latter, we keep the EFB resolution for the virtual XFB blit.
2203 u32 tex_w = width;
2204 u32 tex_h = height;
2205 u32 scaled_tex_w = g_framebuffer_manager->EFBToScaledX(width);
2206 u32 scaled_tex_h = g_framebuffer_manager->EFBToScaledY(height);
2207
2208 if (scaleByHalf)
2209 {
2210 tex_w /= 2;
2211 tex_h /= 2;
2212 scaled_tex_w /= 2;
2213 scaled_tex_h /= 2;
2214 }
2215
2216 if (!is_xfb_copy && !g_ActiveConfig.bCopyEFBScaled)
2217 {
2218 // No upscaling
2219 scaled_tex_w = tex_w;
2220 scaled_tex_h = tex_h;
2221 }
2222
2223 // Get the base (in memory) format of this efb copy.
2224 TextureFormat baseFormat = TexDecoder_GetEFBCopyBaseFormat(dstFormat);
2225
2226 u32 blockH = TexDecoder_GetBlockHeightInTexels(baseFormat);
2227 const u32 blockW = TexDecoder_GetBlockWidthInTexels(baseFormat);
2228
2229 // Round up source height to multiple of block size
2230 u32 actualHeight = Common::AlignUp(tex_h, blockH);
2231 const u32 actualWidth = Common::AlignUp(tex_w, blockW);
2232
2233 u32 num_blocks_y = actualHeight / blockH;
2234 const u32 num_blocks_x = actualWidth / blockW;
2235
2236 // RGBA takes two cache lines per block; all others take one
2237 const u32 bytes_per_block = baseFormat == TextureFormat::RGBA8 ? 64 : 32;
2238
2239 const u32 bytes_per_row = num_blocks_x * bytes_per_block;
2240 const u32 covered_range = num_blocks_y * dstStride;
2241
2242 auto& system = Core::System::GetInstance();
2243 auto& memory = system.GetMemory();
2244 u8* dst = memory.GetPointerForRange(dstAddr, covered_range);
2245 if (dst == nullptr)
2246 {
2247 ERROR_LOG_FMT(VIDEO, "Trying to copy from EFB to invalid address {:#010x}", dstAddr);
2248 return;
2249 }
2250
2251 if (g_ActiveConfig.bGraphicMods)
2252 {
2253 FBInfo info;
2254 info.m_width = tex_w;
2255 info.m_height = tex_h;
2256 info.m_texture_format = baseFormat;
2257 if (is_xfb_copy)
2258 {
2259 for (const auto& action : g_graphics_mod_manager->GetXFBActions(info))
2260 {
2261 action->BeforeXFB();
2262 }
2263 }
2264 else
2265 {
2266 bool skip = false;
2267 GraphicsModActionData::PreEFB efb{tex_w, tex_h, &skip, &scaled_tex_w, &scaled_tex_h};
2268 for (const auto& action : g_graphics_mod_manager->GetEFBActions(info))
2269 {
2270 action->BeforeEFB(&efb);
2271 }
2272 if (skip == true)
2273 {
2274 if (copy_to_ram)
2275 UninitializeEFBMemory(dst, dstStride, bytes_per_row, num_blocks_y);
2276 return;
2277 }
2278 }
2279 }
2280
2281 if (dstStride < bytes_per_row)
2282 {
2283 // This kind of efb copy results in a scrambled image.
2284 // I'm pretty sure no game actually wants to do this, it might be caused by a
2285 // programming bug in the game, or a CPU/Bounding box emulation issue with dolphin.
2286 // The copy_to_ram code path above handles this "correctly" and scrambles the image
2287 // but the copy_to_vram code path just saves and uses unscrambled texture instead.
2288
2289 // To avoid a "incorrect" result, we simply skip doing the copy_to_vram code path
2290 // so if the game does try to use the scrambled texture, dolphin will grab the scrambled
2291 // texture (or black if copy_to_ram is also disabled) out of ram.
2292 ERROR_LOG_FMT(VIDEO, "Memory stride too small ({} < {})", dstStride, bytes_per_row);
2293 copy_to_vram = false;
2294 }
2295
2296 // We also linear filtering for both box filtering and downsampling higher resolutions to 1x.
2297 // TODO: This only produces perfect downsampling for 2x IR, other resolutions will need more
2298 // complex down filtering to average all pixels and produce the correct result.
2299 const bool linear_filter =
2300 !is_depth_copy &&
2301 (scaleByHalf || g_framebuffer_manager->GetEFBScale() != 1 || y_scale > 1.0f);
2302
2303 RcTcacheEntry entry;
2304 if (copy_to_vram)
2305 {
2306 // create the texture
2307 const TextureConfig config(scaled_tex_w, scaled_tex_h, 1, g_framebuffer_manager->GetEFBLayers(),
2308 1, AbstractTextureFormat::RGBA8, AbstractTextureFlag_RenderTarget,
2309 AbstractTextureType::Texture_2DArray);
2310 entry = AllocateCacheEntry(config);
2311 if (entry)
2312 {
2313 entry->SetGeneralParameters(dstAddr, 0, baseFormat, is_xfb_copy);
2314 entry->SetDimensions(tex_w, tex_h, 1);
2315 entry->frameCount = FRAMECOUNT_INVALID;
2316 if (is_xfb_copy)
2317 {
2318 entry->should_force_safe_hashing = is_xfb_copy;
2319 entry->SetXfbCopy(dstStride);
2320 }
2321 else
2322 {
2323 entry->SetEfbCopy(dstStride);
2324 }
2325 entry->may_have_overlapping_textures = false;
2326 entry->is_custom_tex = false;
2327
2328 CopyEFBToCacheEntry(entry, is_depth_copy, srcRect, scaleByHalf, linear_filter, dstFormat,
2329 isIntensity, gamma, clamp_top, clamp_bottom,
2330 GetVRAMCopyFilterCoefficients(filter_coefficients));
2331
2332 if (g_ActiveConfig.bGraphicMods)
2333 {
2334 FBInfo info;
2335 info.m_width = tex_w;
2336 info.m_height = tex_h;
2337 info.m_texture_format = baseFormat;
2338 if (!is_xfb_copy)
2339 {
2340 GraphicsModActionData::PostEFB efb;
2341 for (const auto& action : g_graphics_mod_manager->GetEFBActions(info))
2342 {
2343 action->AfterEFB(&efb);
2344 if (efb.material)
2345 {
2346 ApplyMaterialToCacheEntry(*efb.material, entry.get());
2347 }
2348 }
2349 }
2350 }
2351
2352 if (is_xfb_copy && (g_ActiveConfig.bDumpXFBTarget || g_ActiveConfig.bGraphicMods))
2353 {
2354 const std::string id = fmt::format("{}x{}", tex_w, tex_h);
2355 if (g_ActiveConfig.bGraphicMods)
2356 {
2357 entry->texture_info_name = fmt::format("{}_{}", XFB_DUMP_PREFIX, id);
2358 }
2359
2360 if (g_ActiveConfig.bDumpXFBTarget)
2361 {
2362 entry->texture->Save(fmt::format("{}{}_n{:06}_{}.png",
2363 File::GetUserPath(D_DUMPTEXTURES_IDX), XFB_DUMP_PREFIX,
2364 xfb_count++, id),
2365 0);
2366 }
2367 }
2368 else if (g_ActiveConfig.bDumpEFBTarget || g_ActiveConfig.bGraphicMods)
2369 {
2370 const std::string id = fmt::format("{}x{}_{}", tex_w, tex_h, static_cast<int>(baseFormat));
2371 if (g_ActiveConfig.bGraphicMods)
2372 {
2373 entry->texture_info_name = fmt::format("{}_{}", EFB_DUMP_PREFIX, id);
2374 }
2375
2376 if (g_ActiveConfig.bDumpEFBTarget)
2377 {
2378 static int efb_count = 0;
2379 entry->texture->Save(fmt::format("{}{}_n{:06}_{}.png",
2380 File::GetUserPath(D_DUMPTEXTURES_IDX), EFB_DUMP_PREFIX,
2381 efb_count++, id),
2382 0);
2383 }
2384 }
2385 }
2386 }
2387
2388 if (copy_to_ram)
2389 {
2390 const std::array<u32, 3> coefficients = GetRAMCopyFilterCoefficients(filter_coefficients);
2391 PixelFormat srcFormat = bpmem.zcontrol.pixel_format;
2392 EFBCopyParams format(srcFormat, dstFormat, is_depth_copy, isIntensity,
2393 AllCopyFilterCoefsNeeded(coefficients),
2394 CopyFilterCanOverflow(coefficients), gamma != 1.0);
2395
2396 std::unique_ptr<AbstractStagingTexture> staging_texture = GetEFBCopyStagingTexture();
2397 if (staging_texture)
2398 {
2399 CopyEFB(staging_texture.get(), format, tex_w, bytes_per_row, num_blocks_y, dstStride, srcRect,
2400 scaleByHalf, linear_filter, y_scale, gamma, clamp_top, clamp_bottom, coefficients);
2401
2402 // We can't defer if there is no VRAM copy (since we need to update the hash).
2403 if (!copy_to_vram || !g_ActiveConfig.bDeferEFBCopies)
2404 {
2405 // Immediately flush it.
2406 WriteEFBCopyToRAM(dst, bytes_per_row / sizeof(u32), num_blocks_y, dstStride,
2407 std::move(staging_texture));
2408 }
2409 else
2410 {
2411 // Defer the flush until later.
2412 entry->pending_efb_copy = std::move(staging_texture);
2413 entry->pending_efb_copy_width = bytes_per_row / sizeof(u32);
2414 entry->pending_efb_copy_height = num_blocks_y;
2415 m_pending_efb_copies.push_back(entry);
2416 }
2417 }
2418 }
2419 else
2420 {
2421 if (is_xfb_copy)
2422 {
2423 UninitializeXFBMemory(dst, dstStride, bytes_per_row, num_blocks_y);
2424 }
2425 else
2426 {
2427 UninitializeEFBMemory(dst, dstStride, bytes_per_row, num_blocks_y);
2428 }
2429 }
2430
2431 // Invalidate all textures, if they are either fully overwritten by our efb copy, or if they
2432 // have a different stride than our efb copy. Partly overwritten textures with the same stride
2433 // as our efb copy are marked to check them for partial texture updates.
2434 // TODO: The logic to detect overlapping strided efb copies is not 100% accurate.
2435 bool strided_efb_copy = dstStride != bytes_per_row;
2436 auto iter = FindOverlappingTextures(dstAddr, covered_range);
2437 while (iter.first != iter.second)
2438 {
2439 RcTcacheEntry& overlapping_entry = iter.first->second;
2440
2441 if (overlapping_entry->addr == dstAddr && overlapping_entry->is_xfb_copy)
2442 {
2443 for (auto& reference : overlapping_entry->references)
2444 {
2445 reference->reference_changed = true;
2446 }
2447 }
2448
2449 if (overlapping_entry->OverlapsMemoryRange(dstAddr, covered_range))
2450 {
2451 u32 overlap_range = std::min(overlapping_entry->addr + overlapping_entry->size_in_bytes,
2452 dstAddr + covered_range) -
2453 std::max(overlapping_entry->addr, dstAddr);
2454 if (!copy_to_vram || overlapping_entry->memory_stride != dstStride ||
2455 (!strided_efb_copy && overlapping_entry->size_in_bytes == overlap_range) ||
2456 (strided_efb_copy && overlapping_entry->size_in_bytes == overlap_range &&
2457 overlapping_entry->addr == dstAddr))
2458 {
2459 // Pending EFB copies which are completely covered by this new copy can simply be tossed,
2460 // instead of having to flush them later on, since this copy will write over everything.
2461 iter.first = InvalidateTexture(iter.first, true);
2462 continue;
2463 }
2464
2465 // We don't want to change the may_have_overlapping_textures flag on XFB container entries
2466 // because otherwise they can't be re-used/updated, leaking textures for several frames.
2467 if (!overlapping_entry->is_xfb_container)
2468 overlapping_entry->may_have_overlapping_textures = true;
2469
2470 // There are cases (Rogue Squadron 2 / Texas Holdem on Wiiware) where
2471 // for xfb copies the textures overlap which causes the hash of the first copy
2472 // to be different (from when it was originally created). This has no implications
2473 // for XFB2Tex because the underlying memory doesn't change (dummy values) but
2474 // can affect XFB2Ram when we compare the texture cache copy hash with the
2475 // newly computed hash
2476 // By calculating the hash when we receive overlapping xfbs, we are able
2477 // to mitigate this
2478 if (overlapping_entry->is_xfb_copy && copy_to_ram)
2479 {
2480 overlapping_entry->hash = overlapping_entry->CalculateHash();
2481 }
2482
2483 // Do not load textures by hash, if they were at least partly overwritten by an efb copy.
2484 // In this case, comparing the hash is not enough to check, if two textures are identical.
2485 if (overlapping_entry->textures_by_hash_iter != m_textures_by_hash.end())
2486 {
2487 m_textures_by_hash.erase(overlapping_entry->textures_by_hash_iter);
2488 overlapping_entry->textures_by_hash_iter = m_textures_by_hash.end();
2489 }
2490 }
2491 ++iter.first;
2492 }
2493
2494 if (OpcodeDecoder::g_record_fifo_data)
2495 {
2496 // Mark the memory behind this efb copy as dynamically generated for the Fifo log
2497 u32 address = dstAddr;
2498 for (u32 i = 0; i < num_blocks_y; i++)
2499 {
2500 Core::System::GetInstance().GetFifoRecorder().UseMemory(address, bytes_per_row,
2501 MemoryUpdate::Type::TextureMap, true);
2502 address += dstStride;
2503 }
2504 }
2505
2506 // Even if the copy is deferred, still compute the hash. This way if the copy is used as a texture
2507 // in a subsequent draw before it is flushed, it will have the same hash.
2508 if (entry)
2509 {
2510 const u64 hash = entry->CalculateHash();
2511 entry->SetHashes(hash, hash);
2512 m_textures_by_address.emplace(dstAddr, std::move(entry));
2513 }
2514 }
2515
2516 void TextureCacheBase::FlushEFBCopies()
2517 {
2518 if (m_pending_efb_copies.empty())
2519 return;
2520
2521 for (auto& entry : m_pending_efb_copies)
2522 FlushEFBCopy(entry.get());
2523 m_pending_efb_copies.clear();
2524 }
2525
2526 void TextureCacheBase::FlushStaleBinds()
2527 {
2528 for (u32 i = 0; i < m_bound_textures.size(); i++)
2529 {
2530 if (!TMEM::IsCached(i))
2531 m_bound_textures[i].reset();
2532 }
2533 }
2534
2535 void TextureCacheBase::WriteEFBCopyToRAM(u8* dst_ptr, u32 width, u32 height, u32 stride,
2536 std::unique_ptr<AbstractStagingTexture> staging_texture)
2537 {
2538 MathUtil::Rectangle<int> copy_rect(0, 0, static_cast<int>(width), static_cast<int>(height));
2539 staging_texture->ReadTexels(copy_rect, dst_ptr, stride);
2540 ReleaseEFBCopyStagingTexture(std::move(staging_texture));
2541 }
2542
2543 void TextureCacheBase::FlushEFBCopy(TCacheEntry* entry)
2544 {
2545 const u32 covered_range = entry->pending_efb_copy_height * entry->memory_stride;
2546
2547 // Copy from texture -> guest memory.
2548 auto& system = Core::System::GetInstance();
2549 auto& memory = system.GetMemory();
2550 u8* const dst = memory.GetPointerForRange(entry->addr, covered_range);
2551 WriteEFBCopyToRAM(dst, entry->pending_efb_copy_width, entry->pending_efb_copy_height,
2552 entry->memory_stride, std::move(entry->pending_efb_copy));
2553
2554 // If the EFB copy was invalidated (e.g. the bloom case mentioned in InvalidateTexture), we don't
2555 // need to do anything more. The entry will be automatically deleted by smart pointers
2556 if (entry->invalidated)
2557 return;
2558
2559 // Re-hash the texture now that the guest memory is populated.
2560 // This should be safe because we'll catch any writes before the game can modify it.
2561 const u64 hash = entry->CalculateHash();
2562 entry->SetHashes(hash, hash);
2563
2564 // Check for any overlapping XFB copies which now need the hash recomputed.
2565 // See the comment above regarding Rogue Squadron 2.
2566 if (entry->is_xfb_copy)
2567 {
2568 auto range = FindOverlappingTextures(entry->addr, covered_range);
2569 for (auto iter = range.first; iter != range.second; ++iter)
2570 {
2571 auto& overlapping_entry = iter->second;
2572 if (overlapping_entry->may_have_overlapping_textures && overlapping_entry->is_xfb_copy &&
2573 overlapping_entry->OverlapsMemoryRange(entry->addr, covered_range))
2574 {
2575 const u64 overlapping_hash = overlapping_entry->CalculateHash();
2576 entry->SetHashes(overlapping_hash, overlapping_hash);
2577 }
2578 }
2579 }
2580 }
2581
2582 std::unique_ptr<AbstractStagingTexture> TextureCacheBase::GetEFBCopyStagingTexture()
2583 {
2584 // Pull off the back first to re-use the most frequently used textures.
2585 if (!m_efb_copy_staging_texture_pool.empty())
2586 {
2587 auto ptr = std::move(m_efb_copy_staging_texture_pool.back());
2588 m_efb_copy_staging_texture_pool.pop_back();
2589 return ptr;
2590 }
2591
2592 std::unique_ptr<AbstractStagingTexture> tex = g_gfx->CreateStagingTexture(
2593 StagingTextureType::Readback, m_efb_encoding_texture->GetConfig());
2594 if (!tex)
2595 WARN_LOG_FMT(VIDEO, "Failed to create EFB copy staging texture");
2596
2597 return tex;
2598 }
2599
2600 void TextureCacheBase::ReleaseEFBCopyStagingTexture(std::unique_ptr<AbstractStagingTexture> tex)
2601 {
2602 m_efb_copy_staging_texture_pool.push_back(std::move(tex));
2603 }
2604
2605 void TextureCacheBase::UninitializeEFBMemory(u8* dst, u32 stride, u32 bytes_per_row,
2606 u32 num_blocks_y)
2607 {
2608 // Hack: Most games don't actually need the correct texture data in RAM
2609 // and we can just keep a copy in VRAM. We zero the memory so we
2610 // can check it hasn't changed before using our copy in VRAM.
2611 u8* ptr = dst;
2612 for (u32 i = 0; i < num_blocks_y; i++)
2613 {
2614 std::memset(ptr, 0, bytes_per_row);
2615 ptr += stride;
2616 }
2617 }
2618
2619 void TextureCacheBase::UninitializeXFBMemory(u8* dst, u32 stride, u32 bytes_per_row,
2620 u32 num_blocks_y)
2621 {
2622 // Originally, we planned on using a 'key color'
2623 // for alpha to address partial xfbs (Mario Strikers / Chicken Little).
2624 // This work was removed since it was unfinished but there
2625 // was still a desire to differentiate between the old and the new approach
2626 // which is why we still set uninitialized xfb memory to fuchsia
2627 // (Y=1,U=254,V=254) instead of dark green (Y=0,U=0,V=0) in YUV
2628 // like is done in the EFB path.
2629
2630 #if defined(_M_X86_64)
2631 __m128i sixteenBytes = _mm_set1_epi16((s16)(u16)0xFE01);
2632 #endif
2633
2634 for (u32 i = 0; i < num_blocks_y; i++)
2635 {
2636 u32 size = bytes_per_row;
2637 u8* rowdst = dst;
2638 #if defined(_M_X86_64)
2639 while (size >= 16)
2640 {
2641 _mm_storeu_si128((__m128i*)rowdst, sixteenBytes);
2642 size -= 16;
2643 rowdst += 16;
2644 }
2645 #endif
2646 for (u32 offset = 0; offset < size; offset++)
2647 {
2648 if (offset & 1)
2649 {
2650 rowdst[offset] = 254;
2651 }
2652 else
2653 {
2654 rowdst[offset] = 1;
2655 }
2656 }
2657 dst += stride;
2658 }
2659 }
2660
2661 RcTcacheEntry TextureCacheBase::AllocateCacheEntry(const TextureConfig& config)
2662 {
2663 std::optional<TexPoolEntry> alloc = AllocateTexture(config);
2664 if (!alloc)
2665 return {};
2666
2667 auto cacheEntry =
2668 std::make_shared<TCacheEntry>(std::move(alloc->texture), std::move(alloc->framebuffer));
2669 cacheEntry->textures_by_hash_iter = m_textures_by_hash.end();
2670 cacheEntry->id = m_last_entry_id++;
2671 return cacheEntry;
2672 }
2673
2674 std::optional<TextureCacheBase::TexPoolEntry>
2675 TextureCacheBase::AllocateTexture(const TextureConfig& config)
2676 {
2677 TexPool::iterator iter = FindMatchingTextureFromPool(config);
2678 if (iter != m_texture_pool.end())
2679 {
2680 auto entry = std::move(iter->second);
2681 m_texture_pool.erase(iter);
2682 return std::move(entry);
2683 }
2684
2685 std::unique_ptr<AbstractTexture> texture = g_gfx->CreateTexture(config);
2686 if (!texture)
2687 {
2688 WARN_LOG_FMT(VIDEO, "Failed to allocate a {}x{}x{} texture", config.width, config.height,
2689 config.layers);
2690 return {};
2691 }
2692
2693 std::unique_ptr<AbstractFramebuffer> framebuffer;
2694 if (config.IsRenderTarget())
2695 {
2696 framebuffer = g_gfx->CreateFramebuffer(texture.get(), nullptr);
2697 if (!framebuffer)
2698 {
2699 WARN_LOG_FMT(VIDEO, "Failed to allocate a {}x{}x{} framebuffer", config.width, config.height,
2700 config.layers);
2701 return {};
2702 }
2703 }
2704
2705 INCSTAT(g_stats.num_textures_created);
2706 return TexPoolEntry(std::move(texture), std::move(framebuffer));
2707 }
2708
2709 TextureCacheBase::TexPool::iterator
2710 TextureCacheBase::FindMatchingTextureFromPool(const TextureConfig& config)
2711 {
2712 // Find a texture from the pool that does not have a frameCount of FRAMECOUNT_INVALID.
2713 // This prevents a texture from being used twice in a single frame with different data,
2714 // which potentially means that a driver has to maintain two copies of the texture anyway.
2715 // Render-target textures are fine through, as they have to be generated in a separate pass.
2716 // As non-render-target textures are usually static, this should not matter much.
2717 auto range = m_texture_pool.equal_range(config);
2718 auto matching_iter = std::find_if(range.first, range.second, [](const auto& iter) {
2719 return iter.first.IsRenderTarget() || iter.second.frameCount != FRAMECOUNT_INVALID;
2720 });
2721 return matching_iter != range.second ? matching_iter : m_texture_pool.end();
2722 }
2723
2724 TextureCacheBase::TexAddrCache::iterator TextureCacheBase::GetTexCacheIter(TCacheEntry* entry)
2725 {
2726 auto iter_range = m_textures_by_address.equal_range(entry->addr);
2727 TexAddrCache::iterator iter = iter_range.first;
2728 while (iter != iter_range.second)
2729 {
2730 if (iter->second.get() == entry)
2731 {
2732 return iter;
2733 }
2734 ++iter;
2735 }
2736 return m_textures_by_address.end();
2737 }
2738
2739 std::pair<TextureCacheBase::TexAddrCache::iterator, TextureCacheBase::TexAddrCache::iterator>
2740 TextureCacheBase::FindOverlappingTextures(u32 addr, u32 size_in_bytes)
2741 {
2742 // We index by the starting address only, so there is no way to query all textures
2743 // which end after the given addr. But the GC textures have a limited size, so we
2744 // look for all textures which have a start address bigger than addr minus the maximal
2745 // texture size. But this yields false-positives which must be checked later on.
2746
2747 // 1024 x 1024 texel times 8 nibbles per texel
2748 constexpr u32 max_texture_size = 1024 * 1024 * 4;
2749 u32 lower_addr = addr > max_texture_size ? addr - max_texture_size : 0;
2750 auto begin = m_textures_by_address.lower_bound(lower_addr);
2751 auto end = m_textures_by_address.upper_bound(addr + size_in_bytes);
2752
2753 return std::make_pair(begin, end);
2754 }
2755
2756 TextureCacheBase::TexAddrCache::iterator
2757 TextureCacheBase::InvalidateTexture(TexAddrCache::iterator iter, bool discard_pending_efb_copy)
2758 {
2759 if (iter == m_textures_by_address.end())
2760 return m_textures_by_address.end();
2761
2762 RcTcacheEntry& entry = iter->second;
2763
2764 if (entry->textures_by_hash_iter != m_textures_by_hash.end())
2765 {
2766 m_textures_by_hash.erase(entry->textures_by_hash_iter);
2767 entry->textures_by_hash_iter = m_textures_by_hash.end();
2768 }
2769
2770 // If this is a pending EFB copy, we don't want to flush it here.
2771 // Why? Because let's say a game is rendering a bloom-type effect, using EFB copies to essentially
2772 // downscale the framebuffer. Copy from EFB->Texture, draw texture to EFB, copy EFB->Texture,
2773 // draw, repeat. The second copy will invalidate the first, forcing a flush. Which means we lose
2774 // any benefit of EFB copy batching. So instead, let's just leave the EFB copy pending, but remove
2775 // it from the texture cache. This way we don't use the old VRAM copy. When the EFB copies are
2776 // eventually flushed, they will overwrite each other, and the end result should be the same.
2777 if (entry->pending_efb_copy)
2778 {
2779 if (discard_pending_efb_copy)
2780 {
2781 // If the RAM copy is being completely overwritten by a new EFB copy, we can discard the
2782 // existing pending copy, and not bother waiting for it in the future. This happens in
2783 // Xenoblade's sunset scene, where 35 copies are done per frame, and 25 of them are
2784 // copied to the same address, and can be skipped.
2785 ReleaseEFBCopyStagingTexture(std::move(entry->pending_efb_copy));
2786 auto pending_it = std::ranges::find(m_pending_efb_copies, entry);
2787 if (pending_it != m_pending_efb_copies.end())
2788 m_pending_efb_copies.erase(pending_it);
2789 }
2790 else
2791 {
2792 // The texture data has already been copied into the staging texture, so it's valid to
2793 // optimistically release the texture data. Will slightly lower VRAM usage.
2794 if (!entry->IsLocked())
2795 ReleaseToPool(entry.get());
2796 }
2797 }
2798 entry->invalidated = true;
2799
2800 return m_textures_by_address.erase(iter);
2801 }
2802
2803 void TextureCacheBase::ReleaseToPool(TCacheEntry* entry)
2804 {
2805 if (!entry->texture)
2806 return;
2807 auto config = entry->texture->GetConfig();
2808 m_texture_pool.emplace(config,
2809 TexPoolEntry(std::move(entry->texture), std::move(entry->framebuffer)));
2810 }
2811
2812 bool TextureCacheBase::CreateUtilityTextures()
2813 {
2814 constexpr TextureConfig encoding_texture_config(
2815 EFB_WIDTH * 4, 1024, 1, 1, 1, AbstractTextureFormat::BGRA8, AbstractTextureFlag_RenderTarget,
2816 AbstractTextureType::Texture_2DArray);
2817 m_efb_encoding_texture = g_gfx->CreateTexture(encoding_texture_config, "EFB encoding texture");
2818 if (!m_efb_encoding_texture)
2819 return false;
2820
2821 m_efb_encoding_framebuffer = g_gfx->CreateFramebuffer(m_efb_encoding_texture.get(), nullptr);
2822 if (!m_efb_encoding_framebuffer)
2823 return false;
2824
2825 if (g_backend_info.bSupportsGPUTextureDecoding)
2826 {
2827 constexpr TextureConfig decoding_texture_config(
2828 1024, 1024, 1, 1, 1, AbstractTextureFormat::RGBA8, AbstractTextureFlag_ComputeImage,
2829 AbstractTextureType::Texture_2DArray);
2830 m_decoding_texture =
2831 g_gfx->CreateTexture(decoding_texture_config, "GPU texture decoding texture");
2832 if (!m_decoding_texture)
2833 return false;
2834 }
2835
2836 return true;
2837 }
2838
2839 void TextureCacheBase::CopyEFBToCacheEntry(RcTcacheEntry& entry, bool is_depth_copy,
2840 const MathUtil::Rectangle<int>& src_rect,
2841 bool scale_by_half, bool linear_filter,
2842 EFBCopyFormat dst_format, bool is_intensity, float gamma,
2843 bool clamp_top, bool clamp_bottom,
2844 const std::array<u32, 3>& filter_coefficients)
2845 {
2846 // Flush EFB pokes first, as they're expected to be included.
2847 g_framebuffer_manager->FlushEFBPokes();
2848
2849 // Get the pipeline which we will be using. If the compilation failed, this will be null.
2850 const AbstractPipeline* copy_pipeline = g_shader_cache->GetEFBCopyToVRAMPipeline(
2851 TextureConversionShaderGen::GetShaderUid(dst_format, is_depth_copy, is_intensity,
2852 scale_by_half, 1.0f / gamma, filter_coefficients));
2853 if (!copy_pipeline)
2854 {
2855 WARN_LOG_FMT(VIDEO, "Skipping EFB copy to VRAM due to missing pipeline.");
2856 return;
2857 }
2858
2859 const auto scaled_src_rect = g_framebuffer_manager->ConvertEFBRectangle(src_rect);
2860 const auto framebuffer_rect = g_gfx->ConvertFramebufferRectangle(
2861 scaled_src_rect, g_framebuffer_manager->GetEFBFramebuffer());
2862 AbstractTexture* src_texture =
2863 is_depth_copy ? g_framebuffer_manager->ResolveEFBDepthTexture(framebuffer_rect) :
2864 g_framebuffer_manager->ResolveEFBColorTexture(framebuffer_rect);
2865
2866 g_gfx->BeginUtilityDrawing();
2867 src_texture->FinishedRendering();
2868
2869 // Fill uniform buffer.
2870 struct Uniforms
2871 {
2872 float src_left, src_top, src_width, src_height;
2873 std::array<u32, 3> filter_coefficients;
2874 float gamma_rcp;
2875 float clamp_top;
2876 float clamp_bottom;
2877 float pixel_height;
2878 u32 padding;
2879 };
2880 Uniforms uniforms;
2881 const float rcp_efb_width = 1.0f / static_cast<float>(g_framebuffer_manager->GetEFBWidth());
2882 const u32 efb_height = g_framebuffer_manager->GetEFBHeight();
2883 const float rcp_efb_height = 1.0f / static_cast<float>(efb_height);
2884 uniforms.src_left = framebuffer_rect.left * rcp_efb_width;
2885 uniforms.src_top = framebuffer_rect.top * rcp_efb_height;
2886 uniforms.src_width = framebuffer_rect.GetWidth() * rcp_efb_width;
2887 uniforms.src_height = framebuffer_rect.GetHeight() * rcp_efb_height;
2888 uniforms.filter_coefficients = filter_coefficients;
2889 uniforms.gamma_rcp = 1.0f / gamma;
2890 // NOTE: when the clamp bits aren't set, the hardware will happily read beyond the EFB,
2891 // which returns random garbage from the empty bus (confirmed by hardware tests).
2892 //
2893 // In our implementation, the garbage just so happens to be the top or bottom row.
2894 // Statistically, that could happen.
2895 const u32 top_coord = clamp_top ? framebuffer_rect.top : 0;
2896 uniforms.clamp_top = (static_cast<float>(top_coord) + .5f) * rcp_efb_height;
2897 const u32 bottom_coord = (clamp_bottom ? framebuffer_rect.bottom : efb_height) - 1;
2898 uniforms.clamp_bottom = (static_cast<float>(bottom_coord) + .5f) * rcp_efb_height;
2899 uniforms.pixel_height = g_ActiveConfig.bCopyEFBScaled ? rcp_efb_height : 1.0f / EFB_HEIGHT;
2900 uniforms.padding = 0;
2901 g_vertex_manager->UploadUtilityUniforms(&uniforms, sizeof(uniforms));
2902
2903 // Use the copy pipeline to render the VRAM copy.
2904 g_gfx->SetAndDiscardFramebuffer(entry->framebuffer.get());
2905 g_gfx->SetViewportAndScissor(entry->framebuffer->GetRect());
2906 g_gfx->SetPipeline(copy_pipeline);
2907 g_gfx->SetTexture(0, src_texture);
2908 g_gfx->SetSamplerState(0, linear_filter ? RenderState::GetLinearSamplerState() :
2909 RenderState::GetPointSamplerState());
2910 g_gfx->Draw(0, 3);
2911 g_gfx->EndUtilityDrawing();
2912 entry->texture->FinishedRendering();
2913 }
2914
2915 void TextureCacheBase::CopyEFB(AbstractStagingTexture* dst, const EFBCopyParams& params,
2916 u32 native_width, u32 bytes_per_row, u32 num_blocks_y,
2917 u32 memory_stride, const MathUtil::Rectangle<int>& src_rect,
2918 bool scale_by_half, bool linear_filter, float y_scale, float gamma,
2919 bool clamp_top, bool clamp_bottom,
2920 const std::array<u32, 3>& filter_coefficients)
2921 {
2922 // Flush EFB pokes first, as they're expected to be included.
2923 g_framebuffer_manager->FlushEFBPokes();
2924
2925 // Get the pipeline which we will be using. If the compilation failed, this will be null.
2926 const AbstractPipeline* copy_pipeline = g_shader_cache->GetEFBCopyToRAMPipeline(params);
2927 if (!copy_pipeline)
2928 {
2929 WARN_LOG_FMT(VIDEO, "Skipping EFB copy to VRAM due to missing pipeline.");
2930 return;
2931 }
2932
2933 const auto scaled_src_rect = g_framebuffer_manager->ConvertEFBRectangle(src_rect);
2934 const auto framebuffer_rect = g_gfx->ConvertFramebufferRectangle(
2935 scaled_src_rect, g_framebuffer_manager->GetEFBFramebuffer());
2936 AbstractTexture* src_texture =
2937 params.depth ? g_framebuffer_manager->ResolveEFBDepthTexture(framebuffer_rect) :
2938 g_framebuffer_manager->ResolveEFBColorTexture(framebuffer_rect);
2939
2940 g_gfx->BeginUtilityDrawing();
2941 src_texture->FinishedRendering();
2942
2943 // Fill uniform buffer.
2944 struct Uniforms
2945 {
2946 std::array<s32, 4> position_uniform;
2947 float y_scale;
2948 float gamma_rcp;
2949 float clamp_top;
2950 float clamp_bottom;
2951 std::array<u32, 3> filter_coefficients;
2952 u32 padding;
2953 };
2954 Uniforms encoder_params;
2955 const u32 efb_height = g_framebuffer_manager->GetEFBHeight();
2956 const float rcp_efb_height = 1.0f / static_cast<float>(efb_height);
2957 encoder_params.position_uniform[0] = src_rect.left;
2958 encoder_params.position_uniform[1] = src_rect.top;
2959 encoder_params.position_uniform[2] = static_cast<s32>(native_width);
2960 encoder_params.position_uniform[3] = scale_by_half ? 2 : 1;
2961 encoder_params.y_scale = y_scale;
2962 encoder_params.gamma_rcp = 1.0f / gamma;
2963 // NOTE: when the clamp bits aren't set, the hardware will happily read beyond the EFB,
2964 // which returns random garbage from the empty bus (confirmed by hardware tests).
2965 //
2966 // In our implementation, the garbage just so happens to be the top or bottom row.
2967 // Statistically, that could happen.
2968 const u32 top_coord = clamp_top ? framebuffer_rect.top : 0;
2969 encoder_params.clamp_top = (static_cast<float>(top_coord) + .5f) * rcp_efb_height;
2970 const u32 bottom_coord = (clamp_bottom ? framebuffer_rect.bottom : efb_height) - 1;
2971 encoder_params.clamp_bottom = (static_cast<float>(bottom_coord) + .5f) * rcp_efb_height;
2972 encoder_params.filter_coefficients = filter_coefficients;
2973 g_vertex_manager->UploadUtilityUniforms(&encoder_params, sizeof(encoder_params));
2974
2975 // Because the shader uses gl_FragCoord and we read it back, we must render to the lower-left.
2976 const u32 render_width = bytes_per_row / sizeof(u32);
2977 const u32 render_height = num_blocks_y;
2978 const auto encode_rect = MathUtil::Rectangle<int>(0, 0, render_width, render_height);
2979
2980 // Render to GPU texture, and then copy to CPU-accessible texture.
2981 g_gfx->SetAndDiscardFramebuffer(m_efb_encoding_framebuffer.get());
2982 g_gfx->SetViewportAndScissor(encode_rect);
2983 g_gfx->SetPipeline(copy_pipeline);
2984 g_gfx->SetTexture(0, src_texture);
2985 g_gfx->SetSamplerState(0, linear_filter ? RenderState::GetLinearSamplerState() :
2986 RenderState::GetPointSamplerState());
2987 g_gfx->Draw(0, 3);
2988 dst->CopyFromTexture(m_efb_encoding_texture.get(), encode_rect, 0, 0, encode_rect);
2989 g_gfx->EndUtilityDrawing();
2990
2991 // Flush if there's sufficient draws between this copy and the last.
2992 g_vertex_manager->OnEFBCopyToRAM();
2993 }
2994
2995 bool TextureCacheBase::DecodeTextureOnGPU(RcTcacheEntry& entry, u32 dst_level, const u8* data,
2996 u32 data_size, TextureFormat format, u32 width,
2997 u32 height, u32 aligned_width, u32 aligned_height,
2998 u32 row_stride, const u8* palette,
2999 TLUTFormat palette_format)
3000 {
3001 const auto* info = TextureConversionShaderTiled::GetDecodingShaderInfo(format);
3002 if (!info)
3003 return false;
3004
3005 const AbstractShader* shader = g_shader_cache->GetTextureDecodingShader(
3006 format, info->palette_size != 0 ? std::make_optional(palette_format) : std::nullopt);
3007 if (!shader)
3008 return false;
3009
3010 // Copy to GPU-visible buffer, aligned to the data type.
3011 const u32 bytes_per_buffer_elem =
3012 VertexManagerBase::GetTexelBufferElementSize(info->buffer_format);
3013
3014 // Allocate space in stream buffer, and copy texture + palette across.
3015 u32 src_offset = 0, palette_offset = 0;
3016 if (info->palette_size > 0)
3017 {
3018 if (!g_vertex_manager->UploadTexelBuffer(data, data_size, info->buffer_format, &src_offset,
3019 palette, info->palette_size,
3020 TEXEL_BUFFER_FORMAT_R16_UINT, &palette_offset))
3021 {
3022 return false;
3023 }
3024 }
3025 else
3026 {
3027 if (!g_vertex_manager->UploadTexelBuffer(data, data_size, info->buffer_format, &src_offset))
3028 return false;
3029 }
3030
3031 // Set up uniforms.
3032 struct Uniforms
3033 {
3034 u32 dst_width, dst_height;
3035 u32 src_width, src_height;
3036 u32 src_offset, src_row_stride;
3037 u32 palette_offset, unused;
3038 } uniforms = {width, height, aligned_width,
3039 aligned_height, src_offset, row_stride / bytes_per_buffer_elem,
3040 palette_offset};
3041 g_vertex_manager->UploadUtilityUniforms(&uniforms, sizeof(uniforms));
3042 g_gfx->SetComputeImageTexture(0, m_decoding_texture.get(), false, true);
3043
3044 auto dispatch_groups =
3045 TextureConversionShaderTiled::GetDispatchCount(info, aligned_width, aligned_height);
3046 g_gfx->DispatchComputeShader(shader, info->group_size_x, info->group_size_y, 1,
3047 dispatch_groups.first, dispatch_groups.second, 1);
3048
3049 // Copy from decoding texture -> final texture
3050 // This is because we don't want to have to create compute view for every layer
3051 const auto copy_rect = entry->texture->GetConfig().GetMipRect(dst_level);
3052 entry->texture->CopyRectangleFromTexture(m_decoding_texture.get(), copy_rect, 0, 0, copy_rect, 0,
3053 dst_level);
3054 entry->texture->FinishedRendering();
3055 return true;
3056 }
3057
3058 void TextureCacheBase::ApplyMaterialToCacheEntry(const VideoCommon::MaterialResource& material,
3059 TCacheEntry* entry)
3060 {
3061 const auto material_data = material.GetData();
3062 if (!material_data) [[unlikely]]
3063 return;
3064
3065 // Make a copy, we can't write to our texture and use its framebuffer
3066 // at the same time
3067 auto new_entry = AllocateCacheEntry(entry->texture->GetConfig());
3068 new_entry->SetGeneralParameters(entry->addr, entry->size_in_bytes, entry->format,
3069 entry->should_force_safe_hashing);
3070 new_entry->SetDimensions(entry->native_width, entry->native_height, 1);
3071 new_entry->SetEfbCopy(entry->memory_stride);
3072 new_entry->may_have_overlapping_textures = false;
3073 new_entry->frameCount = FRAMECOUNT_INVALID;
3074
3075 g_gfx->BeginUtilityDrawing();
3076 entry->texture->FinishedRendering();
3077
3078 const auto custom_uniforms = material_data->GetUniforms();
3079
3080 // Set up uniforms.
3081 // TODO: this struct should be shared with post processing
3082 struct Uniforms
3083 {
3084 std::array<float, 4> source_resolution;
3085 std::array<float, 4> target_resolution;
3086 std::array<float, 4> window_resolution;
3087 std::array<float, 4> source_rectangle;
3088 s32 source_layer;
3089 s32 source_layer_pad[3];
3090 u32 time;
3091 u32 time_pad[3];
3092 s32 graphics_api;
3093 s32 graphics_api_pad[3];
3094 u32 efb_scale;
3095 u32 efb_scale_pad[3];
3096 } uniforms;
3097
3098 const float rcp_src_width = 1.0f / entry->texture->GetWidth();
3099 const float rcp_src_height = 1.0f / entry->texture->GetHeight();
3100
3101 uniforms.source_resolution = {static_cast<float>(entry->texture->GetWidth()),
3102 static_cast<float>(entry->texture->GetHeight()), rcp_src_width,
3103 rcp_src_height};
3104
3105 // The target resolution is the same here, since we're
3106 // injecting into the texture
3107 uniforms.target_resolution = uniforms.source_resolution;
3108
3109 const auto present_rect = g_presenter->GetTargetRectangle();
3110 uniforms.window_resolution = {static_cast<float>(present_rect.GetWidth()),
3111 static_cast<float>(present_rect.GetHeight()),
3112 1.0f / static_cast<float>(present_rect.GetWidth()),
3113 1.0f / static_cast<float>(present_rect.GetHeight())};
3114
3115 uniforms.source_rectangle = {0, 0, 1, 1};
3116 uniforms.source_layer = 0;
3117 uniforms.time = 0;
3118 uniforms.graphics_api = static_cast<s32>(g_backend_info.api_type);
3119 uniforms.efb_scale = g_framebuffer_manager->GetEFBScale();
3120
3121 Common::UniqueBuffer<u8> uniform_buffer(custom_uniforms.size() + sizeof(uniforms));
3122 std::memcpy(uniform_buffer.data(), &uniforms, sizeof(uniforms));
3123 std::memcpy(uniform_buffer.data() + sizeof(uniforms), custom_uniforms.data(),
3124 custom_uniforms.size());
3125 g_vertex_manager->UploadUtilityUniforms(uniform_buffer.data(),
3126 static_cast<u32>(uniform_buffer.size()));
3127
3128 // Set framebuffer and viewport based on new entry
3129 g_gfx->SetAndDiscardFramebuffer(new_entry->framebuffer.get());
3130 g_gfx->SetViewportAndScissor(new_entry->framebuffer->GetRect());
3131 g_gfx->SetPipeline(material_data->GetPipeline());
3132
3133 g_gfx->SetTexture(0, entry->texture.get());
3134 g_gfx->SetSamplerState(0, RenderState::GetPointSamplerState());
3135
3136 for (const auto& texture : material_data->GetTextures())
3137 {
3138 g_gfx->SetTexture(texture.sampler_index, texture.texture);
3139 g_gfx->SetSamplerState(texture.sampler_index, texture.sampler);
3140 }
3141
3142 g_gfx->Draw(0, 3);
3143 g_gfx->EndUtilityDrawing();
3144
3145 // Finish rendering new entry
3146 new_entry->texture->FinishedRendering();
3147
3148 // Swap new entry and existing entry
3149 std::swap(entry->texture, new_entry->texture);
3150 std::swap(entry->framebuffer, new_entry->framebuffer);
3151
3152 // Return old entry to pool for use in another pass
3153 // or future functionality
3154 ReleaseToPool(new_entry.get());
3155
3156 if (auto* const next_material = material_data->GetNextMaterial(); next_material)
3157 {
3158 ApplyMaterialToCacheEntry(*next_material, entry);
3159 }
3160 }
3161
3162 u32 TCacheEntry::BytesPerRow() const
3163 {
3164 // RGBA takes two cache lines per block; all others take one
3165 const u32 bytes_per_block = format == TextureFormat::RGBA8 ? 64 : 32;
3166
3167 return NumBlocksX() * bytes_per_block;
3168 }
3169
3170 u32 TCacheEntry::NumBlocksX() const
3171 {
3172 const u32 blockW = TexDecoder_GetBlockWidthInTexels(format.texfmt);
3173
3174 // Round up source height to multiple of block size
3175 const u32 actualWidth = Common::AlignUp(native_width, blockW);
3176
3177 return actualWidth / blockW;
3178 }
3179
3180 u32 TCacheEntry::NumBlocksY() const
3181 {
3182 u32 blockH = TexDecoder_GetBlockHeightInTexels(format.texfmt);
3183 // Round up source height to multiple of block size
3184 u32 actualHeight = Common::AlignUp(native_height, blockH);
3185
3186 return actualHeight / blockH;
3187 }
3188
3189 void TCacheEntry::SetXfbCopy(u32 stride)
3190 {
3191 is_efb_copy = false;
3192 is_xfb_copy = true;
3193 is_xfb_container = false;
3194 memory_stride = stride;
3195
3196 ASSERT_MSG(VIDEO, memory_stride >= BytesPerRow(), "Memory stride is too small");
3197
3198 size_in_bytes = memory_stride * NumBlocksY();
3199 }
3200
3201 void TCacheEntry::SetEfbCopy(u32 stride)
3202 {
3203 is_efb_copy = true;
3204 is_xfb_copy = false;
3205 is_xfb_container = false;
3206 memory_stride = stride;
3207
3208 ASSERT_MSG(VIDEO, memory_stride >= BytesPerRow(), "Memory stride is too small");
3209
3210 size_in_bytes = memory_stride * NumBlocksY();
3211 }
3212
3213 void TCacheEntry::SetNotCopy()
3214 {
3215 is_efb_copy = false;
3216 is_xfb_copy = false;
3217 is_xfb_container = false;
3218 }
3219
3220 int TCacheEntry::HashSampleSize() const
3221 {
3222 if (should_force_safe_hashing)
3223 {
3224 return 0;
3225 }
3226
3227 return g_ActiveConfig.iSafeTextureCache_ColorSamples;
3228 }
3229
3230 u64 TCacheEntry::CalculateHash() const
3231 {
3232 const u32 bytes_per_row = BytesPerRow();
3233 const u32 hash_sample_size = HashSampleSize();
3234
3235 // FIXME: textures from tmem won't get the correct hash.
3236 auto& system = Core::System::GetInstance();
3237 auto& memory = system.GetMemory();
3238 u8* ptr = memory.GetPointerForRange(addr, size_in_bytes);
3239 if (memory_stride == bytes_per_row)
3240 {
3241 return Common::GetHash64(ptr, size_in_bytes, hash_sample_size);
3242 }
3243 else
3244 {
3245 const u32 num_blocks_y = NumBlocksY();
3246 u64 temp_hash = size_in_bytes;
3247
3248 u32 samples_per_row = 0;
3249 if (hash_sample_size != 0)
3250 {
3251 // Hash at least 4 samples per row to avoid hashing in a bad pattern, like just on the left
3252 // side of the efb copy
3253 samples_per_row = std::max(hash_sample_size / num_blocks_y, 4u);
3254 }
3255
3256 for (u32 i = 0; i < num_blocks_y; i++)
3257 {
3258 // Multiply by a prime number to mix the hash up a bit. This prevents identical blocks from
3259 // canceling each other out
3260 temp_hash = (temp_hash * 397) ^ Common::GetHash64(ptr, bytes_per_row, samples_per_row);
3261 ptr += memory_stride;
3262 }
3263 return temp_hash;
3264 }
3265 }
3266
3267 TextureCacheBase::TexPoolEntry::TexPoolEntry(std::unique_ptr<AbstractTexture> tex,
3268 std::unique_ptr<AbstractFramebuffer> fb)
3269 : texture(std::move(tex)), framebuffer(std::move(fb))
3270 {
3271 }