1 // Copyright (c) 2015- 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 
20 #include "Common/Profiler/Profiler.h"
21 
22 #include "Common/System/Display.h"
23 #include "Common/Math/lin/matrix4x4.h"
24 #include "Common/Data/Convert/ColorConv.h"
25 #include "Common/Data/Convert/SmallDataConvert.h"
26 #include "Common/GPU/thin3d.h"
27 
28 #include "Common/GPU/Vulkan/VulkanContext.h"
29 #include "Common/GPU/Vulkan/VulkanMemory.h"
30 #include "Common/GPU/Vulkan/VulkanImage.h"
31 #include "Common/GPU/Vulkan/VulkanRenderManager.h"
32 #include "Core/MemMap.h"
33 #include "Core/Config.h"
34 #include "Core/ConfigValues.h"
35 #include "Core/System.h"
36 #include "Core/Reporting.h"
37 #include "Core/HLE/sceDisplay.h"
38 #include "GPU/ge_constants.h"
39 #include "GPU/GPUInterface.h"
40 #include "GPU/GPUState.h"
41 
42 #include "GPU/Common/TextureDecoder.h"
43 #include "GPU/Common/FramebufferManagerCommon.h"
44 #include "GPU/Debugger/Stepping.h"
45 #include "GPU/Vulkan/FramebufferManagerVulkan.h"
46 #include "GPU/Vulkan/DrawEngineVulkan.h"
47 #include "GPU/Vulkan/TextureCacheVulkan.h"
48 #include "GPU/Vulkan/ShaderManagerVulkan.h"
49 #include "GPU/Vulkan/VulkanUtil.h"
50 
51 using namespace PPSSPP_VK;
52 
53 static const char tex_fs[] = R"(#version 450
54 #extension GL_ARB_separate_shader_objects : enable
55 #extension GL_ARB_shading_language_420pack : enable
56 layout (binding = 0) uniform sampler2D sampler0;
57 layout (location = 0) in vec2 v_texcoord0;
58 layout (location = 0) out vec4 fragColor;
59 void main() {
60   fragColor = texture(sampler0, v_texcoord0);
61 }
62 )";
63 
64 static const char tex_vs[] = R"(#version 450
65 #extension GL_ARB_separate_shader_objects : enable
66 #extension GL_ARB_shading_language_420pack : enable
67 layout (location = 0) in vec3 a_position;
68 layout (location = 1) in vec2 a_texcoord0;
69 layout (location = 0) out vec2 v_texcoord0;
70 out gl_PerVertex { vec4 gl_Position; };
71 void main() {
72   v_texcoord0 = a_texcoord0;
73   gl_Position = vec4(a_position, 1.0);
74 }
75 )";
76 
77 FramebufferManagerVulkan::FramebufferManagerVulkan(Draw::DrawContext *draw, VulkanContext *vulkan) :
78 	FramebufferManagerCommon(draw),
79 	vulkan_(vulkan) {
80 	presentation_->SetLanguage(GLSL_VULKAN);
81 
82 	InitDeviceObjects();
83 
84 	// After a blit we do need to rebind for the VulkanRenderManager to know what to do.
85 	needGLESRebinds_ = true;
86 }
87 
88 FramebufferManagerVulkan::~FramebufferManagerVulkan() {
89 	DeviceLost();
90 }
91 
92 void FramebufferManagerVulkan::SetTextureCache(TextureCacheVulkan *tc) {
93 	textureCacheVulkan_ = tc;
94 	textureCache_ = tc;
95 }
96 
97 void FramebufferManagerVulkan::SetShaderManager(ShaderManagerVulkan *sm) {
98 	shaderManagerVulkan_ = sm;
99 	shaderManager_ = sm;
100 }
101 
102 void FramebufferManagerVulkan::SetDrawEngine(DrawEngineVulkan *td) {
103 	drawEngineVulkan_ = td;
104 	drawEngine_ = td;
105 }
106 
107 void FramebufferManagerVulkan::InitDeviceObjects() {
108 	std::string fs_errors, vs_errors;
109 	fsBasicTex_ = CompileShaderModule(vulkan_, VK_SHADER_STAGE_FRAGMENT_BIT, tex_fs, &fs_errors);
110 	vsBasicTex_ = CompileShaderModule(vulkan_, VK_SHADER_STAGE_VERTEX_BIT, tex_vs, &vs_errors);
111 	_assert_(fsBasicTex_ != VK_NULL_HANDLE);
112 	_assert_(vsBasicTex_ != VK_NULL_HANDLE);
113 
114 	VkSamplerCreateInfo samp = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
115 	samp.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
116 	samp.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
117 	samp.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
118 	samp.magFilter = VK_FILTER_NEAREST;
119 	samp.minFilter = VK_FILTER_NEAREST;
120 	VkResult res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &nearestSampler_);
121 	_assert_(res == VK_SUCCESS);
122 	samp.magFilter = VK_FILTER_LINEAR;
123 	samp.minFilter = VK_FILTER_LINEAR;
124 	res = vkCreateSampler(vulkan_->GetDevice(), &samp, nullptr, &linearSampler_);
125 	_assert_(res == VK_SUCCESS);
126 }
127 
128 void FramebufferManagerVulkan::DestroyDeviceObjects() {
129 	if (fsBasicTex_ != VK_NULL_HANDLE) {
130 		vulkan2D_->PurgeFragmentShader(fsBasicTex_);
131 		vulkan_->Delete().QueueDeleteShaderModule(fsBasicTex_);
132 	}
133 	if (vsBasicTex_ != VK_NULL_HANDLE) {
134 		vulkan2D_->PurgeVertexShader(vsBasicTex_);
135 		vulkan_->Delete().QueueDeleteShaderModule(vsBasicTex_);
136 	}
137 	if (stencilFs_ != VK_NULL_HANDLE) {
138 		vulkan2D_->PurgeFragmentShader(stencilFs_);
139 		vulkan_->Delete().QueueDeleteShaderModule(stencilFs_);
140 	}
141 	if (stencilVs_ != VK_NULL_HANDLE) {
142 		vulkan2D_->PurgeVertexShader(stencilVs_);
143 		vulkan_->Delete().QueueDeleteShaderModule(stencilVs_);
144 	}
145 
146 	if (linearSampler_ != VK_NULL_HANDLE)
147 		vulkan_->Delete().QueueDeleteSampler(linearSampler_);
148 	if (nearestSampler_ != VK_NULL_HANDLE)
149 		vulkan_->Delete().QueueDeleteSampler(nearestSampler_);
150 }
151 
152 void FramebufferManagerVulkan::NotifyClear(bool clearColor, bool clearAlpha, bool clearDepth, uint32_t color, float depth) {
153 	int mask = 0;
154 	// The Clear detection takes care of doing a regular draw instead if separate masking
155 	// of color and alpha is needed, so we can just treat them as the same.
156 	if (clearColor || clearAlpha)
157 		mask |= Draw::FBChannel::FB_COLOR_BIT;
158 	if (clearDepth)
159 		mask |= Draw::FBChannel::FB_DEPTH_BIT;
160 	if (clearAlpha)
161 		mask |= Draw::FBChannel::FB_STENCIL_BIT;
162 
163 	// Note that since the alpha channel and the stencil channel are shared on the PSP,
164 	// when we clear alpha, we also clear stencil to the same value.
165 	draw_->Clear(mask, color, depth, color >> 24);
166 	if (clearColor || clearAlpha) {
167 		SetColorUpdated(gstate_c.skipDrawReason);
168 	}
169 	if (clearDepth) {
170 		SetDepthUpdated();
171 	}
172 }
173 
174 void FramebufferManagerVulkan::DrawActiveTexture(float x, float y, float w, float h, float destW, float destH, float u0, float v0, float u1, float v1, int uvRotation, int flags) {
175 	float texCoords[8] = {
176 		u0,v0,
177 		u1,v0,
178 		u1,v1,
179 		u0,v1,
180 	};
181 
182 	if (uvRotation != ROTATION_LOCKED_HORIZONTAL) {
183 		float temp[8];
184 		int rotation = 0;
185 		switch (uvRotation) {
186 		case ROTATION_LOCKED_HORIZONTAL180: rotation = 4; break;
187 		case ROTATION_LOCKED_VERTICAL: rotation = 2; break;
188 		case ROTATION_LOCKED_VERTICAL180: rotation = 6; break;
189 		}
190 		for (int i = 0; i < 8; i++) {
191 			temp[i] = texCoords[(i + rotation) & 7];
192 		}
193 		memcpy(texCoords, temp, sizeof(temp));
194 	}
195 
196 	Vulkan2D::Vertex vtx[4] = {
197 		{x,     y,     0, texCoords[0], texCoords[1]},
198 		{x + w, y,     0, texCoords[2], texCoords[3]},
199 		{x,     y + h, 0, texCoords[6], texCoords[7]},
200 		{x + w, y + h, 0, texCoords[4], texCoords[5]},
201 	};
202 
203 	float invDestW = 1.0f / (destW * 0.5f);
204 	float invDestH = 1.0f / (destH * 0.5f);
205 	for (int i = 0; i < 4; i++) {
206 		vtx[i].x = vtx[i].x * invDestW - 1.0f;
207 		vtx[i].y = vtx[i].y * invDestH - 1.0f;
208 	}
209 
210 	if ((flags & DRAWTEX_TO_BACKBUFFER) && g_display_rotation != DisplayRotation::ROTATE_0) {
211 		for (int i = 0; i < 4; i++) {
212 			Lin::Vec3 v(vtx[i].x, vtx[i].y, 0.0f);
213 			// backwards notation, should fix that...
214 			v = v * g_display_rot_matrix;
215 			vtx[i].x = v.x;
216 			vtx[i].y = v.y;
217 		}
218 	}
219 
220 	draw_->FlushState();
221 
222 	// TODO: Should probably use draw_ directly and not go low level
223 
224 	VulkanRenderManager *renderManager = (VulkanRenderManager *)draw_->GetNativeObject(Draw::NativeObject::RENDER_MANAGER);
225 
226 	VkImageView view = (VkImageView)draw_->GetNativeObject(Draw::NativeObject::BOUND_TEXTURE0_IMAGEVIEW);
227 	VkDescriptorSet descSet = vulkan2D_->GetDescriptorSet(view, (flags & DRAWTEX_LINEAR) ? linearSampler_ : nearestSampler_, VK_NULL_HANDLE, VK_NULL_HANDLE);
228 	VkBuffer vbuffer;
229 	VkDeviceSize offset = push_->Push(vtx, sizeof(vtx), &vbuffer);
230 	renderManager->BindPipeline(cur2DPipeline_, (PipelineFlags)0);
231 	renderManager->Draw(vulkan2D_->GetPipelineLayout(), descSet, 0, nullptr, vbuffer, offset, 4);
232 }
233 
234 void FramebufferManagerVulkan::Bind2DShader() {
235 	VkRenderPass rp = (VkRenderPass)draw_->GetNativeObject(Draw::NativeObject::COMPATIBLE_RENDERPASS);
236 	cur2DPipeline_ = vulkan2D_->GetPipeline(rp, vsBasicTex_, fsBasicTex_);
237 }
238 
239 void FramebufferManagerVulkan::BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp, const char *tag) {
240 	if (!dst->fbo || !src->fbo || !useBufferedRendering_) {
241 		// This can happen if they recently switched from non-buffered.
242 		if (useBufferedRendering_) {
243 			draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitFramebuffer_Fail");
244 			gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);
245 		}
246 		return;
247 	}
248 
249 	// Perform a little bit of clipping first.
250 	// Block transfer coords are unsigned so I don't think we need to clip on the left side..
251 	if (dstX + w > dst->bufferWidth) {
252 		w -= dstX + w - dst->bufferWidth;
253 	}
254 	if (dstY + h > dst->bufferHeight) {
255 		h -= dstY + h - dst->bufferHeight;
256 	}
257 	if (srcX + w > src->bufferWidth) {
258 		w -= srcX + w - src->bufferWidth;
259 	}
260 	if (srcY + h > src->bufferHeight) {
261 		h -= srcY + h - src->bufferHeight;
262 	}
263 
264 	if (w <= 0 || h <= 0) {
265 		// The whole rectangle got clipped.
266 		return;
267 	}
268 
269 	float srcXFactor = (float)src->renderScaleFactor;
270 	float srcYFactor = (float)src->renderScaleFactor;
271 
272 	// Some games use wrong-format block transfers. Simulate that.
273 	const int srcBpp = src->format == GE_FORMAT_8888 ? 4 : 2;
274 	if (srcBpp != bpp && bpp != 0) {
275 		srcXFactor = (srcXFactor * bpp) / srcBpp;
276 	}
277 	int srcX1 = srcX * srcXFactor;
278 	int srcX2 = (srcX + w) * srcXFactor;
279 	int srcY1 = srcY * srcYFactor;
280 	int srcY2 = (srcY + h) * srcYFactor;
281 
282 	float dstXFactor = (float)dst->renderScaleFactor;
283 	float dstYFactor = (float)dst->renderScaleFactor;
284 	const int dstBpp = dst->format == GE_FORMAT_8888 ? 4 : 2;
285 	if (dstBpp != bpp && bpp != 0) {
286 		dstXFactor = (dstXFactor * bpp) / dstBpp;
287 	}
288 	int dstX1 = dstX * dstXFactor;
289 	int dstX2 = (dstX + w) * dstXFactor;
290 	int dstY1 = dstY * dstYFactor;
291 	int dstY2 = (dstY + h) * dstYFactor;
292 
293 	if (src == dst && srcX == dstX && srcY == dstY) {
294 		// Let's just skip a copy where the destination is equal to the source.
295 		WARN_LOG_REPORT_ONCE(blitSame, G3D, "Skipped blit with equal dst and src");
296 		return;
297 	}
298 
299 	const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1;
300 	const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight;
301 	const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight;
302 	const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2;
303 	const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2;
304 	if (sameSize && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) {
305 		draw_->CopyFramebufferImage(src->fbo, 0, srcX1, srcY1, 0, dst->fbo, 0, dstX1, dstY1, 0, dstX2 - dstX1, dstY2 - dstY1, 1, Draw::FB_COLOR_BIT, tag);
306 	} else {
307 		draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, Draw::FB_COLOR_BIT, Draw::FB_BLIT_NEAREST, tag);
308 	}
309 }
310 
311 void FramebufferManagerVulkan::BeginFrameVulkan() {
312 	BeginFrame();
313 }
314 
315 void FramebufferManagerVulkan::EndFrame() {
316 }
317 
318 void FramebufferManagerVulkan::DeviceLost() {
319 	FramebufferManagerCommon::DeviceLost();
320 	DestroyDeviceObjects();
321 }
322 
323 void FramebufferManagerVulkan::DeviceRestore(Draw::DrawContext *draw) {
324 	FramebufferManagerCommon::DeviceRestore(draw);
325 	vulkan_ = (VulkanContext *)draw->GetNativeObject(Draw::NativeObject::CONTEXT);
326 	InitDeviceObjects();
327 }
328