Debian Codegraph @

Source/Core/VideoCommon/TextureCacheBase.h

raw symbols SCIP
1 // Copyright 2010 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <array>
7 #include <filesystem>
8 #include <fmt/format.h>
9 #include <map>
10 #include <memory>
11 #include <optional>
12 #include <string>
13 #include <string_view>
14 #include <tuple>
15 #include <unordered_map>
16 #include <unordered_set>
17 #include <vector>
18
19 #include "Common/BitSet.h"
20 #include "Common/CommonTypes.h"
21 #include "Common/Flag.h"
22 #include "Common/MathUtil.h"
23
24 #include "VideoCommon/AbstractTexture.h"
25 #include "VideoCommon/Assets/CustomAsset.h"
26 #include "VideoCommon/BPMemory.h"
27 #include "VideoCommon/HiresTextures.h"
28 #include "VideoCommon/TextureConfig.h"
29 #include "VideoCommon/TextureDecoder.h"
30 #include "VideoCommon/TextureInfo.h"
31 #include "VideoCommon/TextureUtils.h"
32 #include "VideoCommon/VideoEvents.h"
33
34 class AbstractFramebuffer;
35 class AbstractStagingTexture;
36 class PointerWrap;
37 struct SamplerState;
38 struct VideoConfig;
39
40 namespace VideoCommon
41 {
42 class CustomTextureData;
43 class GameTextureAsset;
44 class MaterialResource;
45 } // namespace VideoCommon
46
47 constexpr std::string_view EFB_DUMP_PREFIX = "efb1";
48 constexpr std::string_view XFB_DUMP_PREFIX = "xfb1";
49
50 static constexpr int FRAMECOUNT_INVALID = 0;
51
52 struct TextureAndTLUTFormat
53 {
54 TextureAndTLUTFormat(TextureFormat texfmt_ = TextureFormat::I4,
55 TLUTFormat tlutfmt_ = TLUTFormat::IA8)
56 : texfmt(texfmt_), tlutfmt(tlutfmt_)
57 {
58 }
59
60 bool operator==(const TextureAndTLUTFormat& other) const
61 {
62 if (IsColorIndexed(texfmt))
63 return texfmt == other.texfmt && tlutfmt == other.tlutfmt;
64
65 return texfmt == other.texfmt;
66 }
67
68 TextureFormat texfmt;
69 TLUTFormat tlutfmt;
70 };
71
72 struct EFBCopyParams
73 {
74 EFBCopyParams(PixelFormat efb_format_, EFBCopyFormat copy_format_, bool depth_, bool yuv_,
75 bool all_copy_filter_coefs_needed_, bool copy_filter_can_overflow_,
76 bool apply_gamma_)
77 : efb_format(efb_format_), copy_format(copy_format_), depth(depth_), yuv(yuv_),
78 all_copy_filter_coefs_needed(all_copy_filter_coefs_needed_),
79 copy_filter_can_overflow(copy_filter_can_overflow_), apply_gamma(apply_gamma_)
80 {
81 }
82
83 bool operator<(const EFBCopyParams& rhs) const
84 {
85 return std::tie(efb_format, copy_format, depth, yuv, all_copy_filter_coefs_needed,
86 copy_filter_can_overflow,
87 apply_gamma) < std::tie(rhs.efb_format, rhs.copy_format, rhs.depth, rhs.yuv,
88 rhs.all_copy_filter_coefs_needed,
89 rhs.copy_filter_can_overflow, rhs.apply_gamma);
90 }
91
92 PixelFormat efb_format;
93 EFBCopyFormat copy_format;
94 bool depth;
95 bool yuv;
96 bool all_copy_filter_coefs_needed;
97 bool copy_filter_can_overflow;
98 bool apply_gamma;
99 };
100
101 template <>
102 struct fmt::formatter<EFBCopyParams>
103 {
104 constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
105 template <typename FormatContext>
106 auto format(const EFBCopyParams& uid, FormatContext& ctx) const
107 {
108 std::string copy_format;
109 if (uid.copy_format == EFBCopyFormat::XFB)
110 copy_format = "XFB";
111 else
112 copy_format = fmt::to_string(uid.copy_format);
113 return fmt::format_to(ctx.out(),
114 "format: {}, copy format: {}, depth: {}, yuv: {}, apply_gamma: {}, "
115 "all_copy_filter_coefs_needed: {}, copy_filter_can_overflow: {}",
116 uid.efb_format, copy_format, uid.depth, uid.yuv, uid.apply_gamma,
117 uid.all_copy_filter_coefs_needed, uid.copy_filter_can_overflow);
118 }
119 };
120
121 struct TCacheEntry
122 {
123 // common members
124 std::unique_ptr<AbstractTexture> texture;
125 std::unique_ptr<AbstractFramebuffer> framebuffer;
126 u32 addr = 0;
127 u32 size_in_bytes = 0;
128 u64 base_hash = 0;
129 u64 hash = 0; // for paletted textures, hash = base_hash ^ palette_hash
130 TextureAndTLUTFormat format;
131 u32 memory_stride = 0;
132 bool is_efb_copy = false;
133 bool is_custom_tex = false;
134 bool may_have_overlapping_textures = true;
135 // indicates that the mips in this texture are arbitrary content, aren't just downscaled
136 bool has_arbitrary_mips = false;
137 bool should_force_safe_hashing = false; // for XFB
138 bool is_xfb_copy = false;
139 bool is_xfb_container = false;
140 u64 id = 0;
141 u32 content_semaphore = 0; // Counts up
142
143 // Indicates that this TCacheEntry has been invalided from m_textures_by_address
144 bool invalidated = false;
145
146 bool reference_changed = false; // used by xfb to determine when a reference xfb changed
147
148 // Texture dimensions from the GameCube's point of view
149 u32 native_width = 0;
150 u32 native_height = 0;
151 u32 native_levels = 0;
152
153 // used to delete textures which haven't been used for TEXTURE_KILL_THRESHOLD frames
154 int frameCount = FRAMECOUNT_INVALID;
155
156 // Keep an iterator to the entry in m_textures_by_hash, so it does not need to be searched when
157 // removing the cache entry
158 std::multimap<u64, std::shared_ptr<TCacheEntry>>::iterator textures_by_hash_iter;
159
160 // This is used to keep track of both:
161 // * efb copies used by this partially updated texture
162 // * partially updated textures which refer to this efb copy
163 std::unordered_set<TCacheEntry*> references;
164
165 // Pending EFB copy
166 std::unique_ptr<AbstractStagingTexture> pending_efb_copy;
167 u32 pending_efb_copy_width = 0;
168 u32 pending_efb_copy_height = 0;
169
170 std::string texture_info_name = "";
171
172 VideoCommon::CustomAsset::TimeType last_load_time;
173 std::shared_ptr<HiresTexture> hires_texture;
174
175 explicit TCacheEntry(std::unique_ptr<AbstractTexture> tex,
176 std::unique_ptr<AbstractFramebuffer> fb);
177
178 ~TCacheEntry();
179
180 void SetGeneralParameters(u32 _addr, u32 _size, TextureAndTLUTFormat _format,
181 bool force_safe_hashing)
182 {
183 addr = _addr;
184 size_in_bytes = _size;
185 format = _format;
186 should_force_safe_hashing = force_safe_hashing;
187 }
188
189 void SetDimensions(unsigned int _native_width, unsigned int _native_height,
190 unsigned int _native_levels)
191 {
192 native_width = _native_width;
193 native_height = _native_height;
194 native_levels = _native_levels;
195 memory_stride = _native_width;
196 }
197
198 void SetHashes(u64 _base_hash, u64 _hash)
199 {
200 base_hash = _base_hash;
201 hash = _hash;
202 }
203
204 // This texture entry is used by the other entry as a sub-texture
205 void CreateReference(TCacheEntry* other_entry)
206 {
207 // References are two-way, so they can easily be destroyed later
208 this->references.emplace(other_entry);
209 other_entry->references.emplace(this);
210 }
211
212 // Acquiring a content lock will lock the current contents and prevent texture cache from
213 // reusing the same entry for a newer version of the texture.
214 void AcquireContentLock() { content_semaphore++; }
215 void ReleaseContentLock() { content_semaphore--; }
216
217 // Can this be mutated?
218 bool IsLocked() const { return content_semaphore > 0; }
219
220 void SetXfbCopy(u32 stride);
221 void SetEfbCopy(u32 stride);
222 void SetNotCopy();
223
224 bool OverlapsMemoryRange(u32 range_address, u32 range_size) const;
225
226 bool IsEfbCopy() const { return is_efb_copy; }
227 bool IsCopy() const { return is_xfb_copy || is_efb_copy; }
228 u32 NumBlocksX() const;
229 u32 NumBlocksY() const;
230 u32 BytesPerRow() const;
231
232 u64 CalculateHash() const;
233
234 int HashSampleSize() const;
235 u32 GetWidth() const { return texture->GetConfig().width; }
236 u32 GetHeight() const { return texture->GetConfig().height; }
237 u32 GetNumLevels() const { return texture->GetConfig().levels; }
238 u32 GetNumLayers() const { return texture->GetConfig().layers; }
239 AbstractTextureFormat GetFormat() const { return texture->GetConfig().format; }
240 void DoState(PointerWrap& p);
241 };
242
243 using RcTcacheEntry = std::shared_ptr<TCacheEntry>;
244
245 class TextureCacheBase
246 {
247 public:
248 // Minimal version of TCacheEntry just for TexPool
249 struct TexPoolEntry
250 {
251 std::unique_ptr<AbstractTexture> texture;
252 std::unique_ptr<AbstractFramebuffer> framebuffer;
253 int frameCount = FRAMECOUNT_INVALID;
254
255 TexPoolEntry(std::unique_ptr<AbstractTexture> tex, std::unique_ptr<AbstractFramebuffer> fb);
256 };
257
258 struct TextureCreationInfo
259 {
260 u64 base_hash;
261 u64 full_hash;
262 u32 bytes_per_block;
263 u32 palette_size;
264 };
265
266 TextureCacheBase();
267 virtual ~TextureCacheBase();
268
269 bool Initialize();
270 void Shutdown();
271
272 void OnConfigChanged(const VideoConfig& config);
273
274 // Removes textures which aren't used for more than TEXTURE_KILL_THRESHOLD frames,
275 // frameCount is the current frame number.
276 void Cleanup(int _frameCount);
277
278 void Invalidate();
279 void ReleaseToPool(TCacheEntry* entry);
280
281 TCacheEntry* Load(u32 stage);
282 RcTcacheEntry GetTexture(const int textureCacheSafetyColorSampleSize,
283 const TextureInfo& texture_info);
284 RcTcacheEntry GetXFBTexture(u32 address, u32 width, u32 height, u32 stride,
285 MathUtil::Rectangle<int>* display_rect);
286
287 virtual void BindTextures(BitSet32 used_textures, const std::array<SamplerState, 8>& samplers);
288 void CopyRenderTargetToTexture(u32 dstAddr, EFBCopyFormat dstFormat, u32 width, u32 height,
289 u32 dstStride, bool is_depth_copy,
290 const MathUtil::Rectangle<int>& srcRect, bool isIntensity,
291 bool scaleByHalf, float y_scale, float gamma, bool clamp_top,
292 bool clamp_bottom,
293 const CopyFilterCoefficients::Values& filter_coefficients);
294
295 void ScaleTextureCacheEntryTo(RcTcacheEntry& entry, u32 new_width, u32 new_height);
296
297 // Flushes all pending EFB copies to emulated RAM.
298 void FlushEFBCopies();
299
300 // Flush any Bound textures that can't be reused
301 void FlushStaleBinds();
302
303 // Texture Serialization
304 void SerializeTexture(AbstractTexture* tex, const TextureConfig& config, PointerWrap& p);
305 std::optional<TexPoolEntry> DeserializeTexture(PointerWrap& p);
306
307 // Save States
308 void DoState(PointerWrap& p);
309
310 static bool AllCopyFilterCoefsNeeded(const std::array<u32, 3>& coefficients);
311 static bool CopyFilterCanOverflow(const std::array<u32, 3>& coefficients);
312
313 // Get a new sampler state
314 static SamplerState GetSamplerState(u32 index, float custom_tex_scale, bool custom_tex,
315 bool has_arbitrary_mips);
316
317 protected:
318 // Decodes the specified data to the GPU texture specified by entry.
319 // Returns false if the configuration is not supported.
320 // width, height are the size of the image in pixels.
321 // aligned_width, aligned_height are the size of the image in pixels, aligned to the block size.
322 // row_stride is the number of bytes for a row of blocks, not pixels.
323 bool DecodeTextureOnGPU(RcTcacheEntry& entry, u32 dst_level, const u8* data, u32 data_size,
324 TextureFormat format, u32 width, u32 height, u32 aligned_width,
325 u32 aligned_height, u32 row_stride, const u8* palette,
326 TLUTFormat palette_format);
327
328 virtual void CopyEFB(AbstractStagingTexture* dst, const EFBCopyParams& params, u32 native_width,
329 u32 bytes_per_row, u32 num_blocks_y, u32 memory_stride,
330 const MathUtil::Rectangle<int>& src_rect, bool scale_by_half,
331 bool linear_filter, float y_scale, float gamma, bool clamp_top,
332 bool clamp_bottom, const std::array<u32, 3>& filter_coefficients);
333 virtual void CopyEFBToCacheEntry(RcTcacheEntry& entry, bool is_depth_copy,
334 const MathUtil::Rectangle<int>& src_rect, bool scale_by_half,
335 bool linear_filter, EFBCopyFormat dst_format, bool is_intensity,
336 float gamma, bool clamp_top, bool clamp_bottom,
337 const std::array<u32, 3>& filter_coefficients);
338
339 alignas(16) u8* m_temp = nullptr;
340 size_t m_temp_size = 0;
341
342 private:
343 using TexAddrCache = std::multimap<u32, RcTcacheEntry>;
344 using TexHashCache = std::multimap<u64, RcTcacheEntry>;
345
346 using TexPool = std::unordered_multimap<TextureConfig, TexPoolEntry>;
347
348 static bool DidLinkedAssetsChange(const TCacheEntry& entry);
349
350 TCacheEntry* LoadImpl(u32 stage, bool force_reload);
351
352 bool CreateUtilityTextures();
353
354 void SetBackupConfig(const VideoConfig& config);
355
356 RcTcacheEntry CreateTextureEntry(const TextureCreationInfo& creation_info,
357 const TextureInfo& texture_info, int safety_color_sample_size,
358 VideoCommon::CustomTextureData* custom_texture_data,
359 bool custom_arbitrary_mipmaps, bool skip_texture_dump);
360
361 RcTcacheEntry GetXFBFromCache(u32 address, u32 width, u32 height, u32 stride);
362
363 RcTcacheEntry ApplyPaletteToEntry(RcTcacheEntry& entry, const u8* palette, TLUTFormat tlutfmt);
364
365 RcTcacheEntry ReinterpretEntry(const RcTcacheEntry& existing_entry, TextureFormat new_format);
366
367 RcTcacheEntry DoPartialTextureUpdates(RcTcacheEntry& entry_to_update, const u8* palette,
368 TLUTFormat tlutfmt);
369 void StitchXFBCopy(RcTcacheEntry& entry_to_update);
370
371 void CheckTempSize(size_t required_size);
372
373 RcTcacheEntry AllocateCacheEntry(const TextureConfig& config);
374 std::optional<TexPoolEntry> AllocateTexture(const TextureConfig& config);
375 TexPool::iterator FindMatchingTextureFromPool(const TextureConfig& config);
376 TexAddrCache::iterator GetTexCacheIter(TCacheEntry* entry);
377
378 // Return all possible overlapping textures. As addr+size of the textures is not
379 // indexed, this may return false positives.
380 std::pair<TexAddrCache::iterator, TexAddrCache::iterator>
381 FindOverlappingTextures(u32 addr, u32 size_in_bytes);
382
383 // Removes and unlinks texture from texture cache and returns it to the pool
384 TexAddrCache::iterator InvalidateTexture(TexAddrCache::iterator t_iter,
385 bool discard_pending_efb_copy = false);
386
387 void UninitializeEFBMemory(u8* dst, u32 stride, u32 bytes_per_row, u32 num_blocks_y);
388 void UninitializeXFBMemory(u8* dst, u32 stride, u32 bytes_per_row, u32 num_blocks_y);
389
390 // Precomputing the coefficients for the previous, current, and next lines for the copy filter.
391 static std::array<u32, 3>
392 GetRAMCopyFilterCoefficients(const CopyFilterCoefficients::Values& coefficients);
393 static std::array<u32, 3>
394 GetVRAMCopyFilterCoefficients(const CopyFilterCoefficients::Values& coefficients);
395
396 // Flushes a pending EFB copy to RAM from the host to the guest RAM.
397 void WriteEFBCopyToRAM(u8* dst_ptr, u32 width, u32 height, u32 stride,
398 std::unique_ptr<AbstractStagingTexture> staging_texture);
399 void FlushEFBCopy(TCacheEntry* entry);
400
401 // Returns a staging texture of the maximum EFB copy size.
402 std::unique_ptr<AbstractStagingTexture> GetEFBCopyStagingTexture();
403
404 // Returns an EFB copy staging texture to the pool, so it can be re-used.
405 void ReleaseEFBCopyStagingTexture(std::unique_ptr<AbstractStagingTexture> tex);
406
407 bool CheckReadbackTexture(u32 width, u32 height, AbstractTextureFormat format);
408 void DoSaveState(PointerWrap& p);
409 void DoLoadState(PointerWrap& p);
410
411 void ApplyMaterialToCacheEntry(const VideoCommon::MaterialResource& material, TCacheEntry* entry);
412
413 // m_textures_by_address is the authoritive version of what's actually "in" the texture cache
414 // but it's possible for invalidated TCache entries to live on elsewhere
415 TexAddrCache m_textures_by_address;
416
417 // m_textures_by_hash is an alternative view of the texture cache
418 // All textures in here will also be in m_textures_by_address
419 TexHashCache m_textures_by_hash;
420
421 // m_bound_textures are actually active in the current draw
422 // It's valid for textures to be in here after they've been invalidated
423 std::array<RcTcacheEntry, 8> m_bound_textures{};
424
425 TexPool m_texture_pool;
426 u64 m_last_entry_id = 0;
427
428 // Backup configuration values
429 struct BackupConfig
430 {
431 int color_samples;
432 bool texfmt_overlay;
433 bool texfmt_overlay_center;
434 bool hires_textures;
435 bool cache_hires_textures;
436 bool copy_cache_enable;
437 bool stereo_3d;
438 bool efb_mono_depth;
439 bool gpu_texture_decoding;
440 bool disable_vram_copies;
441 bool arbitrary_mipmap_detection;
442 bool graphics_mods;
443 u32 graphics_mod_change_count;
444 };
445 BackupConfig m_backup_config = {};
446
447 // Encoding texture used for EFB copies to RAM.
448 std::unique_ptr<AbstractTexture> m_efb_encoding_texture;
449 std::unique_ptr<AbstractFramebuffer> m_efb_encoding_framebuffer;
450
451 // Decoding texture used for GPU texture decoding.
452 std::unique_ptr<AbstractTexture> m_decoding_texture;
453
454 // Pool of readback textures used for deferred EFB copies.
455 std::vector<std::unique_ptr<AbstractStagingTexture>> m_efb_copy_staging_texture_pool;
456
457 // List of pending EFB copies. It is important that the order is preserved for these,
458 // so that overlapping textures are written to guest RAM in the order they are issued.
459 // It's valid for textures to live be in here after they've been invalidated
460 std::vector<RcTcacheEntry> m_pending_efb_copies;
461
462 // Staging texture used for readbacks.
463 // We store this in the class so that the same staging texture can be used for multiple
464 // readbacks, saving the overhead of allocating a new buffer every time.
465 std::unique_ptr<AbstractStagingTexture> m_readback_texture;
466
467 void OnFrameEnd();
468
469 Common::EventHook m_frame_event =
470 GetVideoEvents().after_frame_event.Register([this](Core::System&) { OnFrameEnd(); });
471
472 VideoCommon::TextureUtils::TextureDumper m_texture_dumper;
473 };
474
475 extern std::unique_ptr<TextureCacheBase> g_texture_cache;