Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Common/TextureCacheCommon.cpp
3186 views
1
// Copyright (c) 2013- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include "ppsspp_config.h"
19
20
#include <algorithm>
21
22
#include "Common/Common.h"
23
#include "Common/Data/Convert/ColorConv.h"
24
#include "Common/Data/Collections/TinySet.h"
25
#include "Common/Profiler/Profiler.h"
26
#include "Common/LogReporting.h"
27
#include "Common/MemoryUtil.h"
28
#include "Common/StringUtils.h"
29
#include "Common/Math/SIMDHeaders.h"
30
#include "Common/TimeUtil.h"
31
#include "Common/Math/math_util.h"
32
#include "Common/GPU/thin3d.h"
33
#include "Core/HDRemaster.h"
34
#include "Core/Config.h"
35
#include "Core/Debugger/MemBlockInfo.h"
36
#include "Core/System.h"
37
#include "Core/HW/Display.h"
38
#include "GPU/Common/FramebufferManagerCommon.h"
39
#include "GPU/Common/TextureCacheCommon.h"
40
#include "GPU/Common/TextureDecoder.h"
41
#include "GPU/Common/GPUStateUtils.h"
42
#include "GPU/ge_constants.h"
43
#include "GPU/Debugger/Record.h"
44
#include "GPU/GPUState.h"
45
#include "Core/Util/PPGeDraw.h"
46
47
// Videos should be updated every few frames, so we forget quickly.
48
#define VIDEO_DECIMATE_AGE 4
49
50
// If a texture hasn't been seen for this many frames, get rid of it.
51
#define TEXTURE_KILL_AGE 200
52
#define TEXTURE_KILL_AGE_LOWMEM 60
53
// Not used in lowmem mode.
54
#define TEXTURE_SECOND_KILL_AGE 100
55
// Used when there are multiple CLUT variants of a texture.
56
#define TEXTURE_KILL_AGE_CLUT 6
57
58
#define TEXTURE_CLUT_VARIANTS_MIN 6
59
60
// Try to be prime to other decimation intervals.
61
#define TEXCACHE_DECIMATION_INTERVAL 13
62
63
#define TEXCACHE_MIN_PRESSURE 16 * 1024 * 1024 // Total in VRAM
64
#define TEXCACHE_SECOND_MIN_PRESSURE 4 * 1024 * 1024
65
66
// Just for reference
67
68
// PSP Color formats:
69
// 565: BBBBBGGGGGGRRRRR
70
// 5551: ABBBBBGGGGGRRRRR
71
// 4444: AAAABBBBGGGGRRRR
72
// 8888: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (Bytes in memory: RGBA)
73
74
// D3D11/9 Color formats:
75
// DXGI_FORMAT_B4G4R4A4/D3DFMT_A4R4G4B4: AAAARRRRGGGGBBBB
76
// DXGI_FORMAT_B5G5R5A1/D3DFMT_A1R5G6B5: ARRRRRGGGGGBBBBB
77
// DXGI_FORMAT_B5G6R6/D3DFMT_R5G6B5: RRRRRGGGGGGBBBBB
78
// DXGI_FORMAT_B8G8R8A8: AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB (Bytes in memory: BGRA)
79
// These are Data::Format:: A4R4G4B4_PACK16, A1R5G6B5_PACK16, R5G6B5_PACK16, B8G8R8A8.
80
// So these are good matches, just with R/B swapped.
81
82
// OpenGL ES color formats:
83
// GL_UNSIGNED_SHORT_4444: BBBBGGGGRRRRAAAA (4-bit rotation)
84
// GL_UNSIGNED_SHORT_565: BBBBBGGGGGGRRRRR (match)
85
// GL_UNSIGNED_SHORT_1555: BBBBBGGGGGRRRRRA (1-bit rotation)
86
// GL_UNSIGNED_BYTE/RGBA: AAAAAAAABBBBBBBBGGGGGGGGRRRRRRRR (match)
87
// These are Data::Format:: B4G4R4A4_PACK16, B5G6R6_PACK16, B5G5R5A1_PACK16, R8G8B8A8
88
89
TextureCacheCommon::TextureCacheCommon(Draw::DrawContext *draw, Draw2D *draw2D)
90
: draw_(draw), draw2D_(draw2D), replacer_(draw) {
91
decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;
92
93
// It's only possible to have 1KB of palette entries, although we allow 2KB in a hack.
94
clutBufRaw_ = (u32 *)AllocateAlignedMemory(2048, 16);
95
clutBufConverted_ = (u32 *)AllocateAlignedMemory(2048, 16);
96
// Here we need 2KB to expand a 1KB CLUT.
97
expandClut_ = (u32 *)AllocateAlignedMemory(2048, 16);
98
99
_assert_(clutBufRaw_ && clutBufConverted_ && expandClut_);
100
101
// Zap so we get consistent behavior if the game fails to load some of the CLUT.
102
memset(clutBufRaw_, 0, 2048);
103
memset(clutBufConverted_, 0, 2048);
104
clutBuf_ = clutBufConverted_;
105
106
// These buffers will grow if necessary, but most won't need more than this.
107
tmpTexBuf32_.resize(512 * 512); // 1MB
108
tmpTexBufRearrange_.resize(512 * 512); // 1MB
109
110
textureShaderCache_ = new TextureShaderCache(draw, draw2D_);
111
}
112
113
TextureCacheCommon::~TextureCacheCommon() {
114
delete textureShaderCache_;
115
116
FreeAlignedMemory(clutBufConverted_);
117
FreeAlignedMemory(clutBufRaw_);
118
FreeAlignedMemory(expandClut_);
119
}
120
121
void TextureCacheCommon::StartFrame() {
122
ForgetLastTexture();
123
textureShaderCache_->Decimate();
124
timesInvalidatedAllThisFrame_ = 0;
125
replacementTimeThisFrame_ = 0.0;
126
127
float fps;
128
__DisplayGetFPS(nullptr, &fps, nullptr);
129
if (fps <= 5.0f) {
130
fps = 60.0f;
131
}
132
133
float baseValue = 0.5f;
134
switch (g_Config.iReplacementTextureLoadSpeed) {
135
case (int)ReplacementTextureLoadSpeed::SLOW:
136
baseValue = 0.5f;
137
break;
138
case (int)ReplacementTextureLoadSpeed::MEDIUM:
139
baseValue = 0.75f;
140
break;
141
case (int)ReplacementTextureLoadSpeed::FAST:
142
baseValue = 1.0f;
143
break;
144
case (int)ReplacementTextureLoadSpeed::INSTANT:
145
baseValue = 100000.0f; // no budget limit, effectively.
146
break;
147
}
148
149
// Allow spending half a frame on uploading textures.
150
replacementFrameBudgetSeconds_ = baseValue / fps;
151
152
if ((DebugOverlay)g_Config.iDebugOverlay == DebugOverlay::DEBUG_STATS) {
153
gpuStats.numReplacerTrackedTex = replacer_.GetNumTrackedTextures();
154
gpuStats.numCachedReplacedTextures = replacer_.GetNumCachedReplacedTextures();
155
}
156
157
if (texelsScaledThisFrame_) {
158
VERBOSE_LOG(Log::G3D, "Scaled %d texels", texelsScaledThisFrame_);
159
}
160
texelsScaledThisFrame_ = 0;
161
162
if (clearCacheNextFrame_) {
163
Clear(true);
164
clearCacheNextFrame_ = false;
165
} else {
166
Decimate(nullptr, false);
167
}
168
}
169
170
// Produces a signed 1.23.8 value.
171
static int TexLog2(float delta) {
172
union FloatBits {
173
float f;
174
u32 u;
175
};
176
FloatBits f;
177
f.f = delta;
178
// Use the exponent as the tex level, and the top mantissa bits for a frac.
179
// We can't support more than 8 bits of frac, so truncate.
180
int useful = (f.u >> 15) & 0xFFFF;
181
// Now offset so the exponent aligns with log2f (exp=127 is 0.)
182
return useful - 127 * 256;
183
}
184
185
SamplerCacheKey TextureCacheCommon::GetSamplingParams(int maxLevel, const TexCacheEntry *entry) {
186
SamplerCacheKey key{};
187
188
int minFilt = gstate.texfilter & 0x7;
189
key.minFilt = minFilt & 1;
190
key.mipEnable = (minFilt >> 2) & 1;
191
key.mipFilt = (minFilt >> 1) & 1;
192
key.magFilt = gstate.isMagnifyFilteringEnabled();
193
key.sClamp = gstate.isTexCoordClampedS();
194
key.tClamp = gstate.isTexCoordClampedT();
195
key.aniso = false;
196
key.texture3d = gstate_c.curTextureIs3D;
197
198
GETexLevelMode mipMode = gstate.getTexLevelMode();
199
bool autoMip = mipMode == GE_TEXLEVEL_MODE_AUTO;
200
201
// TODO: Slope mipmap bias is still not well understood.
202
float lodBias = (float)gstate.getTexLevelOffset16() * (1.0f / 16.0f);
203
if (mipMode == GE_TEXLEVEL_MODE_SLOPE) {
204
lodBias += 1.0f + TexLog2(gstate.getTextureLodSlope()) * (1.0f / 256.0f);
205
}
206
207
// If mip level is forced to zero, disable mipmapping.
208
bool noMip = maxLevel == 0 || (!autoMip && lodBias <= 0.0f);
209
if (noMip) {
210
// Enforce no mip filtering, for safety.
211
key.mipEnable = false;
212
key.mipFilt = 0;
213
lodBias = 0.0f;
214
}
215
216
if (!key.mipEnable) {
217
key.maxLevel = 0;
218
key.minLevel = 0;
219
key.lodBias = 0;
220
key.mipFilt = 0;
221
} else {
222
switch (mipMode) {
223
case GE_TEXLEVEL_MODE_AUTO:
224
key.maxLevel = maxLevel * 256;
225
key.minLevel = 0;
226
key.lodBias = (int)(lodBias * 256.0f);
227
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
228
key.aniso = true;
229
}
230
break;
231
case GE_TEXLEVEL_MODE_CONST:
232
case GE_TEXLEVEL_MODE_UNKNOWN:
233
key.maxLevel = (int)(lodBias * 256.0f);
234
key.minLevel = (int)(lodBias * 256.0f);
235
key.lodBias = 0;
236
break;
237
case GE_TEXLEVEL_MODE_SLOPE:
238
// It's incorrect to use the slope as a bias. Instead it should be passed
239
// into the shader directly as an explicit lod level, with the bias on top. For now, we just kill the
240
// lodBias in this mode, working around #9772.
241
key.maxLevel = maxLevel * 256;
242
key.minLevel = 0;
243
key.lodBias = 0;
244
break;
245
}
246
}
247
248
// Video bilinear override
249
if (!key.magFilt && entry != nullptr && IsVideo(entry->addr)) {
250
// Enforce bilinear filtering on magnification.
251
key.magFilt = 1;
252
}
253
254
// Filtering overrides from replacements or settings.
255
TextureFiltering forceFiltering = TEX_FILTER_AUTO;
256
bool useReplacerFiltering = false;
257
if (entry && replacer_.Enabled() && entry->replacedTexture) {
258
// If replacement textures have multiple mip levels, enforce mip filtering.
259
if (entry->replacedTexture->State() == ReplacementState::ACTIVE && entry->replacedTexture->NumLevels() > 1) {
260
key.mipEnable = true;
261
key.mipFilt = 1;
262
key.maxLevel = 9 * 256;
263
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
264
key.aniso = true;
265
}
266
}
267
useReplacerFiltering = entry->replacedTexture->ForceFiltering(&forceFiltering);
268
}
269
if (!useReplacerFiltering) {
270
switch (g_Config.iTexFiltering) {
271
case TEX_FILTER_AUTO:
272
// Follow what the game wants. We just do a single heuristic change to avoid bleeding of wacky color test colors
273
// in higher resolution (used by some games for sprites, and they accidentally have linear filter on).
274
if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {
275
bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;
276
if (uglyColorTest)
277
forceFiltering = TEX_FILTER_FORCE_NEAREST;
278
}
279
if (gstate_c.pixelMapped) {
280
forceFiltering = TEX_FILTER_FORCE_NEAREST;
281
}
282
break;
283
case TEX_FILTER_FORCE_LINEAR:
284
// Override to linear filtering if there's no alpha or color testing going on.
285
if ((!gstate.isColorTestEnabled() || IsColorTestTriviallyTrue()) &&
286
(!gstate.isAlphaTestEnabled() || IsAlphaTestTriviallyTrue())) {
287
forceFiltering = TEX_FILTER_FORCE_LINEAR;
288
}
289
break;
290
case TEX_FILTER_FORCE_NEAREST:
291
// Just force to nearest without checks. Safe (but ugly).
292
forceFiltering = TEX_FILTER_FORCE_NEAREST;
293
break;
294
case TEX_FILTER_AUTO_MAX_QUALITY:
295
default:
296
forceFiltering = TEX_FILTER_AUTO_MAX_QUALITY;
297
if (gstate_c.Use(GPU_USE_ANISOTROPY) && g_Config.iAnisotropyLevel > 0) {
298
key.aniso = true;
299
}
300
if (gstate.isModeThrough() && g_Config.iInternalResolution != 1) {
301
bool uglyColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && gstate.getColorTestRef() != 0;
302
if (uglyColorTest) {
303
forceFiltering = TEX_FILTER_FORCE_NEAREST;
304
key.aniso = false;
305
}
306
}
307
if (gstate_c.pixelMapped) {
308
forceFiltering = TEX_FILTER_FORCE_NEAREST;
309
key.aniso = false;
310
}
311
break;
312
}
313
}
314
315
switch (forceFiltering) {
316
case TEX_FILTER_AUTO:
317
break;
318
case TEX_FILTER_FORCE_LINEAR:
319
key.magFilt = 1;
320
key.minFilt = 1;
321
key.mipFilt = 1;
322
break;
323
case TEX_FILTER_FORCE_NEAREST:
324
key.magFilt = 0;
325
key.minFilt = 0;
326
break;
327
case TEX_FILTER_AUTO_MAX_QUALITY:
328
// NOTE: We do not override magfilt here. If a game should have pixellated filtering,
329
// let it keep it. But we do enforce minification and mipmap filtering and max out the level.
330
// Later we'll also auto-generate any missing mipmaps.
331
key.minFilt = 1;
332
key.mipFilt = 1;
333
key.maxLevel = 9 * 256;
334
key.lodBias = 0.0f;
335
break;
336
}
337
338
return key;
339
}
340
341
SamplerCacheKey TextureCacheCommon::GetFramebufferSamplingParams(u16 bufferWidth, u16 bufferHeight) {
342
SamplerCacheKey key = GetSamplingParams(0, nullptr);
343
344
// In case auto max quality was on, restore min filt. Another fix for water in Outrun.
345
if (g_Config.iTexFiltering == TEX_FILTER_AUTO_MAX_QUALITY) {
346
int minFilt = gstate.texfilter & 0x7;
347
key.minFilt = minFilt & 1;
348
}
349
350
// Kill any mipmapping settings.
351
key.mipEnable = false;
352
key.mipFilt = false;
353
key.aniso = 0.0f;
354
key.maxLevel = 0.0f;
355
key.lodBias = 0.0f;
356
357
// Often the framebuffer will not match the texture size. We'll wrap/clamp in the shader in that case.
358
int w = gstate.getTextureWidth(0);
359
int h = gstate.getTextureHeight(0);
360
if (w != bufferWidth || h != bufferHeight) {
361
key.sClamp = true;
362
key.tClamp = true;
363
}
364
return key;
365
}
366
367
void TextureCacheCommon::UpdateMaxSeenV(TexCacheEntry *entry, bool throughMode) {
368
// If the texture is >= 512 pixels tall...
369
if (entry->dim >= 0x900) {
370
if (entry->cluthash != 0 && entry->maxSeenV == 0) {
371
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
372
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
373
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
374
// They should all be the same, just make sure we take any that has already increased.
375
// This is for a new texture.
376
if (it->second->maxSeenV != 0) {
377
entry->maxSeenV = it->second->maxSeenV;
378
break;
379
}
380
}
381
}
382
383
// Texture scale/offset and gen modes don't apply in through.
384
// So we can optimize how much of the texture we look at.
385
if (throughMode) {
386
if (entry->maxSeenV == 0 && gstate_c.vertBounds.maxV > 0) {
387
// Let's not hash less than 272, we might use more later and have to rehash. 272 is very common.
388
entry->maxSeenV = std::max((u16)272, gstate_c.vertBounds.maxV);
389
} else if (gstate_c.vertBounds.maxV > entry->maxSeenV) {
390
// The max height changed, so we're better off hashing the entire thing.
391
entry->maxSeenV = 512;
392
entry->status |= TexCacheEntry::STATUS_FREE_CHANGE;
393
}
394
} else {
395
// Otherwise, we need to reset to ensure we use the whole thing.
396
// Can't tell how much is used.
397
// TODO: We could tell for texcoord UV gen, and apply scale to max?
398
entry->maxSeenV = 512;
399
}
400
401
// We need to keep all CLUT variants in sync so we detect changes properly.
402
// See HandleTextureChange / STATUS_CLUT_RECHECK.
403
if (entry->cluthash != 0) {
404
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
405
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
406
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
407
it->second->maxSeenV = entry->maxSeenV;
408
}
409
}
410
}
411
}
412
413
TexCacheEntry *TextureCacheCommon::SetTexture() {
414
u8 level = 0;
415
if (IsFakeMipmapChange()) {
416
level = std::max(0, gstate.getTexLevelOffset16() / 16);
417
}
418
u32 texaddr = gstate.getTextureAddress(level);
419
if (!Memory::IsValidAddress(texaddr)) {
420
// Bind a null texture and return.
421
Unbind();
422
gstate_c.SetTextureIsVideo(false);
423
gstate_c.SetTextureIs3D(false);
424
gstate_c.SetTextureIsArray(false);
425
gstate_c.SetTextureIsFramebuffer(false);
426
return nullptr;
427
}
428
429
const u16 dim = gstate.getTextureDimension(level);
430
int w = gstate.getTextureWidth(level);
431
int h = gstate.getTextureHeight(level);
432
433
GETextureFormat texFormat = gstate.getTextureFormat();
434
if (texFormat >= 11) {
435
// TODO: Better assumption? Doesn't really matter, these are invalid.
436
texFormat = GE_TFMT_5650;
437
}
438
439
bool hasClut = gstate.isTextureFormatIndexed();
440
bool hasClutGPU = false;
441
u32 cluthash;
442
if (hasClut) {
443
if (clutRenderAddress_ != 0xFFFFFFFF) {
444
gstate_c.curTextureXOffset = 0.0f;
445
gstate_c.curTextureYOffset = 0.0f;
446
hasClutGPU = true;
447
cluthash = 0; // Or should we use some other marker value?
448
} else {
449
if (clutLastFormat_ != gstate.clutformat) {
450
// We update here because the clut format can be specified after the load.
451
// TODO: Unify this as far as possible (I think only GLES backend really needs its own implementation due to different component order).
452
UpdateCurrentClut(gstate.getClutPaletteFormat(), gstate.getClutIndexStartPos(), gstate.isClutIndexSimple());
453
}
454
cluthash = clutHash_ ^ gstate.clutformat;
455
}
456
} else {
457
cluthash = 0;
458
}
459
u64 cachekey = TexCacheEntry::CacheKey(texaddr, texFormat, dim, cluthash);
460
461
int bufw = GetTextureBufw(0, texaddr, texFormat);
462
u8 maxLevel = gstate.getTextureMaxLevel();
463
464
u32 minihash = MiniHash((const u32 *)Memory::GetPointerUnchecked(texaddr));
465
466
TexCache::iterator entryIter = cache_.find(cachekey);
467
TexCacheEntry *entry = nullptr;
468
469
// Note: It's necessary to reset needshadertexclamp, for otherwise DIRTY_TEXCLAMP won't get set later.
470
// Should probably revisit how this works..
471
gstate_c.SetNeedShaderTexclamp(false);
472
gstate_c.skipDrawReason &= ~SKIPDRAW_BAD_FB_TEXTURE;
473
474
if (entryIter != cache_.end()) {
475
entry = entryIter->second.get();
476
477
// Validate the texture still matches the cache entry.
478
bool match = entry->Matches(dim, texFormat, maxLevel);
479
const char *reason = "different params";
480
481
// Check for dynamic CLUT status
482
if (((entry->status & TexCacheEntry::STATUS_CLUT_GPU) != 0) != hasClutGPU) {
483
// Need to recreate, suddenly a CLUT GPU texture was used without it, or vice versa.
484
// I think this can only happen on a clut hash collision with the marker value, so highly unlikely.
485
match = false;
486
}
487
488
// Check for FBO changes.
489
if (entry->status & TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP) {
490
// Fall through to the end where we'll delete the entry if there's a framebuffer.
491
entry->status &= ~TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
492
match = false;
493
}
494
495
bool rehash = entry->GetHashStatus() == TexCacheEntry::STATUS_UNRELIABLE;
496
497
// First let's see if another texture with the same address had a hashfail.
498
if (entry->status & TexCacheEntry::STATUS_CLUT_RECHECK) {
499
// Always rehash in this case, if one changed the rest all probably did.
500
rehash = true;
501
entry->status &= ~TexCacheEntry::STATUS_CLUT_RECHECK;
502
} else if (!gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE)) {
503
// Okay, just some parameter change - the data didn't change, no need to rehash.
504
rehash = false;
505
}
506
507
// Do we need to recreate?
508
if (entry->status & TexCacheEntry::STATUS_FORCE_REBUILD) {
509
match = false;
510
entry->status &= ~TexCacheEntry::STATUS_FORCE_REBUILD;
511
}
512
513
if (match) {
514
if (entry->lastFrame != gpuStats.numFlips) {
515
u32 diff = gpuStats.numFlips - entry->lastFrame;
516
entry->numFrames++;
517
518
if (entry->framesUntilNextFullHash < diff) {
519
// Exponential backoff up to 512 frames. Textures are often reused.
520
if (entry->numFrames > 32) {
521
// Also, try to add some "randomness" to avoid rehashing several textures the same frame.
522
// textureName is unioned with texturePtr and vkTex so will work for the other backends.
523
entry->framesUntilNextFullHash = std::min(512, entry->numFrames) + (((intptr_t)(entry->textureName) >> 12) & 15);
524
} else {
525
entry->framesUntilNextFullHash = entry->numFrames;
526
}
527
rehash = true;
528
} else {
529
entry->framesUntilNextFullHash -= diff;
530
}
531
}
532
533
// If it's not huge or has been invalidated many times, recheck the whole texture.
534
if (entry->invalidHint > 180 || (entry->invalidHint > 15 && (dim >> 8) < 9 && (dim & 0xF) < 9)) {
535
entry->invalidHint = 0;
536
rehash = true;
537
}
538
539
if (minihash != entry->minihash) {
540
match = false;
541
reason = "minihash";
542
} else if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
543
rehash = false;
544
}
545
}
546
547
if (match && (entry->status & TexCacheEntry::STATUS_TO_SCALE) && standardScaleFactor_ != 1 && texelsScaledThisFrame_ < TEXCACHE_MAX_TEXELS_SCALED) {
548
if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) {
549
// INFO_LOG(Log::G3D, "Reloading texture to do the scaling we skipped..");
550
match = false;
551
reason = "scaling";
552
}
553
}
554
555
if (match && (entry->status & TexCacheEntry::STATUS_TO_REPLACE) && replacementTimeThisFrame_ < replacementFrameBudgetSeconds_) {
556
int w0 = gstate.getTextureWidth(0);
557
int h0 = gstate.getTextureHeight(0);
558
int d0 = 1;
559
if (entry->replacedTexture) {
560
PollReplacement(entry, &w0, &h0, &d0);
561
// This texture is pending a replacement load.
562
// So check the replacer if it's reached a conclusion.
563
switch (entry->replacedTexture->State()) {
564
case ReplacementState::NOT_FOUND:
565
// Didn't find a replacement, so stop looking.
566
// DEBUG_LOG(Log::G3D, "No replacement for texture %dx%d", w0, h0);
567
entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
568
if (g_Config.bSaveNewTextures) {
569
// Load it once more to actually save it. Since we don't set STATUS_TO_REPLACE, we won't end up looping.
570
match = false;
571
reason = "replacing";
572
}
573
break;
574
case ReplacementState::ACTIVE:
575
// There is now replacement data available!
576
// Just reload the texture to process the replacement.
577
match = false;
578
reason = "replacing";
579
break;
580
default:
581
// We'll just wait for a result.
582
break;
583
}
584
}
585
}
586
587
if (match) {
588
// got one!
589
gstate_c.curTextureWidth = w;
590
gstate_c.curTextureHeight = h;
591
gstate_c.SetTextureIsVideo(false);
592
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
593
gstate_c.SetTextureIsArray(false);
594
gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);
595
gstate_c.SetTextureIsFramebuffer(false);
596
597
if (rehash) {
598
// Update in case any of these changed.
599
entry->bufw = bufw;
600
entry->cluthash = cluthash;
601
}
602
603
nextTexture_ = entry;
604
nextNeedsRehash_ = rehash;
605
nextNeedsChange_ = false;
606
// Might need a rebuild if the hash fails, but that will be set later.
607
nextNeedsRebuild_ = false;
608
failedTexture_ = false;
609
VERBOSE_LOG(Log::G3D, "Texture at %08x found in cache, applying", texaddr);
610
return entry; //Done!
611
} else {
612
// Wasn't a match, we will rebuild.
613
nextChangeReason_ = reason;
614
nextNeedsChange_ = true;
615
// Fall through to the rebuild case.
616
}
617
}
618
619
// No texture found, or changed (depending on entry).
620
// Check for framebuffers.
621
622
TextureDefinition def{};
623
def.addr = texaddr;
624
def.dim = dim;
625
def.format = texFormat;
626
def.bufw = bufw;
627
628
AttachCandidate bestCandidate;
629
if (GetBestFramebufferCandidate(def, 0, &bestCandidate)) {
630
// If we had a texture entry here, let's get rid of it.
631
if (entryIter != cache_.end()) {
632
DeleteTexture(entryIter);
633
}
634
635
nextTexture_ = nullptr;
636
nextNeedsRebuild_ = false;
637
638
SetTextureFramebuffer(bestCandidate); // sets curTexture3D
639
return nullptr;
640
}
641
642
// Didn't match a framebuffer, keep going.
643
644
if (!entry) {
645
VERBOSE_LOG(Log::G3D, "No texture in cache for %08x, decoding...", texaddr);
646
entry = new TexCacheEntry{};
647
cache_[cachekey].reset(entry);
648
649
if (PPGeIsFontTextureAddress(texaddr)) {
650
// It's the builtin font texture.
651
entry->status = TexCacheEntry::STATUS_RELIABLE;
652
} else if (g_Config.bTextureBackoffCache && !IsVideo(texaddr)) {
653
entry->status = TexCacheEntry::STATUS_HASHING;
654
} else {
655
entry->status = TexCacheEntry::STATUS_UNRELIABLE;
656
}
657
658
if (hasClutGPU) {
659
WARN_LOG_N_TIMES(clutUseRender, 5, Log::G3D, "Using texture with dynamic CLUT: texfmt=%d, clutfmt=%d", gstate.getTextureFormat(), gstate.getClutPaletteFormat());
660
entry->status |= TexCacheEntry::STATUS_CLUT_GPU;
661
}
662
663
if (hasClut && clutRenderAddress_ == 0xFFFFFFFF) {
664
const u64 cachekeyMin = (u64)(texaddr & 0x3FFFFFFF) << 32;
665
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
666
667
int found = 0;
668
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
669
found++;
670
}
671
672
if (found >= TEXTURE_CLUT_VARIANTS_MIN) {
673
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
674
it->second->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;
675
}
676
677
entry->status |= TexCacheEntry::STATUS_CLUT_VARIANTS;
678
}
679
}
680
681
nextNeedsChange_ = false;
682
}
683
684
// We have to decode it, let's setup the cache entry first.
685
entry->addr = texaddr;
686
entry->minihash = minihash;
687
entry->dim = dim;
688
entry->format = texFormat;
689
entry->maxLevel = maxLevel;
690
entry->status &= ~TexCacheEntry::STATUS_BGRA;
691
692
entry->bufw = bufw;
693
694
entry->cluthash = cluthash;
695
696
gstate_c.curTextureWidth = w;
697
gstate_c.curTextureHeight = h;
698
gstate_c.SetTextureIsVideo(false);
699
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
700
gstate_c.SetTextureIsArray(false); // Ordinary 2D textures still aren't used by array view in VK. We probably might as well, though, at this point..
701
gstate_c.SetTextureIsFramebuffer(false);
702
703
failedTexture_ = false;
704
nextTexture_ = entry;
705
nextFramebufferTexture_ = nullptr;
706
nextNeedsRehash_ = true;
707
// We still need to rebuild, to allocate a texture. But we'll bail early.
708
nextNeedsRebuild_ = true;
709
return entry;
710
}
711
712
bool TextureCacheCommon::GetBestFramebufferCandidate(const TextureDefinition &entry, u32 texAddrOffset, AttachCandidate *bestCandidate) const {
713
gpuStats.numFramebufferEvaluations++;
714
715
TinySet<AttachCandidate, 6> candidates;
716
717
const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();
718
719
for (VirtualFramebuffer *framebuffer : framebuffers) {
720
FramebufferMatchInfo match{};
721
if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_COLOR, &match)) {
722
candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_COLOR });
723
}
724
match = {};
725
if (MatchFramebuffer(entry, framebuffer, texAddrOffset, RASTER_DEPTH, &match)) {
726
candidates.push_back(AttachCandidate{ framebuffer, match, RASTER_DEPTH });
727
}
728
}
729
730
if (candidates.size() == 0) {
731
return false;
732
} else if (candidates.size() == 1) {
733
*bestCandidate = candidates[0];
734
return true;
735
}
736
737
bool logging = Reporting::ShouldLogNTimes("multifbcandidate", 5);
738
739
// OK, multiple possible candidates. Will need to figure out which one is the most relevant.
740
int bestRelevancy = -1;
741
size_t bestIndex = -1;
742
743
bool kzCompat = PSP_CoreParameter().compat.flags().SplitFramebufferMargin;
744
745
// We simply use the sequence counter as relevancy nowadays.
746
for (size_t i = 0; i < candidates.size(); i++) {
747
AttachCandidate &candidate = candidates[i];
748
int relevancy = candidate.channel == RASTER_COLOR ? candidate.fb->colorBindSeq : candidate.fb->depthBindSeq;
749
750
// Add a small negative penalty if the texture is currently bound as a framebuffer, and offset is not zero.
751
// Should avoid problems when pingponging two nearby buffers, like in Wipeout Pure in #15927.
752
if (candidate.channel == RASTER_COLOR &&
753
(candidate.match.yOffset != 0 || candidate.match.xOffset != 0) &&
754
candidate.fb->fb_address == (gstate.getFrameBufRawAddress() | 0x04000000)) {
755
relevancy -= 2;
756
}
757
758
if (candidate.match.xOffset != 0 && PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset) {
759
continue;
760
}
761
762
// Avoid binding as texture the framebuffer we're rendering to.
763
// In Killzone, we split the framebuffer but the matching algorithm can still pick the wrong one,
764
// which this avoids completely.
765
if (kzCompat && candidate.fb == framebufferManager_->GetCurrentRenderVFB()) {
766
continue;
767
}
768
769
if (logging) {
770
candidate.relevancy = relevancy;
771
}
772
773
if (relevancy > bestRelevancy) {
774
bestRelevancy = relevancy;
775
bestIndex = i;
776
}
777
}
778
779
if (logging) {
780
std::string cands;
781
for (size_t i = 0; i < candidates.size(); i++) {
782
cands += candidates[i].ToString();
783
if (i != candidates.size() - 1)
784
cands += "\n";
785
}
786
cands += "\n";
787
788
WARN_LOG(Log::G3D, "GetFramebufferCandidates(tex): Multiple (%d) candidate framebuffers. texaddr: %08x offset: %d (%dx%d stride %d, %s):\n%s",
789
(int)candidates.size(),
790
entry.addr, texAddrOffset, dimWidth(entry.dim), dimHeight(entry.dim), entry.bufw, GeTextureFormatToString(entry.format),
791
cands.c_str()
792
);
793
logging = true;
794
}
795
796
if (bestIndex != -1) {
797
if (logging) {
798
WARN_LOG(Log::G3D, "Chose candidate %d:\n%s\n", (int)bestIndex, candidates[bestIndex].ToString().c_str());
799
}
800
*bestCandidate = candidates[bestIndex];
801
return true;
802
} else {
803
return false;
804
}
805
}
806
807
// Removes old textures.
808
void TextureCacheCommon::Decimate(TexCacheEntry *exceptThisOne, bool forcePressure) {
809
if (--decimationCounter_ <= 0) {
810
decimationCounter_ = TEXCACHE_DECIMATION_INTERVAL;
811
} else {
812
return;
813
}
814
815
if (forcePressure || cacheSizeEstimate_ >= TEXCACHE_MIN_PRESSURE) {
816
const u32 had = cacheSizeEstimate_;
817
818
ForgetLastTexture();
819
int killAgeBase = lowMemoryMode_ ? TEXTURE_KILL_AGE_LOWMEM : TEXTURE_KILL_AGE;
820
for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ) {
821
if (iter->second.get() == exceptThisOne) {
822
++iter;
823
continue;
824
}
825
bool hasClut = (iter->second->status & TexCacheEntry::STATUS_CLUT_VARIANTS) != 0;
826
int killAge = hasClut ? TEXTURE_KILL_AGE_CLUT : killAgeBase;
827
if (iter->second->lastFrame + killAge < gpuStats.numFlips) {
828
DeleteTexture(iter++);
829
} else {
830
++iter;
831
}
832
}
833
834
VERBOSE_LOG(Log::G3D, "Decimated texture cache, saved %d estimated bytes - now %d bytes", had - cacheSizeEstimate_, cacheSizeEstimate_);
835
}
836
837
// If enabled, we also need to clear the secondary cache.
838
if (PSP_CoreParameter().compat.flags().SecondaryTextureCache && (forcePressure || secondCacheSizeEstimate_ >= TEXCACHE_SECOND_MIN_PRESSURE)) {
839
const u32 had = secondCacheSizeEstimate_;
840
841
for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ) {
842
if (iter->second.get() == exceptThisOne) {
843
++iter;
844
continue;
845
}
846
// In low memory mode, we kill them all since secondary cache is disabled.
847
if (lowMemoryMode_ || iter->second->lastFrame + TEXTURE_SECOND_KILL_AGE < gpuStats.numFlips) {
848
ReleaseTexture(iter->second.get(), true);
849
secondCacheSizeEstimate_ -= EstimateTexMemoryUsage(iter->second.get());
850
iter = secondCache_.erase(iter);
851
} else {
852
++iter;
853
}
854
}
855
856
VERBOSE_LOG(Log::G3D, "Decimated second texture cache, saved %d estimated bytes - now %d bytes", had - secondCacheSizeEstimate_, secondCacheSizeEstimate_);
857
}
858
859
DecimateVideos();
860
replacer_.Decimate(forcePressure ? ReplacerDecimateMode::FORCE_PRESSURE : ReplacerDecimateMode::NEW_FRAME);
861
}
862
863
void TextureCacheCommon::DecimateVideos() {
864
for (auto iter = videos_.begin(); iter != videos_.end(); ) {
865
if (iter->flips + VIDEO_DECIMATE_AGE < gpuStats.numFlips) {
866
iter = videos_.erase(iter);
867
} else {
868
++iter;
869
}
870
}
871
}
872
873
bool TextureCacheCommon::IsVideo(u32 texaddr) const {
874
texaddr &= 0x3FFFFFFF;
875
for (auto &info : videos_) {
876
if (texaddr < info.addr) {
877
continue;
878
}
879
if (texaddr < info.addr + info.size) {
880
return true;
881
}
882
}
883
return false;
884
}
885
886
void TextureCacheCommon::HandleTextureChange(TexCacheEntry *const entry, const char *reason, bool initialMatch, bool doDelete) {
887
cacheSizeEstimate_ -= EstimateTexMemoryUsage(entry);
888
entry->numInvalidated++;
889
gpuStats.numTextureInvalidations++;
890
DEBUG_LOG(Log::G3D, "Texture different or overwritten, reloading at %08x: %s", entry->addr, reason);
891
if (doDelete) {
892
ForgetLastTexture();
893
ReleaseTexture(entry, true);
894
entry->status &= ~(TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED | TexCacheEntry::STATUS_TO_REPLACE);
895
}
896
897
// Mark as hashing, if marked as reliable.
898
if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
899
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
900
}
901
902
// Also, mark any textures with the same address but different clut. They need rechecking.
903
if (entry->cluthash != 0) {
904
const u64 cachekeyMin = (u64)(entry->addr & 0x3FFFFFFF) << 32;
905
const u64 cachekeyMax = cachekeyMin + (1ULL << 32);
906
for (auto it = cache_.lower_bound(cachekeyMin), end = cache_.upper_bound(cachekeyMax); it != end; ++it) {
907
if (it->second->cluthash != entry->cluthash) {
908
it->second->status |= TexCacheEntry::STATUS_CLUT_RECHECK;
909
}
910
}
911
}
912
913
if (entry->numFrames < TEXCACHE_FRAME_CHANGE_FREQUENT) {
914
if (entry->status & TexCacheEntry::STATUS_FREE_CHANGE) {
915
entry->status &= ~TexCacheEntry::STATUS_FREE_CHANGE;
916
} else {
917
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;
918
}
919
}
920
entry->numFrames = 0;
921
}
922
923
void TextureCacheCommon::NotifyFramebuffer(VirtualFramebuffer *framebuffer, FramebufferNotification msg) {
924
const u32 fb_addr = framebuffer->fb_address;
925
const u32 z_addr = framebuffer->z_address;
926
927
const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);
928
const u32 z_bpp = 2; // No other format exists.
929
const u32 fb_stride = framebuffer->fb_stride;
930
const u32 z_stride = framebuffer->z_stride;
931
932
// NOTE: Some games like Burnout massively misdetects the height of some framebuffers, leading to a lot of unnecessary invalidations.
933
// Let's only actually get rid of textures that cover the very start of the framebuffer.
934
const u32 fb_endAddr = fb_addr + fb_stride * std::min((int)framebuffer->height, 16) * fb_bpp;
935
const u32 z_endAddr = z_addr + z_stride * std::min((int)framebuffer->height, 16) * z_bpp;
936
937
switch (msg) {
938
case NOTIFY_FB_CREATED:
939
case NOTIFY_FB_UPDATED:
940
{
941
// Try to match the new framebuffer to existing textures.
942
// Backwards from the "usual" texturing case so can't share a utility function.
943
944
u64 cacheKey = (u64)fb_addr << 32;
945
// If it has a clut, those are the low 32 bits, so it'll be inside this range.
946
// Also, if it's a subsample of the buffer, it'll also be within the FBO.
947
u64 cacheKeyEnd = (u64)fb_endAddr << 32;
948
949
// Color - no need to look in the mirrors.
950
for (auto it = cache_.lower_bound(cacheKey), end = cache_.upper_bound(cacheKeyEnd); it != end; ++it) {
951
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
952
gpuStats.numTextureInvalidationsByFramebuffer++;
953
}
954
955
if (z_stride != 0) {
956
// Depth. Just look at the range, but in each mirror (0x04200000 and 0x04600000).
957
// Games don't use 0x04400000 as far as I know - it has no swizzle effect so kinda useless.
958
cacheKey = (u64)z_addr << 32;
959
cacheKeyEnd = (u64)z_endAddr << 32;
960
for (auto it = cache_.lower_bound(cacheKey | 0x200000), end = cache_.upper_bound(cacheKeyEnd | 0x200000); it != end; ++it) {
961
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
962
gpuStats.numTextureInvalidationsByFramebuffer++;
963
}
964
for (auto it = cache_.lower_bound(cacheKey | 0x600000), end = cache_.upper_bound(cacheKeyEnd | 0x600000); it != end; ++it) {
965
it->second->status |= TexCacheEntry::STATUS_FRAMEBUFFER_OVERLAP;
966
gpuStats.numTextureInvalidationsByFramebuffer++;
967
}
968
}
969
break;
970
}
971
default:
972
break;
973
}
974
}
975
976
bool TextureCacheCommon::MatchFramebuffer(
977
const TextureDefinition &entry,
978
VirtualFramebuffer *framebuffer, u32 texaddrOffset, RasterChannel channel, FramebufferMatchInfo *matchInfo) const {
979
static const u32 MAX_SUBAREA_Y_OFFSET_SAFE = 32;
980
981
uint32_t fb_address = channel == RASTER_DEPTH ? framebuffer->z_address : framebuffer->fb_address;
982
uint32_t fb_stride = channel == RASTER_DEPTH ? framebuffer->z_stride : framebuffer->fb_stride;
983
GEBufferFormat fb_format = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : framebuffer->fb_format;
984
985
if (channel == RASTER_DEPTH && (framebuffer->z_address == framebuffer->fb_address || framebuffer->z_address == 0)) {
986
// Try to avoid silly matches to somewhat malformed buffers.
987
return false;
988
}
989
990
if (!fb_stride) {
991
// Hard to make decisions.
992
return false;
993
}
994
995
switch (entry.format) {
996
case GE_TFMT_DXT1:
997
case GE_TFMT_DXT3:
998
case GE_TFMT_DXT5:
999
return false;
1000
default: break;
1001
}
1002
1003
uint32_t fb_stride_in_bytes = fb_stride * BufferFormatBytesPerPixel(fb_format);
1004
uint32_t tex_stride_in_bytes = entry.bufw * textureBitsPerPixel[entry.format] / 8; // Note, we're looking up bits here so need to divide by 8.
1005
1006
u32 addr = fb_address;
1007
u32 texaddr = entry.addr + texaddrOffset;
1008
1009
bool texInVRAM = Memory::IsVRAMAddress(texaddr);
1010
bool fbInVRAM = Memory::IsVRAMAddress(fb_address);
1011
1012
if (texInVRAM != fbInVRAM) {
1013
// Shortcut. Cannot possibly be a match.
1014
return false;
1015
}
1016
1017
if (texInVRAM) {
1018
const u32 mirrorMask = 0x041FFFFF;
1019
1020
addr &= mirrorMask;
1021
texaddr &= mirrorMask;
1022
}
1023
1024
const bool noOffset = texaddr == addr;
1025
const bool exactMatch = noOffset && entry.format < 4 && channel == RASTER_COLOR && fb_stride_in_bytes == tex_stride_in_bytes;
1026
1027
const u32 texWidth = 1 << ((entry.dim >> 0) & 0xf);
1028
const u32 texHeight = 1 << ((entry.dim >> 8) & 0xf);
1029
1030
// 512 on a 272 framebuffer is sane, so let's be lenient.
1031
const u32 minSubareaHeight = texHeight / 4;
1032
1033
// If they match "exactly", it's non-CLUT and from the top left.
1034
if (exactMatch) {
1035
// NOTE: This check is okay because the first texture formats are the same as the buffer formats.
1036
if (IsTextureFormatBufferCompatible(entry.format)) {
1037
if (TextureFormatMatchesBufferFormat(entry.format, fb_format) || (framebuffer->usageFlags & FB_USAGE_BLUE_TO_ALPHA)) {
1038
return true;
1039
} else {
1040
WARN_LOG_ONCE(diffFormat1, Log::G3D, "Found matching framebuffer with reinterpretable fb_format: %s != %s at %08x", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);
1041
*matchInfo = FramebufferMatchInfo{ 0, 0, true, TextureFormatToBufferFormat(entry.format) };
1042
return true;
1043
}
1044
} else {
1045
// Format incompatible, ignoring without comment. (maybe some really gnarly hacks will end up here...)
1046
return false;
1047
}
1048
} else {
1049
// Apply to buffered mode only.
1050
if (!framebufferManager_->UseBufferedRendering()) {
1051
return false;
1052
}
1053
1054
// Check works for D16 too.
1055
// These are combinations that we have special-cased handling for. There are more
1056
// ones possible, but rare - we'll add them as we find them used.
1057
const bool matchingClutFormat =
1058
(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_CLUT16) ||
1059
(fb_format == GE_FORMAT_DEPTH16 && entry.format == GE_TFMT_5650) ||
1060
(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT32) ||
1061
(fb_format != GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT16) ||
1062
(fb_format == GE_FORMAT_8888 && entry.format == GE_TFMT_CLUT8) ||
1063
(fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement);
1064
1065
const int texBitsPerPixel = TextureFormatBitsPerPixel(entry.format);
1066
const int byteOffset = texaddr - addr;
1067
if (byteOffset > 0) {
1068
int texbpp = texBitsPerPixel;
1069
if (fb_format == GE_FORMAT_5551 && entry.format == GE_TFMT_CLUT8) {
1070
// In this case we treat CLUT8 as if it were CLUT16, see issue #16210. So we need
1071
// to compute the x offset appropriately.
1072
texbpp = 16;
1073
}
1074
1075
matchInfo->yOffset = byteOffset / fb_stride_in_bytes;
1076
matchInfo->xOffset = 8 * (byteOffset % fb_stride_in_bytes) / texbpp;
1077
} else if (byteOffset < 0) {
1078
int texelOffset = 8 * byteOffset / texBitsPerPixel;
1079
// We don't support negative Y offsets, and negative X offsets are only for the Killzone workaround.
1080
if (texelOffset < -(int)entry.bufw || !PSP_CoreParameter().compat.flags().SplitFramebufferMargin) {
1081
return false;
1082
}
1083
matchInfo->xOffset = entry.bufw == 0 ? 0 : -(-texelOffset % (int)entry.bufw);
1084
}
1085
1086
if (matchInfo->yOffset > 0 && matchInfo->yOffset + minSubareaHeight >= framebuffer->height) {
1087
// Can't be inside the framebuffer.
1088
return false;
1089
}
1090
1091
// Check if it's in bufferWidth (which might be higher than width and may indicate the framebuffer includes the data.)
1092
// Do the computation in bytes so that it's valid even in case of weird reinterpret scenarios.
1093
const int xOffsetInBytes = matchInfo->xOffset * 8 / texBitsPerPixel;
1094
const int texWidthInBytes = texWidth * 8 / texBitsPerPixel;
1095
if (xOffsetInBytes >= framebuffer->BufferWidthInBytes() && xOffsetInBytes + texWidthInBytes <= (int)fb_stride_in_bytes) {
1096
// This happens in Brave Story, see #10045 - the texture is in the space between strides, with matching stride.
1097
return false;
1098
}
1099
1100
// Trying to play it safe. Below 0x04110000 is almost always framebuffers.
1101
// TODO: Maybe we can reduce this check and find a better way above 0x04110000?
1102
if (matchInfo->yOffset > MAX_SUBAREA_Y_OFFSET_SAFE && addr > 0x04110000 && !PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {
1103
WARN_LOG_ONCE(subareaIgnored, Log::G3D, "Ignoring possible texturing from framebuffer at %08x +%dx%d / %dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset, framebuffer->width, framebuffer->height);
1104
return false;
1105
}
1106
1107
// Note the check for texHeight - we really don't care about a stride mismatch if texHeight == 1.
1108
// This also takes care of the 4x1 texture check we used to have here for Burnout Dominator.
1109
if (fb_stride_in_bytes != tex_stride_in_bytes && texHeight > 1) {
1110
// Probably irrelevant.
1111
return false;
1112
}
1113
1114
// Check for CLUT. The framebuffer is always RGB, but it can be interpreted as a CLUT texture.
1115
// 3rd Birthday (and a bunch of other games) render to a 16 bit clut texture.
1116
if (matchingClutFormat) {
1117
if (!noOffset) {
1118
WARN_LOG_ONCE(subareaClut, Log::G3D, "Matching framebuffer (%s) using %s with offset at %08x +%dx%d", RasterChannelToString(channel), GeTextureFormatToString(entry.format), fb_address, matchInfo->xOffset, matchInfo->yOffset);
1119
}
1120
return true;
1121
} else if (IsClutFormat((GETextureFormat)(entry.format)) || IsDXTFormat((GETextureFormat)(entry.format))) {
1122
WARN_LOG_ONCE(fourEightBit, Log::G3D, "%s texture format not matching framebuffer of format %s at %08x/%d", GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address, fb_stride);
1123
return false;
1124
}
1125
1126
// This is either normal or we failed to generate a shader to depalettize
1127
if ((int)fb_format == (int)entry.format || matchingClutFormat) {
1128
if ((int)fb_format != (int)entry.format) {
1129
WARN_LOG_ONCE(diffFormat2, Log::G3D, "Matching framebuffer with different formats %s != %s at %08x",
1130
GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), fb_address);
1131
return true;
1132
} else {
1133
WARN_LOG_ONCE(subarea, Log::G3D, "Matching from framebuffer at %08x +%dx%d", fb_address, matchInfo->xOffset, matchInfo->yOffset);
1134
return true;
1135
}
1136
} else {
1137
WARN_LOG_ONCE(diffFormat2, Log::G3D, "Ignoring possible texturing from framebuffer at %08x with incompatible format %s != %s (+%dx%d)",
1138
fb_address, GeTextureFormatToString(entry.format), GeBufferFormatToString(fb_format), matchInfo->xOffset, matchInfo->yOffset);
1139
return false;
1140
}
1141
}
1142
}
1143
1144
void TextureCacheCommon::SetTextureFramebuffer(const AttachCandidate &candidate) {
1145
VirtualFramebuffer *framebuffer = candidate.fb;
1146
RasterChannel channel = candidate.channel;
1147
1148
if (candidate.match.reinterpret) {
1149
framebuffer = framebufferManager_->ResolveFramebufferColorToFormat(candidate.fb, candidate.match.reinterpretTo);
1150
}
1151
1152
_dbg_assert_msg_(framebuffer != nullptr, "Framebuffer must not be null.");
1153
1154
framebuffer->usageFlags |= FB_USAGE_TEXTURE;
1155
// Keep the framebuffer alive.
1156
framebuffer->last_frame_used = gpuStats.numFlips;
1157
1158
nextFramebufferTextureChannel_ = RASTER_COLOR;
1159
1160
if (framebufferManager_->UseBufferedRendering()) {
1161
FramebufferMatchInfo fbInfo = candidate.match;
1162
// Detect when we need to apply the horizontal texture swizzle.
1163
u64 depthUpperBits = (channel == RASTER_DEPTH && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;
1164
bool needsDepthXSwizzle = depthUpperBits == 2;
1165
1166
// We need to force it, since we may have set it on a texture before attaching.
1167
int texWidth = framebuffer->bufferWidth;
1168
int texHeight = framebuffer->bufferHeight;
1169
if (candidate.channel == RASTER_COLOR && gstate.getTextureFormat() == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {
1170
// See #16210. UV must be adjusted as if the texture was twice the width.
1171
texWidth *= 2.0f;
1172
}
1173
1174
if (needsDepthXSwizzle) {
1175
texWidth = RoundUpToPowerOf2(texWidth);
1176
}
1177
1178
gstate_c.curTextureWidth = texWidth;
1179
gstate_c.curTextureHeight = texHeight;
1180
gstate_c.SetTextureIsFramebuffer(true);
1181
gstate_c.SetTextureIsBGRA(false);
1182
1183
if ((gstate_c.curTextureXOffset == 0) != (fbInfo.xOffset == 0) || (gstate_c.curTextureYOffset == 0) != (fbInfo.yOffset == 0)) {
1184
gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);
1185
}
1186
1187
gstate_c.curTextureXOffset = fbInfo.xOffset;
1188
gstate_c.curTextureYOffset = fbInfo.yOffset;
1189
u32 texW = (u32)gstate.getTextureWidth(0);
1190
u32 texH = (u32)gstate.getTextureHeight(0);
1191
gstate_c.SetNeedShaderTexclamp(gstate_c.curTextureWidth != texW || gstate_c.curTextureHeight != texH);
1192
if (gstate_c.curTextureXOffset != 0 || gstate_c.curTextureYOffset != 0) {
1193
gstate_c.SetNeedShaderTexclamp(true);
1194
}
1195
if (channel == RASTER_DEPTH) {
1196
framebuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;
1197
}
1198
1199
if (channel == RASTER_DEPTH && !gstate_c.Use(GPU_USE_DEPTH_TEXTURE)) {
1200
WARN_LOG_ONCE(ndepthtex, Log::G3D, "Depth textures not supported, not binding");
1201
// Flag to bind a null texture if we can't support depth textures.
1202
// Should only happen on old OpenGL.
1203
nextFramebufferTexture_ = nullptr;
1204
failedTexture_ = true;
1205
} else {
1206
nextFramebufferTexture_ = framebuffer;
1207
nextFramebufferTextureChannel_ = channel;
1208
}
1209
nextTexture_ = nullptr;
1210
} else {
1211
if (framebuffer->fbo) {
1212
framebuffer->fbo->Release();
1213
framebuffer->fbo = nullptr;
1214
}
1215
Unbind();
1216
gstate_c.SetNeedShaderTexclamp(false);
1217
nextFramebufferTexture_ = nullptr;
1218
nextTexture_ = nullptr;
1219
}
1220
1221
gstate_c.SetTextureIsVideo(false);
1222
gstate_c.SetTextureIs3D(false);
1223
gstate_c.SetTextureIsArray(true);
1224
1225
nextNeedsRehash_ = false;
1226
nextNeedsChange_ = false;
1227
nextNeedsRebuild_ = false;
1228
}
1229
1230
// Only looks for framebuffers.
1231
bool TextureCacheCommon::SetOffsetTexture(u32 yOffset) {
1232
if (!framebufferManager_->UseBufferedRendering()) {
1233
return false;
1234
}
1235
1236
u32 texaddr = gstate.getTextureAddress(0);
1237
GETextureFormat fmt = gstate.getTextureFormat();
1238
const u32 bpp = fmt == GE_TFMT_8888 ? 4 : 2;
1239
const u32 texaddrOffset = yOffset * gstate.getTextureWidth(0) * bpp;
1240
1241
if (!Memory::IsValidAddress(texaddr) || !Memory::IsValidAddress(texaddr + texaddrOffset)) {
1242
return false;
1243
}
1244
1245
TextureDefinition def;
1246
def.addr = texaddr;
1247
def.format = fmt;
1248
def.bufw = GetTextureBufw(0, texaddr, fmt);
1249
def.dim = gstate.getTextureDimension(0);
1250
1251
AttachCandidate bestCandidate;
1252
if (GetBestFramebufferCandidate(def, texaddrOffset, &bestCandidate)) {
1253
SetTextureFramebuffer(bestCandidate);
1254
return true;
1255
} else {
1256
return false;
1257
}
1258
}
1259
1260
bool TextureCacheCommon::GetCurrentFramebufferTextureDebug(GPUDebugBuffer &buffer, bool *isFramebuffer) {
1261
if (!nextFramebufferTexture_)
1262
return false;
1263
*isFramebuffer = true;
1264
1265
VirtualFramebuffer *vfb = nextFramebufferTexture_;
1266
u8 sf = vfb->renderScaleFactor;
1267
int x = gstate_c.curTextureXOffset * sf;
1268
int y = gstate_c.curTextureYOffset * sf;
1269
int desiredW = gstate.getTextureWidth(0) * sf;
1270
int desiredH = gstate.getTextureHeight(0) * sf;
1271
int w = std::min(desiredW, vfb->bufferWidth * sf - x);
1272
int h = std::min(desiredH, vfb->bufferHeight * sf - y);
1273
1274
bool retval;
1275
if (nextFramebufferTextureChannel_ == RASTER_DEPTH) {
1276
buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_FLOAT, false);
1277
if (w < desiredW || h < desiredH)
1278
buffer.ZeroBytes();
1279
retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::DEPTH_BIT, x, y, w, h, Draw::DataFormat::D32F, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");
1280
} else {
1281
buffer.Allocate(desiredW, desiredH, GPU_DBG_FORMAT_8888, false);
1282
if (w < desiredW || h < desiredH)
1283
buffer.ZeroBytes();
1284
retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::COLOR_BIT, x, y, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), desiredW, Draw::ReadbackMode::BLOCK, "GetCurrentTextureDebug");
1285
}
1286
1287
// Vulkan requires us to re-apply all dynamic state for each command buffer, and the above will cause us to start a new cmdbuf.
1288
// So let's dirty the things that are involved in Vulkan dynamic state. Readbacks are not frequent so this won't hurt other backends.
1289
gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_BLEND_STATE | DIRTY_DEPTHSTENCIL_STATE);
1290
// We may have blitted to a temp FBO.
1291
framebufferManager_->RebindFramebuffer("RebindFramebuffer - GetCurrentTextureDebug");
1292
if (!retval)
1293
ERROR_LOG(Log::G3D, "Failed to get debug texture: copy to memory failed");
1294
return retval;
1295
}
1296
1297
void TextureCacheCommon::NotifyConfigChanged() {
1298
int scaleFactor = g_Config.iTexScalingLevel;
1299
1300
if (!gstate_c.Use(GPU_USE_TEXTURE_NPOT)) {
1301
// Reduce the scale factor to a power of two (e.g. 2 or 4) if textures must be a power of two.
1302
// TODO: In addition we should probably remove these options from the UI in this case.
1303
while ((scaleFactor & (scaleFactor - 1)) != 0) {
1304
--scaleFactor;
1305
}
1306
}
1307
1308
// Just in case, small display with auto resolution or something.
1309
if (scaleFactor <= 0) {
1310
scaleFactor = 1;
1311
}
1312
1313
standardScaleFactor_ = scaleFactor;
1314
1315
replacer_.NotifyConfigChanged();
1316
}
1317
1318
void TextureCacheCommon::NotifyWriteFormattedFromMemory(u32 addr, int size, int width, GEBufferFormat fmt) {
1319
addr &= 0x3FFFFFFF;
1320
videos_.push_back({ addr, (u32)size, gpuStats.numFlips });
1321
}
1322
1323
void TextureCacheCommon::LoadClut(u32 clutAddr, u32 loadBytes, GPURecord::Recorder *recorder) {
1324
if (loadBytes == 0) {
1325
// Don't accidentally overwrite clutTotalBytes_ with a zero.
1326
return;
1327
}
1328
1329
_assert_(loadBytes <= 2048);
1330
clutTotalBytes_ = loadBytes;
1331
clutRenderAddress_ = 0xFFFFFFFF;
1332
1333
if (!Memory::IsValidAddress(clutAddr)) {
1334
memset(clutBufRaw_, 0x00, loadBytes);
1335
// Reload the clut next time (should we really do it in this case?)
1336
clutLastFormat_ = 0xFFFFFFFF;
1337
clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);
1338
return;
1339
}
1340
1341
if (Memory::IsVRAMAddress(clutAddr)) {
1342
// Clear the uncached and mirror bits, etc. to match framebuffers.
1343
const u32 clutLoadAddr = clutAddr & 0x041FFFFF;
1344
const u32 clutLoadEnd = clutLoadAddr + loadBytes;
1345
static const u32 MAX_CLUT_OFFSET = 4096;
1346
1347
clutRenderOffset_ = MAX_CLUT_OFFSET;
1348
const std::vector<VirtualFramebuffer *> &framebuffers = framebufferManager_->Framebuffers();
1349
1350
u32 bestClutAddress = 0xFFFFFFFF;
1351
1352
VirtualFramebuffer *chosenFramebuffer = nullptr;
1353
for (VirtualFramebuffer *framebuffer : framebuffers) {
1354
// Let's not deal with divide by zero.
1355
if (framebuffer->fb_stride == 0)
1356
continue;
1357
1358
const u32 fb_address = framebuffer->fb_address;
1359
const u32 fb_bpp = BufferFormatBytesPerPixel(framebuffer->fb_format);
1360
int offset = clutLoadAddr - fb_address;
1361
1362
// Is this inside the framebuffer at all? Note that we only check the first line here, this should
1363
// be changed.
1364
bool matchRange = offset >= 0 && offset < (int)(framebuffer->fb_stride * fb_bpp);
1365
if (matchRange) {
1366
// And is it inside the rendered area? Sometimes games pack data in the margin between width and stride.
1367
// If the framebuffer width was detected as 512, we're gonna assume it's really 480.
1368
int fbMatchWidth = framebuffer->width;
1369
if (fbMatchWidth == 512) {
1370
fbMatchWidth = 480;
1371
}
1372
int pixelOffsetX = ((offset / fb_bpp) % framebuffer->fb_stride);
1373
bool inMargin = pixelOffsetX >= fbMatchWidth && (pixelOffsetX + (loadBytes / fb_bpp) <= framebuffer->fb_stride);
1374
1375
// The offset check here means, in the context of the loop, that we'll pick
1376
// the framebuffer with the smallest offset. This is yet another framebuffer matching
1377
// loop with its own rules, eventually we'll probably want to do something
1378
// more systematic.
1379
bool okAge = !PSP_CoreParameter().compat.flags().LoadCLUTFromCurrentFrameOnly || framebuffer->last_frame_render == gpuStats.numFlips; // Here we can try heuristics.
1380
if (matchRange && !inMargin && offset < (int)clutRenderOffset_) {
1381
if (okAge) {
1382
WARN_LOG_N_TIMES(clutfb, 5, Log::G3D, "Detected LoadCLUT(%d bytes) from framebuffer %08x (%s), last render %d frames ago, byte offset %d, pixel offset %d",
1383
loadBytes, fb_address, GeBufferFormatToString(framebuffer->fb_format), gpuStats.numFlips - framebuffer->last_frame_render, offset, offset / fb_bpp);
1384
framebuffer->last_frame_clut = gpuStats.numFlips;
1385
// Also mark used so it's not decimated.
1386
framebuffer->last_frame_used = gpuStats.numFlips;
1387
framebuffer->usageFlags |= FB_USAGE_CLUT;
1388
bestClutAddress = framebuffer->fb_address;
1389
clutRenderOffset_ = (u32)offset;
1390
chosenFramebuffer = framebuffer;
1391
if (offset == 0) {
1392
// Not gonna find a better match according to the smallest-offset rule, so we'll go with this one.
1393
break;
1394
}
1395
} else {
1396
WARN_LOG(Log::G3D, "Ignoring CLUT load from %d frames old buffer at %08x", gpuStats.numFlips - framebuffer->last_frame_render, fb_address);
1397
}
1398
}
1399
}
1400
}
1401
1402
// To turn off dynamic CLUT (for demonstration or testing purposes), add "false &&" to this check.
1403
if (chosenFramebuffer && chosenFramebuffer->fbo) {
1404
clutRenderAddress_ = bestClutAddress;
1405
1406
if (!dynamicClutTemp_) {
1407
Draw::FramebufferDesc desc{};
1408
desc.width = 512;
1409
desc.height = 1;
1410
desc.depth = 1;
1411
desc.z_stencil = false;
1412
desc.numLayers = 1;
1413
desc.multiSampleLevel = 0;
1414
desc.tag = "dynamic_clut";
1415
dynamicClutFbo_ = draw_->CreateFramebuffer(desc);
1416
desc.tag = "dynamic_clut_temp";
1417
dynamicClutTemp_ = draw_->CreateFramebuffer(desc);
1418
}
1419
1420
// We'll need to copy from the offset.
1421
const u32 fb_bpp = BufferFormatBytesPerPixel(chosenFramebuffer->fb_format);
1422
const int totalPixelsOffset = clutRenderOffset_ / fb_bpp;
1423
const int clutYOffset = totalPixelsOffset / chosenFramebuffer->fb_stride;
1424
const int clutXOffset = totalPixelsOffset % chosenFramebuffer->fb_stride;
1425
const int scale = chosenFramebuffer->renderScaleFactor;
1426
1427
// Copy the pixels to our temp clut, scaling down if needed and wrapping.
1428
framebufferManager_->BlitUsingRaster(
1429
chosenFramebuffer->fbo, clutXOffset * scale, clutYOffset * scale, (clutXOffset + 512.0f) * scale, (clutYOffset + 1.0f) * scale,
1430
dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f,
1431
false, scale, framebufferManager_->Get2DPipeline(DRAW2D_COPY_COLOR_RECT2LIN), "copy_clut_to_temp");
1432
1433
framebufferManager_->RebindFramebuffer("after_copy_clut_to_temp");
1434
clutRenderFormat_ = chosenFramebuffer->fb_format;
1435
}
1436
NotifyMemInfo(MemBlockFlags::ALLOC, clutAddr, loadBytes, "CLUT");
1437
}
1438
1439
// It's possible for a game to load CLUT outside valid memory without crashing, should result in zeroes.
1440
u32 bytes = Memory::ValidSize(clutAddr, loadBytes);
1441
_assert_(bytes <= 2048);
1442
bool performDownload = PSP_CoreParameter().compat.flags().AllowDownloadCLUT;
1443
if (recorder->IsActive())
1444
performDownload = true;
1445
if (clutRenderAddress_ != 0xFFFFFFFF && performDownload) {
1446
framebufferManager_->DownloadFramebufferForClut(clutRenderAddress_, clutRenderOffset_ + bytes);
1447
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1448
if (bytes < loadBytes) {
1449
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1450
}
1451
} else {
1452
// Here we could check for clutRenderAddress_ != 0xFFFFFFFF and zero the CLUT or something,
1453
// but choosing not to for now. Though the results of loading the CLUT from RAM here is
1454
// almost certainly going to be bogus.
1455
#ifdef _M_SSE
1456
if (bytes == loadBytes) {
1457
const __m128i *source = (const __m128i *)Memory::GetPointerUnchecked(clutAddr);
1458
__m128i *dest = (__m128i *)clutBufRaw_;
1459
int numBlocks = bytes / 32;
1460
for (int i = 0; i < numBlocks; i++, source += 2, dest += 2) {
1461
__m128i data1 = _mm_loadu_si128(source);
1462
__m128i data2 = _mm_loadu_si128(source + 1);
1463
_mm_store_si128(dest, data1);
1464
_mm_store_si128(dest + 1, data2);
1465
}
1466
} else {
1467
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1468
if (bytes < loadBytes) {
1469
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1470
}
1471
}
1472
#elif PPSSPP_ARCH(ARM_NEON)
1473
if (bytes == loadBytes) {
1474
const uint32_t *source = (const uint32_t *)Memory::GetPointerUnchecked(clutAddr);
1475
uint32_t *dest = (uint32_t *)clutBufRaw_;
1476
int numBlocks = bytes / 32;
1477
for (int i = 0; i < numBlocks; i++, source += 8, dest += 8) {
1478
uint32x4_t data1 = vld1q_u32(source);
1479
uint32x4_t data2 = vld1q_u32(source + 4);
1480
vst1q_u32(dest, data1);
1481
vst1q_u32(dest + 4, data2);
1482
}
1483
} else {
1484
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1485
if (bytes < loadBytes) {
1486
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1487
}
1488
}
1489
#else
1490
Memory::MemcpyUnchecked(clutBufRaw_, clutAddr, bytes);
1491
if (bytes < loadBytes) {
1492
memset((u8 *)clutBufRaw_ + bytes, 0x00, loadBytes - bytes);
1493
}
1494
#endif
1495
}
1496
1497
// Reload the clut next time.
1498
clutLastFormat_ = 0xFFFFFFFF;
1499
clutMaxBytes_ = std::max(clutMaxBytes_, loadBytes);
1500
}
1501
1502
void TextureCacheCommon::UnswizzleFromMem(u32 *dest, u32 destPitch, const u8 *texptr, u32 bufw, u32 height, u32 bytesPerPixel) {
1503
// Note: bufw is always aligned to 16 bytes, so rowWidth is always >= 16.
1504
const u32 rowWidth = (bytesPerPixel > 0) ? (bufw * bytesPerPixel) : (bufw / 2);
1505
// A visual mapping of unswizzling, where each letter is 16-byte and 8 letters is a block:
1506
//
1507
// ABCDEFGH IJKLMNOP
1508
// ->
1509
// AI
1510
// BJ
1511
// CK
1512
// ...
1513
//
1514
// bxc is the number of blocks in the x direction, and byc the number in the y direction.
1515
const int bxc = rowWidth / 16;
1516
// The height is not always aligned to 8, but rounds up.
1517
int byc = (height + 7) / 8;
1518
1519
DoUnswizzleTex16(texptr, dest, bxc, byc, destPitch);
1520
}
1521
1522
bool TextureCacheCommon::GetCurrentClutBuffer(GPUDebugBuffer &buffer) {
1523
const u32 bpp = gstate.getClutPaletteFormat() == GE_CMODE_32BIT_ABGR8888 ? 4 : 2;
1524
const u32 pixels = 1024 / bpp;
1525
1526
buffer.Allocate(pixels, 1, (GEBufferFormat)gstate.getClutPaletteFormat());
1527
memcpy(buffer.GetData(), clutBufRaw_, 1024);
1528
return true;
1529
}
1530
1531
// Host memory usage, not PSP memory usage.
1532
u32 TextureCacheCommon::EstimateTexMemoryUsage(const TexCacheEntry *entry) {
1533
const u16 dim = entry->dim;
1534
// TODO: This does not take into account the HD remaster's larger textures.
1535
const u8 dimW = ((dim >> 0) & 0xf);
1536
const u8 dimH = ((dim >> 8) & 0xf);
1537
1538
u32 pixelSize = 2;
1539
switch (entry->format) {
1540
case GE_TFMT_CLUT4:
1541
case GE_TFMT_CLUT8:
1542
case GE_TFMT_CLUT16:
1543
case GE_TFMT_CLUT32:
1544
// We assume cluts always point to 8888 for simplicity.
1545
pixelSize = 4;
1546
break;
1547
case GE_TFMT_4444:
1548
case GE_TFMT_5551:
1549
case GE_TFMT_5650:
1550
break;
1551
1552
case GE_TFMT_8888:
1553
case GE_TFMT_DXT1:
1554
case GE_TFMT_DXT3:
1555
case GE_TFMT_DXT5:
1556
default:
1557
pixelSize = 4;
1558
break;
1559
}
1560
1561
// This in other words multiplies by w and h.
1562
return pixelSize << (dimW + dimH);
1563
}
1564
1565
ReplacedTexture *TextureCacheCommon::FindReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {
1566
if (*d != 1) {
1567
// We don't yet support replacing 3D textures.
1568
return nullptr;
1569
}
1570
1571
// Short circuit the non-enabled case.
1572
// Otherwise, due to bReplaceTexturesAllowLate, we'll still spawn tasks looking for replacements
1573
// that then won't be used.
1574
if (!replacer_.ReplaceEnabled()) {
1575
return nullptr;
1576
}
1577
1578
if ((entry->status & TexCacheEntry::STATUS_VIDEO) && !replacer_.AllowVideo()) {
1579
return nullptr;
1580
}
1581
1582
double replaceStart = time_now_d();
1583
u64 cachekey = entry->CacheKey();
1584
ReplacedTexture *replaced = replacer_.FindReplacement(cachekey, entry->fullhash, *w, *h);
1585
replacementTimeThisFrame_ += time_now_d() - replaceStart;
1586
if (!replaced) {
1587
// TODO: Remove the flag here?
1588
// entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
1589
return nullptr;
1590
}
1591
entry->replacedTexture = replaced; // we know it's non-null here.
1592
PollReplacement(entry, w, h, d);
1593
return replaced;
1594
}
1595
1596
void TextureCacheCommon::PollReplacement(TexCacheEntry *entry, int *w, int *h, int *d) {
1597
double waitBudget = replacementFrameBudgetSeconds_ - replacementTimeThisFrame_;
1598
// Note: Don't avoid the Poll call if budget is 0, we do meaningful things there.
1599
// Poll also handles negative budgets.
1600
1601
double replaceStart = time_now_d();
1602
1603
// Unless the mode is set to Instant (where the user explicitly wants to wait for each texture),
1604
// it's just a waste of time to wait here really. OK, we might get a texture one frame early but
1605
// we wasted a lot of time waiting, likely slowing down our framerate.
1606
if (g_Config.iReplacementTextureLoadSpeed != ReplacementTextureLoadSpeed::INSTANT) {
1607
waitBudget = 0.0;
1608
}
1609
if (entry->replacedTexture->Poll(waitBudget)) {
1610
if (entry->replacedTexture->State() == ReplacementState::ACTIVE) {
1611
entry->replacedTexture->GetSize(0, w, h);
1612
// Consider it already "scaled.".
1613
entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;
1614
}
1615
1616
// Remove the flag, even if it was invalid.
1617
entry->status &= ~TexCacheEntry::STATUS_TO_REPLACE;
1618
}
1619
replacementTimeThisFrame_ += time_now_d() - replaceStart;
1620
1621
switch (entry->replacedTexture->State()) {
1622
case ReplacementState::UNLOADED:
1623
case ReplacementState::PENDING:
1624
// Make sure we keep polling.
1625
entry->status |= TexCacheEntry::STATUS_TO_REPLACE;
1626
break;
1627
default:
1628
break;
1629
}
1630
}
1631
1632
// This is only used in the GLES backend, where we don't point these to video memory.
1633
// So we shouldn't add a check for dstBuf != srcBuf, as long as the functions we call can handle that.
1634
static void ReverseColors(void *dstBuf, const void *srcBuf, GETextureFormat fmt, int numPixels) {
1635
switch (fmt) {
1636
case GE_TFMT_4444:
1637
ConvertRGBA4444ToABGR4444((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1638
break;
1639
// Final Fantasy 2 uses this heavily in animated textures.
1640
case GE_TFMT_5551:
1641
ConvertRGBA5551ToABGR1555((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1642
break;
1643
case GE_TFMT_5650:
1644
ConvertRGB565ToBGR565((u16 *)dstBuf, (const u16 *)srcBuf, numPixels);
1645
break;
1646
default:
1647
// No need to convert RGBA8888, right order already
1648
if (dstBuf != srcBuf) {
1649
memcpy(dstBuf, srcBuf, numPixels * sizeof(u32));
1650
}
1651
break;
1652
}
1653
}
1654
1655
static inline void ConvertFormatToRGBA8888(GETextureFormat format, u32 *dst, const u16 *src, u32 numPixels) {
1656
switch (format) {
1657
case GE_TFMT_4444:
1658
ConvertRGBA4444ToRGBA8888(dst, src, numPixels);
1659
break;
1660
case GE_TFMT_5551:
1661
ConvertRGBA5551ToRGBA8888(dst, src, numPixels);
1662
break;
1663
case GE_TFMT_5650:
1664
ConvertRGB565ToRGBA8888(dst, src, numPixels);
1665
break;
1666
default:
1667
_dbg_assert_msg_(false, "Incorrect texture format.");
1668
break;
1669
}
1670
}
1671
1672
static inline void ConvertFormatToRGBA8888(GEPaletteFormat format, u32 *dst, const u16 *src, u32 numPixels) {
1673
// The supported values are 1:1 identical.
1674
ConvertFormatToRGBA8888(GETextureFormat(format), dst, src, numPixels);
1675
}
1676
1677
template <typename DXTBlock, int n>
1678
static CheckAlphaResult DecodeDXTBlocks(uint8_t *out, int outPitch, uint32_t texaddr, const uint8_t *texptr,
1679
int w, int h, int bufw, bool reverseColors) {
1680
1681
int minw = std::min(bufw, w);
1682
uint32_t *dst = (uint32_t *)out;
1683
int outPitch32 = outPitch / sizeof(uint32_t);
1684
const DXTBlock *src = (const DXTBlock *)texptr;
1685
1686
if (!Memory::IsValidRange(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock))) {
1687
ERROR_LOG_REPORT(Log::G3D, "DXT%d texture extends beyond valid RAM: %08x + %d x %d", n, texaddr, bufw, h);
1688
uint32_t limited = Memory::ValidSize(texaddr, (h / 4) * (bufw / 4) * sizeof(DXTBlock));
1689
// This might possibly be 0, but try to decode what we can (might even be how the PSP behaves.)
1690
h = (((int)limited / sizeof(DXTBlock)) / (bufw / 4)) * 4;
1691
}
1692
1693
u32 alphaSum = 1;
1694
for (int y = 0; y < h; y += 4) {
1695
u32 blockIndex = (y / 4) * (bufw / 4);
1696
int blockHeight = std::min(h - y, 4);
1697
for (int x = 0; x < minw; x += 4) {
1698
int blockWidth = std::min(minw - x, 4);
1699
if constexpr (n == 1)
1700
DecodeDXT1Block(dst + outPitch32 * y + x, (const DXT1Block *)src + blockIndex, outPitch32, blockWidth, blockHeight, &alphaSum);
1701
else if constexpr (n == 3)
1702
DecodeDXT3Block(dst + outPitch32 * y + x, (const DXT3Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);
1703
else if constexpr (n == 5)
1704
DecodeDXT5Block(dst + outPitch32 * y + x, (const DXT5Block *)src + blockIndex, outPitch32, blockWidth, blockHeight);
1705
blockIndex++;
1706
}
1707
}
1708
1709
if (reverseColors) {
1710
ReverseColors(out, out, GE_TFMT_8888, outPitch32 * h);
1711
}
1712
1713
if constexpr (n == 1) {
1714
return alphaSum == 1 ? CHECKALPHA_FULL : CHECKALPHA_ANY;
1715
} else {
1716
// Just report that we don't have full alpha, since these formats are made for that.
1717
return CHECKALPHA_ANY;
1718
}
1719
}
1720
1721
inline u32 ClutFormatToFullAlpha(GEPaletteFormat fmt, bool reverseColors) {
1722
switch (fmt) {
1723
case GE_CMODE_16BIT_ABGR4444: return reverseColors ? 0x000F : 0xF000;
1724
case GE_CMODE_16BIT_ABGR5551: return reverseColors ? 0x0001 : 0x8000;
1725
case GE_CMODE_32BIT_ABGR8888: return 0xFF000000;
1726
case GE_CMODE_16BIT_BGR5650: return 0;
1727
default: return 0;
1728
}
1729
}
1730
1731
inline u32 TfmtRawToFullAlpha(GETextureFormat fmt) {
1732
switch (fmt) {
1733
case GE_TFMT_4444: return 0xF000;
1734
case GE_TFMT_5551: return 0x8000;
1735
case GE_TFMT_8888: return 0xFF000000;
1736
case GE_TFMT_5650: return 0;
1737
default: return 0;
1738
}
1739
}
1740
1741
// Used for converting CLUT4 to CLUT8.
1742
// Could SIMD or whatever, though will hardly be a bottleneck.
1743
static void Expand4To8Bits(u8 *dest, const u8 *src, int srcWidth) {
1744
for (int i = 0; i < (srcWidth + 1) / 2; i++) {
1745
u8 lower = src[i] & 0xF;
1746
u8 upper = src[i] >> 4;
1747
dest[i * 2] = lower;
1748
dest[i * 2 + 1] = upper;
1749
}
1750
}
1751
1752
CheckAlphaResult TextureCacheCommon::DecodeTextureLevel(u8 *out, int outPitch, GETextureFormat format, GEPaletteFormat clutformat, uint32_t texaddr, int level, int bufw, TexDecodeFlags flags) {
1753
u32 alphaSum = 0xFFFFFFFF;
1754
u32 fullAlphaMask = 0x0;
1755
1756
bool expandTo32bit = (flags & TexDecodeFlags::EXPAND32) != 0;
1757
bool reverseColors = (flags & TexDecodeFlags::REVERSE_COLORS) != 0;
1758
bool toClut8 = (flags & TexDecodeFlags::TO_CLUT8) != 0;
1759
1760
if (toClut8 && format != GE_TFMT_CLUT8 && format != GE_TFMT_CLUT4) {
1761
_dbg_assert_(false);
1762
}
1763
1764
bool swizzled = gstate.isTextureSwizzled();
1765
if ((texaddr & 0x00600000) != 0 && Memory::IsVRAMAddress(texaddr)) {
1766
// This means it's in a mirror, possibly a swizzled mirror. Let's report.
1767
WARN_LOG_REPORT_ONCE(texmirror, Log::G3D, "Decoding texture from VRAM mirror at %08x swizzle=%d", texaddr, swizzled ? 1 : 0);
1768
if ((texaddr & 0x00200000) == 0x00200000) {
1769
// Technically 2 and 6 are slightly different, but this is better than nothing probably.
1770
// We should only see this with depth textures anyway which we don't support uploading (yet).
1771
swizzled = !swizzled;
1772
}
1773
// Note that (texaddr & 0x00600000) == 0x00600000 is very likely to be depth texturing.
1774
}
1775
1776
int w = gstate.getTextureWidth(level);
1777
int h = gstate.getTextureHeight(level);
1778
const u8 *texptr = Memory::GetPointer(texaddr);
1779
const uint32_t byteSize = (textureBitsPerPixel[format] * bufw * h) / 8;
1780
1781
char buf[128];
1782
size_t len = snprintf(buf, sizeof(buf), "Tex_%08x_%dx%d_%s", texaddr, w, h, GeTextureFormatToString(format, clutformat));
1783
NotifyMemInfo(MemBlockFlags::TEXTURE, texaddr, byteSize, buf, len);
1784
1785
switch (format) {
1786
case GE_TFMT_CLUT4:
1787
{
1788
const bool mipmapShareClut = gstate.isClutSharedForMipmaps();
1789
const int clutSharingOffset = mipmapShareClut ? 0 : level * 16;
1790
1791
if (swizzled) {
1792
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1793
UnswizzleFromMem(tmpTexBuf32_.data(), bufw / 2, texptr, bufw, h, 0);
1794
texptr = (u8 *)tmpTexBuf32_.data();
1795
}
1796
1797
if (toClut8) {
1798
// We just need to expand from 4 to 8 bits.
1799
for (int y = 0; y < h; ++y) {
1800
Expand4To8Bits((u8 *)out + outPitch * y, texptr + (bufw * y) / 2, w);
1801
}
1802
// We can't know anything about alpha.
1803
return CHECKALPHA_ANY;
1804
}
1805
1806
switch (clutformat) {
1807
case GE_CMODE_16BIT_BGR5650:
1808
case GE_CMODE_16BIT_ABGR5551:
1809
case GE_CMODE_16BIT_ABGR4444:
1810
{
1811
// The w > 1 check is to not need a case that handles a single pixel
1812
// in DeIndexTexture4Optimal<u16>.
1813
if (clutAlphaLinear_ && mipmapShareClut && !expandTo32bit && w >= 4) {
1814
// We don't bother with fullalpha here (clutAlphaLinear_)
1815
// Here, reverseColors means the CLUT is already reversed.
1816
if (reverseColors) {
1817
for (int y = 0; y < h; ++y) {
1818
DeIndexTexture4Optimal((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);
1819
}
1820
} else {
1821
for (int y = 0; y < h; ++y) {
1822
DeIndexTexture4OptimalRev((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clutAlphaLinearColor_);
1823
}
1824
}
1825
} else {
1826
// Need to have the "un-reversed" (raw) CLUT here since we are using a generic conversion function.
1827
if (expandTo32bit) {
1828
// We simply expand the CLUT to 32-bit, then we deindex as usual. Probably the fastest way.
1829
const u16 *clut = GetCurrentRawClut<u16>() + clutSharingOffset;
1830
const int clutStart = gstate.getClutIndexStartPos();
1831
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexMask() <= 16) {
1832
ConvertFormatToRGBA8888(clutformat, expandClut_ + clutStart, clut + clutStart, 16);
1833
} else {
1834
// To be safe for shifts and wrap around, convert the entire CLUT.
1835
ConvertFormatToRGBA8888(clutformat, expandClut_, clut, 512);
1836
}
1837
fullAlphaMask = 0xFF000000;
1838
for (int y = 0; y < h; ++y) {
1839
DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, expandClut_, &alphaSum);
1840
}
1841
} else {
1842
// If we're reversing colors, the CLUT was already reversed, no special handling needed.
1843
const u16 *clut = GetCurrentClut<u16>() + clutSharingOffset;
1844
fullAlphaMask = ClutFormatToFullAlpha(clutformat, reverseColors);
1845
for (int y = 0; y < h; ++y) {
1846
DeIndexTexture4<u16>((u16 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);
1847
}
1848
}
1849
}
1850
1851
if (clutformat == GE_CMODE_16BIT_BGR5650) {
1852
// Our formula at the end of the function can't handle this cast so we return early.
1853
return CHECKALPHA_FULL;
1854
}
1855
}
1856
break;
1857
1858
case GE_CMODE_32BIT_ABGR8888:
1859
{
1860
const u32 *clut = GetCurrentClut<u32>() + clutSharingOffset;
1861
fullAlphaMask = 0xFF000000;
1862
for (int y = 0; y < h; ++y) {
1863
DeIndexTexture4<u32>((u32 *)(out + outPitch * y), texptr + (bufw * y) / 2, w, clut, &alphaSum);
1864
}
1865
}
1866
break;
1867
1868
default:
1869
ERROR_LOG_REPORT(Log::G3D, "Unknown CLUT4 texture mode %d", gstate.getClutPaletteFormat());
1870
return CHECKALPHA_ANY;
1871
}
1872
}
1873
break;
1874
1875
case GE_TFMT_CLUT8:
1876
if (toClut8) {
1877
if (gstate.isTextureSwizzled()) {
1878
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1879
UnswizzleFromMem(tmpTexBuf32_.data(), bufw, texptr, bufw, h, 1);
1880
texptr = (u8 *)tmpTexBuf32_.data();
1881
}
1882
// After deswizzling, we are in the correct format and can just copy.
1883
for (int y = 0; y < h; ++y) {
1884
memcpy((u8 *)out + outPitch * y, texptr + (bufw * y), w);
1885
}
1886
// We can't know anything about alpha.
1887
return CHECKALPHA_ANY;
1888
}
1889
return ReadIndexedTex(out, outPitch, level, texptr, 1, bufw, reverseColors, expandTo32bit);
1890
1891
case GE_TFMT_CLUT16:
1892
return ReadIndexedTex(out, outPitch, level, texptr, 2, bufw, reverseColors, expandTo32bit);
1893
1894
case GE_TFMT_CLUT32:
1895
return ReadIndexedTex(out, outPitch, level, texptr, 4, bufw, reverseColors, expandTo32bit);
1896
1897
case GE_TFMT_4444:
1898
case GE_TFMT_5551:
1899
case GE_TFMT_5650:
1900
if (!swizzled) {
1901
// Just a simple copy, we swizzle the color format.
1902
fullAlphaMask = TfmtRawToFullAlpha(format);
1903
if (expandTo32bit) {
1904
// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.
1905
for (int y = 0; y < h; ++y) {
1906
CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1907
ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)texptr + bufw * y, w);
1908
}
1909
} else if (reverseColors) {
1910
// Just check the input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.
1911
for (int y = 0; y < h; ++y) {
1912
CheckMask16((const u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1913
ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u16) * y, format, w);
1914
}
1915
} else {
1916
for (int y = 0; y < h; ++y) {
1917
CopyAndSumMask16((u16 *)(out + outPitch * y), (u16 *)(texptr + bufw * sizeof(u16) * y), w, &alphaSum);
1918
}
1919
}
1920
} /* else if (h >= 8 && bufw <= w && !expandTo32bit) {
1921
// TODO: Handle alpha mask. This will require special versions of UnswizzleFromMem to keep the optimization.
1922
// Note: this is always safe since h must be a power of 2, so a multiple of 8.
1923
UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 2);
1924
if (reverseColors) {
1925
ReverseColors(out, out, format, h * outPitch / 2, useBGRA);
1926
}
1927
}*/ else {
1928
// We don't have enough space for all rows in out, so use a temp buffer.
1929
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1930
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 2, texptr, bufw, h, 2);
1931
const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();
1932
1933
fullAlphaMask = TfmtRawToFullAlpha(format);
1934
if (expandTo32bit) {
1935
// This is OK even if reverseColors is on, because it expands to the 8888 format which is the same in reverse mode.
1936
// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ConvertFormatToRGBA8888 that checks as we go.
1937
for (int y = 0; y < h; ++y) {
1938
CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1939
ConvertFormatToRGBA8888(format, (u32 *)(out + outPitch * y), (const u16 *)unswizzled + bufw * y, w);
1940
}
1941
} else if (reverseColors) {
1942
// Just check the swizzled input's alpha to reuse code. TODO: make a specialized ReverseColors that checks as we go.
1943
for (int y = 0; y < h; ++y) {
1944
CheckMask16((const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1945
ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u16) * y, format, w);
1946
}
1947
} else {
1948
for (int y = 0; y < h; ++y) {
1949
CopyAndSumMask16((u16 *)(out + outPitch * y), (const u16 *)(unswizzled + bufw * sizeof(u16) * y), w, &alphaSum);
1950
}
1951
}
1952
}
1953
if (format == GE_TFMT_5650) {
1954
return CHECKALPHA_FULL;
1955
}
1956
break;
1957
1958
case GE_TFMT_8888:
1959
if (!swizzled) {
1960
fullAlphaMask = TfmtRawToFullAlpha(format);
1961
if (reverseColors) {
1962
for (int y = 0; y < h; ++y) {
1963
CheckMask32((const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);
1964
ReverseColors(out + outPitch * y, texptr + bufw * sizeof(u32) * y, format, w);
1965
}
1966
} else {
1967
for (int y = 0; y < h; ++y) {
1968
CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(texptr + bufw * sizeof(u32) * y), w, &alphaSum);
1969
}
1970
}
1971
} /* else if (h >= 8 && bufw <= w) {
1972
// TODO: Handle alpha mask
1973
UnswizzleFromMem((u32 *)out, outPitch, texptr, bufw, h, 4);
1974
if (reverseColors) {
1975
ReverseColors(out, out, format, h * outPitch / 4, useBGRA);
1976
}
1977
}*/ else {
1978
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
1979
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * 4, texptr, bufw, h, 4);
1980
const u8 *unswizzled = (u8 *)tmpTexBuf32_.data();
1981
1982
fullAlphaMask = TfmtRawToFullAlpha(format);
1983
if (reverseColors) {
1984
for (int y = 0; y < h; ++y) {
1985
CheckMask32((const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);
1986
ReverseColors(out + outPitch * y, unswizzled + bufw * sizeof(u32) * y, format, w);
1987
}
1988
} else {
1989
for (int y = 0; y < h; ++y) {
1990
CopyAndSumMask32((u32 *)(out + outPitch * y), (const u32 *)(unswizzled + bufw * sizeof(u32) * y), w, &alphaSum);
1991
}
1992
}
1993
}
1994
break;
1995
1996
case GE_TFMT_DXT1:
1997
return DecodeDXTBlocks<DXT1Block, 1>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
1998
1999
case GE_TFMT_DXT3:
2000
return DecodeDXTBlocks<DXT3Block, 3>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
2001
2002
case GE_TFMT_DXT5:
2003
return DecodeDXTBlocks<DXT5Block, 5>(out, outPitch, texaddr, texptr, w, h, bufw, reverseColors);
2004
2005
default:
2006
ERROR_LOG_REPORT(Log::G3D, "Unknown Texture Format %d!!!", format);
2007
break;
2008
}
2009
2010
return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;
2011
}
2012
2013
CheckAlphaResult TextureCacheCommon::ReadIndexedTex(u8 *out, int outPitch, int level, const u8 *texptr, int bytesPerIndex, int bufw, bool reverseColors, bool expandTo32Bit) {
2014
int w = gstate.getTextureWidth(level);
2015
int h = gstate.getTextureHeight(level);
2016
2017
if (gstate.isTextureSwizzled()) {
2018
tmpTexBuf32_.resize(bufw * ((h + 7) & ~7));
2019
UnswizzleFromMem(tmpTexBuf32_.data(), bufw * bytesPerIndex, texptr, bufw, h, bytesPerIndex);
2020
texptr = (u8 *)tmpTexBuf32_.data();
2021
}
2022
2023
// Misshitsu no Sacrifice has separate CLUT data, this is a hack to allow it.
2024
// Normally separate CLUTs are not allowed for 8-bit or higher indices.
2025
const bool mipmapShareClut = gstate.isClutSharedForMipmaps() || gstate.getClutLoadBlocks() != 0x40;
2026
const int clutSharingOffset = mipmapShareClut ? 0 : (level & 1) * 256;
2027
2028
GEPaletteFormat palFormat = (GEPaletteFormat)gstate.getClutPaletteFormat();
2029
2030
const u16 *clut16 = (const u16 *)clutBuf_ + clutSharingOffset;
2031
const u32 *clut32 = (const u32 *)clutBuf_ + clutSharingOffset;
2032
2033
if (expandTo32Bit && palFormat != GE_CMODE_32BIT_ABGR8888) {
2034
const u16 *clut16raw = (const u16 *)clutBufRaw_ + clutSharingOffset;
2035
// It's possible to access the latter half of the CLUT using the start pos.
2036
const int clutStart = gstate.getClutIndexStartPos();
2037
if (clutStart > 256) {
2038
// Access wraps around when start + index goes over.
2039
ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_, clut16raw, 512);
2040
} else {
2041
ConvertFormatToRGBA8888(GEPaletteFormat(palFormat), expandClut_ + clutStart, clut16raw + clutStart, 256);
2042
}
2043
clut32 = expandClut_;
2044
palFormat = GE_CMODE_32BIT_ABGR8888;
2045
}
2046
2047
u32 alphaSum = 0xFFFFFFFF;
2048
u32 fullAlphaMask = ClutFormatToFullAlpha(palFormat, reverseColors);
2049
2050
switch (palFormat) {
2051
case GE_CMODE_16BIT_BGR5650:
2052
case GE_CMODE_16BIT_ABGR5551:
2053
case GE_CMODE_16BIT_ABGR4444:
2054
{
2055
switch (bytesPerIndex) {
2056
case 1:
2057
for (int y = 0; y < h; ++y) {
2058
DeIndexTexture((u16 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut16, &alphaSum);
2059
}
2060
break;
2061
2062
case 2:
2063
for (int y = 0; y < h; ++y) {
2064
DeIndexTexture((u16 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut16, &alphaSum);
2065
}
2066
break;
2067
2068
case 4:
2069
for (int y = 0; y < h; ++y) {
2070
DeIndexTexture((u16 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut16, &alphaSum);
2071
}
2072
break;
2073
}
2074
}
2075
break;
2076
2077
case GE_CMODE_32BIT_ABGR8888:
2078
{
2079
2080
switch (bytesPerIndex) {
2081
case 1:
2082
for (int y = 0; y < h; ++y) {
2083
DeIndexTexture((u32 *)(out + outPitch * y), (const u8 *)texptr + bufw * y, w, clut32, &alphaSum);
2084
}
2085
break;
2086
2087
case 2:
2088
for (int y = 0; y < h; ++y) {
2089
DeIndexTexture((u32 *)(out + outPitch * y), (const u16_le *)texptr + bufw * y, w, clut32, &alphaSum);
2090
}
2091
break;
2092
2093
case 4:
2094
for (int y = 0; y < h; ++y) {
2095
DeIndexTexture((u32 *)(out + outPitch * y), (const u32_le *)texptr + bufw * y, w, clut32, &alphaSum);
2096
}
2097
break;
2098
}
2099
}
2100
break;
2101
2102
default:
2103
ERROR_LOG_REPORT(Log::G3D, "Unhandled clut texture mode %d!!!", gstate.getClutPaletteFormat());
2104
break;
2105
}
2106
2107
if (palFormat == GE_CMODE_16BIT_BGR5650) {
2108
return CHECKALPHA_FULL;
2109
} else {
2110
return AlphaSumIsFull(alphaSum, fullAlphaMask) ? CHECKALPHA_FULL : CHECKALPHA_ANY;
2111
}
2112
}
2113
2114
void TextureCacheCommon::ApplyTexture(bool doBind) {
2115
TexCacheEntry *entry = nextTexture_;
2116
if (!entry) {
2117
// Maybe we bound a framebuffer?
2118
ForgetLastTexture();
2119
if (failedTexture_) {
2120
// Backends should handle this by binding a black texture with 0 alpha.
2121
BindTexture(nullptr);
2122
} else if (nextFramebufferTexture_) {
2123
// ApplyTextureFrameBuffer is responsible for setting SetTextureFullAlpha.
2124
ApplyTextureFramebuffer(nextFramebufferTexture_, gstate.getTextureFormat(), nextFramebufferTextureChannel_);
2125
nextFramebufferTexture_ = nullptr;
2126
}
2127
2128
// We don't set the 3D texture state here or anything else, on some backends (?)
2129
// a nextTexture_ of nullptr means keep the current texture.
2130
return;
2131
}
2132
2133
nextTexture_ = nullptr;
2134
2135
UpdateMaxSeenV(entry, gstate.isModeThrough());
2136
2137
if (nextNeedsRebuild_) {
2138
// Regardless of hash fails or otherwise, if this is a video, mark it frequently changing.
2139
// This prevents temporary scaling perf hits on the first second of video.
2140
if (IsVideo(entry->addr)) {
2141
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT | TexCacheEntry::STATUS_VIDEO;
2142
} else {
2143
entry->status &= ~TexCacheEntry::STATUS_VIDEO;
2144
}
2145
2146
if (nextNeedsRehash_) {
2147
PROFILE_THIS_SCOPE("texhash");
2148
// Update the hash on the texture.
2149
int w = gstate.getTextureWidth(0);
2150
int h = gstate.getTextureHeight(0);
2151
bool swizzled = gstate.isTextureSwizzled();
2152
entry->fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);
2153
2154
// TODO: Here we could check the secondary cache; maybe the texture is in there?
2155
// We would need to abort the build if so.
2156
}
2157
if (nextNeedsChange_) {
2158
// This texture existed previously, let's handle the change.
2159
HandleTextureChange(entry, nextChangeReason_, false, true);
2160
}
2161
// We actually build afterward (shared with rehash rebuild.)
2162
} else if (nextNeedsRehash_) {
2163
// Okay, this matched and didn't change - but let's check the hash. Maybe it will change.
2164
bool doDelete = true;
2165
if (!CheckFullHash(entry, doDelete)) {
2166
HandleTextureChange(entry, "hash fail", true, doDelete);
2167
nextNeedsRebuild_ = true;
2168
} else if (nextTexture_ != nullptr) {
2169
// The secondary cache may choose an entry from its storage by setting nextTexture_.
2170
// This means we should set that, instead of our previous entry.
2171
entry = nextTexture_;
2172
nextTexture_ = nullptr;
2173
UpdateMaxSeenV(entry, gstate.isModeThrough());
2174
}
2175
}
2176
2177
// Okay, now actually rebuild the texture if needed.
2178
if (nextNeedsRebuild_) {
2179
_assert_(!entry->texturePtr);
2180
BuildTexture(entry);
2181
ForgetLastTexture();
2182
}
2183
2184
gstate_c.SetTextureIsVideo((entry->status & TexCacheEntry::STATUS_VIDEO) != 0);
2185
if (entry->status & TexCacheEntry::STATUS_CLUT_GPU) {
2186
// Special process.
2187
ApplyTextureDepal(entry);
2188
entry->lastFrame = gpuStats.numFlips;
2189
gstate_c.SetTextureFullAlpha(false);
2190
gstate_c.SetTextureIs3D(false);
2191
gstate_c.SetTextureIsArray(false);
2192
gstate_c.SetTextureIsBGRA(false);
2193
} else {
2194
entry->lastFrame = gpuStats.numFlips;
2195
if (doBind) {
2196
BindTexture(entry);
2197
}
2198
gstate_c.SetTextureFullAlpha(entry->GetAlphaStatus() == TexCacheEntry::STATUS_ALPHA_FULL);
2199
gstate_c.SetTextureIs3D((entry->status & TexCacheEntry::STATUS_3D) != 0);
2200
gstate_c.SetTextureIsArray(false);
2201
gstate_c.SetTextureIsBGRA((entry->status & TexCacheEntry::STATUS_BGRA) != 0);
2202
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2203
}
2204
}
2205
2206
// Can we depalettize at all? This refers to both in-fragment-shader depal and "traditional" depal through a separate pass.
2207
static bool CanDepalettize(GETextureFormat texFormat, GEBufferFormat bufferFormat) {
2208
if (IsClutFormat(texFormat)) {
2209
switch (bufferFormat) {
2210
case GE_FORMAT_4444:
2211
case GE_FORMAT_565:
2212
case GE_FORMAT_5551:
2213
case GE_FORMAT_DEPTH16:
2214
if (texFormat == GE_TFMT_CLUT16) {
2215
return true;
2216
}
2217
if (texFormat == GE_TFMT_CLUT8 && bufferFormat == GE_FORMAT_5551 && PSP_CoreParameter().compat.flags().SOCOMClut8Replacement) {
2218
// Wacky case from issue #16210 (SOCOM etc).
2219
return true;
2220
}
2221
break;
2222
case GE_FORMAT_8888:
2223
if (texFormat == GE_TFMT_CLUT32 || texFormat == GE_TFMT_CLUT8) { // clut8 takes a special depal mode.
2224
return true;
2225
}
2226
break;
2227
case GE_FORMAT_CLUT8:
2228
case GE_FORMAT_INVALID:
2229
// Shouldn't happen here.
2230
return false;
2231
}
2232
WARN_LOG(Log::G3D, "Invalid CLUT/framebuffer combination: %s vs %s", GeTextureFormatToString(texFormat), GeBufferFormatToString(bufferFormat));
2233
return false;
2234
} else if (texFormat == GE_TFMT_5650 && bufferFormat == GE_FORMAT_DEPTH16) {
2235
// We can also "depal" 565 format, this is used to read depth buffers as 565 on occasion (#15491).
2236
return true;
2237
}
2238
return false;
2239
}
2240
2241
// If the palette is detected as a smooth ramp, we can interpolate for higher color precision.
2242
// But we only do it if the mask/shift exactly matches a color channel, else something different might be going
2243
// on and we definitely don't want to interpolate.
2244
// Great enhancement for Test Drive and Manhunt 2.
2245
static bool CanUseSmoothDepal(const GPUgstate &gstate, GEBufferFormat framebufferFormat, const ClutTexture &clutTexture) {
2246
for (int i = 0; i < ClutTexture::MAX_RAMPS; i++) {
2247
if (gstate.getClutIndexStartPos() == clutTexture.rampStarts[i] &&
2248
gstate.getClutIndexMask() < clutTexture.rampLengths[i]) {
2249
switch (framebufferFormat) {
2250
case GE_FORMAT_565:
2251
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 11) {
2252
return gstate.getClutIndexMask() == 0x1F;
2253
} else if (gstate.getClutIndexShift() == 5) {
2254
return gstate.getClutIndexMask() == 0x3F;
2255
}
2256
break;
2257
case GE_FORMAT_5551:
2258
if (gstate.getClutIndexShift() == 0 || gstate.getClutIndexShift() == 5 || gstate.getClutIndexShift() == 10) {
2259
return gstate.getClutIndexMask() == 0x1F;
2260
}
2261
break;
2262
default:
2263
// No uses for the other formats yet, add if needed.
2264
break;
2265
}
2266
}
2267
}
2268
return false;
2269
}
2270
2271
void TextureCacheCommon::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, RasterChannel channel) {
2272
Draw2DPipeline *textureShader = nullptr;
2273
uint32_t clutMode = gstate.clutformat & 0xFFFFFF;
2274
2275
bool depth = channel == RASTER_DEPTH;
2276
bool need_depalettize = CanDepalettize(texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format);
2277
2278
// Shader depal is not supported during 3D texturing or depth texturing, and requires 32-bit integer instructions in the shader.
2279
bool useShaderDepal = framebufferManager_->GetCurrentRenderVFB() != framebuffer &&
2280
!depth && clutRenderAddress_ == 0xFFFFFFFF &&
2281
!gstate_c.curTextureIs3D &&
2282
draw_->GetShaderLanguageDesc().bitwiseOps &&
2283
!(texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_5551); // socom
2284
2285
switch (draw_->GetShaderLanguageDesc().shaderLanguage) {
2286
case ShaderLanguage::GLSL_1xx:
2287
// Force off for now, in case <= GLSL 1.20 or GLES 2, which don't support switch-case.
2288
useShaderDepal = false;
2289
break;
2290
default:
2291
break;
2292
}
2293
2294
const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();
2295
ClutTexture clutTexture{};
2296
bool smoothedDepal = false;
2297
u32 depthUpperBits = 0;
2298
2299
if (need_depalettize) {
2300
if (clutRenderAddress_ == 0xFFFFFFFF) {
2301
clutTexture = textureShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBufRaw_);
2302
smoothedDepal = CanUseSmoothDepal(gstate, framebuffer->fb_format, clutTexture);
2303
} else {
2304
// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.
2305
// Instead of texturing directly from that, we copy to a temporary CLUT texture.
2306
GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat;
2307
2308
// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.
2309
// If no reinterpretation is needed, we'll automatically just get a copy shader.
2310
float scaleFactorX = 1.0f;
2311
Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);
2312
framebufferManager_->BlitUsingRaster(dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f, dynamicClutFbo_, 0.0f, 0.0f, scaleFactorX * 512.0f, 1.0f, false, 1.0f, reinterpret, "reinterpret_clut");
2313
}
2314
2315
if (useShaderDepal) {
2316
// Very icky conflation here of native and thin3d rendering. This will need careful work per backend in BindAsClutTexture.
2317
BindAsClutTexture(clutTexture.texture, smoothedDepal);
2318
2319
framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);
2320
// Vulkan needs to do some extra work here to pick out the native handle from Draw.
2321
BoundFramebufferTexture();
2322
2323
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);
2324
samplerKey.magFilt = false;
2325
samplerKey.minFilt = false;
2326
samplerKey.mipEnable = false;
2327
ApplySamplingParams(samplerKey);
2328
2329
ShaderDepalMode mode = ShaderDepalMode::NORMAL;
2330
if (texFormat == GE_TFMT_CLUT8 && framebuffer->fb_format == GE_FORMAT_8888) {
2331
mode = ShaderDepalMode::CLUT8_8888;
2332
smoothedDepal = false; // just in case
2333
} else if (smoothedDepal) {
2334
mode = ShaderDepalMode::SMOOTHED;
2335
}
2336
2337
gstate_c.Dirty(DIRTY_DEPAL);
2338
gstate_c.SetUseShaderDepal(mode);
2339
gstate_c.depalFramebufferFormat = framebuffer->fb_format;
2340
2341
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2342
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2343
CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);
2344
gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);
2345
2346
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2347
return;
2348
}
2349
2350
depthUpperBits = (depth && framebuffer->fb_format == GE_FORMAT_8888) ? ((gstate.getTextureAddress(0) & 0x600000) >> 20) : 0;
2351
2352
textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, texFormat, depth ? GE_FORMAT_DEPTH16 : framebuffer->fb_format, smoothedDepal, depthUpperBits);
2353
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2354
}
2355
2356
if (textureShader) {
2357
bool needsDepthXSwizzle = depthUpperBits == 2;
2358
2359
int depalWidth = framebuffer->renderWidth;
2360
int texWidth = framebuffer->bufferWidth;
2361
if (needsDepthXSwizzle) {
2362
texWidth = RoundUpToPowerOf2(framebuffer->bufferWidth);
2363
depalWidth = texWidth * framebuffer->renderScaleFactor;
2364
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2365
}
2366
2367
// If min is not < max, then we don't have values (wasn't set during decode.)
2368
const KnownVertexBounds &bounds = gstate_c.vertBounds;
2369
float u1 = 0.0f;
2370
float v1 = 0.0f;
2371
float u2 = depalWidth;
2372
float v2 = framebuffer->renderHeight;
2373
if (bounds.minV < bounds.maxV) {
2374
u1 = (bounds.minU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;
2375
v1 = (bounds.minV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;
2376
u2 = (bounds.maxU + gstate_c.curTextureXOffset) * framebuffer->renderScaleFactor;
2377
v2 = (bounds.maxV + gstate_c.curTextureYOffset) * framebuffer->renderScaleFactor;
2378
// We need to reapply the texture next time since we cropped UV.
2379
gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);
2380
}
2381
2382
Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, depalWidth, framebuffer->renderHeight);
2383
draw_->BindTexture(0, nullptr);
2384
draw_->BindTexture(1, nullptr);
2385
draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");
2386
draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::Aspect::DEPTH_BIT | Draw::Aspect::STENCIL_BIT);
2387
draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);
2388
Draw::Viewport viewport{ 0.0f, 0.0f, (float)depalWidth, (float)framebuffer->renderHeight, 0.0f, 1.0f };
2389
draw_->SetViewport(viewport);
2390
2391
draw_->BindFramebufferAsTexture(framebuffer->fbo, 0, depth ? Draw::Aspect::DEPTH_BIT : Draw::Aspect::COLOR_BIT, Draw::ALL_LAYERS);
2392
if (clutRenderAddress_ == 0xFFFFFFFF) {
2393
draw_->BindTexture(1, clutTexture.texture);
2394
} else {
2395
draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::Aspect::COLOR_BIT, 0);
2396
}
2397
Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);
2398
Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(smoothedDepal);
2399
draw_->BindSamplerStates(0, 1, &nearest);
2400
draw_->BindSamplerStates(1, 1, &clutSampler);
2401
2402
draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, framebuffer->renderWidth, framebuffer->renderHeight, depalWidth, framebuffer->renderHeight, false, framebuffer->renderScaleFactor);
2403
2404
gpuStats.numDepal++;
2405
2406
gstate_c.curTextureWidth = texWidth;
2407
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2408
2409
draw_->BindTexture(0, nullptr);
2410
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2411
2412
draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::Aspect::COLOR_BIT, Draw::ALL_LAYERS);
2413
BoundFramebufferTexture();
2414
2415
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2416
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2417
2418
CheckAlphaResult alphaStatus = CheckCLUTAlpha((const uint8_t *)clutBufRaw_, clutFormat, clutTotalColors);
2419
gstate_c.SetTextureFullAlpha(alphaStatus == CHECKALPHA_FULL);
2420
2421
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2422
shaderManager_->DirtyLastShader();
2423
} else {
2424
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2425
framebufferManager_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET, Draw::ALL_LAYERS);
2426
BoundFramebufferTexture();
2427
2428
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2429
gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650);
2430
}
2431
2432
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);
2433
ApplySamplingParams(samplerKey);
2434
2435
// Since we've drawn using thin3d, might need these.
2436
gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);
2437
}
2438
2439
// Applies depal to a normal (non-framebuffer) texture, pre-decoded to CLUT8 format.
2440
void TextureCacheCommon::ApplyTextureDepal(TexCacheEntry *entry) {
2441
uint32_t clutMode = gstate.clutformat & 0xFFFFFF;
2442
2443
switch (entry->format) {
2444
case GE_TFMT_CLUT4:
2445
case GE_TFMT_CLUT8:
2446
break; // These are OK
2447
default:
2448
_dbg_assert_(false);
2449
return;
2450
}
2451
2452
const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();
2453
u32 depthUpperBits = 0;
2454
2455
// The CLUT texture is dynamic, it's the framebuffer pointed to by clutRenderAddress.
2456
// Instead of texturing directly from that, we copy to a temporary CLUT texture.
2457
GEBufferFormat expectedCLUTBufferFormat = (GEBufferFormat)clutFormat; // All entries from clutFormat correspond directly to buffer formats.
2458
2459
// OK, figure out what format we want our framebuffer in, so it can be reinterpreted if needed.
2460
// If no reinterpretation is needed, we'll automatically just get a copy shader.
2461
float scaleFactorX = 1.0f;
2462
Draw2DPipeline *reinterpret = framebufferManager_->GetReinterpretPipeline(clutRenderFormat_, expectedCLUTBufferFormat, &scaleFactorX);
2463
framebufferManager_->BlitUsingRaster(
2464
dynamicClutTemp_, 0.0f, 0.0f, 512.0f, 1.0f, dynamicClutFbo_, 0.0f, 0.0f, scaleFactorX * 512.0f, 1.0f, false, 1.0f, reinterpret, "reinterpret_clut");
2465
2466
Draw2DPipeline *textureShader = textureShaderCache_->GetDepalettizeShader(clutMode, GE_TFMT_CLUT8, GE_FORMAT_CLUT8, false, 0);
2467
gstate_c.SetUseShaderDepal(ShaderDepalMode::OFF);
2468
2469
int texWidth = gstate.getTextureWidth(0);
2470
int texHeight = gstate.getTextureHeight(0);
2471
2472
// If min is not < max, then we don't have values (wasn't set during decode.)
2473
const KnownVertexBounds &bounds = gstate_c.vertBounds;
2474
float u1 = 0.0f;
2475
float v1 = 0.0f;
2476
float u2 = texWidth;
2477
float v2 = texHeight;
2478
if (bounds.minV < bounds.maxV) {
2479
// These are already in pixel coords! Doesn't seem like we should multiply by texwidth/height.
2480
u1 = bounds.minU + gstate_c.curTextureXOffset;
2481
v1 = bounds.minV + gstate_c.curTextureYOffset;
2482
u2 = bounds.maxU + gstate_c.curTextureXOffset + 1.0f;
2483
v2 = bounds.maxV + gstate_c.curTextureYOffset + 1.0f;
2484
// We need to reapply the texture next time since we cropped UV.
2485
gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);
2486
}
2487
2488
Draw::Framebuffer *depalFBO = framebufferManager_->GetTempFBO(TempFBO::DEPAL, texWidth, texHeight);
2489
draw_->BindTexture(0, nullptr);
2490
draw_->BindTexture(1, nullptr);
2491
draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");
2492
draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_STORE, Draw::Aspect::DEPTH_BIT | Draw::Aspect::STENCIL_BIT);
2493
draw_->SetScissorRect(u1, v1, u2 - u1, v2 - v1);
2494
Draw::Viewport viewport{ 0.0f, 0.0f, (float)texWidth, (float)texHeight, 0.0f, 1.0f };
2495
draw_->SetViewport(viewport);
2496
2497
draw_->BindNativeTexture(0, GetNativeTextureView(entry, false));
2498
draw_->BindFramebufferAsTexture(dynamicClutFbo_, 1, Draw::Aspect::COLOR_BIT, 0);
2499
Draw::SamplerState *nearest = textureShaderCache_->GetSampler(false);
2500
Draw::SamplerState *clutSampler = textureShaderCache_->GetSampler(false);
2501
draw_->BindSamplerStates(0, 1, &nearest);
2502
draw_->BindSamplerStates(1, 1, &clutSampler);
2503
2504
draw2D_->Blit(textureShader, u1, v1, u2, v2, u1, v1, u2, v2, texWidth, texHeight, texWidth, texHeight, false, 1);
2505
2506
gpuStats.numDepal++;
2507
2508
gstate_c.curTextureWidth = texWidth;
2509
gstate_c.Dirty(DIRTY_UVSCALEOFFSET);
2510
2511
draw_->BindTexture(0, nullptr);
2512
framebufferManager_->RebindFramebuffer("ApplyTextureFramebuffer");
2513
2514
draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::Aspect::COLOR_BIT, 0);
2515
BoundFramebufferTexture();
2516
2517
const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
2518
const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
2519
2520
// We don't know about alpha at all.
2521
gstate_c.SetTextureFullAlpha(false);
2522
2523
draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);
2524
shaderManager_->DirtyLastShader();
2525
2526
SamplerCacheKey samplerKey = GetFramebufferSamplingParams(texWidth, texHeight);
2527
ApplySamplingParams(samplerKey);
2528
2529
// Since we've drawn using thin3d, might need these.
2530
gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);
2531
}
2532
2533
void TextureCacheCommon::Clear(bool delete_them) {
2534
textureShaderCache_->Clear();
2535
2536
for (TexCache::iterator iter = cache_.begin(); iter != cache_.end(); ++iter) {
2537
ReleaseTexture(iter->second.get(), delete_them);
2538
}
2539
// In case the setting was changed, we ALWAYS clear the secondary cache (enabled or not.)
2540
for (TexCache::iterator iter = secondCache_.begin(); iter != secondCache_.end(); ++iter) {
2541
ReleaseTexture(iter->second.get(), delete_them);
2542
}
2543
if (cache_.size() + secondCache_.size()) {
2544
INFO_LOG(Log::G3D, "Texture cached cleared from %i textures", (int)(cache_.size() + secondCache_.size()));
2545
cache_.clear();
2546
secondCache_.clear();
2547
cacheSizeEstimate_ = 0;
2548
secondCacheSizeEstimate_ = 0;
2549
}
2550
videos_.clear();
2551
2552
if (dynamicClutFbo_) {
2553
dynamicClutFbo_->Release();
2554
dynamicClutFbo_ = nullptr;
2555
}
2556
if (dynamicClutTemp_) {
2557
dynamicClutTemp_->Release();
2558
dynamicClutTemp_ = nullptr;
2559
}
2560
}
2561
2562
void TextureCacheCommon::DeleteTexture(TexCache::iterator it) {
2563
ReleaseTexture(it->second.get(), true);
2564
cacheSizeEstimate_ -= EstimateTexMemoryUsage(it->second.get());
2565
cache_.erase(it);
2566
}
2567
2568
bool TextureCacheCommon::CheckFullHash(TexCacheEntry *entry, bool &doDelete) {
2569
int w = gstate.getTextureWidth(0);
2570
int h = gstate.getTextureHeight(0);
2571
bool isVideo = IsVideo(entry->addr);
2572
bool swizzled = gstate.isTextureSwizzled();
2573
2574
// Don't even check the texture, just assume it has changed.
2575
if (isVideo && g_Config.bTextureBackoffCache) {
2576
// Attempt to ensure the hash doesn't incorrectly match in if the video stops.
2577
entry->fullhash = (entry->fullhash + 0xA535A535) * 11 + (entry->fullhash & 4);
2578
return false;
2579
}
2580
2581
u32 fullhash;
2582
{
2583
PROFILE_THIS_SCOPE("texhash");
2584
fullhash = QuickTexHash(replacer_, entry->addr, entry->bufw, w, h, swizzled, GETextureFormat(entry->format), entry);
2585
}
2586
2587
if (fullhash == entry->fullhash) {
2588
if (g_Config.bTextureBackoffCache && !isVideo) {
2589
if (entry->GetHashStatus() != TexCacheEntry::STATUS_HASHING && entry->numFrames > TexCacheEntry::FRAMES_REGAIN_TRUST) {
2590
// Reset to STATUS_HASHING.
2591
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2592
entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;
2593
}
2594
} else if (entry->numFrames > TEXCACHE_FRAME_CHANGE_FREQUENT_REGAIN_TRUST) {
2595
entry->status &= ~TexCacheEntry::STATUS_CHANGE_FREQUENT;
2596
}
2597
2598
return true;
2599
}
2600
2601
// Don't give up just yet. Let's try the secondary cache if it's been invalidated before.
2602
if (PSP_CoreParameter().compat.flags().SecondaryTextureCache) {
2603
// Don't forget this one was unreliable (in case we match a secondary entry.)
2604
entry->status |= TexCacheEntry::STATUS_UNRELIABLE;
2605
2606
// If it's failed a bunch of times, then the second cache is just wasting time and VRAM.
2607
// In that case, skip.
2608
if (entry->numInvalidated > 2 && entry->numInvalidated < 128 && !lowMemoryMode_) {
2609
// We have a new hash: look for that hash in the secondary cache.
2610
u64 secondKey = fullhash | (u64)entry->cluthash << 32;
2611
TexCache::iterator secondIter = secondCache_.find(secondKey);
2612
if (secondIter != secondCache_.end()) {
2613
// Found it, but does it match our current params? If not, abort.
2614
TexCacheEntry *secondEntry = secondIter->second.get();
2615
if (secondEntry->Matches(entry->dim, entry->format, entry->maxLevel)) {
2616
// Reset the numInvalidated value lower, we got a match.
2617
if (entry->numInvalidated > 8) {
2618
--entry->numInvalidated;
2619
}
2620
2621
// Now just use our archived texture, instead of entry.
2622
nextTexture_ = secondEntry;
2623
return true;
2624
}
2625
} else {
2626
// It wasn't found, so we're about to throw away the entry and rebuild a texture.
2627
// Let's save this in the secondary cache in case it gets used again.
2628
secondKey = entry->fullhash | ((u64)entry->cluthash << 32);
2629
secondCacheSizeEstimate_ += EstimateTexMemoryUsage(entry);
2630
2631
// If the entry already exists in the secondary texture cache, drop it nicely.
2632
auto oldIter = secondCache_.find(secondKey);
2633
if (oldIter != secondCache_.end()) {
2634
ReleaseTexture(oldIter->second.get(), true);
2635
}
2636
2637
// Archive the entire texture entry as is, since we'll use its params if it is seen again.
2638
// We keep parameters on the current entry, since we are STILL building a new texture here.
2639
secondCache_[secondKey].reset(new TexCacheEntry(*entry));
2640
2641
// Make sure we don't delete the texture we just archived.
2642
entry->texturePtr = nullptr;
2643
doDelete = false;
2644
}
2645
}
2646
}
2647
2648
// We know it failed, so update the full hash right away.
2649
entry->fullhash = fullhash;
2650
return false;
2651
}
2652
2653
void TextureCacheCommon::Invalidate(u32 addr, int size, GPUInvalidationType type) {
2654
// They could invalidate inside the texture, let's just give a bit of leeway.
2655
// TODO: Keep track of the largest texture size in bytes, and use that instead of this
2656
// humongous unrealistic value.
2657
2658
const int LARGEST_TEXTURE_SIZE = 512 * 512 * 4;
2659
2660
addr &= 0x3FFFFFFF;
2661
const u32 addr_end = addr + size;
2662
2663
if (type == GPU_INVALIDATE_ALL) {
2664
// This is an active signal from the game that something in the texture cache may have changed.
2665
gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);
2666
} else {
2667
// Do a quick check to see if the current texture could potentially be in range.
2668
const u32 currentAddr = gstate.getTextureAddress(0);
2669
// TODO: This can be made tighter.
2670
if (addr_end >= currentAddr && addr < currentAddr + LARGEST_TEXTURE_SIZE) {
2671
gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);
2672
}
2673
}
2674
2675
// If we're hashing every use, without backoff, then this isn't needed.
2676
if (!g_Config.bTextureBackoffCache && type != GPU_INVALIDATE_FORCE) {
2677
return;
2678
}
2679
2680
const u64 startKey = (u64)(addr - LARGEST_TEXTURE_SIZE) << 32;
2681
u64 endKey = (u64)(addr + size + LARGEST_TEXTURE_SIZE) << 32;
2682
if (endKey < startKey) {
2683
endKey = (u64)-1;
2684
}
2685
2686
for (TexCache::iterator iter = cache_.lower_bound(startKey), end = cache_.upper_bound(endKey); iter != end; ++iter) {
2687
auto &entry = iter->second;
2688
u32 texAddr = entry->addr;
2689
// Intentional underestimate here.
2690
u32 texEnd = entry->addr + entry->SizeInRAM() / 2;
2691
2692
// Quick check for overlap. Yes the check is right.
2693
if (addr < texEnd && addr_end > texAddr) {
2694
if (entry->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
2695
entry->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2696
}
2697
if (type == GPU_INVALIDATE_FORCE) {
2698
// Just random values to force the hash not to match.
2699
entry->fullhash = (entry->fullhash ^ 0x12345678) + 13;
2700
entry->minihash = (entry->minihash ^ 0x89ABCDEF) + 89;
2701
}
2702
if (type != GPU_INVALIDATE_ALL) {
2703
gpuStats.numTextureInvalidations++;
2704
// Start it over from 0 (unless it's safe.)
2705
entry->numFrames = type == GPU_INVALIDATE_SAFE ? 256 : 0;
2706
if (type == GPU_INVALIDATE_SAFE) {
2707
u32 diff = gpuStats.numFlips - entry->lastFrame;
2708
// We still need to mark if the texture is frequently changing, even if it's safely changing.
2709
if (diff < TEXCACHE_FRAME_CHANGE_FREQUENT) {
2710
entry->status |= TexCacheEntry::STATUS_CHANGE_FREQUENT;
2711
}
2712
}
2713
entry->framesUntilNextFullHash = 0;
2714
} else {
2715
entry->invalidHint++;
2716
}
2717
}
2718
}
2719
}
2720
2721
void TextureCacheCommon::InvalidateAll(GPUInvalidationType /*unused*/) {
2722
// If we're hashing every use, without backoff, then this isn't needed.
2723
if (!g_Config.bTextureBackoffCache) {
2724
return;
2725
}
2726
2727
if (timesInvalidatedAllThisFrame_ > 5) {
2728
return;
2729
}
2730
timesInvalidatedAllThisFrame_++;
2731
2732
for (TexCache::iterator iter = cache_.begin(), end = cache_.end(); iter != end; ++iter) {
2733
if (iter->second->GetHashStatus() == TexCacheEntry::STATUS_RELIABLE) {
2734
iter->second->SetHashStatus(TexCacheEntry::STATUS_HASHING);
2735
}
2736
iter->second->invalidHint++;
2737
}
2738
}
2739
2740
void TextureCacheCommon::ClearNextFrame() {
2741
clearCacheNextFrame_ = true;
2742
}
2743
2744
std::string AttachCandidate::ToString() const {
2745
return StringFromFormat("[%s seq:%d rel:%d C:%08x/%d(%s) Z:%08x/%d X:%d Y:%d reint: %s]",
2746
RasterChannelToString(this->channel),
2747
this->channel == RASTER_COLOR ? this->fb->colorBindSeq : this->fb->depthBindSeq,
2748
this->relevancy,
2749
this->fb->fb_address, this->fb->fb_stride, GeBufferFormatToString(this->fb->fb_format),
2750
this->fb->z_address, this->fb->z_stride,
2751
this->match.xOffset, this->match.yOffset, this->match.reinterpret ? "true" : "false");
2752
}
2753
2754
bool TextureCacheCommon::PrepareBuildTexture(BuildTexturePlan &plan, TexCacheEntry *entry) {
2755
gpuStats.numTexturesDecoded++;
2756
2757
// For the estimate, we assume cluts always point to 8888 for simplicity.
2758
cacheSizeEstimate_ += EstimateTexMemoryUsage(entry);
2759
2760
plan.badMipSizes = false;
2761
// maxLevel here is the max level to upload. Not the count.
2762
plan.levelsToLoad = entry->maxLevel + 1;
2763
for (int i = 0; i < plan.levelsToLoad; i++) {
2764
// If encountering levels pointing to nothing, adjust max level.
2765
u32 levelTexaddr = gstate.getTextureAddress(i);
2766
if (!Memory::IsValidAddress(levelTexaddr)) {
2767
plan.levelsToLoad = i;
2768
break;
2769
}
2770
2771
// If size reaches 1, stop, and override maxlevel.
2772
int tw = gstate.getTextureWidth(i);
2773
int th = gstate.getTextureHeight(i);
2774
if (tw == 1 || th == 1) {
2775
plan.levelsToLoad = i + 1; // next level is assumed to be invalid
2776
break;
2777
}
2778
2779
if (i > 0) {
2780
int lastW = gstate.getTextureWidth(i - 1);
2781
int lastH = gstate.getTextureHeight(i - 1);
2782
2783
if (gstate_c.Use(GPU_USE_TEXTURE_LOD_CONTROL)) {
2784
if (tw != 1 && tw != (lastW >> 1))
2785
plan.badMipSizes = true;
2786
else if (th != 1 && th != (lastH >> 1))
2787
plan.badMipSizes = true;
2788
}
2789
}
2790
}
2791
2792
plan.scaleFactor = standardScaleFactor_;
2793
plan.depth = 1;
2794
2795
// Rachet down scale factor in low-memory mode.
2796
// TODO: I think really we should just turn it off?
2797
if (lowMemoryMode_ && !plan.hardwareScaling) {
2798
// Keep it even, though, just in case of npot troubles.
2799
plan.scaleFactor = plan.scaleFactor > 4 ? 4 : (plan.scaleFactor > 2 ? 2 : 1);
2800
}
2801
2802
bool isFakeMipmapChange = false;
2803
if (plan.badMipSizes) {
2804
isFakeMipmapChange = IsFakeMipmapChange();
2805
2806
// Check for pure 3D texture.
2807
int tw = gstate.getTextureWidth(0);
2808
int th = gstate.getTextureHeight(0);
2809
bool pure3D = true;
2810
for (int i = 0; i < plan.levelsToLoad; i++) {
2811
if (gstate.getTextureWidth(i) != gstate.getTextureWidth(0) || gstate.getTextureHeight(i) != gstate.getTextureHeight(0)) {
2812
pure3D = false;
2813
break;
2814
}
2815
}
2816
2817
// Check early for the degenerate case from Tactics Ogre.
2818
if (pure3D && plan.levelsToLoad == 2 && gstate.getTextureAddress(0) == gstate.getTextureAddress(1)) {
2819
// Simply treat it as a regular 2D texture, no fake mipmaps or anything.
2820
// levelsToLoad/Create gets set to 1 on the way out from the surrounding if.
2821
isFakeMipmapChange = false;
2822
pure3D = false;
2823
} else if (isFakeMipmapChange) {
2824
// We don't want to create a volume texture, if this is a "fake mipmap change".
2825
// In practice due to the compat flag, the only time we end up here is in JP Tactics Ogre.
2826
pure3D = false;
2827
}
2828
2829
if (pure3D && draw_->GetDeviceCaps().texture3DSupported) {
2830
plan.depth = plan.levelsToLoad;
2831
plan.scaleFactor = 1;
2832
}
2833
2834
plan.levelsToLoad = 1;
2835
plan.levelsToCreate = 1;
2836
}
2837
2838
if (plan.hardwareScaling) {
2839
plan.scaleFactor = shaderScaleFactor_;
2840
}
2841
2842
// We generate missing mipmaps from maxLevel+1 up to this level. maxLevel can get overwritten below
2843
// such as when using replacement textures - but let's keep the same amount of levels for generation.
2844
// Not all backends will generate mipmaps, and in GL we can't really control the number of levels.
2845
plan.levelsToCreate = plan.levelsToLoad;
2846
2847
plan.w = gstate.getTextureWidth(0);
2848
plan.h = gstate.getTextureHeight(0);
2849
2850
bool isPPGETexture = entry->addr >= PSP_GetKernelMemoryBase() && entry->addr < PSP_GetKernelMemoryEnd();
2851
2852
// Don't scale the PPGe texture.
2853
if (isPPGETexture) {
2854
plan.scaleFactor = 1;
2855
} else if (!g_DoubleTextureCoordinates) {
2856
// Refuse to load invalid-ly sized textures, which can happen through display list corruption.
2857
// However, turns out some games uses huge textures for font rendering for no apparent reason.
2858
// These will only work correctly in the top 512x512 part. So, I've increased the threshold quite a bit.
2859
// We probably should handle these differently, by clamping the texture size and texture coordinates, but meh.
2860
if (plan.w > 2048 || plan.h > 2048) {
2861
ERROR_LOG(Log::G3D, "Bad texture dimensions: %dx%d", plan.w, plan.h);
2862
return false;
2863
}
2864
}
2865
2866
if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn && gstate.FrameBufStride() < 0x1E0) {
2867
// A bit of an esoteric workaround - force off upscaling for static textures that participate directly in small-resolution framebuffer effects.
2868
// This fixes the water in Outrun/DiRT 2 with upscaling enabled.
2869
plan.scaleFactor = 1;
2870
}
2871
2872
if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && plan.scaleFactor != 1 && plan.slowScaler) {
2873
// Remember for later that we /wanted/ to scale this texture.
2874
entry->status |= TexCacheEntry::STATUS_TO_SCALE;
2875
plan.scaleFactor = 1;
2876
}
2877
2878
if (plan.scaleFactor != 1) {
2879
if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED && plan.slowScaler) {
2880
entry->status |= TexCacheEntry::STATUS_TO_SCALE;
2881
plan.scaleFactor = 1;
2882
} else {
2883
entry->status &= ~TexCacheEntry::STATUS_TO_SCALE;
2884
entry->status |= TexCacheEntry::STATUS_IS_SCALED_OR_REPLACED;
2885
texelsScaledThisFrame_ += plan.w * plan.h;
2886
}
2887
}
2888
2889
plan.isVideo = IsVideo(entry->addr);
2890
2891
// TODO: Support reading actual mip levels for upscaled images, instead of just generating them.
2892
// Maybe can just remove this check?
2893
if (plan.scaleFactor > 1) {
2894
plan.levelsToLoad = 1;
2895
2896
bool enableVideoUpscaling = false;
2897
2898
if (!enableVideoUpscaling && plan.isVideo) {
2899
plan.scaleFactor = 1;
2900
plan.levelsToCreate = 1;
2901
}
2902
}
2903
2904
bool canReplace = !isPPGETexture;
2905
if (entry->status & TexCacheEntry::TexStatus::STATUS_CLUT_GPU) {
2906
_dbg_assert_(entry->format == GE_TFMT_CLUT4 || entry->format == GE_TFMT_CLUT8);
2907
plan.decodeToClut8 = true;
2908
// We only support 1 mip level when doing CLUT on GPU for now.
2909
// Supporting more would be possible, just not very interesting until we need it.
2910
plan.levelsToCreate = 1;
2911
plan.levelsToLoad = 1;
2912
plan.maxPossibleLevels = 1;
2913
plan.scaleFactor = 1;
2914
plan.saveTexture = false; // Can't yet save these properly.
2915
canReplace = false;
2916
} else {
2917
plan.decodeToClut8 = false;
2918
}
2919
2920
if (canReplace) {
2921
// This is the "trigger point" for replacement.
2922
plan.replaced = FindReplacement(entry, &plan.w, &plan.h, &plan.depth);
2923
plan.doReplace = plan.replaced ? plan.replaced->State() == ReplacementState::ACTIVE : false;
2924
} else {
2925
plan.replaced = nullptr;
2926
plan.doReplace = false;
2927
}
2928
2929
// NOTE! Last chance to change scale factor here!
2930
2931
plan.saveTexture = false;
2932
if (plan.doReplace) {
2933
// We're replacing, so we won't scale.
2934
plan.scaleFactor = 1;
2935
// We're ignoring how many levels were specified - instead we just load all available from the replacer.
2936
plan.levelsToLoad = plan.replaced->NumLevels();
2937
plan.levelsToCreate = plan.levelsToLoad; // Or more, if we wanted to generate.
2938
plan.badMipSizes = false;
2939
// But, we still need to create the texture at a larger size.
2940
plan.replaced->GetSize(0, &plan.createW, &plan.createH);
2941
} else {
2942
if (replacer_.SaveEnabled() && !plan.doReplace && plan.depth == 1 && canReplace) {
2943
ReplacedTextureDecodeInfo replacedInfo;
2944
// TODO: Do we handle the race where a replacement becomes valid AFTER this but before we save?
2945
replacedInfo.cachekey = entry->CacheKey();
2946
replacedInfo.hash = entry->fullhash;
2947
replacedInfo.addr = entry->addr;
2948
replacedInfo.isFinal = (entry->status & TexCacheEntry::STATUS_TO_SCALE) == 0;
2949
replacedInfo.isVideo = plan.isVideo;
2950
replacedInfo.fmt = Draw::DataFormat::R8G8B8A8_UNORM;
2951
plan.saveTexture = replacer_.WillSave(replacedInfo);
2952
}
2953
plan.createW = plan.w * plan.scaleFactor;
2954
plan.createH = plan.h * plan.scaleFactor;
2955
}
2956
2957
// Always load base level texture here
2958
plan.baseLevelSrc = 0;
2959
if (isFakeMipmapChange) {
2960
// NOTE: Since the level is not part of the cache key, we assume it never changes.
2961
plan.baseLevelSrc = std::max(0, gstate.getTexLevelOffset16() / 16);
2962
// Tactics Ogre: If this is an odd level and it has the same texture address the below even level,
2963
// let's just say it's the even level for the purposes of replacement.
2964
// I assume this is done to avoid blending between levels accidentally?
2965
// The Japanese version of Tactics Ogre uses multiple of these "double" levels to fit more characters.
2966
if ((plan.baseLevelSrc & 1) && gstate.getTextureAddress(plan.baseLevelSrc) == gstate.getTextureAddress(plan.baseLevelSrc & ~1)) {
2967
plan.baseLevelSrc &= ~1;
2968
}
2969
plan.levelsToCreate = 1;
2970
plan.levelsToLoad = 1;
2971
// Make sure we already decided not to do a 3D texture above.
2972
_dbg_assert_(plan.depth == 1);
2973
}
2974
2975
if (plan.isVideo || plan.depth != 1 || plan.decodeToClut8) {
2976
plan.levelsToLoad = 1;
2977
plan.maxPossibleLevels = 1;
2978
} else {
2979
plan.maxPossibleLevels = log2i(std::max(plan.createW, plan.createH)) + 1;
2980
}
2981
2982
if (plan.levelsToCreate == 1) {
2983
entry->status |= TexCacheEntry::STATUS_NO_MIPS;
2984
} else {
2985
entry->status &= ~TexCacheEntry::STATUS_NO_MIPS;
2986
}
2987
2988
// Will be filled in again during decode.
2989
entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK;
2990
return true;
2991
}
2992
2993
// Passing 0 into dataSize will disable checking.
2994
void TextureCacheCommon::LoadTextureLevel(TexCacheEntry &entry, uint8_t *data, size_t dataSize, int stride, BuildTexturePlan &plan, int srcLevel, Draw::DataFormat dstFmt, TexDecodeFlags texDecFlags) {
2995
int w = gstate.getTextureWidth(srcLevel);
2996
int h = gstate.getTextureHeight(srcLevel);
2997
2998
PROFILE_THIS_SCOPE("decodetex");
2999
3000
if (plan.doReplace) {
3001
plan.replaced->GetSize(srcLevel, &w, &h);
3002
double replaceStart = time_now_d();
3003
plan.replaced->CopyLevelTo(srcLevel, data, dataSize, stride);
3004
replacementTimeThisFrame_ += time_now_d() - replaceStart;
3005
} else {
3006
GETextureFormat tfmt = (GETextureFormat)entry.format;
3007
GEPaletteFormat clutformat = gstate.getClutPaletteFormat();
3008
u32 texaddr = gstate.getTextureAddress(srcLevel);
3009
const int bufw = GetTextureBufw(srcLevel, texaddr, tfmt);
3010
u32 *pixelData;
3011
int decPitch;
3012
if (plan.scaleFactor > 1) {
3013
tmpTexBufRearrange_.resize(std::max(bufw, w) * h);
3014
pixelData = tmpTexBufRearrange_.data();
3015
// We want to end up with a neatly packed texture for scaling.
3016
decPitch = w * 4;
3017
} else {
3018
pixelData = (u32 *)data;
3019
decPitch = stride;
3020
}
3021
3022
if (!gstate_c.Use(GPU_USE_16BIT_FORMATS) || dstFmt == Draw::DataFormat::R8G8B8A8_UNORM) {
3023
texDecFlags |= TexDecodeFlags::EXPAND32;
3024
}
3025
if (entry.status & TexCacheEntry::STATUS_CLUT_GPU) {
3026
texDecFlags |= TexDecodeFlags::TO_CLUT8;
3027
}
3028
3029
CheckAlphaResult alphaResult = DecodeTextureLevel((u8 *)pixelData, decPitch, tfmt, clutformat, texaddr, srcLevel, bufw, texDecFlags);
3030
entry.SetAlphaStatus(alphaResult, srcLevel);
3031
3032
int scaledW = w, scaledH = h;
3033
if (plan.scaleFactor > 1) {
3034
// Note that this updates w and h!
3035
scaler_.ScaleAlways((u32 *)data, pixelData, w, h, &scaledW, &scaledH, plan.scaleFactor);
3036
pixelData = (u32 *)data;
3037
3038
decPitch = scaledW * sizeof(u32);
3039
3040
if (decPitch != stride) {
3041
// Rearrange in place to match the requested pitch.
3042
// (it can only be larger than w * bpp, and a match is likely.)
3043
// Note! This is bad because it reads the mapped memory!
3044
for (int y = scaledH - 1; y >= 0; --y) {
3045
memcpy((u8 *)data + stride * y, (u8 *)data + decPitch * y, scaledW *4);
3046
}
3047
decPitch = stride;
3048
}
3049
}
3050
3051
if (plan.saveTexture && !lowMemoryMode_) {
3052
ReplacedTextureDecodeInfo replacedInfo;
3053
replacedInfo.cachekey = entry.CacheKey();
3054
replacedInfo.hash = entry.fullhash;
3055
replacedInfo.addr = entry.addr;
3056
replacedInfo.isVideo = IsVideo(entry.addr);
3057
replacedInfo.isFinal = (entry.status & TexCacheEntry::STATUS_TO_SCALE) == 0;
3058
replacedInfo.fmt = dstFmt;
3059
3060
// NOTE: Reading the decoded texture here may be very slow, if we just wrote it to write-combined memory.
3061
replacer_.NotifyTextureDecoded(plan.replaced, replacedInfo, pixelData, decPitch, srcLevel, w, h, scaledW, scaledH);
3062
}
3063
}
3064
}
3065
3066
CheckAlphaResult TextureCacheCommon::CheckCLUTAlpha(const uint8_t *pixelData, GEPaletteFormat clutFormat, int w) {
3067
switch (clutFormat) {
3068
case GE_CMODE_16BIT_ABGR4444:
3069
return CheckAlpha16((const u16 *)pixelData, w, 0xF000);
3070
case GE_CMODE_16BIT_ABGR5551:
3071
return CheckAlpha16((const u16 *)pixelData, w, 0x8000);
3072
case GE_CMODE_16BIT_BGR5650:
3073
// Never has any alpha.
3074
return CHECKALPHA_FULL;
3075
default:
3076
return CheckAlpha32((const u32 *)pixelData, w, 0xFF000000);
3077
}
3078
}
3079
3080