1 // Copyright (c) 2012- 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 <algorithm>
19 #include <cstring>
20 
21 #include "Core/MemMap.h"
22 #include "Core/Reporting.h"
23 #include "GPU/ge_constants.h"
24 
25 #include "GPU/GPUState.h"
26 #include "GPU/Directx9/TextureCacheDX9.h"
27 #include "GPU/Directx9/FramebufferManagerDX9.h"
28 #include "GPU/Directx9/ShaderManagerDX9.h"
29 #include "GPU/Directx9/DepalettizeShaderDX9.h"
30 #include "Common/GPU/D3D9/D3D9StateCache.h"
31 #include "GPU/Common/FramebufferManagerCommon.h"
32 #include "GPU/Common/TextureDecoder.h"
33 #include "Core/Config.h"
34 #include "Core/Host.h"
35 
36 #include "ext/xxhash.h"
37 #include "Common/Math/math_util.h"
38 
39 
40 namespace DX9 {
41 
42 #define INVALID_TEX (LPDIRECT3DTEXTURE9)(-1)
43 
44 static const D3DVERTEXELEMENT9 g_FramebufferVertexElements[] = {
45 	{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
46 	{ 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
47 	D3DDECL_END()
48 };
49 
TextureCacheDX9(Draw::DrawContext * draw)50 TextureCacheDX9::TextureCacheDX9(Draw::DrawContext *draw)
51 	: TextureCacheCommon(draw) {
52 	lastBoundTexture = INVALID_TEX;
53 	isBgraBackend_ = true;
54 
55 	device_ = (LPDIRECT3DDEVICE9)draw->GetNativeObject(Draw::NativeObject::DEVICE);
56 	deviceEx_ = (LPDIRECT3DDEVICE9EX)draw->GetNativeObject(Draw::NativeObject::DEVICE_EX);
57 	D3DCAPS9 pCaps;
58 	ZeroMemory(&pCaps, sizeof(pCaps));
59 	HRESULT result = 0;
60 	if (deviceEx_) {
61 		result = deviceEx_->GetDeviceCaps(&pCaps);
62 	} else {
63 		result = device_->GetDeviceCaps(&pCaps);
64 	}
65 	if (FAILED(result)) {
66 		WARN_LOG(G3D, "Failed to get the device caps!");
67 		maxAnisotropyLevel = 16;
68 	} else {
69 		maxAnisotropyLevel = pCaps.MaxAnisotropy;
70 	}
71 	SetupTextureDecoder();
72 
73 	nextTexture_ = nullptr;
74 	device_->CreateVertexDeclaration(g_FramebufferVertexElements, &pFramebufferVertexDecl);
75 }
76 
~TextureCacheDX9()77 TextureCacheDX9::~TextureCacheDX9() {
78 	pFramebufferVertexDecl->Release();
79 	Clear(true);
80 }
81 
SetFramebufferManager(FramebufferManagerDX9 * fbManager)82 void TextureCacheDX9::SetFramebufferManager(FramebufferManagerDX9 *fbManager) {
83 	framebufferManagerDX9_ = fbManager;
84 	framebufferManager_ = fbManager;
85 }
86 
ReleaseTexture(TexCacheEntry * entry,bool delete_them)87 void TextureCacheDX9::ReleaseTexture(TexCacheEntry *entry, bool delete_them) {
88 	LPDIRECT3DTEXTURE9 &texture = DxTex(entry);
89 	if (texture) {
90 		texture->Release();
91 		texture = nullptr;
92 	}
93 }
94 
InvalidateLastTexture()95 void TextureCacheDX9::InvalidateLastTexture() {
96 	lastBoundTexture = INVALID_TEX;
97 }
98 
getClutDestFormat(GEPaletteFormat format)99 D3DFORMAT getClutDestFormat(GEPaletteFormat format) {
100 	switch (format) {
101 	case GE_CMODE_16BIT_ABGR4444:
102 		return D3DFMT_A4R4G4B4;
103 	case GE_CMODE_16BIT_ABGR5551:
104 		return D3DFMT_A1R5G5B5;
105 	case GE_CMODE_16BIT_BGR5650:
106 		return D3DFMT_R5G6B5;
107 	case GE_CMODE_32BIT_ABGR8888:
108 		return D3DFMT_A8R8G8B8;
109 	}
110 	// Should never be here !
111 	return D3DFMT_A8R8G8B8;
112 }
113 
ApplySamplingParams(const SamplerCacheKey & key)114 void TextureCacheDX9::ApplySamplingParams(const SamplerCacheKey &key) {
115 	dxstate.texMinFilter.set(key.minFilt ? D3DTEXF_LINEAR : D3DTEXF_POINT);
116 	dxstate.texMipFilter.set(key.mipFilt ? D3DTEXF_LINEAR : D3DTEXF_POINT);
117 	dxstate.texMagFilter.set(key.magFilt ? D3DTEXF_LINEAR : D3DTEXF_POINT);
118 
119 	// DX9 mip levels are .. odd. The "max level" sets the LARGEST mip to use.
120 	// We can enforce only the top mip level by setting a massive negative lod bias.
121 
122 	if (!key.mipEnable) {
123 		dxstate.texMaxMipLevel.set(0);
124 		dxstate.texMipLodBias.set(-100.0f);
125 	} else {
126 		dxstate.texMipLodBias.set((float)key.lodBias / 256.0f);
127 		dxstate.texMaxMipLevel.set(key.minLevel / 256);
128 	}
129 
130 	dxstate.texAddressU.set(key.sClamp ? D3DTADDRESS_CLAMP : D3DTADDRESS_WRAP);
131 	dxstate.texAddressV.set(key.tClamp ? D3DTADDRESS_CLAMP : D3DTADDRESS_WRAP);
132 }
133 
StartFrame()134 void TextureCacheDX9::StartFrame() {
135 	InvalidateLastTexture();
136 	timesInvalidatedAllThisFrame_ = 0;
137 
138 	if (texelsScaledThisFrame_) {
139 		VERBOSE_LOG(G3D, "Scaled %i texels", texelsScaledThisFrame_);
140 	}
141 	texelsScaledThisFrame_ = 0;
142 	if (clearCacheNextFrame_) {
143 		Clear(true);
144 		clearCacheNextFrame_ = false;
145 	} else {
146 		Decimate();
147 	}
148 
149 	if (gstate_c.Supports(GPU_SUPPORTS_ANISOTROPY)) {
150 		DWORD aniso = 1 << g_Config.iAnisotropyLevel;
151 		DWORD anisotropyLevel = aniso > maxAnisotropyLevel ? maxAnisotropyLevel : aniso;
152 		device_->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, anisotropyLevel);
153 	}
154 }
155 
UpdateCurrentClut(GEPaletteFormat clutFormat,u32 clutBase,bool clutIndexIsSimple)156 void TextureCacheDX9::UpdateCurrentClut(GEPaletteFormat clutFormat, u32 clutBase, bool clutIndexIsSimple) {
157 	const u32 clutBaseBytes = clutBase * (clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16));
158 	// Technically, these extra bytes weren't loaded, but hopefully it was loaded earlier.
159 	// If not, we're going to hash random data, which hopefully doesn't cause a performance issue.
160 	//
161 	// TODO: Actually, this seems like a hack.  The game can upload part of a CLUT and reference other data.
162 	// clutTotalBytes_ is the last amount uploaded.  We should hash clutMaxBytes_, but this will often hash
163 	// unrelated old entries for small palettes.
164 	// Adding clutBaseBytes may just be mitigating this for some usage patterns.
165 	const u32 clutExtendedBytes = std::min(clutTotalBytes_ + clutBaseBytes, clutMaxBytes_);
166 
167 	if (replacer_.Enabled())
168 		clutHash_ = XXH32((const char *)clutBufRaw_, clutExtendedBytes, 0xC0108888);
169 	else
170 		clutHash_ = XXH3_64bits((const char *)clutBufRaw_, clutExtendedBytes) & 0xFFFFFFFF;
171 	clutBuf_ = clutBufRaw_;
172 
173 	// Special optimization: fonts typically draw clut4 with just alpha values in a single color.
174 	clutAlphaLinear_ = false;
175 	clutAlphaLinearColor_ = 0;
176 	if (clutFormat == GE_CMODE_16BIT_ABGR4444 && clutIndexIsSimple) {
177 		const u16_le *clut = GetCurrentClut<u16_le>();
178 		clutAlphaLinear_ = true;
179 		clutAlphaLinearColor_ = clut[15] & 0x0FFF;
180 		for (int i = 0; i < 16; ++i) {
181 			u16 step = clutAlphaLinearColor_ | (i << 12);
182 			if (clut[i] != step) {
183 				clutAlphaLinear_ = false;
184 				break;
185 			}
186 		}
187 	}
188 
189 	clutLastFormat_ = gstate.clutformat;
190 }
191 
BindTexture(TexCacheEntry * entry)192 void TextureCacheDX9::BindTexture(TexCacheEntry *entry) {
193 	LPDIRECT3DTEXTURE9 texture = DxTex(entry);
194 	if (texture != lastBoundTexture) {
195 		device_->SetTexture(0, texture);
196 		lastBoundTexture = texture;
197 	}
198 	int maxLevel = (entry->status & TexCacheEntry::STATUS_BAD_MIPS) ? 0 : entry->maxLevel;
199 	SamplerCacheKey samplerKey = GetSamplingParams(maxLevel, entry);
200 	ApplySamplingParams(samplerKey);
201 }
202 
Unbind()203 void TextureCacheDX9::Unbind() {
204 	device_->SetTexture(0, NULL);
205 	InvalidateLastTexture();
206 }
207 
208 class TextureShaderApplierDX9 {
209 public:
210 	struct Pos {
PosDX9::TextureShaderApplierDX9::Pos211 		Pos(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {
212 		}
PosDX9::TextureShaderApplierDX9::Pos213 		Pos() {
214 		}
215 
216 		float x;
217 		float y;
218 		float z;
219 	};
220 	struct UV {
UVDX9::TextureShaderApplierDX9::UV221 		UV(float u_, float v_) : u(u_), v(v_) {
222 		}
UVDX9::TextureShaderApplierDX9::UV223 		UV() {
224 		}
225 
226 		float u;
227 		float v;
228 	};
229 
230 	struct PosUV {
231 		Pos pos;
232 		UV uv;
233 	};
234 
TextureShaderApplierDX9(LPDIRECT3DDEVICE9 device,LPDIRECT3DPIXELSHADER9 pshader,LPDIRECT3DVERTEXDECLARATION9 decl,float bufferW,float bufferH,int renderW,int renderH,float xoff,float yoff)235 	TextureShaderApplierDX9(LPDIRECT3DDEVICE9 device, LPDIRECT3DPIXELSHADER9 pshader, LPDIRECT3DVERTEXDECLARATION9 decl, float bufferW, float bufferH, int renderW, int renderH, float xoff, float yoff)
236 		: device_(device), pshader_(pshader), decl_(decl), bufferW_(bufferW), bufferH_(bufferH), renderW_(renderW), renderH_(renderH) {
237 		static const Pos pos[4] = {
238 			{-1,  1, 0},
239 			{ 1,  1, 0},
240 			{-1, -1, 0},
241 			{ 1, -1, 0},
242 		};
243 		static const UV uv[4] = {
244 			{0, 0},
245 			{1, 0},
246 			{0, 1},
247 			{1, 1},
248 		};
249 
250 		for (int i = 0; i < 4; ++i) {
251 			verts_[i].pos = pos[i];
252 			verts_[i].pos.x += xoff;
253 			verts_[i].pos.y += yoff;
254 			verts_[i].uv = uv[i];
255 		}
256 	}
257 
ApplyBounds(const KnownVertexBounds & bounds,u32 uoff,u32 voff,float xoff,float yoff)258 	void ApplyBounds(const KnownVertexBounds &bounds, u32 uoff, u32 voff, float xoff, float yoff) {
259 		// If min is not < max, then we don't have values (wasn't set during decode.)
260 		if (bounds.minV < bounds.maxV) {
261 			const float invWidth = 1.0f / bufferW_;
262 			const float invHeight = 1.0f / bufferH_;
263 			// Inverse of half = double.
264 			const float invHalfWidth = invWidth * 2.0f;
265 			const float invHalfHeight = invHeight * 2.0f;
266 
267 			const int u1 = bounds.minU + uoff;
268 			const int v1 = bounds.minV + voff;
269 			const int u2 = bounds.maxU + uoff;
270 			const int v2 = bounds.maxV + voff;
271 
272 			const float left = u1 * invHalfWidth - 1.0f + xoff;
273 			const float right = u2 * invHalfWidth - 1.0f + xoff;
274 			const float top = (bufferH_ - v1) * invHalfHeight - 1.0f + yoff;
275 			const float bottom = (bufferH_ - v2) * invHalfHeight - 1.0f + yoff;
276 
277 			float z = 0.0f;
278 			verts_[0].pos = Pos(left, top, z);
279 			verts_[1].pos = Pos(right, top, z);
280 			verts_[2].pos = Pos(left, bottom, z);
281 			verts_[3].pos = Pos(right, bottom, z);
282 
283 			// And also the UVs, same order.
284 			const float uvleft = u1 * invWidth;
285 			const float uvright = u2 * invWidth;
286 			const float uvtop = v1 * invHeight;
287 			const float uvbottom = v2 * invHeight;
288 
289 			verts_[0].uv = UV(uvleft, uvtop);
290 			verts_[1].uv = UV(uvright, uvtop);
291 			verts_[2].uv = UV(uvleft, uvbottom);
292 			verts_[3].uv = UV(uvright, uvbottom);
293 
294 			// We need to reapply the texture next time since we cropped UV.
295 			gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);
296 		}
297 	}
298 
Use(LPDIRECT3DVERTEXSHADER9 vshader)299 	void Use(LPDIRECT3DVERTEXSHADER9 vshader) {
300 		device_->SetPixelShader(pshader_);
301 		device_->SetVertexShader(vshader);
302 		device_->SetVertexDeclaration(decl_);
303 	}
304 
Shade()305 	void Shade() {
306 		device_->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
307 		device_->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
308 		device_->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA);
309 		device_->SetRenderState(D3DRS_ZENABLE, FALSE);
310 		device_->SetRenderState(D3DRS_STENCILENABLE, FALSE);
311 		device_->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
312 		device_->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
313 
314 		D3DVIEWPORT9 vp{ 0, 0, (DWORD)renderW_, (DWORD)renderH_, 0.0f, 1.0f };
315 		device_->SetViewport(&vp);
316 		HRESULT hr = device_->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts_, (3 + 2) * sizeof(float));
317 		if (FAILED(hr)) {
318 			ERROR_LOG_REPORT(G3D, "Depal render failed: %08x", (uint32_t)hr);
319 		}
320 
321 		dxstate.Restore();
322 	}
323 
324 protected:
325 	LPDIRECT3DDEVICE9 device_;
326 	LPDIRECT3DPIXELSHADER9 pshader_;
327 	LPDIRECT3DVERTEXDECLARATION9 decl_;
328 	PosUV verts_[4];
329 	float bufferW_;
330 	float bufferH_;
331 	int renderW_;
332 	int renderH_;
333 };
334 
ApplyTextureFramebuffer(VirtualFramebuffer * framebuffer,GETextureFormat texFormat,FramebufferNotificationChannel channel)335 void TextureCacheDX9::ApplyTextureFramebuffer(VirtualFramebuffer *framebuffer, GETextureFormat texFormat, FramebufferNotificationChannel channel) {
336 	LPDIRECT3DPIXELSHADER9 pshader = nullptr;
337 	uint32_t clutMode = gstate.clutformat & 0xFFFFFF;
338 	bool need_depalettize = IsClutFormat(texFormat);
339 	if (need_depalettize && !g_Config.bDisableSlowFramebufEffects) {
340 		pshader = depalShaderCache_->GetDepalettizePixelShader(clutMode, framebuffer->drawnFormat);
341 	}
342 
343 	if (pshader) {
344 		const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat();
345 		LPDIRECT3DTEXTURE9 clutTexture = depalShaderCache_->GetClutTexture(clutFormat, clutHash_, clutBuf_);
346 
347 		Draw::Framebuffer *depalFBO = framebufferManagerDX9_->GetTempFBO(TempFBO::DEPAL, framebuffer->renderWidth, framebuffer->renderHeight);
348 		draw_->BindFramebufferAsRenderTarget(depalFBO, { Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE, Draw::RPAction::DONT_CARE }, "Depal");
349 		shaderManager_->DirtyLastShader();
350 
351 		float xoff = -0.5f / framebuffer->renderWidth;
352 		float yoff = 0.5f / framebuffer->renderHeight;
353 
354 		TextureShaderApplierDX9 shaderApply(device_, pshader, pFramebufferVertexDecl, framebuffer->bufferWidth, framebuffer->bufferHeight, framebuffer->renderWidth, framebuffer->renderHeight, xoff, yoff);
355 		shaderApply.ApplyBounds(gstate_c.vertBounds, gstate_c.curTextureXOffset, gstate_c.curTextureYOffset, xoff, yoff);
356 		shaderApply.Use(depalShaderCache_->GetDepalettizeVertexShader());
357 
358 		device_->SetTexture(1, clutTexture);
359 		device_->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_POINT);
360 		device_->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
361 		device_->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
362 
363 		framebufferManagerDX9_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_SKIP_COPY | BINDFBCOLOR_FORCE_SELF);
364 		device_->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
365 		device_->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
366 		device_->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
367 		device_->SetSamplerState(0, D3DSAMP_MIPMAPLODBIAS, 0);
368 		device_->SetSamplerState(0, D3DSAMP_MAXMIPLEVEL, 0);
369 
370 		shaderApply.Shade();
371 
372 		draw_->BindFramebufferAsTexture(depalFBO, 0, Draw::FB_COLOR_BIT, 0);
373 
374 		const u32 bytesPerColor = clutFormat == GE_CMODE_32BIT_ABGR8888 ? sizeof(u32) : sizeof(u16);
375 		const u32 clutTotalColors = clutMaxBytes_ / bytesPerColor;
376 
377 		TexCacheEntry::TexStatus alphaStatus = CheckAlpha(clutBuf_, getClutDestFormat(clutFormat), clutTotalColors, clutTotalColors, 1);
378 		gstate_c.SetTextureFullAlpha(alphaStatus == TexCacheEntry::STATUS_ALPHA_FULL);
379 	} else {
380 		framebufferManagerDX9_->BindFramebufferAsColorTexture(0, framebuffer, BINDFBCOLOR_MAY_COPY_WITH_UV | BINDFBCOLOR_APPLY_TEX_OFFSET);
381 
382 		gstate_c.SetTextureFullAlpha(gstate.getTextureFormat() == GE_TFMT_5650);
383 	}
384 
385 	framebufferManagerDX9_->RebindFramebuffer("RebindFramebuffer - ApplyTextureFromFramebuffer");
386 
387 	SamplerCacheKey samplerKey = GetFramebufferSamplingParams(framebuffer->bufferWidth, framebuffer->bufferHeight);
388 	ApplySamplingParams(samplerKey);
389 }
390 
BuildTexture(TexCacheEntry * const entry)391 void TextureCacheDX9::BuildTexture(TexCacheEntry *const entry) {
392 	entry->status &= ~TexCacheEntry::STATUS_ALPHA_MASK;
393 
394 	// For the estimate, we assume cluts always point to 8888 for simplicity.
395 	cacheSizeEstimate_ += EstimateTexMemoryUsage(entry);
396 
397 	if ((entry->bufw == 0 || (gstate.texbufwidth[0] & 0xf800) != 0) && entry->addr >= PSP_GetKernelMemoryEnd()) {
398 		ERROR_LOG_REPORT(G3D, "Texture with unexpected bufw (full=%d)", gstate.texbufwidth[0] & 0xffff);
399 		// Proceeding here can cause a crash.
400 		return;
401 	}
402 
403 	// Adjust maxLevel to actually present levels..
404 	bool badMipSizes = false;
405 	int maxLevel = entry->maxLevel;
406 	for (int i = 0; i <= maxLevel; i++) {
407 		// If encountering levels pointing to nothing, adjust max level.
408 		u32 levelTexaddr = gstate.getTextureAddress(i);
409 		if (!Memory::IsValidAddress(levelTexaddr)) {
410 			maxLevel = i - 1;
411 			break;
412 		}
413 
414 		// If size reaches 1, stop, and override maxlevel.
415 		int tw = gstate.getTextureWidth(i);
416 		int th = gstate.getTextureHeight(i);
417 		if (tw == 1 || th == 1) {
418 			maxLevel = i;
419 			break;
420 		}
421 
422 		if (i > 0 && gstate_c.Supports(GPU_SUPPORTS_TEXTURE_LOD_CONTROL)) {
423 			if (tw != 1 && tw != (gstate.getTextureWidth(i - 1) >> 1))
424 				badMipSizes = true;
425 			else if (th != 1 && th != (gstate.getTextureHeight(i - 1) >> 1))
426 				badMipSizes = true;
427 		}
428 	}
429 
430 	// If GLES3 is available, we can preallocate the storage, which makes texture loading more efficient.
431 	D3DFORMAT dstFmt = GetDestFormat(GETextureFormat(entry->format), gstate.getClutPaletteFormat());
432 
433 	int scaleFactor = standardScaleFactor_;
434 
435 	// Rachet down scale factor in low-memory mode.
436 	if (lowMemoryMode_) {
437 		// Keep it even, though, just in case of npot troubles.
438 		scaleFactor = scaleFactor > 4 ? 4 : (scaleFactor > 2 ? 2 : 1);
439 	}
440 
441 	u64 cachekey = replacer_.Enabled() ? entry->CacheKey() : 0;
442 	int w = gstate.getTextureWidth(0);
443 	int h = gstate.getTextureHeight(0);
444 	ReplacedTexture &replaced = replacer_.FindReplacement(cachekey, entry->fullhash, w, h);
445 	if (replaced.GetSize(0, w, h)) {
446 		// We're replacing, so we won't scale.
447 		scaleFactor = 1;
448 		entry->status |= TexCacheEntry::STATUS_IS_SCALED;
449 		maxLevel = replaced.MaxLevel();
450 		badMipSizes = false;
451 	}
452 
453 	// Don't scale the PPGe texture.
454 	if (entry->addr > 0x05000000 && entry->addr < PSP_GetKernelMemoryEnd())
455 		scaleFactor = 1;
456 	if ((entry->status & TexCacheEntry::STATUS_CHANGE_FREQUENT) != 0 && scaleFactor != 1) {
457 		// Remember for later that we /wanted/ to scale this texture.
458 		entry->status |= TexCacheEntry::STATUS_TO_SCALE;
459 		scaleFactor = 1;
460 	}
461 
462 	if (scaleFactor != 1) {
463 		if (texelsScaledThisFrame_ >= TEXCACHE_MAX_TEXELS_SCALED) {
464 			entry->status |= TexCacheEntry::STATUS_TO_SCALE;
465 			scaleFactor = 1;
466 		} else {
467 			entry->status &= ~TexCacheEntry::STATUS_TO_SCALE;
468 			entry->status |= TexCacheEntry::STATUS_IS_SCALED;
469 			texelsScaledThisFrame_ += w * h;
470 		}
471 	}
472 
473 	// Seems to cause problems in Tactics Ogre.
474 	if (badMipSizes) {
475 		maxLevel = 0;
476 	}
477 
478 	if (IsFakeMipmapChange()) {
479 		// NOTE: Since the level is not part of the cache key, we assume it never changes.
480 		u8 level = std::max(0, gstate.getTexLevelOffset16() / 16);
481 		LoadTextureLevel(*entry, replaced, level, maxLevel, scaleFactor, dstFmt);
482 	} else {
483 		LoadTextureLevel(*entry, replaced, 0, maxLevel, scaleFactor, dstFmt);
484 	}
485 	LPDIRECT3DTEXTURE9 &texture = DxTex(entry);
486 	if (!texture) {
487 		return;
488 	}
489 
490 	// Mipmapping is only enabled when texture scaling is disabled.
491 	if (maxLevel > 0 && scaleFactor == 1) {
492 		for (int i = 1; i <= maxLevel; i++) {
493 			LoadTextureLevel(*entry, replaced, i, maxLevel, scaleFactor, dstFmt);
494 		}
495 	}
496 
497 	if (maxLevel == 0) {
498 		entry->status |= TexCacheEntry::STATUS_BAD_MIPS;
499 	} else {
500 		entry->status &= ~TexCacheEntry::STATUS_BAD_MIPS;
501 	}
502 	if (replaced.Valid()) {
503 		entry->SetAlphaStatus(TexCacheEntry::TexStatus(replaced.AlphaStatus()));
504 	}
505 }
506 
GetDestFormat(GETextureFormat format,GEPaletteFormat clutFormat) const507 D3DFORMAT TextureCacheDX9::GetDestFormat(GETextureFormat format, GEPaletteFormat clutFormat) const {
508 	switch (format) {
509 	case GE_TFMT_CLUT4:
510 	case GE_TFMT_CLUT8:
511 	case GE_TFMT_CLUT16:
512 	case GE_TFMT_CLUT32:
513 		return getClutDestFormat(clutFormat);
514 	case GE_TFMT_4444:
515 		return D3DFMT_A4R4G4B4;
516 	case GE_TFMT_5551:
517 		return D3DFMT_A1R5G5B5;
518 	case GE_TFMT_5650:
519 		return D3DFMT_R5G6B5;
520 	case GE_TFMT_8888:
521 	case GE_TFMT_DXT1:
522 	case GE_TFMT_DXT3:
523 	case GE_TFMT_DXT5:
524 	default:
525 		return D3DFMT_A8R8G8B8;
526 	}
527 }
528 
CheckAlpha(const u32 * pixelData,u32 dstFmt,int stride,int w,int h)529 TexCacheEntry::TexStatus TextureCacheDX9::CheckAlpha(const u32 *pixelData, u32 dstFmt, int stride, int w, int h) {
530 	CheckAlphaResult res;
531 	switch (dstFmt) {
532 	case D3DFMT_A4R4G4B4:
533 		res = CheckAlphaRGBA4444Basic(pixelData, stride, w, h);
534 		break;
535 	case D3DFMT_A1R5G5B5:
536 		res = CheckAlphaRGBA5551Basic(pixelData, stride, w, h);
537 		break;
538 	case D3DFMT_R5G6B5:
539 		// Never has any alpha.
540 		res = CHECKALPHA_FULL;
541 		break;
542 	default:
543 		res = CheckAlphaRGBA8888Basic(pixelData, stride, w, h);
544 		break;
545 	}
546 
547 	return (TexCacheEntry::TexStatus)res;
548 }
549 
FromD3D9Format(u32 fmt)550 ReplacedTextureFormat FromD3D9Format(u32 fmt) {
551 	switch (fmt) {
552 	case D3DFMT_R5G6B5: return ReplacedTextureFormat::F_5650;
553 	case D3DFMT_A1R5G5B5: return ReplacedTextureFormat::F_5551;
554 	case D3DFMT_A4R4G4B4: return ReplacedTextureFormat::F_4444;
555 	case D3DFMT_A8R8G8B8: default: return ReplacedTextureFormat::F_8888;
556 	}
557 }
558 
ToD3D9Format(ReplacedTextureFormat fmt)559 D3DFORMAT ToD3D9Format(ReplacedTextureFormat fmt) {
560 	switch (fmt) {
561 	case ReplacedTextureFormat::F_5650: return D3DFMT_R5G6B5;
562 	case ReplacedTextureFormat::F_5551: return D3DFMT_A1R5G5B5;
563 	case ReplacedTextureFormat::F_4444: return D3DFMT_A4R4G4B4;
564 	case ReplacedTextureFormat::F_8888: default: return D3DFMT_A8R8G8B8;
565 	}
566 }
567 
LoadTextureLevel(TexCacheEntry & entry,ReplacedTexture & replaced,int level,int maxLevel,int scaleFactor,u32 dstFmt)568 void TextureCacheDX9::LoadTextureLevel(TexCacheEntry &entry, ReplacedTexture &replaced, int level, int maxLevel, int scaleFactor, u32 dstFmt) {
569 	int w = gstate.getTextureWidth(level);
570 	int h = gstate.getTextureHeight(level);
571 
572 	LPDIRECT3DTEXTURE9 &texture = DxTex(&entry);
573 	if ((level == 0 || IsFakeMipmapChange()) && texture == nullptr) {
574 		// Create texture
575 		D3DPOOL pool = D3DPOOL_MANAGED;
576 		int usage = 0;
577 		pool = D3DPOOL_DEFAULT;
578 		usage = D3DUSAGE_DYNAMIC;  // TODO: Switch to using a staging texture?
579 		int levels = scaleFactor == 1 ? maxLevel + 1 : 1;
580 		int tw = w, th = h;
581 		D3DFORMAT tfmt = (D3DFORMAT)(dstFmt);
582 		if (replaced.GetSize(level, tw, th)) {
583 			tfmt = ToD3D9Format(replaced.Format(level));
584 		} else {
585 			tw *= scaleFactor;
586 			th *= scaleFactor;
587 			if (scaleFactor > 1) {
588 				tfmt = D3DFMT_A8R8G8B8;
589 			}
590 		}
591 		HRESULT hr;
592 		if (IsFakeMipmapChange())
593 			hr = device_->CreateTexture(tw, th, 1, usage, tfmt, pool, &texture, NULL);
594 		else
595 			hr = device_->CreateTexture(tw, th, levels, usage, tfmt, pool, &texture, NULL);
596 		if (FAILED(hr)) {
597 			INFO_LOG(G3D, "Failed to create D3D texture: %dx%d", tw, th);
598 			ReleaseTexture(&entry, true);
599 			return;
600 		}
601 	}
602 
603 	D3DLOCKED_RECT rect;
604 
605 	HRESULT result;
606 	uint32_t lockFlag = level == 0 ? D3DLOCK_DISCARD : 0;  // Can only discard the top level
607 	if (IsFakeMipmapChange())
608 		result = texture->LockRect(0, &rect, NULL, lockFlag);
609 	else
610 		result = texture->LockRect(level, &rect, NULL, lockFlag);
611 	if (FAILED(result)) {
612 		ERROR_LOG(G3D, "Failed to lock D3D texture: %dx%d", w, h);
613 		return;
614 	}
615 
616 	gpuStats.numTexturesDecoded++;
617 	if (replaced.GetSize(level, w, h)) {
618 		replaced.Load(level, rect.pBits, rect.Pitch);
619 		dstFmt = ToD3D9Format(replaced.Format(level));
620 	} else {
621 		GETextureFormat tfmt = (GETextureFormat)entry.format;
622 		GEPaletteFormat clutformat = gstate.getClutPaletteFormat();
623 		u32 texaddr = gstate.getTextureAddress(level);
624 		int bufw = GetTextureBufw(level, texaddr, tfmt);
625 		int bpp = dstFmt == D3DFMT_A8R8G8B8 ? 4 : 2;
626 
627 		u32 *pixelData = (u32 *)rect.pBits;
628 		int decPitch = rect.Pitch;
629 		if (scaleFactor > 1) {
630 			tmpTexBufRearrange_.resize(std::max(bufw, w) * h);
631 			pixelData = tmpTexBufRearrange_.data();
632 			// We want to end up with a neatly packed texture for scaling.
633 			decPitch = w * bpp;
634 		}
635 
636 		DecodeTextureLevel((u8 *)pixelData, decPitch, tfmt, clutformat, texaddr, level, bufw, false, false, false);
637 
638 		// We check before scaling since scaling shouldn't invent alpha from a full alpha texture.
639 		if ((entry.status & TexCacheEntry::STATUS_CHANGE_FREQUENT) == 0) {
640 			TexCacheEntry::TexStatus alphaStatus = CheckAlpha(pixelData, dstFmt, decPitch / bpp, w, h);
641 			entry.SetAlphaStatus(alphaStatus, level);
642 		} else {
643 			entry.SetAlphaStatus(TexCacheEntry::STATUS_ALPHA_UNKNOWN);
644 		}
645 
646 		if (scaleFactor > 1) {
647 			scaler.ScaleAlways((u32 *)rect.pBits, pixelData, dstFmt, w, h, scaleFactor);
648 			pixelData = (u32 *)rect.pBits;
649 
650 			// We always end up at 8888.  Other parts assume this.
651 			_assert_(dstFmt == D3DFMT_A8R8G8B8);
652 			bpp = sizeof(u32);
653 			decPitch = w * bpp;
654 
655 			if (decPitch != rect.Pitch) {
656 				// Rearrange in place to match the requested pitch.
657 				// (it can only be larger than w * bpp, and a match is likely.)
658 				for (int y = h - 1; y >= 0; --y) {
659 					memcpy((u8 *)rect.pBits + rect.Pitch * y, (u8 *)rect.pBits + decPitch * y, w * bpp);
660 				}
661 				decPitch = rect.Pitch;
662 			}
663 		}
664 
665 		if (replacer_.Enabled()) {
666 			ReplacedTextureDecodeInfo replacedInfo;
667 			replacedInfo.cachekey = entry.CacheKey();
668 			replacedInfo.hash = entry.fullhash;
669 			replacedInfo.addr = entry.addr;
670 			replacedInfo.isVideo = IsVideo(entry.addr);
671 			replacedInfo.isFinal = (entry.status & TexCacheEntry::STATUS_TO_SCALE) == 0;
672 			replacedInfo.scaleFactor = scaleFactor;
673 			replacedInfo.fmt = FromD3D9Format(dstFmt);
674 
675 			replacer_.NotifyTextureDecoded(replacedInfo, pixelData, decPitch, level, w, h);
676 		}
677 	}
678 
679 	if (IsFakeMipmapChange())
680 		texture->UnlockRect(0);
681 	else
682 		texture->UnlockRect(level);
683 }
684 
GetCurrentTextureDebug(GPUDebugBuffer & buffer,int level)685 bool TextureCacheDX9::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level) {
686 	SetTexture();
687 	ApplyTexture();
688 
689 	LPDIRECT3DBASETEXTURE9 baseTex;
690 	LPDIRECT3DTEXTURE9 tex;
691 	LPDIRECT3DSURFACE9 offscreen = nullptr;
692 	HRESULT hr;
693 
694 	bool success = false;
695 	hr = device_->GetTexture(0, &baseTex);
696 	if (SUCCEEDED(hr) && baseTex != NULL) {
697 		hr = baseTex->QueryInterface(IID_IDirect3DTexture9, (void **)&tex);
698 		if (SUCCEEDED(hr)) {
699 			D3DSURFACE_DESC desc;
700 			D3DLOCKED_RECT locked;
701 			tex->GetLevelDesc(level, &desc);
702 			RECT rect = { 0, 0, (LONG)desc.Width, (LONG)desc.Height };
703 			hr = tex->LockRect(level, &locked, &rect, D3DLOCK_READONLY);
704 
705 			// If it fails, this means it's a render-to-texture, so we have to get creative.
706 			if (FAILED(hr)) {
707 				LPDIRECT3DSURFACE9 renderTarget = nullptr;
708 				hr = tex->GetSurfaceLevel(level, &renderTarget);
709 				if (renderTarget && SUCCEEDED(hr)) {
710 					hr = device_->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &offscreen, NULL);
711 					if (SUCCEEDED(hr)) {
712 						hr = device_->GetRenderTargetData(renderTarget, offscreen);
713 						if (SUCCEEDED(hr)) {
714 							hr = offscreen->LockRect(&locked, &rect, D3DLOCK_READONLY);
715 						}
716 					}
717 					renderTarget->Release();
718 				}
719 			}
720 
721 			if (SUCCEEDED(hr)) {
722 				GPUDebugBufferFormat fmt;
723 				int pixelSize;
724 				switch (desc.Format) {
725 				case D3DFMT_A1R5G5B5:
726 					fmt = gstate_c.bgraTexture ? GPU_DBG_FORMAT_5551 : GPU_DBG_FORMAT_5551_BGRA;
727 					pixelSize = 2;
728 					break;
729 				case D3DFMT_A4R4G4B4:
730 					fmt = gstate_c.bgraTexture ? GPU_DBG_FORMAT_4444 : GPU_DBG_FORMAT_4444_BGRA;
731 					pixelSize = 2;
732 					break;
733 				case D3DFMT_R5G6B5:
734 					fmt = gstate_c.bgraTexture ? GPU_DBG_FORMAT_565 : GPU_DBG_FORMAT_565_BGRA;
735 					pixelSize = 2;
736 					break;
737 				case D3DFMT_A8R8G8B8:
738 					fmt = gstate_c.bgraTexture ? GPU_DBG_FORMAT_8888 : GPU_DBG_FORMAT_8888_BGRA;
739 					pixelSize = 4;
740 					break;
741 				default:
742 					fmt = GPU_DBG_FORMAT_INVALID;
743 					break;
744 				}
745 
746 				if (fmt != GPU_DBG_FORMAT_INVALID) {
747 					buffer.Allocate(locked.Pitch / pixelSize, desc.Height, fmt, false);
748 					memcpy(buffer.GetData(), locked.pBits, locked.Pitch * desc.Height);
749 					success = true;
750 				} else {
751 					success = false;
752 				}
753 				if (offscreen) {
754 					offscreen->UnlockRect();
755 					offscreen->Release();
756 				} else {
757 					tex->UnlockRect(level);
758 				}
759 			}
760 			tex->Release();
761 		}
762 		baseTex->Release();
763 	}
764 
765 	return success;
766 }
767 
768 };
769