Path: blob/master/GPU/Common/FramebufferManagerCommon.cpp
3186 views
// Copyright (c) 2012- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <algorithm>18#include <sstream>19#include <cmath>2021#include "Common/GPU/thin3d.h"22#include "Common/Data/Collections/TinySet.h"23#include "Common/Data/Convert/ColorConv.h"24#include "Common/LogReporting.h"25#include "Common/System/Display.h"26#include "Common/VR/PPSSPPVR.h"27#include "Common/CommonTypes.h"28#include "Common/StringUtils.h"29#include "Core/Config.h"30#include "Core/ConfigValues.h"31#include "Core/Core.h"32#include "Core/CoreParameter.h"33#include "Core/Debugger/MemBlockInfo.h"34#include "GPU/Common/DrawEngineCommon.h"35#include "GPU/Common/FramebufferManagerCommon.h"36#include "GPU/Common/PresentationCommon.h"37#include "GPU/Common/TextureCacheCommon.h"38#include "GPU/Common/ReinterpretFramebuffer.h"39#include "GPU/GPUCommon.h"40#include "GPU/GPUState.h"4142static size_t FormatFramebufferName(const VirtualFramebuffer *vfb, char *tag, size_t len) {43return snprintf(tag, len, "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, vfb->bufferWidth, vfb->bufferHeight, GeBufferFormatToString(vfb->fb_format));44}4546FramebufferManagerCommon::FramebufferManagerCommon(Draw::DrawContext *draw)47: draw_(draw), draw2D_(draw_) {48presentation_ = new PresentationCommon(draw);49}5051FramebufferManagerCommon::~FramebufferManagerCommon() {52DeviceLost();5354DecimateFBOs();55for (auto vfb : vfbs_) {56DestroyFramebuf(vfb);57}58vfbs_.clear();5960for (auto &tempFB : tempFBOs_) {61tempFB.second.fbo->Release();62}63tempFBOs_.clear();6465// Do the same for ReadFramebuffersToMemory's VFBs66for (auto vfb : bvfbs_) {67DestroyFramebuf(vfb);68}69bvfbs_.clear();7071delete presentation_;72delete[] convBuf_;73}7475void FramebufferManagerCommon::Init(int msaaLevel) {76// We may need to override the render size if the shader is upscaling or SSAA.77NotifyDisplayResized();78NotifyRenderResized(msaaLevel);79}8081// Returns true if we need to stop the render thread82bool FramebufferManagerCommon::UpdateRenderSize(int msaaLevel) {83const bool newRender = renderWidth_ != (float)PSP_CoreParameter().renderWidth || renderHeight_ != (float)PSP_CoreParameter().renderHeight || msaaLevel_ != msaaLevel;8485int effectiveBloomHack = g_Config.iBloomHack;86if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {87effectiveBloomHack = 3;88} else if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOff) {89effectiveBloomHack = 0;90}9192bool newBuffered = !g_Config.bSkipBufferEffects;93const bool newSettings = bloomHack_ != effectiveBloomHack || useBufferedRendering_ != newBuffered;9495renderWidth_ = (float)PSP_CoreParameter().renderWidth;96renderHeight_ = (float)PSP_CoreParameter().renderHeight;97renderScaleFactor_ = (float)PSP_CoreParameter().renderScaleFactor;98msaaLevel_ = msaaLevel;99100bloomHack_ = effectiveBloomHack;101useBufferedRendering_ = newBuffered;102103presentation_->UpdateRenderSize(renderWidth_, renderHeight_);104105// If just switching TO buffered rendering, no need to pause the threads. In fact this causes problems due to the open backbuffer renderpass.106if (!useBufferedRendering_ && newBuffered) {107return false;108}109return newRender || newSettings;110}111112void FramebufferManagerCommon::CheckPostShaders() {113if (updatePostShaders_) {114presentation_->UpdatePostShader();115updatePostShaders_ = false;116}117}118119void FramebufferManagerCommon::BeginFrame() {120DecimateFBOs();121presentation_->BeginFrame();122currentRenderVfb_ = nullptr;123}124125bool FramebufferManagerCommon::PresentedThisFrame() const {126return presentation_->PresentedThisFrame();127}128129void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) {130displayFramebufPtr_ = framebuf & 0x3FFFFFFF;131if (Memory::IsVRAMAddress(displayFramebufPtr_))132displayFramebufPtr_ = framebuf & 0x041FFFFF;133displayStride_ = stride;134displayFormat_ = format;135}136137VirtualFramebuffer *FramebufferManagerCommon::GetVFBAt(u32 addr) const {138addr &= 0x3FFFFFFF;139if (Memory::IsVRAMAddress(addr))140addr &= 0x041FFFFF;141VirtualFramebuffer *match = nullptr;142for (auto vfb : vfbs_) {143if (vfb->fb_address == addr) {144// Could check w too but whatever (actually, might very well make sense to do so, depending on context).145if (!match || vfb->last_frame_render > match->last_frame_render) {146match = vfb;147}148}149}150return match;151}152153VirtualFramebuffer *FramebufferManagerCommon::GetExactVFB(u32 addr, int stride, GEBufferFormat format) const {154addr &= 0x3FFFFFFF;155if (Memory::IsVRAMAddress(addr))156addr &= 0x041FFFFF;157VirtualFramebuffer *newest = nullptr;158for (auto vfb : vfbs_) {159if (vfb->fb_address == addr && vfb->fb_stride == stride && vfb->fb_format == format) {160if (newest) {161if (vfb->colorBindSeq > newest->colorBindSeq) {162newest = vfb;163}164} else {165newest = vfb;166}167}168}169return newest;170}171172VirtualFramebuffer *FramebufferManagerCommon::ResolveVFB(u32 addr, int stride, GEBufferFormat format) {173addr &= 0x3FFFFFFF;174if (Memory::IsVRAMAddress(addr))175addr &= 0x041FFFFF;176// Find the newest one matching addr and stride.177VirtualFramebuffer *newest = nullptr;178for (auto vfb : vfbs_) {179if (vfb->fb_address == addr && vfb->FbStrideInBytes() == stride * BufferFormatBytesPerPixel(format)) {180if (newest) {181if (vfb->colorBindSeq > newest->colorBindSeq) {182newest = vfb;183}184} else {185newest = vfb;186}187}188}189190if (newest && newest->fb_format != format) {191WARN_LOG_ONCE(resolvevfb, Log::G3D, "ResolveVFB: Resolving from %s to %s at %08x/%d", GeBufferFormatToString(newest->fb_format), GeBufferFormatToString(format), addr, stride);192return ResolveFramebufferColorToFormat(newest, format);193}194195return newest;196}197198VirtualFramebuffer *FramebufferManagerCommon::GetDisplayVFB() {199return GetExactVFB(displayFramebufPtr_, displayStride_, displayFormat_);200}201202// Heuristics to figure out the size of FBO to create.203// TODO: Possibly differentiate on whether through mode is used (since in through mode, viewport is meaningless?)204void FramebufferManagerCommon::EstimateDrawingSize(u32 fb_address, int fb_stride, GEBufferFormat fb_format, int viewport_width, int viewport_height, int region_width, int region_height, int scissor_width, int scissor_height, int &drawing_width, int &drawing_height) {205static const int MAX_FRAMEBUF_HEIGHT = 512;206207// Games don't always set any of these. Take the greatest parameter that looks valid based on stride.208if (viewport_width > 4 && viewport_width <= fb_stride && viewport_height > 0) {209drawing_width = viewport_width;210drawing_height = viewport_height;211// Some games specify a viewport with 0.5, but don't have VRAM for 273. 480x272 is the buffer size.212if (viewport_width == 481 && region_width == 480 && viewport_height == 273 && region_height == 272) {213drawing_width = 480;214drawing_height = 272;215}216// Sometimes region is set larger than the VRAM for the framebuffer.217// However, in one game it's correctly set as a larger height (see #7277) with the same width.218// A bit of a hack, but we try to handle that unusual case here.219if (region_width <= fb_stride && (region_width > drawing_width || (region_width == drawing_width && region_height > drawing_height)) && region_height <= MAX_FRAMEBUF_HEIGHT) {220drawing_width = region_width;221drawing_height = std::max(drawing_height, region_height);222}223// Scissor is often set to a subsection of the framebuffer, so we pay the least attention to it.224if (scissor_width <= fb_stride && scissor_width > drawing_width && scissor_height <= MAX_FRAMEBUF_HEIGHT) {225drawing_width = scissor_width;226drawing_height = std::max(drawing_height, scissor_height);227}228} else {229// If viewport wasn't valid, let's just take the greatest anything regardless of stride.230drawing_width = std::min(std::max(region_width, scissor_width), fb_stride);231drawing_height = std::max(region_height, scissor_height);232}233234if (scissor_width == 481 && region_width == 480 && scissor_height == 273 && region_height == 272) {235drawing_width = 480;236drawing_height = 272;237}238239// Assume no buffer is > 512 tall, it couldn't be textured or displayed fully if so.240if (drawing_height >= MAX_FRAMEBUF_HEIGHT) {241if (region_height < MAX_FRAMEBUF_HEIGHT) {242drawing_height = region_height;243} else if (scissor_height < MAX_FRAMEBUF_HEIGHT) {244drawing_height = scissor_height;245}246}247248if (viewport_width != region_width) {249// The majority of the time, these are equal. If not, let's check what we know.250u32 nearest_address = 0xFFFFFFFF;251for (auto vfb : vfbs_) {252const u32 other_address = vfb->fb_address;253if (other_address > fb_address && other_address < nearest_address) {254nearest_address = other_address;255}256}257258// Unless the game is using overlapping buffers, the next buffer should be far enough away.259// This catches some cases where we can know this.260// Hmm. The problem is that we could only catch it for the first of two buffers...261const u32 bpp = BufferFormatBytesPerPixel(fb_format);262int avail_height = (nearest_address - fb_address) / (fb_stride * bpp);263if (avail_height < drawing_height && avail_height == region_height) {264drawing_width = std::min(region_width, fb_stride);265drawing_height = avail_height;266}267268// Some games draw buffers interleaved, with a high stride/region/scissor but default viewport.269if (fb_stride == 1024 && region_width == 1024 && scissor_width == 1024) {270drawing_width = 1024;271}272}273274bool margin = false;275// Let's check if we're in a stride gap of a full-size framebuffer.276for (auto vfb : vfbs_) {277if (fb_address == vfb->fb_address) {278continue;279}280if (vfb->fb_stride != 512) {281continue;282}283284int vfb_stride_in_bytes = BufferFormatBytesPerPixel(vfb->fb_format) * vfb->fb_stride;285int stride_in_bytes = BufferFormatBytesPerPixel(fb_format) * fb_stride;286if (stride_in_bytes != vfb_stride_in_bytes) {287// Mismatching stride in bytes, not interesting288continue;289}290291if (fb_address > vfb->fb_address && fb_address < vfb->fb_address + vfb_stride_in_bytes) {292// Candidate!293if (vfb->height == drawing_height) {294// Might have a margin texture! Fix the drawing width if it's too large.295int width_in_bytes = vfb->fb_address + vfb_stride_in_bytes - fb_address;296int width_in_pixels = width_in_bytes / BufferFormatBytesPerPixel(fb_format);297298// Final check299if (width_in_pixels <= 32) {300drawing_width = std::min(drawing_width, width_in_pixels);301margin = true;302// Don't really need to keep looking.303break;304}305}306}307}308309DEBUG_LOG(Log::G3D, "Est: %08x V: %ix%i, R: %ix%i, S: %ix%i, STR: %i, THR:%i, Z:%08x = %ix%i %s", fb_address, viewport_width,viewport_height, region_width, region_height, scissor_width, scissor_height, fb_stride, gstate.isModeThrough(), gstate.isDepthWriteEnabled() ? gstate.getDepthBufAddress() : 0, drawing_width, drawing_height, margin ? " (margin!)" : "");310}311312void GetFramebufferHeuristicInputs(FramebufferHeuristicParams *params, const GPUgstate &gstate) {313// GetFramebufferHeuristicInputs is only called from rendering, and thus, it's VRAM.314params->fb_address = gstate.getFrameBufRawAddress() | 0x04000000;315params->fb_stride = gstate.FrameBufStride();316317params->z_address = gstate.getDepthBufRawAddress() | 0x04000000;318params->z_stride = gstate.DepthBufStride();319320if (params->z_address == params->fb_address) {321// Probably indicates that the game doesn't care about Z for this VFB.322// Let's avoid matching it for Z copies and other shenanigans.323params->z_address = 0;324params->z_stride = 0;325}326327params->fb_format = gstate_c.framebufFormat;328329params->isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask();330// Technically, it may write depth later, but we're trying to detect it only when it's really true.331if (gstate.isModeClear()) {332// Not quite seeing how this makes sense..333params->isWritingDepth = !gstate.isClearModeDepthMask() && gstate.isDepthWriteEnabled();334} else {335params->isWritingDepth = gstate.isDepthWriteEnabled();336}337params->isDrawing = !gstate.isModeClear() || !gstate.isClearModeColorMask() || !gstate.isClearModeAlphaMask();338params->isModeThrough = gstate.isModeThrough();339const bool alphaBlending = gstate.isAlphaBlendEnabled();340const bool logicOpBlending = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_CLEAR && gstate.getLogicOp() != GE_LOGIC_COPY;341params->isBlending = alphaBlending || logicOpBlending;342343// Viewport-X1 and Y1 are not the upper left corner, but half the width/height. A bit confusing.344float vpx = gstate.getViewportXScale();345float vpy = gstate.getViewportYScale();346347// Work around problem in F1 Grand Prix, where it draws in through mode with a bogus viewport.348// We set bad values to 0 which causes the framebuffer size heuristic to rely on the other parameters instead.349if (std::isnan(vpx) || vpx > 10000000.0f) {350vpx = 0.f;351}352if (std::isnan(vpy) || vpy > 10000000.0f) {353vpy = 0.f;354}355params->viewportWidth = (int)(fabsf(vpx) * 2.0f);356params->viewportHeight = (int)(fabsf(vpy) * 2.0f);357params->regionWidth = gstate.getRegionX2() + 1;358params->regionHeight = gstate.getRegionY2() + 1;359360params->scissorLeft = gstate.getScissorX1();361params->scissorTop = gstate.getScissorY1();362params->scissorRight = gstate.getScissorX2() + 1;363params->scissorBottom = gstate.getScissorY2() + 1;364365if (gstate.getRegionRateX() != 0x100 || gstate.getRegionRateY() != 0x100) {366WARN_LOG_REPORT_ONCE(regionRate, Log::G3D, "Drawing region rate add non-zero: %04x, %04x of %04x, %04x", gstate.getRegionRateX(), gstate.getRegionRateY(), gstate.getRegionX2(), gstate.getRegionY2());367}368}369370static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width);371372VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(FramebufferHeuristicParams ¶ms, u32 skipDrawReason) {373gstate_c.Clean(DIRTY_FRAMEBUF);374375// Collect all parameters. This whole function has really become a cesspool of heuristics...376// but it appears that's what it takes, unless we emulate VRAM layout more accurately somehow.377378// As there are no clear "framebuffer width" and "framebuffer height" registers,379// we need to infer the size of the current framebuffer somehow.380int drawing_width, drawing_height;381EstimateDrawingSize(params.fb_address, std::max(params.fb_stride, (u16)4), params.fb_format, params.viewportWidth, params.viewportHeight, params.regionWidth, params.regionHeight, params.scissorRight, params.scissorBottom, drawing_width, drawing_height);382383if (params.fb_address == params.z_address) {384// Most likely Z will not be used in this pass, as that would wreak havoc (undefined behavior for sure)385// We probably don't need to do anything about that, but let's log it.386WARN_LOG_ONCE(color_equal_z, Log::G3D, "Framebuffer bound with color addr == z addr, likely will not use Z in this pass: %08x", params.fb_address);387}388389// Compatibility hack for Killzone, see issue #6207.390if (PSP_CoreParameter().compat.flags().SplitFramebufferMargin && params.fb_format == GE_FORMAT_8888) {391ApplyKillzoneFramebufferSplit(¶ms, &drawing_width);392} else {393gstate_c.SetCurRTOffset(0, 0);394}395396// Find a matching framebuffer.397VirtualFramebuffer *normal_vfb = nullptr;398int y_offset;399VirtualFramebuffer *large_offset_vfb = nullptr;400401for (auto v : vfbs_) {402const u32 bpp = BufferFormatBytesPerPixel(v->fb_format);403404if (params.fb_address == v->fb_address && params.fb_format == v->fb_format && params.fb_stride == v->fb_stride) {405if (!normal_vfb) {406normal_vfb = v;407}408} else if (!PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset && !PSP_CoreParameter().compat.flags().SplitFramebufferMargin &&409v->fb_stride == params.fb_stride && v->fb_format == params.fb_format) {410u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp;411u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp;412413if (!normal_vfb && params.fb_address > v->fb_address && params.fb_address < v_fb_first_line_end_ptr) {414const int x_offset = (params.fb_address - v->fb_address) / bpp;415if (x_offset < params.fb_stride && v->height >= drawing_height) {416// Pretty certainly a pure render-to-X-offset.417WARN_LOG_REPORT_ONCE(renderoffset, Log::FrameBuf, "Rendering to framebuffer offset at %08x +%dx%d (stride %d)", v->fb_address, x_offset, 0, v->fb_stride);418normal_vfb = v;419gstate_c.SetCurRTOffset(x_offset, 0);420normal_vfb->width = std::max((int)normal_vfb->width, x_offset + drawing_width);421// To prevent the newSize code from being confused.422drawing_width += x_offset;423break;424}425} else if (PSP_CoreParameter().compat.flags().FramebufferAllowLargeVerticalOffset &&426params.fb_address > v->fb_address && v->fb_stride > 0 && (params.fb_address - v->fb_address) % v->FbStrideInBytes() == 0 &&427params.fb_address != 0x04088000 && v->fb_address != 0x04000000) { // Heuristic to avoid merging the main framebuffers.428y_offset = (params.fb_address - v->fb_address) / v->FbStrideInBytes();429if (y_offset <= v->bufferHeight) { // note: v->height is misdetected as 256 instead of 272 here in tokimeki. Note that 272 is just the height of the upper part, it's supersampling vertically.430large_offset_vfb = v;431break;432}433}434}435}436437VirtualFramebuffer *vfb = nullptr;438if (large_offset_vfb) {439// These are prioritized over normal VFBs matches, to ensure things work even if the higher-address one440// is created first. Only enabled under compat flag.441vfb = large_offset_vfb;442WARN_LOG_REPORT_ONCE(tokimeki, Log::FrameBuf, "Detected FBO at Y offset %d of %08x: %08x", y_offset, large_offset_vfb->fb_address, params.fb_address);443gstate_c.SetCurRTOffset(0, y_offset);444vfb->height = std::max((int)vfb->height, y_offset + drawing_height);445drawing_height += y_offset;446// TODO: We can allow X/Y overlaps too, but haven't seen any so safer to not.447} else if (normal_vfb) {448vfb = normal_vfb;449if (vfb->z_address == 0 && vfb->z_stride == 0 && params.z_stride != 0) {450// Got one that was created by CreateRAMFramebuffer. Since it has no depth buffer,451// we just recreate it immediately.452ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);453}454455// Keep track, but this isn't really used.456vfb->z_stride = params.z_stride;457// Heuristic: In throughmode, a higher height could be used. Let's avoid shrinking the buffer.458if (params.isModeThrough && (int)vfb->width <= params.fb_stride) {459vfb->width = std::max((int)vfb->width, drawing_width);460vfb->height = std::max((int)vfb->height, drawing_height);461} else {462vfb->width = drawing_width;463vfb->height = drawing_height;464}465}466467if (vfb) {468bool resized = false;469if ((drawing_width != vfb->bufferWidth || drawing_height != vfb->bufferHeight)) {470// Even if it's not newly wrong, if this is larger we need to resize up.471if (vfb->width > vfb->bufferWidth || vfb->height > vfb->bufferHeight) {472ResizeFramebufFBO(vfb, vfb->width, vfb->height);473resized = true;474} else if (vfb->newWidth != drawing_width || vfb->newHeight != drawing_height) {475// If it's newly wrong, or changing every frame, just keep track.476vfb->newWidth = drawing_width;477vfb->newHeight = drawing_height;478vfb->lastFrameNewSize = gpuStats.numFlips;479} else if (vfb->lastFrameNewSize + FBO_OLD_AGE < gpuStats.numFlips) {480// Okay, it's changed for a while (and stayed that way.) Let's start over.481// But only if we really need to, to avoid blinking.482bool needsRecreate = vfb->bufferWidth > params.fb_stride;483needsRecreate = needsRecreate || vfb->newWidth > vfb->bufferWidth || vfb->newWidth * 2 < vfb->bufferWidth;484needsRecreate = needsRecreate || vfb->newHeight > vfb->bufferHeight || vfb->newHeight * 2 < vfb->bufferHeight;485486// Whether we resize or not, change the size parameters so we stop detecting a resize.487// It might be larger if all drawing has been in throughmode.488vfb->width = drawing_width;489vfb->height = drawing_height;490491if (needsRecreate) {492ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);493resized = true;494// Let's discard this information, might be wrong now.495vfb->safeWidth = 0;496vfb->safeHeight = 0;497}498}499} else {500// It's not different, let's keep track of that too.501vfb->lastFrameNewSize = gpuStats.numFlips;502}503504if (!resized && renderScaleFactor_ != 1 && vfb->renderScaleFactor == 1) {505// Might be time to change this framebuffer - have we used depth?506if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {507ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);508_assert_(vfb->renderScaleFactor != 1);509}510}511}512513// None found? Create one.514if (!vfb) {515gstate_c.usingDepth = false; // reset depth buffer tracking516517vfb = new VirtualFramebuffer{};518vfb->fbo = nullptr;519vfb->fb_address = params.fb_address;520vfb->fb_stride = params.fb_stride;521vfb->z_address = params.z_address;522vfb->z_stride = params.z_stride;523524// The other width/height parameters are set in ResizeFramebufFBO below.525vfb->width = drawing_width;526vfb->height = drawing_height;527vfb->newWidth = drawing_width;528vfb->newHeight = drawing_height;529vfb->lastFrameNewSize = gpuStats.numFlips;530vfb->fb_format = params.fb_format;531vfb->usageFlags = FB_USAGE_RENDER_COLOR;532533u32 colorByteSize = vfb->BufferByteSize(RASTER_COLOR);534if (Memory::IsVRAMAddress(params.fb_address) && params.fb_address + colorByteSize > framebufColorRangeEnd_) {535framebufColorRangeEnd_ = params.fb_address + colorByteSize;536}537538// This is where we actually create the framebuffer. The true is "force".539ResizeFramebufFBO(vfb, drawing_width, drawing_height, true);540NotifyRenderFramebufferCreated(vfb);541542// Note that we do not even think about depth right now. That'll be handled543// on the first depth access, which will call SetDepthFramebuffer.544545CopyToColorFromOverlappingFramebuffers(vfb);546SetColorUpdated(vfb, skipDrawReason);547548INFO_LOG(Log::FrameBuf, "Creating FBO for %08x (z: %08x) : %d x %d x %s", vfb->fb_address, vfb->z_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format));549550vfb->last_frame_render = gpuStats.numFlips;551frameLastFramebufUsed_ = gpuStats.numFlips;552vfbs_.push_back(vfb);553currentRenderVfb_ = vfb;554555// Assume that if we're clearing right when switching to a new framebuffer, we don't need to upload.556if (useBufferedRendering_ && params.isDrawing && vfb->fb_stride > 0) {557gpu->PerformWriteColorFromMemory(params.fb_address, colorByteSize);558// Alpha was already done by PerformWriteColorFromMemory.559PerformWriteStencilFromMemory(params.fb_address, colorByteSize, WriteStencil::STENCIL_IS_ZERO | WriteStencil::IGNORE_ALPHA);560// TODO: Is it worth trying to upload the depth buffer (only if it wasn't copied above..?)561}562563DiscardFramebufferCopy();564565// We already have it!566} else if (vfb != currentRenderVfb_) {567// Use it as a render target.568DEBUG_LOG(Log::FrameBuf, "Switching render target to FBO for %08x: %d x %d x %d ", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format);569vfb->usageFlags |= FB_USAGE_RENDER_COLOR;570vfb->last_frame_render = gpuStats.numFlips;571frameLastFramebufUsed_ = gpuStats.numFlips;572vfb->dirtyAfterDisplay = true;573if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)574vfb->reallyDirtyAfterDisplay = true;575576VirtualFramebuffer *prev = currentRenderVfb_;577currentRenderVfb_ = vfb;578NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth);579CopyToColorFromOverlappingFramebuffers(vfb);580gstate_c.usingDepth = false; // reset depth buffer tracking581582DiscardFramebufferCopy();583} else {584// Something changed, but we still got the same framebuffer we were already rendering to.585// Might not be a lot to do here, we check in NotifyRenderFramebufferUpdated586vfb->last_frame_render = gpuStats.numFlips;587frameLastFramebufUsed_ = gpuStats.numFlips;588vfb->dirtyAfterDisplay = true;589if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)590vfb->reallyDirtyAfterDisplay = true;591NotifyRenderFramebufferUpdated(vfb);592}593594vfb->colorBindSeq = GetBindSeqCount();595596gstate_c.curRTWidth = vfb->width;597gstate_c.curRTHeight = vfb->height;598gstate_c.curRTRenderWidth = vfb->renderWidth;599gstate_c.curRTRenderHeight = vfb->renderHeight;600return vfb;601}602603// Called on the first use of depth in a render pass.604void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) {605if (!currentRenderVfb_) {606return;607}608609// First time use of this framebuffer's depth buffer.610bool newlyUsingDepth = (currentRenderVfb_->usageFlags & FB_USAGE_RENDER_DEPTH) == 0;611currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH;612613uint32_t boundDepthBuffer = gstate.getDepthBufRawAddress() | 0x04000000;614uint32_t boundDepthStride = gstate.DepthBufStride();615if (currentRenderVfb_->z_address != boundDepthBuffer || currentRenderVfb_->z_stride != boundDepthStride) {616if (currentRenderVfb_->fb_address == boundDepthBuffer) {617// Disallow setting depth buffer to the same address as the color buffer, usually means it's not used.618WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Ignoring color matching depth buffer at %08x", boundDepthBuffer);619boundDepthBuffer = 0;620boundDepthStride = 0;621}622WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Framebuffer at %08x/%d has switched associated depth buffer from %08x to %08x, updating.",623currentRenderVfb_->fb_address, currentRenderVfb_->fb_stride, currentRenderVfb_->z_address, boundDepthBuffer);624625// Technically, here we should copy away the depth buffer to another framebuffer that uses that z_address, or maybe626// even write it back to RAM. However, this is rare. Silent Hill is one example, see #16126.627currentRenderVfb_->z_address = boundDepthBuffer;628// Update the stride in case it changed.629currentRenderVfb_->z_stride = boundDepthStride;630631if (currentRenderVfb_->fbo) {632char tag[128];633FormatFramebufferName(currentRenderVfb_, tag, sizeof(tag));634currentRenderVfb_->fbo->UpdateTag(tag);635}636}637638// If this first draw call is anything other than a clear, "resolve" the depth buffer,639// by copying from any overlapping buffers with fresher content.640if (!isClearingDepth && useBufferedRendering_) {641CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_);642643// Need to upload the first line of depth buffers, for Burnout Dominator lens flares. See issue #11100 and comments to #16081.644// Might make this more generic and upload the whole depth buffer if we find it's needed for something.645if (newlyUsingDepth && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {646// Sanity check the depth buffer pointer.647if (Memory::IsValidRange(currentRenderVfb_->z_address, currentRenderVfb_->width * 2)) {648const u16 *src = (const u16 *)Memory::GetPointerUnchecked(currentRenderVfb_->z_address);649DrawPixels(currentRenderVfb_, 0, 0, (const u8 *)src, GE_FORMAT_DEPTH16, currentRenderVfb_->z_stride, currentRenderVfb_->width, currentRenderVfb_->height, RASTER_DEPTH, "Depth Upload");650}651}652}653654currentRenderVfb_->depthBindSeq = GetBindSeqCount();655}656657struct CopySource {658VirtualFramebuffer *vfb;659RasterChannel channel;660int xOffset;661int yOffset;662663int seq() const {664return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq;665}666667bool operator < (const CopySource &other) const {668return seq() < other.seq();669}670};671672// Not sure if it's more profitable to always do these copies with raster (which may screw up early-Z due to explicit depth buffer write)673// or to use image copies when possible (which may make it easier for the driver to preserve early-Z, but on the other hand, will cost additional memory674// bandwidth on tilers due to the load operation, which we might otherwise be able to skip).675void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) {676std::vector<CopySource> sources;677for (auto src : vfbs_) {678if (src == dest)679continue;680681if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->fb_format == GE_FORMAT_565) {682if (src->colorBindSeq > dest->depthBindSeq) {683// Source has newer data than the current buffer, use it.684sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });685}686} else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) {687sources.push_back(CopySource{ src, RASTER_DEPTH, 0, 0 });688} else {689// TODO: Do more detailed overlap checks here.690}691}692693std::sort(sources.begin(), sources.end());694695// TODO: A full copy will overwrite anything else. So we can eliminate696// anything that comes before such a copy.697698// For now, let's just do the last thing, if there are multiple.699700// for (auto &source : sources) {701if (!sources.empty()) {702draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);703704auto &source = sources.back();705if (source.channel == RASTER_DEPTH) {706// Good old depth->depth copy.707BlitFramebufferDepth(source.vfb, dest);708gpuStats.numDepthCopies++;709dest->last_frame_depth_updated = gpuStats.numFlips;710} else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {711VirtualFramebuffer *src = source.vfb;712if (src->fb_format != GE_FORMAT_565) {713WARN_LOG_ONCE(not565, Log::FrameBuf, "fb_format of buffer at %08x not 565 as expected", src->fb_address);714}715716// Really hate to do this, but tracking the depth swizzle state across multiple717// copies is not easy.718Draw2DShader shader = DRAW2D_565_TO_DEPTH;719if (PSP_CoreParameter().compat.flags().DeswizzleDepth) {720shader = DRAW2D_565_TO_DEPTH_DESWIZZLE;721}722723gpuStats.numReinterpretCopies++;724src->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;725dest->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;726727// Copying color to depth.728BlitUsingRaster(729src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,730dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,731false, dest->renderScaleFactor, Get2DPipeline(shader), "565_to_depth");732}733}734735gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);736}737738// Can't easily dynamically create these strings, we just pass along the pointer.739static const char *reinterpretStrings[4][4] = {740{741"self_reinterpret_565",742"reinterpret_565_to_5551",743"reinterpret_565_to_4444",744"reinterpret_565_to_8888",745},746{747"reinterpret_5551_to_565",748"self_reinterpret_5551",749"reinterpret_5551_to_4444",750"reinterpret_5551_to_8888",751},752{753"reinterpret_4444_to_565",754"reinterpret_4444_to_5551",755"self_reinterpret_4444",756"reinterpret_4444_to_8888",757},758{759"reinterpret_8888_to_565",760"reinterpret_8888_to_5551",761"reinterpret_8888_to_4444",762"self_reinterpret_8888",763},764};765766// Call this after the target has been bound for rendering. For color, raster is probably always going to win over blits/copies.767void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dst) {768if (!useBufferedRendering_) {769return;770}771772std::vector<CopySource> sources;773for (auto src : vfbs_) {774// Discard old and equal potential inputs.775if (src == dst || src->colorBindSeq < dst->colorBindSeq) {776continue;777}778779if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) {780// Another render target at the exact same location but gotta be a different format or a different stride, otherwise781// it would be the same, and should have been detected in DoSetRenderFrameBuffer.782if (src->fb_format != dst->fb_format) {783// This will result in reinterpret later, if both formats are 16-bit.784sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });785} else {786// This shouldn't happen anymore. I think when it happened last, we still had787// lax stride checking when video was incoming, and a resize happened causing a duplicate.788}789} else if (src->fb_stride == dst->fb_stride && src->fb_format == dst->fb_format) {790u32 bytesPerPixel = BufferFormatBytesPerPixel(src->fb_format);791792u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest793794u32 srcColorStart = src->fb_address;795u32 srcFirstLineEnd = src->fb_address + strideInBytes;796u32 srcColorEnd = strideInBytes * src->height;797798u32 dstColorStart = dst->fb_address;799u32 dstFirstLineEnd = dst->fb_address + strideInBytes;800u32 dstColorEnd = strideInBytes * dst->height;801802// Initially we'll only allow pure horizontal and vertical overlap,803// to reduce the risk for false positives. We can allow diagonal overlap too if needed804// in the future.805806// Check for potential vertical overlap, like in Juiced 2.807int xOffset = 0;808int yOffset = 0;809810// TODO: Get rid of the compatibility flag check.811if ((dstColorStart - srcColorStart) % strideInBytes == 0812&& PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {813// Buffers are aligned.814yOffset = ((int)dstColorStart - (int)srcColorStart) / strideInBytes;815if (yOffset <= -(int)src->height) {816// Not overlapping817continue;818} else if (yOffset >= dst->height) {819// Not overlapping820continue;821}822} else {823// Buffers not stride-aligned - ignoring for now.824// This is where we'll add the horizontal offset for GoW.825continue;826}827sources.push_back(CopySource{ src, RASTER_COLOR, xOffset, yOffset });828} else if (src->fb_address == dst->fb_address && src->FbStrideInBytes() == dst->FbStrideInBytes()) {829if (src->fb_stride == dst->fb_stride * 2) {830// Reinterpret from 16-bit to 32-bit.831sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });832} else if (src->fb_stride * 2 == dst->fb_stride) {833// Reinterpret from 32-bit to 16-bit.834sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });835} else {836// 16-to-16 reinterpret, should have been caught above already.837_assert_msg_(false, "Reinterpret: Shouldn't get here");838}839}840}841842std::sort(sources.begin(), sources.end());843844draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);845846bool tookActions = false;847848// TODO: Only do the latest one.849for (const CopySource &source : sources) {850VirtualFramebuffer *src = source.vfb;851852// Copy a rectangle from the original to the new buffer.853// Yes, we mean to look at src->width/height for the dest rectangle.854855// TODO: Try to bound the blit using gstate_c.vertBounds like depal does.856857int srcWidth = src->width * src->renderScaleFactor;858int srcHeight = src->height * src->renderScaleFactor;859int dstWidth = src->width * dst->renderScaleFactor;860int dstHeight = src->height * dst->renderScaleFactor;861862int dstX1 = -source.xOffset * dst->renderScaleFactor;863int dstY1 = -source.yOffset * dst->renderScaleFactor;864int dstX2 = dstX1 + dstWidth;865int dstY2 = dstY1 + dstHeight;866867if (source.channel == RASTER_COLOR) {868Draw2DPipeline *pipeline = nullptr;869const char *pass_name = "N/A";870float scaleFactorX = 1.0f;871if (src->fb_format == dst->fb_format) {872gpuStats.numColorCopies++;873pipeline = Get2DPipeline(DRAW2D_COPY_COLOR);874pass_name = "copy_color";875} else {876if (PSP_CoreParameter().compat.flags().BlueToAlpha) {877WARN_LOG_ONCE(bta, Log::FrameBuf, "WARNING: Reinterpret encountered with BlueToAlpha on");878}879880// Reinterpret!881WARN_LOG_N_TIMES(reint, 5, Log::FrameBuf, "Reinterpret detected from %08x_%s to %08x_%s",882src->fb_address, GeBufferFormatToString(src->fb_format),883dst->fb_address, GeBufferFormatToString(dst->fb_format));884885pipeline = GetReinterpretPipeline(src->fb_format, dst->fb_format, &scaleFactorX);886dstX1 *= scaleFactorX;887dstX2 *= scaleFactorX;888889pass_name = reinterpretStrings[(int)src->fb_format][(int)dst->fb_format];890891gpuStats.numReinterpretCopies++;892}893894if (pipeline) {895tookActions = true;896// OK we have the pipeline, now just do the blit.897BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight,898dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, pass_name);899}900901if (scaleFactorX == 1.0f && dst->z_address == src->z_address && dst->z_stride == src->z_stride) {902// We should also copy the depth buffer in this case!903BlitFramebufferDepth(src, dst, true);904}905}906}907908if (currentRenderVfb_ && dst != currentRenderVfb_ && tookActions) {909// Will probably just change the name of the current renderpass, since one was started by the reinterpret itself.910draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "After Reinterpret");911}912913shaderManager_->DirtyLastShader();914textureCache_->ForgetLastTexture();915}916917Draw2DPipeline *FramebufferManagerCommon::GetReinterpretPipeline(GEBufferFormat from, GEBufferFormat to, float *scaleFactorX) {918if (from == to) {919*scaleFactorX = 1.0f;920return Get2DPipeline(DRAW2D_COPY_COLOR);921}922923if (IsBufferFormat16Bit(from) && !IsBufferFormat16Bit(to)) {924// We halve the X coordinates in the destination framebuffer.925// The shader will collect two pixels worth of input data and merge into one.926*scaleFactorX = 0.5f;927} else if (!IsBufferFormat16Bit(from) && IsBufferFormat16Bit(to)) {928// We double the X coordinates in the destination framebuffer.929// The shader will sample and depending on the X coordinate & 1, use the upper or lower bits.930*scaleFactorX = 2.0f;931} else {932*scaleFactorX = 1.0f;933}934935Draw2DPipeline *pipeline = reinterpretFromTo_[(int)from][(int)to];936if (!pipeline) {937pipeline = draw2D_.Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo {938return GenerateReinterpretFragmentShader(shaderWriter, from, to);939});940reinterpretFromTo_[(int)from][(int)to] = pipeline;941}942return pipeline;943}944945void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) {946// Notify the texture cache of both the color and depth buffers.947textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED);948if (v->fbo) {949v->fbo->Release();950v->fbo = nullptr;951}952953// Wipe some pointers954DiscardFramebufferCopy();955if (currentRenderVfb_ == v)956currentRenderVfb_ = nullptr;957if (displayFramebuf_ == v)958displayFramebuf_ = nullptr;959if (prevDisplayFramebuf_ == v)960prevDisplayFramebuf_ = nullptr;961if (prevPrevDisplayFramebuf_ == v)962prevPrevDisplayFramebuf_ = nullptr;963964delete v;965}966967void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst, bool allowSizeMismatch) {968_dbg_assert_(src && dst);969970_dbg_assert_(src != dst);971972// Check that the depth address is even the same before actually blitting.973bool matchingDepthBuffer = src->z_address == dst->z_address && src->z_stride != 0 && dst->z_stride != 0;974bool matchingSize = (src->width == dst->width || (src->width == 512 && dst->width == 480) || (src->width == 480 && dst->width == 512)) && src->height == dst->height;975if (!matchingDepthBuffer || (!matchingSize && !allowSizeMismatch)) {976return;977}978979// Copy depth value from the previously bound framebuffer to the current one.980bool hasNewerDepth = src->last_frame_depth_render != 0 && src->last_frame_depth_render >= dst->last_frame_depth_updated;981if (!src->fbo || !dst->fbo || !useBufferedRendering_ || !hasNewerDepth) {982// If depth wasn't updated, then we're at least "two degrees" away from the data.983// This is an optimization: it probably doesn't need to be copied in this case.984return;985}986987bool useCopy = draw_->GetDeviceCaps().framebufferSeparateDepthCopySupported || (!draw_->GetDeviceCaps().framebufferDepthBlitSupported && draw_->GetDeviceCaps().framebufferCopySupported);988bool useBlit = draw_->GetDeviceCaps().framebufferDepthBlitSupported;989990bool useRaster = draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported && draw_->GetDeviceCaps().textureDepthSupported;991992if (src->fbo->MultiSampleLevel() > 0 && dst->fbo->MultiSampleLevel() > 0) {993// If multisampling, we want to copy depth properly so we get all the samples, to avoid aliased edges.994// Can be seen in the fire in Jeanne D'arc, for example.995if (useRaster && useCopy) {996useRaster = false;997}998}9991000int w = std::min(src->renderWidth, dst->renderWidth);1001int h = std::min(src->renderHeight, dst->renderHeight);10021003// Some GPUs can copy depth but only if stencil gets to come along for the ride. We only want to use this if there is no blit functionality.1004if (useRaster) {1005BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, dst->renderScaleFactor, Get2DPipeline(Draw2DShader::DRAW2D_COPY_DEPTH), "BlitDepthRaster");1006} else if (useCopy) {1007draw_->CopyFramebufferImage(src->fbo, 0, 0, 0, 0, dst->fbo, 0, 0, 0, 0, w, h, 1, Draw::Aspect::DEPTH_BIT, "CopyFramebufferDepth");1008RebindFramebuffer("After BlitFramebufferDepth");1009} else if (useBlit) {1010// We'll accept whether we get a separate depth blit or not...1011draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::Aspect::DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth");1012RebindFramebuffer("After BlitFramebufferDepth");1013}10141015draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);1016}10171018void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) {1019if (!useBufferedRendering_) {1020// Let's ignore rendering to targets that have not (yet) been displayed.1021gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1022} else if (currentRenderVfb_) {1023DownloadFramebufferOnSwitch(currentRenderVfb_);1024}10251026textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);10271028NotifyRenderFramebufferUpdated(vfb);1029}10301031void FramebufferManagerCommon::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb) {1032if (gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) {1033gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1034}1035if (gstate_c.curRTRenderWidth != vfb->renderWidth || gstate_c.curRTRenderHeight != vfb->renderHeight) {1036gstate_c.Dirty(DIRTY_PROJMATRIX);1037gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX);1038}1039}10401041void FramebufferManagerCommon::DownloadFramebufferOnSwitch(VirtualFramebuffer *vfb) {1042if (vfb && vfb->safeWidth > 0 && vfb->safeHeight > 0 && !(vfb->usageFlags & FB_USAGE_FIRST_FRAME_SAVED) && !vfb->memoryUpdated) {1043// Some games will draw to some memory once, and use it as a render-to-texture later.1044// To support this, we save the first frame to memory when we have a safe w/h.1045// Saving each frame would be slow.10461047// TODO: This type of download could be made async, for less stutter on framebuffer creation.1048if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && !PSP_CoreParameter().compat.flags().DisableFirstFrameReadback) {1049ReadFramebufferToMemory(vfb, 0, 0, vfb->safeWidth, vfb->safeHeight, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1050vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1051vfb->safeWidth = 0;1052vfb->safeHeight = 0;1053}1054}1055}10561057bool FramebufferManagerCommon::ShouldDownloadFramebufferColor(const VirtualFramebuffer *vfb) {1058// Dangan Ronpa hack1059return PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000;1060}10611062bool FramebufferManagerCommon::ShouldDownloadFramebufferDepth(const VirtualFramebuffer *vfb) {1063// Download depth buffer if compat flag set (previously used for Syphon Filter lens flares, now used for nothing)1064if (!PSP_CoreParameter().compat.flags().ReadbackDepth || GetSkipGPUReadbackMode() != SkipGPUReadbackMode::NO_SKIP) {1065return false;1066}1067return (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) != 0 && vfb->width >= 480 && vfb->height >= 272;1068}10691070void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) {1071if (prevVfb) {1072if (ShouldDownloadFramebufferColor(prevVfb) && !prevVfb->memoryUpdated) {1073// NOTE: This path is ONLY for the Dangan Ronpa hack, see ShouldDownloadFramebufferColor1074ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RASTER_COLOR, Draw::ReadbackMode::OLD_DATA_OK);1075prevVfb->usageFlags = (prevVfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1076} else {1077DownloadFramebufferOnSwitch(prevVfb);1078}10791080if (ShouldDownloadFramebufferDepth(prevVfb)) {1081ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RasterChannel::RASTER_DEPTH, Draw::ReadbackMode::BLOCK);1082}1083}10841085textureCache_->ForgetLastTexture();1086shaderManager_->DirtyLastShader();10871088if (useBufferedRendering_) {1089if (vfb->fbo) {1090shaderManager_->DirtyLastShader();1091Draw::RPAction depthAction = Draw::RPAction::KEEP;1092float clearDepth = 0.0f;1093if (vfb->usageFlags & FB_USAGE_INVALIDATE_DEPTH) {1094depthAction = Draw::RPAction::CLEAR;1095clearDepth = GetDepthScaleFactors(gstate_c.UseFlags()).Offset();1096vfb->usageFlags &= ~FB_USAGE_INVALIDATE_DEPTH;1097}1098draw_->BindFramebufferAsRenderTarget(vfb->fbo, {Draw::RPAction::KEEP, depthAction, Draw::RPAction::KEEP, 0, clearDepth}, "FBSwitch");1099} else {1100// This should only happen very briefly when toggling useBufferedRendering_.1101ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);1102}1103} else {1104if (vfb->fbo) {1105// This should only happen very briefly when toggling useBufferedRendering_.1106textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_DESTROYED);1107vfb->fbo->Release();1108vfb->fbo = nullptr;1109}11101111// Let's ignore rendering to targets that have not (yet) been displayed.1112if (vfb->usageFlags & FB_USAGE_DISPLAYED_FRAMEBUFFER) {1113gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;1114} else {1115gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1116}1117}1118textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_UPDATED);11191120NotifyRenderFramebufferUpdated(vfb);1121}11221123void FramebufferManagerCommon::PerformWriteFormattedFromMemory(u32 addr, int size, int stride, GEBufferFormat fmt) {1124// Note: UpdateFromMemory() is still called later.1125// This is a special case where we have extra information prior to the invalidation,1126// because it's called from sceJpeg, sceMpeg, scePsmf etc.11271128// TODO: Could possibly be at an offset...1129// Also, stride needs better handling.1130VirtualFramebuffer *vfb = ResolveVFB(addr, stride, fmt);1131if (vfb) {1132// Let's count this as a "render". This will also force us to use the correct format.1133vfb->last_frame_render = gpuStats.numFlips;1134vfb->colorBindSeq = GetBindSeqCount();11351136if (vfb->fb_stride < stride) {1137INFO_LOG(Log::FrameBuf, "Changing stride for %08x from %d to %d", addr, vfb->fb_stride, stride);1138const int bpp = BufferFormatBytesPerPixel(fmt);1139ResizeFramebufFBO(vfb, stride, size / (bpp * stride));1140// Resizing may change the viewport/etc.1141gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1142vfb->fb_stride = stride;1143// This might be a bit wider than necessary, but we'll redetect on next render.1144vfb->width = stride;1145}1146}1147}11481149void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size) {1150// Take off the uncached flag from the address. Not to be confused with the start of VRAM.1151addr &= 0x3FFFFFFF;1152if (Memory::IsVRAMAddress(addr))1153addr &= 0x041FFFFF;1154// TODO: Could go through all FBOs, but probably not important?1155// TODO: Could also check for inner changes, but video is most important.1156// TODO: This shouldn't care if it's a display framebuf or not, should work exactly the same.1157bool isDisplayBuf = addr == CurrentDisplayFramebufAddr() || addr == PrevDisplayFramebufAddr();1158// TODO: Deleting the FBO is a heavy hammer solution, so let's only do it if it'd help.1159if (!Memory::IsValidAddress(displayFramebufPtr_))1160return;11611162for (size_t i = 0; i < vfbs_.size(); ++i) {1163VirtualFramebuffer *vfb = vfbs_[i];1164if (vfb->fb_address == addr) {1165FlushBeforeCopy();11661167if (useBufferedRendering_ && vfb->fbo) {1168GEBufferFormat fmt = vfb->fb_format;1169if (vfb->last_frame_render + 1 < gpuStats.numFlips && isDisplayBuf) {1170// If we're not rendering to it, format may be wrong. Use displayFormat_ instead.1171// TODO: This doesn't seem quite right anymore.1172fmt = displayFormat_;1173}1174DrawPixels(vfb, 0, 0, Memory::GetPointerUnchecked(addr), fmt, vfb->fb_stride, vfb->width, vfb->height, RASTER_COLOR, "UpdateFromMemory_DrawPixels");1175SetColorUpdated(vfb, gstate_c.skipDrawReason);1176} else {1177INFO_LOG(Log::FrameBuf, "Invalidating FBO for %08x (%dx%d %s)", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format));1178DestroyFramebuf(vfb);1179vfbs_.erase(vfbs_.begin() + i--);1180}1181}1182}11831184RebindFramebuffer("RebindFramebuffer - UpdateFromMemory");11851186// TODO: Necessary?1187gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);1188}11891190void FramebufferManagerCommon::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height, RasterChannel channel, const char *tag) {1191textureCache_->ForgetLastTexture();1192shaderManager_->DirtyLastShader();1193float u0 = 0.0f, u1 = 1.0f;1194float v0 = 0.0f, v1 = 1.0f;11951196DrawTextureFlags flags;1197if (useBufferedRendering_ && vfb && vfb->fbo) {1198if (channel == RASTER_DEPTH || PSP_CoreParameter().compat.flags().NearestFilteringOnFramebufferCreate) {1199flags = DRAWTEX_NEAREST;1200} else {1201flags = DRAWTEX_LINEAR;1202}1203draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag);1204SetViewport2D(0, 0, vfb->renderWidth, vfb->renderHeight);1205draw_->SetScissorRect(0, 0, vfb->renderWidth, vfb->renderHeight);1206} else {1207_dbg_assert_(channel == RASTER_COLOR);1208// We are drawing directly to the back buffer so need to flip.1209// Should more of this be handled by the presentation engine?1210if (needBackBufferYSwap_)1211std::swap(v0, v1);1212flags = g_Config.iDisplayFilter == SCALE_LINEAR ? DRAWTEX_LINEAR : DRAWTEX_NEAREST;1213flags = flags | DRAWTEX_TO_BACKBUFFER;1214FRect frame = GetScreenFrame(pixelWidth_, pixelHeight_);1215FRect rc;1216CalculateDisplayOutputRect(&rc, 480.0f, 272.0f, frame, ROTATION_LOCKED_HORIZONTAL);1217SetViewport2D(rc.x, rc.y, rc.w, rc.h);1218draw_->SetScissorRect(0, 0, pixelWidth_, pixelHeight_);1219}12201221if (channel == RASTER_DEPTH) {1222_dbg_assert_(srcPixelFormat == GE_FORMAT_DEPTH16);1223flags = flags | DRAWTEX_DEPTH;1224if (vfb)1225vfb->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;1226}12271228Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, width, height);1229if (pixelsTex) {1230draw_->BindTextures(0, 1, &pixelsTex, Draw::TextureBindFlags::VULKAN_BIND_ARRAY);12311232// TODO: Replace with draw2D_.Blit() directly.1233DrawActiveTexture(dstX, dstY, width, height,1234vfb ? vfb->bufferWidth : g_display.pixel_xres,1235vfb ? vfb->bufferHeight : g_display.pixel_yres,1236u0, v0, u1, v1, ROTATION_LOCKED_HORIZONTAL, flags);12371238draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);12391240gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);1241}1242}12431244bool FramebufferManagerCommon::BindFramebufferAsColorTexture(int stage, VirtualFramebuffer *framebuffer, int flags, int layer) {1245if (!framebuffer->fbo || !useBufferedRendering_) {1246draw_->BindTexture(stage, nullptr);1247gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1248return false;1249}12501251// currentRenderVfb_ will always be set when this is called, except from the GE debugger.1252// Let's just not bother with the copy in that case.1253bool skipCopy = !(flags & BINDFBCOLOR_MAY_COPY);12541255// Currently rendering to this framebuffer. Need to make a copy.1256if (!skipCopy && framebuffer == currentRenderVfb_) {1257// Self-texturing, need a copy currently (some backends can potentially support it though).1258WARN_LOG_ONCE(selfTextureCopy, Log::G3D, "Attempting to texture from current render target (src=%08x / target=%08x / flags=%d), making a copy", framebuffer->fb_address, currentRenderVfb_->fb_address, flags);1259// TODO: Maybe merge with bvfbs_? Not sure if those could be packing, and they're created at a different size.1260if (currentFramebufferCopy_ && (flags & BINDFBCOLOR_UNCACHED) == 0) {1261// We have a copy already that hasn't been invalidated, let's keep using it.1262draw_->BindFramebufferAsTexture(currentFramebufferCopy_, stage, Draw::Aspect::COLOR_BIT, layer);1263return true;1264}12651266Draw::Framebuffer *renderCopy = GetTempFBO(TempFBO::COPY, framebuffer->renderWidth, framebuffer->renderHeight);1267if (renderCopy) {1268VirtualFramebuffer copyInfo = *framebuffer;1269copyInfo.fbo = renderCopy;12701271bool partial = false;1272CopyFramebufferForColorTexture(©Info, framebuffer, flags, layer, &partial);1273RebindFramebuffer("After BindFramebufferAsColorTexture");1274draw_->BindFramebufferAsTexture(renderCopy, stage, Draw::Aspect::COLOR_BIT, layer);12751276// Only cache the copy if it wasn't a partial copy.1277// TODO: Improve on this.1278if (!partial && (flags & BINDFBCOLOR_UNCACHED) == 0) {1279currentFramebufferCopy_ = renderCopy;1280}1281gpuStats.numCopiesForSelfTex++;1282} else {1283// Failed to get temp FBO? Weird.1284draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::Aspect::COLOR_BIT, layer);1285}1286return true;1287} else if (framebuffer != currentRenderVfb_ || (flags & BINDFBCOLOR_FORCE_SELF) != 0) {1288draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::Aspect::COLOR_BIT, layer);1289return true;1290} else {1291// Here it's an error because for some reason skipCopy is true. That shouldn't really happen.1292ERROR_LOG_REPORT_ONCE(selfTextureFail, Log::G3D, "Attempting to texture from target (src=%08x / target=%08x / flags=%d)", framebuffer->fb_address, currentRenderVfb_->fb_address, flags);1293// To do this safely in Vulkan, we need to use input attachments.1294// Actually if the texture region and render regions don't overlap, this is safe, but we need1295// to transition to GENERAL image layout which will take some trickery.1296// Badness on D3D11 to bind the currently rendered-to framebuffer as a texture.1297draw_->BindTexture(stage, nullptr);1298gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1299return false;1300}1301}13021303void FramebufferManagerCommon::CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags, int layer, bool *partial) {1304int x = 0;1305int y = 0;1306int w = src->drawnWidth;1307int h = src->drawnHeight;13081309*partial = false;13101311// If max is not > min, we probably could not detect it. Skip.1312// See the vertex decoder, where this is updated.1313// TODO: We're currently not hitting this path in Dante. See #170321314if ((flags & BINDFBCOLOR_MAY_COPY_WITH_UV) == BINDFBCOLOR_MAY_COPY_WITH_UV && gstate_c.vertBounds.maxU > gstate_c.vertBounds.minU) {1315x = std::max(gstate_c.vertBounds.minU, (u16)0);1316y = std::max(gstate_c.vertBounds.minV, (u16)0);1317w = std::min(gstate_c.vertBounds.maxU, src->drawnWidth) - x;1318h = std::min(gstate_c.vertBounds.maxV, src->drawnHeight) - y;13191320// If we bound a framebuffer, apply the byte offset as pixels to the copy too.1321if (flags & BINDFBCOLOR_APPLY_TEX_OFFSET) {1322x += gstate_c.curTextureXOffset;1323y += gstate_c.curTextureYOffset;1324}13251326// We'll have to reapply these next time since we cropped to UV.1327gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);1328}13291330if (x < src->drawnWidth && y < src->drawnHeight && w > 0 && h > 0) {1331if (x != 0 || y != 0 || w < src->drawnWidth || h < src->drawnHeight) {1332*partial = true;1333}1334BlitFramebuffer(dst, x, y, src, x, y, w, h, 0, RASTER_COLOR, "CopyFBForColorTexture");1335}1336}13371338Draw::Texture *FramebufferManagerCommon::MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) {1339Draw::DataFormat depthFormat = Draw::DataFormat::UNDEFINED;13401341int bpp = BufferFormatBytesPerPixel(srcPixelFormat);1342int srcStrideInBytes = srcStride * bpp;1343int widthInBytes = width * bpp;13441345// Compute hash of contents.1346uint64_t imageHash;1347if (widthInBytes == srcStrideInBytes) {1348imageHash = XXH3_64bits(srcPixels, widthInBytes * height);1349} else {1350XXH3_state_t *hashState = XXH3_createState();1351XXH3_64bits_reset(hashState);1352for (int y = 0; y < height; y++) {1353XXH3_64bits_update(hashState, srcPixels + srcStrideInBytes * y, widthInBytes);1354}1355imageHash = XXH3_64bits_digest(hashState);1356XXH3_freeState(hashState);1357}13581359Draw::DataFormat texFormat = preferredPixelsFormat_;13601361if (srcPixelFormat == GE_FORMAT_DEPTH16) {1362if ((draw_->GetDataFormatSupport(Draw::DataFormat::R16_UNORM) & Draw::FMT_TEXTURE) != 0) {1363texFormat = Draw::DataFormat::R16_UNORM;1364} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R8_UNORM) & Draw::FMT_TEXTURE) != 0) {1365// This could be improved by using specific draw shaders to pack full precision in two channels.1366// However, not really worth the trouble until we find a game that requires it.1367texFormat = Draw::DataFormat::R8_UNORM;1368} else {1369// No usable single channel format. Can't be bothered.1370return nullptr;1371}1372} else if (srcPixelFormat == GE_FORMAT_565) {1373// Check for supported matching formats.1374// This mainly benefits the redundant copies in God of War on low-end platforms.1375if ((draw_->GetDataFormatSupport(Draw::DataFormat::B5G6R5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1376texFormat = Draw::DataFormat::B5G6R5_UNORM_PACK16;1377} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R5G6B5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1378texFormat = Draw::DataFormat::R5G6B5_UNORM_PACK16;1379}1380}13811382// TODO: We can just change the texture format and flip some bits around instead of this.1383// Could share code with the texture cache perhaps.1384auto generateTexture = [&](uint8_t *data, const uint8_t *initData, uint32_t w, uint32_t h, uint32_t d, uint32_t byteStride, uint32_t sliceByteStride) {1385for (int y = 0; y < height; y++) {1386const u16_le *src16 = (const u16_le *)srcPixels + srcStride * y;1387const u32_le *src32 = (const u32_le *)srcPixels + srcStride * y;1388u32 *dst = (u32 *)(data + byteStride * y);1389u16 *dst16 = (u16 *)(data + byteStride * y);1390u8 *dst8 = (u8 *)(data + byteStride * y);1391switch (srcPixelFormat) {1392case GE_FORMAT_565:1393if (texFormat == Draw::DataFormat::B5G6R5_UNORM_PACK16) {1394memcpy(dst16, src16, w * sizeof(uint16_t));1395} else if (texFormat == Draw::DataFormat::R5G6B5_UNORM_PACK16) {1396ConvertRGB565ToBGR565(dst16, src16, width); // Fast!1397} else if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM) {1398ConvertRGB565ToBGRA8888(dst, src16, width);1399} else {1400ConvertRGB565ToRGBA8888(dst, src16, width);1401}1402break;14031404case GE_FORMAT_5551:1405if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1406ConvertRGBA5551ToBGRA8888(dst, src16, width);1407else1408ConvertRGBA5551ToRGBA8888(dst, src16, width);1409break;14101411case GE_FORMAT_4444:1412if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1413ConvertRGBA4444ToBGRA8888(dst, src16, width);1414else1415ConvertRGBA4444ToRGBA8888(dst, src16, width);1416break;14171418case GE_FORMAT_8888:1419if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1420ConvertRGBA8888ToBGRA8888(dst, src32, width);1421// This means use original pointer as-is. May avoid or optimize a copy.1422else if (srcStride == width)1423return false;1424else1425memcpy(dst, src32, width * 4);1426break;14271428case GE_FORMAT_DEPTH16:1429// TODO: Must take the depth range into account, unless it's already 0-1.1430// TODO: Depending on the color buffer format used with this depth buffer, we need1431// to do one of two different swizzle operations. However, for the only use of this so far,1432// the Burnout lens flare trickery, swizzle doesn't matter since it's just a 0, 7fff, 0, 7fff pattern1433// which comes out the same.1434if (texFormat == Draw::DataFormat::R16_UNORM) {1435// We just use this format straight.1436memcpy(dst16, src16, w * 2);1437} else if (texFormat == Draw::DataFormat::R8_UNORM) {1438// We fall back to R8_UNORM. Precision is enough for most cases of depth clearing and initialization we've seen,1439// but hardly ideal.1440for (int i = 0; i < width; i++) {1441dst8[i] = src16[i] >> 8;1442}1443}1444break;14451446case GE_FORMAT_INVALID:1447case GE_FORMAT_CLUT8:1448// Bad1449break;1450}1451}1452return true;1453};14541455int frameNumber = draw_->GetFrameCount();14561457// First look for an exact match (including contents hash) that we can re-use.1458for (auto &iter : drawPixelsCache_) {1459if (iter.contentsHash == imageHash && iter.tex->Width() == width && iter.tex->Height() == height && iter.tex->Format() == texFormat) {1460iter.frameNumber = frameNumber;1461gpuStats.numCachedUploads++;1462return iter.tex;1463}1464}14651466// Then, look for an alternative one that's not been used recently that we can overwrite.1467for (auto &iter : drawPixelsCache_) {1468if (iter.frameNumber >= frameNumber - 3 || iter.tex->Width() != width || iter.tex->Height() != height || iter.tex->Format() != texFormat) {1469continue;1470}14711472// OK, current one seems good, let's use it (and mark it used).1473gpuStats.numUploads++;1474draw_->UpdateTextureLevels(iter.tex, &srcPixels, generateTexture, 1);1475// NOTE: numFlips is no good - this is called every frame when paused sometimes!1476iter.frameNumber = frameNumber;1477// We need to update the hash for future matching.1478iter.contentsHash = imageHash;1479return iter.tex;1480}14811482// Note: For depth, we create an R16_UNORM texture, that'll be just fine for uploading depth through a shader,1483// and likely more efficient.1484Draw::TextureDesc desc{1485Draw::TextureType::LINEAR2D,1486texFormat,1487width,1488height,14891,14901,1491false,1492Draw::TextureSwizzle::DEFAULT,1493"DrawPixels",1494{ (uint8_t *)srcPixels },1495generateTexture,1496};14971498// Hot Shots Golf (#12355) does tons of these in a frame in some situations! So creating textures1499// better be fast. So does God of War, a lot of the time, a bit unclear what it's doing.1500Draw::Texture *tex = draw_->CreateTexture(desc);1501if (!tex) {1502ERROR_LOG(Log::G3D, "Failed to create DrawPixels texture");1503}1504// We don't need to count here, already counted by numUploads by the caller.15051506// INFO_LOG(Log::G3D, "Creating drawPixelsCache texture: %dx%d", tex->Width(), tex->Height());15071508DrawPixelsEntry entry{ tex, imageHash, frameNumber };1509drawPixelsCache_.push_back(entry);1510gpuStats.numUploads++;1511return tex;1512}15131514bool FramebufferManagerCommon::DrawFramebufferToOutput(const u8 *srcPixels, int srcStride, GEBufferFormat srcPixelFormat) {1515textureCache_->ForgetLastTexture();1516shaderManager_->DirtyLastShader();15171518float u0 = 0.0f, u1 = 480.0f / 512.0f;1519float v0 = 0.0f, v1 = 1.0f;1520Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, 512, 272);1521if (!pixelsTex)1522return false;15231524int uvRotation = useBufferedRendering_ ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1525OutputFlags flags = g_Config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1526if (needBackBufferYSwap_) {1527flags |= OutputFlags::BACKBUFFER_FLIPPED;1528}1529// CopyToOutput reverses these, probably to match "up".1530if (GetGPUBackend() == GPUBackend::DIRECT3D11) {1531flags |= OutputFlags::POSITION_FLIPPED;1532}15331534presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1535presentation_->SourceTexture(pixelsTex, 512, 272);1536presentation_->CopyToOutput(flags, uvRotation, u0, v0, u1, v1);15371538// PresentationCommon sets all kinds of state, we can't rely on anything.1539gstate_c.Dirty(DIRTY_ALL);15401541DiscardFramebufferCopy();1542currentRenderVfb_ = nullptr;15431544return true;1545}15461547void FramebufferManagerCommon::SetViewport2D(int x, int y, int w, int h) {1548Draw::Viewport viewport{ (float)x, (float)y, (float)w, (float)h, 0.0f, 1.0f };1549draw_->SetViewport(viewport);1550}15511552void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) {1553DownloadFramebufferOnSwitch(currentRenderVfb_);1554shaderManager_->DirtyLastShader();15551556if (displayFramebufPtr_ == 0) {1557if (GetUIState() != UISTATE_PAUSEMENU) {1558if (Core_IsStepping())1559VERBOSE_LOG(Log::FrameBuf, "Display disabled, displaying only black");1560else1561DEBUG_LOG(Log::FrameBuf, "Display disabled, displaying only black");1562}1563// No framebuffer to display! Clear to black.1564if (useBufferedRendering_) {1565draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput");1566}1567gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1568presentation_->NotifyPresent();1569return;1570}15711572u32 offsetX = 0;1573u32 offsetY = 0;15741575// If it's not really dirty, we're probably frameskipping. Use the last working one.1576u32 fbaddr = reallyDirty ? displayFramebufPtr_ : prevDisplayFramebufPtr_;1577prevDisplayFramebufPtr_ = fbaddr;15781579VirtualFramebuffer *vfb = ResolveVFB(fbaddr, displayStride_, displayFormat_);1580if (!vfb) {1581// Let's search for a framebuf within this range. Note that we also look for1582// "framebuffers" sitting in RAM (created from block transfer or similar) so we only take off the kernel1583// and uncached bits of the address when comparing.1584const u32 addr = fbaddr;1585for (auto v : vfbs_) {1586const u32 v_addr = v->fb_address;1587const u32 v_size = v->BufferByteSize(RASTER_COLOR);15881589if (v->fb_format != displayFormat_ || v->fb_stride != displayStride_) {1590// Displaying a buffer of the wrong format or stride is nonsense, ignore it.1591continue;1592}15931594if (addr >= v_addr && addr < v_addr + v_size) {1595const u32 dstBpp = BufferFormatBytesPerPixel(v->fb_format);1596const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride;1597const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride;1598// We have enough space there for the display, right?1599if (v_offsetX + 480 > (u32)v->fb_stride || v->bufferHeight < v_offsetY + 272) {1600continue;1601}1602// Check for the closest one.1603if (offsetY == 0 || offsetY > v_offsetY) {1604offsetX = v_offsetX;1605offsetY = v_offsetY;1606vfb = v;1607}1608}1609}16101611if (vfb) {1612// Okay, we found one above.1613// Log should be "Displaying from framebuf" but not worth changing the report.1614INFO_LOG(Log::FrameBuf, "Rendering from framebuf with offset %08x -> %08x+%dx%d", addr, vfb->fb_address, offsetX, offsetY);1615}1616}16171618// Reject too-tiny framebuffers to display (Godfather, see issue #16915).1619if (vfb && vfb->height < 64) {1620vfb = nullptr;1621}16221623if (!vfb) {1624if (Memory::IsValidAddress(fbaddr)) {1625// The game is displaying something directly from RAM. In GTA, it's decoded video.1626// If successful, this effectively calls presentation_->NotifyPresent();1627if (!DrawFramebufferToOutput(Memory::GetPointerUnchecked(fbaddr), displayStride_, displayFormat_)) {1628if (useBufferedRendering_) {1629// Bind and clear the backbuffer. This should be the first time during the frame that it's bound.1630draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput_DrawError");1631}1632presentation_->NotifyPresent();1633}1634return;1635} else {1636DEBUG_LOG(Log::FrameBuf, "Found no FBO to display! displayFBPtr = %08x", fbaddr);1637// No framebuffer to display! Clear to black.1638if (useBufferedRendering_) {1639// Bind and clear the backbuffer. This should be the first time during the frame that it's bound.1640draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput_NoFBO");1641} // For non-buffered rendering, every frame is cleared anyway.1642gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1643presentation_->NotifyPresent();1644return;1645}1646}16471648vfb->usageFlags |= FB_USAGE_DISPLAYED_FRAMEBUFFER;1649vfb->last_frame_displayed = gpuStats.numFlips;1650vfb->dirtyAfterDisplay = false;1651vfb->reallyDirtyAfterDisplay = false;16521653if (prevDisplayFramebuf_ != displayFramebuf_) {1654prevPrevDisplayFramebuf_ = prevDisplayFramebuf_;1655}1656if (displayFramebuf_ != vfb) {1657prevDisplayFramebuf_ = displayFramebuf_;1658}1659displayFramebuf_ = vfb;16601661if (vfb->fbo) {1662if (GetUIState() != UISTATE_PAUSEMENU) {1663if (Core_IsStepping())1664VERBOSE_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1665else1666DEBUG_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1667}16681669float u0 = offsetX / (float)vfb->bufferWidth;1670float v0 = offsetY / (float)vfb->bufferHeight;1671float u1 = (480.0f + offsetX) / (float)vfb->bufferWidth;1672float v1 = (272.0f + offsetY) / (float)vfb->bufferHeight;16731674//clip the VR framebuffer to keep the aspect ratio1675if (IsVREnabled() && !IsFlatVRGame() && !IsGameVRScene()) {1676float aspect = 272.0f / 480.0f * (IsImmersiveVRMode() ? 2.0f : 1.0f);1677float clipY = 272.0f * (1.0f - aspect) / 2.0f;1678v0 = (clipY + offsetY) / (float)vfb->bufferHeight;1679v1 = (272.0f - clipY + offsetY) / (float)vfb->bufferHeight;16801681//zoom inside1682float zoom = IsImmersiveVRMode() ? 0.4f : 0.1f;1683u0 += zoom / aspect;1684u1 -= zoom / aspect;1685v0 += zoom;1686v1 -= zoom;1687}16881689textureCache_->ForgetLastTexture();16901691int uvRotation = useBufferedRendering_ ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1692OutputFlags flags = g_Config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1693if (needBackBufferYSwap_) {1694flags |= OutputFlags::BACKBUFFER_FLIPPED;1695}1696// DrawActiveTexture reverses these, probably to match "up".1697if (GetGPUBackend() == GPUBackend::DIRECT3D11) {1698flags |= OutputFlags::POSITION_FLIPPED;1699}17001701int actualWidth = (vfb->bufferWidth * vfb->renderWidth) / vfb->width;1702int actualHeight = (vfb->bufferHeight * vfb->renderHeight) / vfb->height;1703presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1704presentation_->SourceFramebuffer(vfb->fbo, actualWidth, actualHeight);1705presentation_->CopyToOutput(flags, uvRotation, u0, v0, u1, v1);1706} else if (useBufferedRendering_) {1707WARN_LOG(Log::FrameBuf, "Using buffered rendering, and current VFB lacks an FBO: %08x", vfb->fb_address);1708} else {1709// This is OK because here we're in "skip buffered" mode, so even if we haven't presented1710// we will have a render target.1711presentation_->NotifyPresent();1712}17131714// This may get called mid-draw if the game uses an immediate flip.1715// PresentationCommon sets all kinds of state, we can't rely on anything.1716gstate_c.Dirty(DIRTY_ALL);1717DiscardFramebufferCopy();1718currentRenderVfb_ = nullptr;1719}17201721void FramebufferManagerCommon::DecimateFBOs() {1722DiscardFramebufferCopy();1723currentRenderVfb_ = nullptr;17241725for (auto iter : fbosToDelete_) {1726iter->Release();1727}1728fbosToDelete_.clear();17291730for (size_t i = 0; i < vfbs_.size(); ++i) {1731VirtualFramebuffer *vfb = vfbs_[i];1732int age = frameLastFramebufUsed_ - std::max(vfb->last_frame_render, vfb->last_frame_used);17331734if (ShouldDownloadFramebufferColor(vfb) && age == 0 && !vfb->memoryUpdated) {1735ReadFramebufferToMemory(vfb, 0, 0, vfb->width, vfb->height, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1736vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1737}17381739// Let's also "decimate" the usageFlags.1740UpdateFramebufUsage(vfb);17411742if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) {1743if (age > FBO_OLD_AGE) {1744INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%ix%i %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1745DestroyFramebuf(vfb);1746vfbs_.erase(vfbs_.begin() + i--);1747}1748}1749}17501751for (auto it = tempFBOs_.begin(); it != tempFBOs_.end(); ) {1752int age = frameLastFramebufUsed_ - it->second.last_frame_used;1753if (age > FBO_OLD_AGE) {1754it->second.fbo->Release();1755it = tempFBOs_.erase(it);1756} else {1757++it;1758}1759}17601761// Do the same for ReadFramebuffersToMemory's VFBs1762for (size_t i = 0; i < bvfbs_.size(); ++i) {1763VirtualFramebuffer *vfb = bvfbs_[i];1764int age = frameLastFramebufUsed_ - vfb->last_frame_render;1765if (age > FBO_OLD_AGE) {1766INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%dx%d %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1767DestroyFramebuf(vfb);1768bvfbs_.erase(bvfbs_.begin() + i--);1769}1770}17711772// And DrawPixels cached textures.17731774for (auto it = drawPixelsCache_.begin(); it != drawPixelsCache_.end(); ) {1775int age = draw_->GetFrameCount() - it->frameNumber;1776if (age > 10) {1777// INFO_LOG(Log::G3D, "Releasing drawPixelsCache texture: %dx%d", it->tex->Width(), it->tex->Height());1778it->tex->Release();1779it->tex = nullptr;1780it = drawPixelsCache_.erase(it);1781} else {1782++it;1783}1784}1785}17861787// Requires width/height to be set already.1788void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, int h, bool force, bool skipCopy) {1789_dbg_assert_(w > 0);1790_dbg_assert_(h > 0);1791VirtualFramebuffer old = *vfb;17921793int oldWidth = vfb->bufferWidth;1794int oldHeight = vfb->bufferHeight;17951796if (force) {1797vfb->bufferWidth = w;1798vfb->bufferHeight = h;1799} else {1800if (vfb->bufferWidth >= w && vfb->bufferHeight >= h) {1801return;1802}18031804// In case it gets thin and wide, don't resize down either side.1805vfb->bufferWidth = std::max((int)vfb->bufferWidth, w);1806vfb->bufferHeight = std::max((int)vfb->bufferHeight, h);1807}18081809bool force1x = false;1810switch (bloomHack_) {1811case 1:1812force1x = vfb->bufferWidth <= 128 || vfb->bufferHeight <= 64;1813break;1814case 2:1815force1x = vfb->bufferWidth <= 256 || vfb->bufferHeight <= 128;1816break;1817case 3:1818force1x = vfb->bufferWidth < 480 || vfb->bufferWidth > 800 || vfb->bufferHeight < 272; // GOW uses 864x2721819break;1820}18211822if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {1823force1x = false;1824}1825if (PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000) {1826force1x = true;1827}18281829if (force1x && g_Config.iInternalResolution != 1) {1830vfb->renderScaleFactor = 1;1831vfb->renderWidth = vfb->bufferWidth;1832vfb->renderHeight = vfb->bufferHeight;1833} else {1834vfb->renderScaleFactor = renderScaleFactor_;1835vfb->renderWidth = (u16)(vfb->bufferWidth * renderScaleFactor_);1836vfb->renderHeight = (u16)(vfb->bufferHeight * renderScaleFactor_);1837}18381839bool creating = old.bufferWidth == 0;1840if (creating) {1841INFO_LOG(Log::FrameBuf, "Creating %s FBO at %08x/%08x stride=%d %dx%d (force=%d)", GeBufferFormatToString(vfb->fb_format), vfb->fb_address, vfb->z_address, vfb->fb_stride, vfb->bufferWidth, vfb->bufferHeight, (int)force);1842} else {1843INFO_LOG(Log::FrameBuf, "Resizing %s FBO at %08x/%08x stride=%d from %dx%d to %dx%d (force=%d, skipCopy=%d)", GeBufferFormatToString(vfb->fb_format), vfb->fb_address, vfb->z_address, vfb->fb_stride, old.bufferWidth, old.bufferHeight, vfb->bufferWidth, vfb->bufferHeight, (int)force, (int)skipCopy);1844}18451846// During hardware rendering, we always render at full color depth even if the game wouldn't on real hardware.1847// It's not worth the trouble trying to support lower bit-depth rendering, just1848// more cases to test that nobody will ever use.18491850textureCache_->ForgetLastTexture();18511852if (!useBufferedRendering_) {1853if (vfb->fbo) {1854vfb->fbo->Release();1855vfb->fbo = nullptr;1856}1857return;1858}1859if (!old.fbo && vfb->last_frame_failed != 0 && vfb->last_frame_failed - gpuStats.numFlips < 63) {1860// Don't constantly retry FBOs which failed to create.1861return;1862}18631864shaderManager_->DirtyLastShader();1865char tag[128];1866size_t len = FormatFramebufferName(vfb, tag, sizeof(tag));18671868gpuStats.numFBOsCreated++;18691870vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), msaaLevel_, true, tag });1871if (Memory::IsVRAMAddress(vfb->fb_address) && vfb->fb_stride != 0) {1872NotifyMemInfo(MemBlockFlags::ALLOC, vfb->fb_address, vfb->BufferByteSize(RASTER_COLOR), tag, len);1873}1874if (Memory::IsVRAMAddress(vfb->z_address) && vfb->z_stride != 0) {1875char buf[128];1876size_t len = snprintf(buf, sizeof(buf), "Z_%s", tag);1877NotifyMemInfo(MemBlockFlags::ALLOC, vfb->z_address, vfb->z_stride * vfb->height * sizeof(uint16_t), buf, len);1878}1879if (old.fbo) {1880INFO_LOG(Log::FrameBuf, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->fb_format));1881if (vfb->fbo) {1882draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1883if (!skipCopy) {1884BlitFramebuffer(vfb, 0, 0, &old, 0, 0, std::min((u16)oldWidth, std::min(vfb->bufferWidth, vfb->width)), std::min((u16)oldHeight, std::min(vfb->height, vfb->bufferHeight)), 0, RASTER_COLOR, "BlitColor_ResizeFramebufFBO");1885}1886if (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) {1887BlitFramebuffer(vfb, 0, 0, &old, 0, 0, std::min((u16)oldWidth, std::min(vfb->bufferWidth, vfb->width)), std::min((u16)oldHeight, std::min(vfb->height, vfb->bufferHeight)), 0, RASTER_DEPTH, "BlitDepth_ResizeFramebufFBO");1888}1889}1890fbosToDelete_.push_back(old.fbo);1891draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "ResizeFramebufFBO");1892} else {1893draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1894}1895DiscardFramebufferCopy();1896currentRenderVfb_ = vfb;18971898if (!vfb->fbo) {1899ERROR_LOG(Log::FrameBuf, "Error creating FBO during resize! %dx%d", vfb->renderWidth, vfb->renderHeight);1900vfb->last_frame_failed = gpuStats.numFlips;1901}1902}19031904struct CopyCandidate {1905VirtualFramebuffer *vfb = nullptr;1906int y = 0;1907int h = 0;19081909std::string ToString(RasterChannel channel) const {1910return StringFromFormat("%08x %s %dx%d y=%d h=%d", vfb->Address(channel), GeBufferFormatToString(vfb->Format(channel)), vfb->width, vfb->height, y, h);1911}1912};19131914static const CopyCandidate *GetBestCopyCandidate(const TinySet<CopyCandidate, 4> &candidates, uint32_t basePtr, RasterChannel channel) {1915const CopyCandidate *best = nullptr;19161917// Pick the "best" candidate by comparing to the old best using heuristics.1918for (size_t i = 0; i < candidates.size(); i++) {1919const CopyCandidate *candidate = &candidates[i];19201921bool better = !best;1922if (!better) {1923// Heuristics determined from the old algorithm, that we might want to keep:1924// * Lower yOffsets are prioritized.1925// * Bindseq1926better = candidate->y < best->y;1927if (!better) {1928better = candidate->vfb->BindSeq(channel) > best->vfb->BindSeq(channel);1929}1930}19311932if (better) {1933best = candidate;1934}1935}1936return best;1937}19381939// This is called from detected memcopies and framebuffer initialization from VRAM. Not block transfers.1940// Also with specialized flags from some replacement functions. Only those will currently request depth copies!1941// NOTE: This is very tricky because there's no information about color depth here, so we'll have to make guesses1942// about what underlying framebuffer is the most likely to be the relevant ones. For src, we can probably prioritize recent1943// ones. For dst, less clear.1944bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, GPUCopyFlag flags, u32 skipDrawReason) {1945if (size == 0) {1946return false;1947}19481949dst &= 0x3FFFFFFF;1950src &= 0x3FFFFFFF;19511952if (Memory::IsVRAMAddress(dst))1953dst &= 0x041FFFFF;1954if (Memory::IsVRAMAddress(src))1955src &= 0x041FFFFF;19561957// TODO: Merge the below into FindTransferFramebuffer.1958// Or at least this should be like the other ones, gathering possible candidates1959// with the ability to list them out for debugging.19601961bool ignoreDstBuffer = flags & GPUCopyFlag::FORCE_DST_MATCH_MEM;1962bool ignoreSrcBuffer = flags & (GPUCopyFlag::FORCE_SRC_MATCH_MEM | GPUCopyFlag::MEMSET);19631964// TODO: In the future we should probably check both channels. Currently depth is only on request.1965RasterChannel channel = (flags & GPUCopyFlag::DEPTH_REQUESTED) ? RASTER_DEPTH : RASTER_COLOR;19661967TinySet<CopyCandidate, 4> srcCandidates;1968TinySet<CopyCandidate, 4> dstCandidates;19691970// TODO: These two loops should be merged into one utility function, similar to what's done with rectangle copies.19711972// First find candidates for the source.1973// We only look at the color channel for now.1974for (auto vfb : vfbs_) {1975if (vfb->fb_stride == 0 || ignoreSrcBuffer) {1976continue;1977}19781979// We only remove the kernel and uncached bits when comparing.1980const u32 vfb_address = vfb->Address(channel);1981const u32 vfb_size = vfb->BufferByteSize(channel);1982const u32 vfb_byteStride = vfb->BufferByteStride(channel);1983const int vfb_byteWidth = vfb->BufferByteWidth(channel);19841985CopyCandidate srcCandidate;1986srcCandidate.vfb = vfb;19871988// Special path for depth for now.1989if (channel == RASTER_DEPTH) {1990if (src == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {1991srcCandidate.y = 0;1992srcCandidate.h = vfb->height;1993srcCandidates.push_back(srcCandidate);1994}1995continue;1996}19971998if (src >= vfb_address && (src + size <= vfb_address + vfb_size || src == vfb_address)) {1999// Heuristic originally from dest below, but just as valid looking for the source.2000// Fixes a misdetection in Brothers in Arms: D-Day, issue #18512.2001if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {2002// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM2003// that can be displayed from, or another matching buffer with the right format if rendering is going on.2004// If we had scoring here, we should strongly penalize this target instead of ignoring it.2005WARN_LOG_N_TIMES(notify_copy_2x, 5, Log::FrameBuf, "Framebuffer size %08x conspicuously not matching copy size %08x for source in NotifyFramebufferCopy. Ignoring.", size, vfb_size);2006continue;2007}20082009if ((u32)size > vfb_size + 0x1000 && vfb->fb_format != GE_FORMAT_8888 && vfb->last_frame_render < gpuStats.numFlips) {2010// Seems likely we are looking at a potential copy of 32-bit pixels (like video) to an old 16-bit buffer,2011// which is very likely simply the wrong target, so skip it. See issue #17740 where this happens in Naruto Ultimate Ninja Heroes 2.2012// Probably no point to give it a bad score and let it pass to sorting, as we're pretty sure here.2013WARN_LOG_N_TIMES(notify_copy_2x, 5, Log::FrameBuf, "Framebuffer size %08x too small for %08x bytes of data and also 16-bit (%s), and not rendered to this frame. Ignoring.", vfb_size, size, GeBufferFormatToString(vfb->fb_format));2014continue;2015}20162017const u32 offset = src - vfb_address;2018const u32 yOffset = offset / vfb_byteStride;2019if ((offset % vfb_byteStride) == 0 && (size == vfb_byteWidth || (size % vfb_byteStride) == 0)) {2020srcCandidate.y = yOffset;2021srcCandidate.h = size == vfb_byteWidth ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2022} else if ((offset % vfb_byteStride) == 0 && size == vfb->fb_stride) {2023// Valkyrie Profile reads 512 bytes at a time, rather than 2048. So, let's whitelist fb_stride also.2024srcCandidate.y = yOffset;2025srcCandidate.h = 1;2026} else if (yOffset == 0 && (vfb->usageFlags & FB_USAGE_CLUT)) {2027// Okay, last try - it might be a clut.2028srcCandidate.y = yOffset;2029srcCandidate.h = 1;2030} else {2031continue;2032}2033srcCandidates.push_back(srcCandidate);2034}2035}20362037for (auto vfb : vfbs_) {2038if (vfb->fb_stride == 0 || ignoreDstBuffer) {2039continue;2040}20412042// We only remove the kernel and uncached bits when comparing.2043const u32 vfb_address = vfb->Address(channel);2044const u32 vfb_size = vfb->BufferByteSize(channel);2045const u32 vfb_byteStride = vfb->BufferByteStride(channel);2046const int vfb_byteWidth = vfb->BufferByteWidth(channel);20472048// Heuristic to try to prevent potential glitches with video playback.2049if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {2050// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM2051// that can be displayed from, or another matching buffer with the right format if rendering is going on.2052// If we had scoring here, we should strongly penalize this target instead of ignoring it.2053WARN_LOG_N_TIMES(notify_copy_2x, 5, Log::FrameBuf, "Framebuffer size %08x conspicuously not matching copy size %08x for dest in NotifyFramebufferCopy. Ignoring.", size, vfb_size);2054continue;2055}20562057CopyCandidate dstCandidate;2058dstCandidate.vfb = vfb;20592060// Special path for depth for now.2061if (channel == RASTER_DEPTH) {2062// Let's assume exact matches only for simplicity.2063if (dst == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {2064dstCandidate.y = 0;2065dstCandidate.h = vfb->height;2066dstCandidates.push_back(dstCandidate);2067}2068continue;2069}20702071if (!ignoreDstBuffer && dst >= vfb_address && (dst + size <= vfb_address + vfb_size || dst == vfb_address)) {2072const u32 offset = dst - vfb_address;2073const u32 yOffset = offset / vfb_byteStride;2074if ((offset % vfb_byteStride) == 0 && (size <= vfb_byteWidth || (size % vfb_byteStride) == 0)) {2075dstCandidate.y = yOffset;2076dstCandidate.h = (size <= vfb_byteWidth) ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2077dstCandidates.push_back(dstCandidate);2078}2079}2080}20812082// For now fill in these old variables from the candidates to reduce the initial diff.2083VirtualFramebuffer *dstBuffer = nullptr;2084VirtualFramebuffer *srcBuffer = nullptr;2085int srcY;2086int srcH;2087int dstY;2088int dstH;20892090const CopyCandidate *bestSrc = GetBestCopyCandidate(srcCandidates, src, channel);2091if (bestSrc) {2092srcBuffer = bestSrc->vfb;2093srcY = bestSrc->y;2094srcH = bestSrc->h;2095}2096const CopyCandidate *bestDst = GetBestCopyCandidate(dstCandidates, dst, channel);2097if (bestDst) {2098dstBuffer = bestDst->vfb;2099dstY = bestDst->y;2100dstH = bestDst->h;2101}21022103if (srcCandidates.size() > 1) {2104if (Reporting::ShouldLogNTimes("mulblock", 5)) {2105std::string log;2106for (size_t i = 0; i < srcCandidates.size(); i++) {2107log += " - " + srcCandidates[i].ToString(channel);2108if (bestSrc && srcCandidates[i].vfb == bestSrc->vfb) {2109log += " * \n";2110} else {2111log += "\n";2112}2113}2114WARN_LOG(Log::FrameBuf, "Copy: Multiple src vfb candidates for (src: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2115}2116}21172118if (dstCandidates.size() > 1) {2119if (Reporting::ShouldLogNTimes("mulblock", 5)) {2120std::string log;2121for (size_t i = 0; i < dstCandidates.size(); i++) {2122log += " - " + dstCandidates[i].ToString(channel);2123if (bestDst && dstCandidates[i].vfb == bestDst->vfb) {2124log += " * \n";2125} else {2126log += "\n";2127}2128}2129WARN_LOG(Log::FrameBuf, "Copy: Multiple dst vfb candidates for (dst: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2130}2131}21322133if (!useBufferedRendering_) {2134// If we're copying into a recently used display buf, it's probably destined for the screen.2135if (channel == RASTER_DEPTH || srcBuffer || (dstBuffer != displayFramebuf_ && dstBuffer != prevDisplayFramebuf_)) {2136return false;2137}2138}21392140if (!dstBuffer && srcBuffer && channel != RASTER_DEPTH) {2141// Note - if we're here, we're in a memcpy, not a block transfer. Not allowing IntraVRAMBlockTransferAllowCreateFB.2142// Technically, that makes BlockTransferAllowCreateFB a bit of a misnomer.2143bool allowCreateFB = (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB || GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE);2144if (allowCreateFB && !(flags & GPUCopyFlag::DISALLOW_CREATE_VFB)) {2145dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->fb_format);2146dstY = 0;2147}2148}2149if (dstBuffer) {2150dstBuffer->last_frame_used = gpuStats.numFlips;2151if (channel == RASTER_DEPTH && !srcBuffer)2152dstBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;2153}2154if (srcBuffer && channel == RASTER_DEPTH && !dstBuffer)2155srcBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;21562157if (dstBuffer && srcBuffer) {2158if (srcBuffer == dstBuffer) {2159WARN_LOG_ONCE(dstsrccpy, Log::FrameBuf, "Intra-buffer memcpy (not supported) %08x -> %08x (size: %x)", src, dst, size);2160} else {2161WARN_LOG_ONCE(dstnotsrccpy, Log::FrameBuf, "Inter-buffer memcpy %08x -> %08x (size: %x)", src, dst, size);2162// Just do the blit!2163BlitFramebuffer(dstBuffer, 0, dstY, srcBuffer, 0, srcY, srcBuffer->width, srcH, 0, channel, "Blit_InterBufferMemcpy");2164SetColorUpdated(dstBuffer, skipDrawReason);2165RebindFramebuffer("RebindFramebuffer - Inter-buffer memcpy");2166}2167return false;2168} else if (dstBuffer) {2169if (flags & GPUCopyFlag::MEMSET) {2170gpuStats.numClears++;2171}2172WARN_LOG_N_TIMES(btucpy, 5, Log::FrameBuf, "Memcpy fbo upload %08x -> %08x (size: %x)", src, dst, size);2173FlushBeforeCopy();21742175// TODO: Hot Shots Golf makes a lot of these during the "meter", to copy back the image to the screen, it copies line by line.2176// We could collect these in a buffer and flush on the next draw, or something like that, to avoid that. The line copies cause2177// awkward visual artefacts.2178const u8 *srcBase = Memory::GetPointerUnchecked(src);2179GEBufferFormat srcFormat = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : dstBuffer->fb_format;2180int srcStride = channel == RASTER_DEPTH ? dstBuffer->z_stride : dstBuffer->fb_stride;2181DrawPixels(dstBuffer, 0, dstY, srcBase, srcFormat, srcStride, dstBuffer->width, dstH, channel, "MemcpyFboUpload_DrawPixels");2182SetColorUpdated(dstBuffer, skipDrawReason);2183RebindFramebuffer("RebindFramebuffer - Memcpy fbo upload");2184// This is a memcpy, let's still copy just in case.2185return false;2186} else if (srcBuffer) {2187WARN_LOG_N_TIMES(btdcpy, 5, Log::FrameBuf, "Memcpy fbo download %08x -> %08x", src, dst);2188FlushBeforeCopy();2189// TODO: In Hot Shots Golf, check if we can do a readback to a framebuffer here.2190// Again we have the problem though that it's doing a lot of small copies here, one for each line.2191if (srcH == 0 || srcY + srcH > srcBuffer->bufferHeight) {2192WARN_LOG_ONCE(btdcpyheight, Log::FrameBuf, "Memcpy fbo download %08x -> %08x skipped, %d+%d is taller than %d", src, dst, srcY, srcH, srcBuffer->bufferHeight);2193} else if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && (!srcBuffer->memoryUpdated || channel == RASTER_DEPTH)) {2194ReadFramebufferToMemory(srcBuffer, 0, srcY, srcBuffer->width, srcH, channel, Draw::ReadbackMode::BLOCK);2195srcBuffer->usageFlags = (srcBuffer->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2196}2197return false;2198} else {2199return false;2200}2201}22022203std::string BlockTransferRect::ToString() const {2204int bpp = BufferFormatBytesPerPixel(channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : vfb->fb_format);2205return StringFromFormat("%s %08x/%d/%s seq:%d %d,%d %dx%d", RasterChannelToString(channel), vfb->fb_address, vfb->FbStrideInBytes(), GeBufferFormatToString(vfb->fb_format), vfb->colorBindSeq, x_bytes / bpp, y, w_bytes / bpp, h);2206}22072208// This is used when looking for framebuffers for a block transfer.2209// The only known game to block transfer depth buffers is Iron Man, see #16530, so2210// we have a compat flag and pretty limited functionality for that.2211bool FramebufferManagerCommon::FindTransferFramebuffer(u32 basePtr, int stride_pixels, int x_pixels, int y, int w_pixels, int h, int bpp, bool destination, BlockTransferRect *rect) {2212basePtr &= 0x3FFFFFFF;2213if (Memory::IsVRAMAddress(basePtr))2214basePtr &= 0x041FFFFF;2215rect->vfb = nullptr;22162217if (!stride_pixels) {2218WARN_LOG(Log::FrameBuf, "Zero stride in FindTransferFrameBuffer, ignoring");2219return false;2220}22212222const u32 byteStride = stride_pixels * bpp;2223int x_bytes = x_pixels * bpp;2224int w_bytes = w_pixels * bpp;22252226TinySet<BlockTransferRect, 4> candidates;22272228// We work entirely in bytes when we do the matching, because games don't consistently use bpps that match2229// that of their buffers. Then after matching we try to map the copy to the simplest operation that does2230// what we need.22312232// We are only looking at color for now, have not found any block transfers of depth data (although it's plausible).22332234for (auto vfb : vfbs_) {2235BlockTransferRect candidate{ vfb, RASTER_COLOR };22362237// Two cases so far of games depending on depth copies: Iron Man in issue #16530 (buffer->buffer)2238// and also #17878 where a game does ram->buffer to an auto-swizzling (|0x600000) address,2239// to initialize Z with a pre-rendered depth buffer.2240if (vfb->z_address == basePtr && vfb->BufferByteStride(RASTER_DEPTH) == byteStride && PSP_CoreParameter().compat.flags().BlockTransferDepth) {2241WARN_LOG_N_TIMES(z_xfer, 5, Log::FrameBuf, "FindTransferFramebuffer: found matching depth buffer, %08x (dest=%d, bpp=%d)", basePtr, (int)destination, bpp);2242candidate.channel = RASTER_DEPTH;2243candidate.x_bytes = x_pixels * bpp;2244candidate.w_bytes = w_pixels * bpp;2245candidate.y = y;2246candidate.h = h;2247candidates.push_back(candidate);2248continue;2249}22502251const u32 vfb_address = vfb->fb_address;2252const u32 vfb_size = vfb->BufferByteSize(RASTER_COLOR);22532254if (basePtr < vfb_address || basePtr >= vfb_address + vfb_size) {2255continue;2256}22572258const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format);2259const u32 vfb_byteStride = vfb->FbStrideInBytes();2260const u32 vfb_byteWidth = vfb->WidthInBytes();22612262candidate.w_bytes = w_pixels * bpp;2263candidate.h = h;22642265const u32 byteOffset = basePtr - vfb_address;2266const int memXOffset = byteOffset % byteStride;2267const int memYOffset = byteOffset / byteStride;22682269// Some games use mismatching bitdepths. But make sure the stride matches.2270// If it doesn't, generally this means we detected the framebuffer with too large a height.2271// Use bufferHeight in case of buffers that resize up and down often per frame (Valkyrie Profile.)22722273// If it's outside the vfb by a single pixel, we currently disregard it.2274if (memYOffset > vfb->bufferHeight - h) {2275continue;2276}22772278if (byteOffset == vfb->WidthInBytes() && w_bytes < vfb->FbStrideInBytes()) {2279// Looks like we're in a margin texture of the vfb, which is not the vfb itself.2280// Ignore the match.2281continue;2282}22832284if (vfb_byteStride != byteStride) {2285// Grand Knights History occasionally copies with a mismatching stride but a full line at a time.2286// That's why we multiply by height, not width - this copy is a rectangle with the wrong stride but a line with the correct one.2287// Makes it hard to detect the wrong transfers in e.g. God of War.2288if (w_pixels != stride_pixels || (byteStride * h != vfb_byteStride && byteStride * h != vfb_byteWidth)) {2289if (destination) {2290// However, some other games write cluts to framebuffers.2291// Let's catch this and upload. Otherwise reject the match.2292bool match = (vfb->usageFlags & FB_USAGE_CLUT) != 0;2293if (match) {2294candidate.w_bytes = byteStride * h;2295h = 1;2296} else {2297continue;2298}2299} else {2300continue;2301}2302} else {2303// This is the Grand Knights History case.2304candidate.w_bytes = byteStride * h;2305candidate.h = 1;2306}2307} else {2308candidate.w_bytes = w_bytes;2309candidate.h = h;2310}23112312candidate.x_bytes = x_bytes + memXOffset;2313candidate.y = y + memYOffset;2314candidate.vfb = vfb;2315candidates.push_back(candidate);2316}23172318const BlockTransferRect *best = nullptr;2319// Sort candidates by just recency for now, we might add other.2320for (size_t i = 0; i < candidates.size(); i++) {2321const BlockTransferRect *candidate = &candidates[i];23222323bool better = !best;2324if (!better) {2325if (candidate->channel == best->channel) {2326better = candidate->vfb->BindSeq(candidate->channel) > best->vfb->BindSeq(candidate->channel);2327} else {2328// Prefer depth over color if the address match is perfect.2329if (candidate->channel == RASTER_DEPTH && best->channel == RASTER_COLOR && candidate->vfb->z_address == basePtr) {2330better = true;2331}2332}2333}23342335if ((candidate->vfb->usageFlags & FB_USAGE_CLUT) && candidate->x_bytes == 0 && candidate->y == 0 && destination) {2336// Hack to prioritize copies to clut buffers.2337best = candidate;2338break;2339}2340if (better) {2341best = candidate;2342}2343}23442345if (candidates.size() > 1) {2346if (Reporting::ShouldLogNTimes("mulblock", 5)) {2347std::string log;2348for (size_t i = 0; i < candidates.size(); i++) {2349log += " - " + candidates[i].ToString() + "\n";2350}2351WARN_LOG(Log::FrameBuf, "Multiple framebuffer candidates for %08x/%d/%d %d,%d %dx%d (dest = %d):\n%s", basePtr, stride_pixels, bpp, x_pixels, y, w_pixels, h, (int)destination, log.c_str());2352}2353}23542355if (best) {2356*rect = *best;2357return true;2358} else {2359if (Memory::IsVRAMAddress(basePtr) && destination && h >= 128) {2360WARN_LOG_N_TIMES(nocands, 5, Log::FrameBuf, "Didn't find a destination candidate for %08x/%d/%d %d,%d %dx%d", basePtr, stride_pixels, bpp, x_pixels, y, w_pixels, h);2361}2362return false;2363}2364}23652366VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAddress, int width, int height, int stride, GEBufferFormat format) {2367INFO_LOG(Log::FrameBuf, "Creating RAM framebuffer at %08x (%dx%d, stride %d, fb_format %d)", fbAddress, width, height, stride, format);23682369RasterChannel channel = format == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR;23702371// A target for the destination is missing - so just create one!2372// Make sure this one would be found by the algorithm above so we wouldn't2373// create a new one each frame.2374VirtualFramebuffer *vfb = new VirtualFramebuffer{};2375vfb->fbo = nullptr;2376uint32_t mask = Memory::IsVRAMAddress(fbAddress) ? 0x041FFFFF : 0x3FFFFFFF;2377if (format == GE_FORMAT_DEPTH16) {2378vfb->fb_address = 0xFFFFFFFF; // Invalid address2379vfb->fb_stride = 0;2380vfb->z_address = fbAddress; // marks that if anyone tries to render with depth to this framebuffer, it should be dropped and recreated.2381vfb->z_stride = stride;2382vfb->width = width;2383} else {2384vfb->fb_address = fbAddress & mask; // NOTE - not necessarily in VRAM!2385vfb->fb_stride = stride;2386vfb->z_address = 0;2387vfb->z_stride = 0;2388vfb->width = std::max(width, stride);2389}2390vfb->height = height;2391vfb->newWidth = vfb->width;2392vfb->newHeight = vfb->height;2393vfb->lastFrameNewSize = gpuStats.numFlips;2394vfb->renderScaleFactor = renderScaleFactor_;2395vfb->renderWidth = (u16)(vfb->width * renderScaleFactor_);2396vfb->renderHeight = (u16)(vfb->height * renderScaleFactor_);2397vfb->bufferWidth = vfb->width;2398vfb->bufferHeight = vfb->height;2399vfb->fb_format = format == GE_FORMAT_DEPTH16 ? GE_FORMAT_8888 : format;2400vfb->usageFlags = format == GE_FORMAT_DEPTH16 ? FB_USAGE_RENDER_DEPTH : FB_USAGE_RENDER_COLOR;2401if (format != GE_FORMAT_DEPTH16) {2402SetColorUpdated(vfb, 0);2403}2404char name[64];2405snprintf(name, sizeof(name), "%08x_%s_RAM", vfb->Address(channel), RasterChannelToString(channel));2406textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);2407bool createDepthBuffer = format == GE_FORMAT_DEPTH16;2408vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, createDepthBuffer, name });2409vfbs_.push_back(vfb);24102411u32 byteSize = vfb->BufferByteSize(channel);2412if (fbAddress + byteSize > framebufColorRangeEnd_) {2413framebufColorRangeEnd_ = fbAddress + byteSize;2414}24152416return vfb;2417}24182419// 1:1 pixel size buffers, we resize buffers to these before we read them back.2420// TODO: We shouldn't keep whole VirtualFramebuffer structs for these - the fbo and last_frame_render is enough.2421VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFramebuffer *vfb, RasterChannel channel) {2422// For now we'll keep these on the same struct as the ones that can get displayed2423// (and blatantly copy work already done above while at it).2424VirtualFramebuffer *nvfb = nullptr;24252426// We maintain a separate vector of framebuffer objects for blitting.2427for (VirtualFramebuffer *v : bvfbs_) {2428if (v->Address(channel) == vfb->Address(channel) && v->Format(channel) == vfb->Format(channel)) {2429if (v->bufferWidth == vfb->bufferWidth && v->bufferHeight == vfb->bufferHeight) {2430nvfb = v;2431if (channel == RASTER_COLOR) {2432v->fb_stride = vfb->fb_stride;2433} else {2434v->z_stride = vfb->z_stride;2435}2436v->width = vfb->width;2437v->height = vfb->height;2438break;2439}2440}2441}24422443// Create a new fbo if none was found for the size2444if (!nvfb) {2445nvfb = new VirtualFramebuffer{};2446nvfb->fbo = nullptr;2447nvfb->fb_address = channel == RASTER_COLOR ? vfb->fb_address : 0;2448nvfb->fb_stride = channel == RASTER_COLOR ? vfb->fb_stride : 0;2449nvfb->z_address = channel == RASTER_DEPTH ? vfb->z_address : 0;2450nvfb->z_stride = channel == RASTER_DEPTH ? vfb->z_stride : 0;2451nvfb->width = vfb->width;2452nvfb->height = vfb->height;2453nvfb->renderWidth = vfb->bufferWidth;2454nvfb->renderHeight = vfb->bufferHeight;2455nvfb->renderScaleFactor = 1; // For readbacks we resize to the original size, of course.2456nvfb->bufferWidth = vfb->bufferWidth;2457nvfb->bufferHeight = vfb->bufferHeight;2458nvfb->fb_format = vfb->fb_format;2459nvfb->drawnWidth = vfb->drawnWidth;2460nvfb->drawnHeight = vfb->drawnHeight;24612462char name[64];2463snprintf(name, sizeof(name), "download_temp_%08x_%s", vfb->Address(channel), RasterChannelToString(channel));24642465// We always create a color-only framebuffer here - readbacks of depth convert to color while translating the values.2466nvfb->fbo = draw_->CreateFramebuffer({ nvfb->bufferWidth, nvfb->bufferHeight, 1, 1, 0, false, name });2467if (!nvfb->fbo) {2468ERROR_LOG(Log::FrameBuf, "Error creating FBO! %d x %d", nvfb->renderWidth, nvfb->renderHeight);2469delete nvfb;2470return nullptr;2471}2472bvfbs_.push_back(nvfb);2473} else {2474UpdateDownloadTempBuffer(nvfb);2475}24762477nvfb->usageFlags |= FB_USAGE_RENDER_COLOR;2478nvfb->last_frame_render = gpuStats.numFlips;2479nvfb->dirtyAfterDisplay = true;24802481return nvfb;2482}24832484void FramebufferManagerCommon::ApplyClearToMemory(int x1, int y1, int x2, int y2, u32 clearColor) {2485if (currentRenderVfb_) {2486if ((currentRenderVfb_->usageFlags & FB_USAGE_DOWNLOAD_CLEAR) != 0) {2487// Already zeroed in memory.2488return;2489}2490}24912492if (!Memory::IsValidAddress(gstate.getFrameBufAddress())) {2493return;2494}24952496u8 *addr = Memory::GetPointerWriteUnchecked(gstate.getFrameBufAddress());2497const int bpp = BufferFormatBytesPerPixel(gstate_c.framebufFormat);24982499u32 clearBits = clearColor;2500if (bpp == 2) {2501u16 clear16 = 0;2502switch (gstate_c.framebufFormat) {2503case GE_FORMAT_565: clear16 = RGBA8888toRGB565(clearColor); break;2504case GE_FORMAT_5551: clear16 = RGBA8888toRGBA5551(clearColor); break;2505case GE_FORMAT_4444: clear16 = RGBA8888toRGBA4444(clearColor); break;2506default: _dbg_assert_(0); break;2507}2508clearBits = clear16 | (clear16 << 16);2509}25102511const bool singleByteClear = (clearBits >> 16) == (clearBits & 0xFFFF) && (clearBits >> 24) == (clearBits & 0xFF);2512const int stride = gstate.FrameBufStride();2513const int width = x2 - x1;25142515const int byteStride = stride * bpp;2516const int byteWidth = width * bpp;2517for (int y = y1; y < y2; ++y) {2518NotifyMemInfo(MemBlockFlags::WRITE, gstate.getFrameBufAddress() + x1 * bpp + y * byteStride, byteWidth, "FramebufferClear");2519}25202521// Can use memset for simple cases. Often alpha is different and gums up the works.2522if (singleByteClear) {2523addr += x1 * bpp;2524for (int y = y1; y < y2; ++y) {2525memset(addr + y * byteStride, clearBits, byteWidth);2526}2527} else {2528// This will most often be true - rarely is the width not aligned.2529// TODO: We should really use non-temporal stores here to avoid the cache,2530// as it's unlikely that these bytes will be read.2531if ((width & 3) == 0 && (x1 & 3) == 0) {2532u64 val64 = clearBits | ((u64)clearBits << 32);2533int xstride = 8 / bpp;25342535u64 *addr64 = (u64 *)addr;2536const int stride64 = stride / xstride;2537const int x1_64 = x1 / xstride;2538const int x2_64 = x2 / xstride;2539for (int y = y1; y < y2; ++y) {2540for (int x = x1_64; x < x2_64; ++x) {2541addr64[y * stride64 + x] = val64;2542}2543}2544} else if (bpp == 4) {2545u32 *addr32 = (u32 *)addr;2546for (int y = y1; y < y2; ++y) {2547for (int x = x1; x < x2; ++x) {2548addr32[y * stride + x] = clearBits;2549}2550}2551} else if (bpp == 2) {2552u16 *addr16 = (u16 *)addr;2553for (int y = y1; y < y2; ++y) {2554for (int x = x1; x < x2; ++x) {2555addr16[y * stride + x] = (u16)clearBits;2556}2557}2558}2559}25602561if (currentRenderVfb_) {2562// The current content is in memory now, so update the flag.2563if (x1 == 0 && y1 == 0 && x2 >= currentRenderVfb_->width && y2 >= currentRenderVfb_->height) {2564currentRenderVfb_->usageFlags |= FB_USAGE_DOWNLOAD_CLEAR;2565currentRenderVfb_->memoryUpdated = true;2566}2567}2568}25692570bool FramebufferManagerCommon::NotifyBlockTransferBefore(u32 dstBasePtr, int dstStride, int dstX, int dstY, u32 srcBasePtr, int srcStride, int srcX, int srcY, int width, int height, int bpp, u32 skipDrawReason) {2571if (!useBufferedRendering_) {2572return false;2573}25742575// Skip checking if there's no framebuffers in that area. Make a special exception for obvious transfers to depth buffer, see issue #178782576bool dstDepthSwizzle = Memory::IsVRAMAddress(dstBasePtr) && ((dstBasePtr & 0x600000) == 0x600000);25772578if (!dstDepthSwizzle && !MayIntersectFramebufferColor(srcBasePtr) && !MayIntersectFramebufferColor(dstBasePtr)) {2579return false;2580}25812582BlockTransferRect dstRect{};2583BlockTransferRect srcRect{};25842585// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2586bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2587bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);25882589if (srcRect.channel == RASTER_DEPTH) {2590// Ignore the found buffer if it's not 16-bit - we create a new more suitable one instead.2591if (dstRect.channel == RASTER_COLOR && dstRect.vfb->fb_format == GE_FORMAT_8888) {2592dstBuffer = false;2593}2594}25952596if (!srcBuffer && dstBuffer && dstRect.channel == RASTER_DEPTH) {2597dstBuffer = true;2598}25992600if (srcBuffer && !dstBuffer) {2601// In here, we can't read from dstRect.2602if (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB ||2603GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE ||2604(PSP_CoreParameter().compat.flags().IntraVRAMBlockTransferAllowCreateFB &&2605Memory::IsVRAMAddress(srcRect.vfb->fb_address) && Memory::IsVRAMAddress(dstBasePtr))) {2606GEBufferFormat ramFormat;2607// Try to guess the appropriate format. We only know the bpp from the block transfer command (16 or 32 bit).2608if (srcRect.channel == RASTER_COLOR) {2609if (bpp == 4) {2610// Only one possibility unless it's doing split pixel tricks (which we could detect through stride maybe).2611ramFormat = GE_FORMAT_8888;2612} else if (srcRect.vfb->fb_format != GE_FORMAT_8888) {2613// We guess that the game will interpret the data the same as it was in the source of the copy.2614// Seems like a likely good guess, and works in Test Drive Unlimited.2615ramFormat = srcRect.vfb->fb_format;2616} else {2617// No info left - just fall back to something. But this is definitely split pixel tricks.2618ramFormat = GE_FORMAT_5551;2619}2620dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, ramFormat);2621} else {2622dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, GE_FORMAT_DEPTH16);2623dstRect.x_bytes = 0;2624dstRect.w_bytes = 2 * width;2625dstRect.y = 0;2626dstRect.h = height;2627dstRect.channel = RASTER_DEPTH;2628}2629dstBuffer = true;2630}2631}26322633if (dstBuffer) {2634dstRect.vfb->last_frame_used = gpuStats.numFlips;2635// Mark the destination as fresh.2636if (dstRect.channel == RASTER_COLOR) {2637dstRect.vfb->colorBindSeq = GetBindSeqCount();2638} else {2639dstRect.vfb->depthBindSeq = GetBindSeqCount();2640}2641}26422643if (dstBuffer && srcBuffer) {2644if (srcRect.vfb && srcRect.vfb == dstRect.vfb && srcRect.channel == dstRect.channel) {2645// Transfer within the same buffer.2646// This is a simple case because there will be no format conversion or similar shenanigans needed.2647// However, the BPP might still mismatch, but in such a case we can convert the coordinates.2648if (srcX == dstX && srcY == dstY) {2649// Ignore, nothing to do. Tales of Phantasia X does this by accident.2650// Returning true to also skip the memory copy.2651return true;2652}26532654int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));26552656if (bpp != buffer_bpp) {2657WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in intra-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2658// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2659bpp = buffer_bpp;2660}26612662WARN_LOG_N_TIMES(dstsrc, 5, Log::G3D, "Intra-buffer block transfer %dx%d %dbpp from %08x (x:%d y:%d stride:%d) -> %08x (x:%d y:%d stride:%d)",2663width, height, bpp,2664srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2665dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2666FlushBeforeCopy();2667// Some backends can handle blitting within a framebuffer. Others will just have to deal with it or ignore it, apparently.2668BlitFramebuffer(dstRect.vfb, dstX, dstY, srcRect.vfb, srcX, srcY, dstRect.w_bytes / bpp, dstRect.h, bpp, dstRect.channel, "Blit_IntraBufferBlockTransfer");2669RebindFramebuffer("rebind after intra block transfer");2670SetColorUpdated(dstRect.vfb, skipDrawReason);2671return true; // Skip the memory copy.2672}26732674// Straightforward blit between two same-format framebuffers.2675if (srcRect.vfb && srcRect.channel == dstRect.channel && srcRect.vfb->Format(srcRect.channel) == dstRect.vfb->Format(dstRect.channel)) {2676WARN_LOG_N_TIMES(dstnotsrc, 5, Log::G3D, "Inter-buffer %s block transfer %dx%d %dbpp from %08x (x:%d y:%d stride:%d %s) -> %08x (x:%d y:%d stride:%d %s)",2677RasterChannelToString(srcRect.channel),2678width, height, bpp,2679srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride, GeBufferFormatToString(srcRect.vfb->fb_format),2680dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride, GeBufferFormatToString(dstRect.vfb->fb_format));26812682// Straight blit will do, but check the bpp, we might need to convert coordinates differently.2683int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));2684if (bpp != buffer_bpp) {2685WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in inter-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2686// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2687bpp = buffer_bpp;2688}2689FlushBeforeCopy();2690BlitFramebuffer(dstRect.vfb, dstRect.x_bytes / bpp, dstRect.y, srcRect.vfb, srcRect.x_bytes / bpp, srcRect.y, srcRect.w_bytes / bpp, height, bpp, srcRect.channel, "Blit_InterBufferBlockTransfer");2691RebindFramebuffer("RebindFramebuffer - Inter-buffer block transfer");2692SetColorUpdated(dstRect.vfb, skipDrawReason);2693return true;2694}26952696// Getting to the more complex cases. Have not actually seen much of these yet.2697WARN_LOG_N_TIMES(blockformat, 5, Log::G3D, "Mismatched buffer formats in block transfer: %s->%s (%dx%d)",2698GeBufferFormatToString(srcRect.vfb->Format(srcRect.channel)), GeBufferFormatToString(dstRect.vfb->Format(dstRect.channel)),2699width, height);27002701// TODO27022703// No need to actually do the memory copy behind, probably.2704return true;27052706} else if (dstBuffer) {2707// Handle depth uploads directly here, and let's not bother copying the data. This is compat-flag-gated for now,2708// may generalize it when I remove the compat flag.2709if (dstRect.channel == RASTER_DEPTH) {2710WARN_LOG_ONCE(btud, Log::G3D, "Block transfer upload %08x -> %08x (%dx%d %d,%d bpp=%d %s)", srcBasePtr, dstBasePtr, width, height, dstX, dstY, bpp, RasterChannelToString(dstRect.channel));2711FlushBeforeCopy();2712const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;2713DrawPixels(dstRect.vfb, dstX, dstY, srcBase, dstRect.vfb->Format(dstRect.channel), srcStride * bpp / 2, (int)(dstRect.w_bytes / 2), dstRect.h, dstRect.channel, "BlockTransferCopy_DrawPixelsDepth");2714RebindFramebuffer("RebindFramebuffer - UploadDepth");2715return true;2716}27172718// Here we should just draw the pixels into the buffer. Return false to copy the memory first.2719// NotifyBlockTransferAfter will take care of the rest.2720return false;2721} else if (srcBuffer) {2722if (width == 48 && height == 48 && srcY == 224 && srcX == 432 && PSP_CoreParameter().compat.flags().TacticsOgreEliminateDebugReadback) {2723return false;2724}27252726WARN_LOG_N_TIMES(btd, 10, Log::G3D, "Block transfer readback %dx%d %dbpp from %08x (x:%d y:%d stride:%d) -> %08x (x:%d y:%d stride:%d)",2727width, height, bpp,2728srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2729dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2730FlushBeforeCopy();2731if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && !srcRect.vfb->memoryUpdated) {2732const int srcBpp = BufferFormatBytesPerPixel(srcRect.vfb->fb_format);2733const float srcXFactor = (float)bpp / srcBpp;2734const bool tooTall = srcY + srcRect.h > srcRect.vfb->bufferHeight;2735if (srcRect.h <= 0 || (tooTall && srcY != 0)) {2736WARN_LOG_ONCE(btdheight, Log::G3D, "Block transfer download %08x -> %08x skipped, %d+%d is taller than %d", srcBasePtr, dstBasePtr, srcRect.y, srcRect.h, srcRect.vfb->bufferHeight);2737} else {2738if (tooTall) {2739WARN_LOG_ONCE(btdheight, Log::G3D, "Block transfer download %08x -> %08x dangerous, %d+%d is taller than %d", srcBasePtr, dstBasePtr, srcRect.y, srcRect.h, srcRect.vfb->bufferHeight);2740}2741ReadFramebufferToMemory(srcRect.vfb, static_cast<int>(srcX * srcXFactor), srcY, static_cast<int>(srcRect.w_bytes * srcXFactor), srcRect.h, RASTER_COLOR, Draw::ReadbackMode::BLOCK);2742srcRect.vfb->usageFlags = (srcRect.vfb->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2743}2744}2745return false; // Let the bit copy happen2746} else {2747return false;2748}2749}27502751SkipGPUReadbackMode FramebufferManagerCommon::GetSkipGPUReadbackMode() {2752if (PSP_CoreParameter().compat.flags().ForceEnableGPUReadback) {2753return SkipGPUReadbackMode::NO_SKIP;2754} else {2755return (SkipGPUReadbackMode)g_Config.iSkipGPUReadbackMode;2756}2757}27582759void FramebufferManagerCommon::NotifyBlockTransferAfter(u32 dstBasePtr, int dstStride, int dstX, int dstY, u32 srcBasePtr, int srcStride, int srcX, int srcY, int width, int height, int bpp, u32 skipDrawReason) {2760// If it's a block transfer direct to the screen, and we're not using buffers, draw immediately.2761// We may still do a partial block draw below if this doesn't pass.2762if (!useBufferedRendering_ && dstStride >= 480 && width >= 480 && height == 272) {2763bool isPrevDisplayBuffer = PrevDisplayFramebufAddr() == dstBasePtr;2764bool isDisplayBuffer = CurrentDisplayFramebufAddr() == dstBasePtr;2765if (isPrevDisplayBuffer || isDisplayBuffer) {2766FlushBeforeCopy();2767DrawFramebufferToOutput(Memory::GetPointerUnchecked(dstBasePtr), dstStride, displayFormat_);2768return;2769}2770}27712772if (MayIntersectFramebufferColor(srcBasePtr) || MayIntersectFramebufferColor(dstBasePtr)) {2773// TODO: Figure out how we can avoid repeating the search here.27742775BlockTransferRect dstRect{};2776BlockTransferRect srcRect{};27772778// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2779bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2780bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);27812782// A few games use this INSTEAD of actually drawing the video image to the screen, they just blast it to2783// the backbuffer. Detect this and have the framebuffermanager draw the pixels.2784if ((!useBufferedRendering_ && currentRenderVfb_ != dstRect.vfb) || dstRect.vfb == nullptr) {2785return;2786}27872788if (dstBuffer && !srcBuffer) {2789WARN_LOG_ONCE(btu, Log::G3D, "Block transfer upload %08x -> %08x (%dx%d %d,%d bpp=%d)", srcBasePtr, dstBasePtr, width, height, dstX, dstY, bpp);2790FlushBeforeCopy();2791const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;27922793int dstBpp = BufferFormatBytesPerPixel(dstRect.vfb->fb_format);2794float dstXFactor = (float)bpp / dstBpp;2795if (dstRect.w_bytes / bpp > dstRect.vfb->width || dstRect.h > dstRect.vfb->height) {2796// The buffer isn't big enough, and we have a clear hint of size. Resize.2797// This happens in Valkyrie Profile when uploading video at the ending.2798// Also happens to the CLUT framebuffer in the Burnout Dominator lens flare effect. See #160752799ResizeFramebufFBO(dstRect.vfb, dstRect.w_bytes / bpp, dstRect.h, false, true);2800// Make sure we don't flop back and forth.2801dstRect.vfb->newWidth = std::max(dstRect.w_bytes / bpp, (int)dstRect.vfb->width);2802dstRect.vfb->newHeight = std::max(dstRect.h, (int)dstRect.vfb->height);2803dstRect.vfb->lastFrameNewSize = gpuStats.numFlips;2804// Resizing may change the viewport/etc.2805gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);2806}2807DrawPixels(dstRect.vfb, static_cast<int>(dstX * dstXFactor), dstY, srcBase, dstRect.vfb->fb_format, static_cast<int>(srcStride * dstXFactor), static_cast<int>(dstRect.w_bytes / bpp * dstXFactor), dstRect.h, RASTER_COLOR, "BlockTransferCopy_DrawPixels");2808SetColorUpdated(dstRect.vfb, skipDrawReason);2809RebindFramebuffer("RebindFramebuffer - NotifyBlockTransferAfter");2810}2811}2812}28132814void FramebufferManagerCommon::SetSafeSize(u16 w, u16 h) {2815VirtualFramebuffer *vfb = currentRenderVfb_;2816if (vfb) {2817vfb->safeWidth = std::min(vfb->bufferWidth, std::max(vfb->safeWidth, w));2818vfb->safeHeight = std::min(vfb->bufferHeight, std::max(vfb->safeHeight, h));2819}2820}28212822void FramebufferManagerCommon::NotifyDisplayResized() {2823pixelWidth_ = PSP_CoreParameter().pixelWidth;2824pixelHeight_ = PSP_CoreParameter().pixelHeight;2825presentation_->UpdateDisplaySize(pixelWidth_, pixelHeight_);28262827INFO_LOG(Log::G3D, "FramebufferManagerCommon::NotifyDisplayResized: %dx%d", pixelWidth_, pixelHeight_);28282829// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2830// So we need to defer the post processing initialization.2831updatePostShaders_ = true;2832}28332834void FramebufferManagerCommon::NotifyRenderResized(int msaaLevel) {2835gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;28362837int w, h, scaleFactor;2838presentation_->CalculateRenderResolution(&w, &h, &scaleFactor, &postShaderIsUpscalingFilter_, &postShaderIsSupersampling_);2839PSP_CoreParameter().renderWidth = w;2840PSP_CoreParameter().renderHeight = h;2841PSP_CoreParameter().renderScaleFactor = scaleFactor;28422843if (UpdateRenderSize(msaaLevel)) {2844draw_->StopThreads();2845DestroyAllFBOs();2846draw_->StartThreads();2847}28482849// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2850// So we need to defer the post processing initialization.2851updatePostShaders_ = true;2852}28532854void FramebufferManagerCommon::NotifyConfigChanged() {2855updatePostShaders_ = true;2856}28572858void FramebufferManagerCommon::DestroyAllFBOs() {2859DiscardFramebufferCopy();2860currentRenderVfb_ = nullptr;2861displayFramebuf_ = nullptr;2862prevDisplayFramebuf_ = nullptr;2863prevPrevDisplayFramebuf_ = nullptr;28642865for (VirtualFramebuffer *vfb : vfbs_) {2866INFO_LOG(Log::FrameBuf, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format);2867DestroyFramebuf(vfb);2868}2869vfbs_.clear();28702871for (VirtualFramebuffer *vfb : bvfbs_) {2872DestroyFramebuf(vfb);2873}2874bvfbs_.clear();28752876for (auto &tempFB : tempFBOs_) {2877tempFB.second.fbo->Release();2878}2879tempFBOs_.clear();28802881for (auto &iter : fbosToDelete_) {2882iter->Release();2883}2884fbosToDelete_.clear();28852886for (auto &iter : drawPixelsCache_) {2887iter.tex->Release();2888}2889drawPixelsCache_.clear();2890}28912892static const char *TempFBOReasonToString(TempFBO reason) {2893switch (reason) {2894case TempFBO::DEPAL: return "depal";2895case TempFBO::BLIT: return "blit";2896case TempFBO::COPY: return "copy";2897case TempFBO::STENCIL: return "stencil";2898default: break;2899}2900return "";2901}29022903Draw::Framebuffer *FramebufferManagerCommon::GetTempFBO(TempFBO reason, u16 w, u16 h) {2904u64 key = ((u64)reason << 48) | ((u32)w << 16) | h;2905auto it = tempFBOs_.find(key);2906if (it != tempFBOs_.end()) {2907it->second.last_frame_used = gpuStats.numFlips;2908return it->second.fbo;2909}29102911bool z_stencil = reason == TempFBO::STENCIL;2912char name[128];2913snprintf(name, sizeof(name), "tempfbo_%s_%dx%d", TempFBOReasonToString(reason), w / renderScaleFactor_, h / renderScaleFactor_);29142915Draw::Framebuffer *fbo = draw_->CreateFramebuffer({ w, h, 1, GetFramebufferLayers(), 0, z_stencil, name });2916if (!fbo) {2917return nullptr;2918}29192920const TempFBOInfo info = { fbo, gpuStats.numFlips };2921tempFBOs_[key] = info;2922return fbo;2923}29242925void FramebufferManagerCommon::UpdateFramebufUsage(VirtualFramebuffer *vfb) const {2926auto checkFlag = [&](u16 flag, int last_frame) {2927if (vfb->usageFlags & flag) {2928const int age = frameLastFramebufUsed_ - last_frame;2929if (age > FBO_OLD_USAGE_FLAG) {2930vfb->usageFlags &= ~flag;2931}2932}2933};29342935checkFlag(FB_USAGE_DISPLAYED_FRAMEBUFFER, vfb->last_frame_displayed);2936checkFlag(FB_USAGE_TEXTURE, vfb->last_frame_used);2937checkFlag(FB_USAGE_RENDER_COLOR, vfb->last_frame_render);2938checkFlag(FB_USAGE_CLUT, vfb->last_frame_clut);2939}29402941void FramebufferManagerCommon::ClearAllDepthBuffers() {2942for (auto vfb : vfbs_) {2943vfb->usageFlags |= FB_USAGE_INVALIDATE_DEPTH;2944}2945}29462947// We might also want to implement an asynchronous callback-style version of this. Would probably2948// only be possible to implement optimally on Vulkan, but on GL and D3D11 we could do pixel buffers2949// and read on the next frame, then call the callback.2950//2951// The main use cases for this are:2952// * GE debugging(in practice async will not matter because it will stall anyway.)2953// * Video file recording(would probably be great if it was async.)2954// * Screenshots(benefit slightly from async.)2955// * Save state screenshots(could probably be async but need to manage the stall.)2956bool FramebufferManagerCommon::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer, int maxScaleFactor) {2957VirtualFramebuffer *vfb = currentRenderVfb_;2958if (!vfb || vfb->fb_address != fb_address) {2959vfb = ResolveVFB(fb_address, fb_stride, format);2960}29612962if (!vfb) {2963if (!Memory::IsValidAddress(fb_address))2964return false;2965// If there's no vfb and we're drawing there, must be memory?2966buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(fb_address), fb_stride, 512, format);2967return true;2968}29692970int w = vfb->renderWidth, h = vfb->renderHeight;29712972Draw::Framebuffer *bound = nullptr;29732974if (vfb->fbo) {2975if (maxScaleFactor > 0 && vfb->renderWidth > vfb->width * maxScaleFactor) {2976w = vfb->width * maxScaleFactor;2977h = vfb->height * maxScaleFactor;29782979Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::COPY, w, h);2980VirtualFramebuffer tempVfb = *vfb;2981tempVfb.fbo = tempFBO;2982tempVfb.bufferWidth = vfb->width;2983tempVfb.bufferHeight = vfb->height;2984tempVfb.renderWidth = w;2985tempVfb.renderHeight = h;2986tempVfb.renderScaleFactor = maxScaleFactor;2987BlitFramebuffer(&tempVfb, 0, 0, vfb, 0, 0, vfb->width, vfb->height, 0, RASTER_COLOR, "Blit_GetFramebuffer");29882989bound = tempFBO;2990} else {2991bound = vfb->fbo;2992}2993}29942995if (!useBufferedRendering_) {2996// Safety check.2997w = std::min(w, PSP_CoreParameter().pixelWidth);2998h = std::min(h, PSP_CoreParameter().pixelHeight);2999}30003001// TODO: Maybe should handle flipY inside CopyFramebufferToMemorySync somehow?3002bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3003buffer.Allocate(w, h, GE_FORMAT_8888, flipY);3004bool retval = draw_->CopyFramebufferToMemory(bound, Draw::Aspect::COLOR_BIT, 0, 0, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetFramebuffer");30053006// Don't need to increment gpu stats for readback count here, this is a debugger-only function.30073008// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3009gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3010// We may have blitted to a temp FBO.3011RebindFramebuffer("RebindFramebuffer - GetFramebuffer");3012return retval;3013}30143015bool FramebufferManagerCommon::GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer) {3016VirtualFramebuffer *vfb = currentRenderVfb_;3017if (!vfb) {3018vfb = GetVFBAt(fb_address);3019}30203021if (!vfb) {3022if (!Memory::IsValidAddress(z_address))3023return false;3024// If there's no vfb and we're drawing there, must be memory?3025buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(z_address), z_stride, 512, GPU_DBG_FORMAT_16BIT);3026return true;3027}30283029int w = vfb->renderWidth;3030int h = vfb->renderHeight;3031if (!useBufferedRendering_) {3032// Safety check.3033w = std::min(w, PSP_CoreParameter().pixelWidth);3034h = std::min(h, PSP_CoreParameter().pixelHeight);3035}30363037bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;30383039// Old code3040if (gstate_c.Use(GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT)) {3041buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT_DIV_256, flipY);3042} else {3043buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT, flipY);3044}3045// No need to free on failure, that's the caller's job (it likely will reuse a buffer.)3046bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::DEPTH_BIT, 0, 0, w, h, Draw::DataFormat::D32F, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetDepthBuffer");3047if (!retval) {3048// Try ReadbackDepthbufferSync, in case GLES.3049buffer.Allocate(w, h, GPU_DBG_FORMAT_16BIT, flipY);3050retval = ReadbackDepthbuffer(vfb->fbo, 0, 0, w, h, (uint16_t *)buffer.GetData(), w, w, h, Draw::ReadbackMode::BLOCK);3051}30523053// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3054gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3055// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3056RebindFramebuffer("RebindFramebuffer - GetDepthbuffer");3057return retval;3058}30593060bool FramebufferManagerCommon::GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer) {3061VirtualFramebuffer *vfb = currentRenderVfb_;3062if (!vfb) {3063vfb = GetVFBAt(fb_address);3064}30653066if (!vfb) {3067if (!Memory::IsValidAddress(fb_address))3068return false;3069// If there's no vfb and we're drawing there, must be memory?3070// TODO: Actually get the stencil.3071buffer = GPUDebugBuffer(Memory::GetPointerWrite(fb_address), fb_stride, 512, GPU_DBG_FORMAT_8888);3072return true;3073}30743075int w = vfb->renderWidth;3076int h = vfb->renderHeight;3077if (!useBufferedRendering_) {3078// Safety check.3079w = std::min(w, PSP_CoreParameter().pixelWidth);3080h = std::min(h, PSP_CoreParameter().pixelHeight);3081}30823083bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3084// No need to free on failure, the caller/destructor will do that. Usually this is a reused buffer, anyway.3085buffer.Allocate(w, h, GPU_DBG_FORMAT_8BIT, flipY);3086bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::STENCIL_BIT, 0, 0, w,h, Draw::DataFormat::S8, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetStencilbuffer");3087if (!retval) {3088retval = ReadbackStencilbuffer(vfb->fbo, 0, 0, w, h, buffer.GetData(), w, Draw::ReadbackMode::BLOCK);3089}3090// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3091RebindFramebuffer("RebindFramebuffer - GetStencilbuffer");3092return retval;3093}30943095bool GetOutputFramebuffer(Draw::DrawContext *draw, GPUDebugBuffer &buffer) {3096int w, h;3097draw->GetFramebufferDimensions(nullptr, &w, &h);3098Draw::DataFormat fmt = draw->PreferredFramebufferReadbackFormat(nullptr);3099// Ignore preferred formats other than BGRA.3100if (fmt != Draw::DataFormat::B8G8R8A8_UNORM)3101fmt = Draw::DataFormat::R8G8B8A8_UNORM;31023103bool flipped = g_Config.iGPUBackend == (int)GPUBackend::OPENGL;31043105buffer.Allocate(w, h, fmt == Draw::DataFormat::R8G8B8A8_UNORM ? GPU_DBG_FORMAT_8888 : GPU_DBG_FORMAT_8888_BGRA, flipped);3106return draw->CopyFramebufferToMemory(nullptr, Draw::Aspect::COLOR_BIT, 0, 0, w, h, fmt, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetOutputFramebuffer");3107}31083109bool FramebufferManagerCommon::GetOutputFramebuffer(GPUDebugBuffer &buffer) {3110bool retval = ::GetOutputFramebuffer(draw_, buffer);3111// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3112RebindFramebuffer("RebindFramebuffer - GetOutputFramebuffer");3113return retval;3114}31153116// This reads a channel of a framebuffer into emulated PSP VRAM, taking care of scaling down as needed.3117//3118// Color conversion is currently done on CPU but should theoretically be done on GPU.3119// (Except using the GPU might cause problems because of various implementations'3120// dithering behavior and games that expect exact colors like Danganronpa, so we3121// can't entirely be rid of the CPU path.) -- unknown3122void FramebufferManagerCommon::ReadbackFramebuffer(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3123if (w <= 0 || h <= 0) {3124ERROR_LOG(Log::FrameBuf, "Bad inputs to ReadbackFramebufferSync: %d %d %d %d", x, y, w, h);3125return;3126}31273128// Note that ReadbackDepthBufferSync can stretch on its own while converting data format, so we don't need to downscale in that case.3129if (vfb->renderScaleFactor == 1 || channel == RASTER_DEPTH) {3130// No need to stretch-blit3131} else {3132VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb, channel);3133if (nvfb) {3134BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0, channel, "Blit_ReadFramebufferToMemory");3135vfb = nvfb;3136}3137}31383139const u32 fb_address = channel == RASTER_COLOR ? vfb->fb_address : vfb->z_address;31403141Draw::DataFormat destFormat = channel == RASTER_COLOR ? GEFormatToThin3D(vfb->fb_format) : GEFormatToThin3D(GE_FORMAT_DEPTH16);3142const int dstBpp = (int)DataFormatSizeInBytes(destFormat);31433144int stride = channel == RASTER_COLOR ? vfb->fb_stride : vfb->z_stride;31453146const int dstByteOffset = (y * stride + x) * dstBpp;3147// Leave the gap between the end of the last line and the full stride.3148// This is only used for the NotifyMemInfo range.3149const int dstSize = ((h - 1) * stride + w) * dstBpp;31503151if (!Memory::IsValidRange(fb_address + dstByteOffset, dstSize)) {3152ERROR_LOG_REPORT(Log::G3D, "ReadbackFramebufferSync would write outside of memory, ignoring");3153return;3154}31553156u8 *destPtr = Memory::GetPointerWriteUnchecked(fb_address + dstByteOffset);31573158// We always need to convert from the framebuffer native format.3159// Right now that's always 8888.3160DEBUG_LOG(Log::FrameBuf, "Reading framebuffer to mem, fb_address = %08x, ptr=%p", fb_address, destPtr);31613162if (channel == RASTER_DEPTH) {3163_assert_msg_(vfb && vfb->z_address != 0 && vfb->z_stride != 0, "Depth buffer invalid");3164ReadbackDepthbuffer(vfb->fbo,3165x * vfb->renderScaleFactor, y * vfb->renderScaleFactor,3166w * vfb->renderScaleFactor, h * vfb->renderScaleFactor, (uint16_t *)destPtr, stride, w, h, mode);3167} else {3168draw_->CopyFramebufferToMemory(vfb->fbo, channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, x, y, w, h, destFormat, destPtr, stride, mode, "ReadbackFramebufferSync");3169}31703171char tag[128];3172size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format));3173NotifyMemInfo(MemBlockFlags::WRITE, fb_address + dstByteOffset, dstSize, tag, len);31743175if (mode == Draw::ReadbackMode::BLOCK) {3176gpuStats.numBlockingReadbacks++;3177} else {3178gpuStats.numReadbacks++;3179}3180}31813182bool FramebufferManagerCommon::ReadbackStencilbuffer(Draw::Framebuffer *fbo, int x, int y, int w, int h, uint8_t *pixels, int pixelsStride, Draw::ReadbackMode mode) {3183return draw_->CopyFramebufferToMemory(fbo, Draw::Aspect::DEPTH_BIT, x, y, w, h, Draw::DataFormat::S8, pixels, pixelsStride, mode, "ReadbackStencilbufferSync");3184}31853186void FramebufferManagerCommon::ReadFramebufferToMemory(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3187if (!vfb || !vfb->fbo) {3188return;3189}31903191// Clamp to bufferWidth. Sometimes block transfers can cause this to hit.3192if (x + w >= vfb->bufferWidth) {3193w = vfb->bufferWidth - x;3194}3195if (gameUsesSequentialCopies_) {3196// Ignore the x/y/etc., read the entire thing. See below.3197x = 0;3198y = 0;3199w = vfb->width;3200h = vfb->height;3201vfb->memoryUpdated = true;3202vfb->usageFlags |= FB_USAGE_DOWNLOAD;3203} else if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3204// Mark it as fully downloaded until next render to it.3205if (channel == RASTER_COLOR)3206vfb->memoryUpdated = true;3207vfb->usageFlags |= FB_USAGE_DOWNLOAD;3208} else {3209// Let's try to set the flag eventually, if the game copies a lot.3210// Some games (like Grand Knights History) copy subranges very frequently.3211const static int FREQUENT_SEQUENTIAL_COPIES = 3;3212static int frameLastCopy = 0;3213static u32 bufferLastCopy = 0;3214static int copiesThisFrame = 0;3215if (frameLastCopy != gpuStats.numFlips || bufferLastCopy != vfb->fb_address) {3216frameLastCopy = gpuStats.numFlips;3217bufferLastCopy = vfb->fb_address;3218copiesThisFrame = 0;3219}3220if (++copiesThisFrame > FREQUENT_SEQUENTIAL_COPIES) {3221gameUsesSequentialCopies_ = true;3222}3223}32243225// This handles any required stretching internally.3226ReadbackFramebuffer(vfb, x, y, w, h, channel, mode);32273228draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3229textureCache_->ForgetLastTexture();3230RebindFramebuffer("RebindFramebuffer - ReadFramebufferToMemory");3231}32323233void FramebufferManagerCommon::FlushBeforeCopy() {3234drawEngine_->FlushQueuedDepth();3235// Flush anything not yet drawn before blitting, downloading, or uploading.3236// This might be a stalled list, or unflushed before a block transfer, etc.3237// Only bother if any draws are pending.3238if (drawEngine_->GetNumDrawCalls() > 0) {3239// TODO: It's really bad that we are calling SetRenderFramebuffer here with3240// all the irrelevant state checking it'll use to decide what to do. Should3241// do something more focused here.3242bool changed;3243SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason, &changed);3244drawEngine_->Flush();3245}3246}32473248// TODO: Replace with with depal, reading the palette from the texture on the GPU directly.3249void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) {3250VirtualFramebuffer *vfb = GetVFBAt(fb_address);3251if (vfb && vfb->fb_stride != 0) {3252const u32 bpp = BufferFormatBytesPerPixel(vfb->fb_format);3253int x = 0;3254int y = 0;3255int pixels = loadBytes / bpp;3256// The height will be 1 for each stride or part thereof.3257int w = std::min(pixels % vfb->fb_stride, (int)vfb->width);3258int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height);32593260if (w == 0 || h > 1) {3261// Exactly aligned, or more than one row.3262w = std::min(vfb->fb_stride, vfb->width);3263}32643265// We might still have a pending draw to the fb in question, flush if so.3266FlushBeforeCopy();32673268// No need to download if we already have it.3269if (w > 0 && h > 0 && !vfb->memoryUpdated && vfb->clutUpdatedBytes < loadBytes) {3270// We intentionally don't try to optimize into a full download here - we don't want to over download.32713272// CLUT framebuffers are often incorrectly estimated in size.3273if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3274vfb->memoryUpdated = true;3275}3276vfb->clutUpdatedBytes = loadBytes;32773278// This function now handles scaling down internally.3279ReadbackFramebuffer(vfb, x, y, w, h, RASTER_COLOR, Draw::ReadbackMode::BLOCK);32803281textureCache_->ForgetLastTexture();3282RebindFramebuffer("RebindFramebuffer - DownloadFramebufferForClut");3283}3284}3285}32863287void FramebufferManagerCommon::RebindFramebuffer(const char *tag) {3288draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3289shaderManager_->DirtyLastShader();3290// Needed for D3D11 to run validation clean. I don't think it's actually an issue.3291// textureCache_->ForgetLastTexture();3292if (currentRenderVfb_ && currentRenderVfb_->fbo) {3293draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag);3294} else {3295// This can happen (like it does in Parappa) when a frame starts with copies instead of rendering.3296// Let's do nothing and assume it'll take care of itself.3297}3298}32993300std::vector<const VirtualFramebuffer *> FramebufferManagerCommon::GetFramebufferList() const {3301std::vector<const VirtualFramebuffer *> list;3302for (auto vfb : vfbs_) {3303list.push_back(vfb);3304}3305return list;3306}33073308template <typename T>3309static void DoRelease(T *&obj) {3310if (obj)3311obj->Release();3312obj = nullptr;3313}33143315void FramebufferManagerCommon::ReleasePipelines() {3316for (int i = 0; i < ARRAY_SIZE(reinterpretFromTo_); i++) {3317for (int j = 0; j < ARRAY_SIZE(reinterpretFromTo_); j++) {3318DoRelease(reinterpretFromTo_[i][j]);3319}3320}3321DoRelease(stencilWriteSampler_);3322DoRelease(stencilWritePipeline_);3323DoRelease(stencilReadbackSampler_);3324DoRelease(stencilReadbackPipeline_);3325DoRelease(depthReadbackSampler_);3326DoRelease(depthReadbackPipeline_);3327DoRelease(draw2DPipelineCopyColor_);3328DoRelease(draw2DPipelineColorRect2Lin_);3329DoRelease(draw2DPipelineCopyDepth_);3330DoRelease(draw2DPipelineEncodeDepth_);3331DoRelease(draw2DPipeline565ToDepth_);3332DoRelease(draw2DPipeline565ToDepthDeswizzle_);3333}33343335void FramebufferManagerCommon::DeviceLost() {3336DestroyAllFBOs();33373338presentation_->DeviceLost();3339draw2D_.DeviceLost();33403341ReleasePipelines();33423343draw_ = nullptr;3344}33453346void FramebufferManagerCommon::DeviceRestore(Draw::DrawContext *draw) {3347draw_ = draw;3348draw2D_.DeviceRestore(draw_);3349presentation_->DeviceRestore(draw_);3350}33513352void FramebufferManagerCommon::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) {3353// Will be drawn as a strip.3354Draw2DVertex coord[4] = {3355{x, y, u0, v0},3356{x + w, y, u1, v0},3357{x + w, y + h, u1, v1},3358{x, y + h, u0, v1},3359};33603361if (uvRotation != ROTATION_LOCKED_HORIZONTAL) {3362float temp[8];3363int rotation = 0;3364switch (uvRotation) {3365case ROTATION_LOCKED_HORIZONTAL180: rotation = 2; break;3366case ROTATION_LOCKED_VERTICAL: rotation = 1; break;3367case ROTATION_LOCKED_VERTICAL180: rotation = 3; break;3368}3369for (int i = 0; i < 4; i++) {3370temp[i * 2] = coord[((i + rotation) & 3)].u;3371temp[i * 2 + 1] = coord[((i + rotation) & 3)].v;3372}33733374for (int i = 0; i < 4; i++) {3375coord[i].u = temp[i * 2];3376coord[i].v = temp[i * 2 + 1];3377}3378}33793380const float invDestW = 2.0f / destW;3381const float invDestH = 2.0f / destH;3382for (int i = 0; i < 4; i++) {3383coord[i].x = coord[i].x * invDestW - 1.0f;3384coord[i].y = coord[i].y * invDestH - 1.0f;3385}33863387if ((flags & DRAWTEX_TO_BACKBUFFER) && g_display.rotation != DisplayRotation::ROTATE_0) {3388for (int i = 0; i < 4; i++) {3389// backwards notation, should fix that...3390Lin::Vec3 pos = Lin::Vec3(coord[i].x, coord[i].y, 0.0);3391pos = pos * g_display.rot_matrix;3392coord[i].x = pos.x;3393coord[i].y = pos.y;3394}3395}33963397// Rearrange to strip form.3398std::swap(coord[2], coord[3]);33993400draw2D_.DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline((flags & DRAWTEX_DEPTH) ? DRAW2D_ENCODE_R16_TO_DEPTH : DRAW2D_COPY_COLOR));34013402gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3403}34043405void FramebufferManagerCommon::BlitFramebuffer(VirtualFramebuffer *dst, int dstX, int dstY, VirtualFramebuffer *src, int srcX, int srcY, int w, int h, int bpp, RasterChannel channel, const char *tag) {3406if (!dst->fbo || !src->fbo || !useBufferedRendering_) {3407// This can happen if they recently switched from non-buffered.3408if (useBufferedRendering_) {3409// Just bind the back buffer for rendering, forget about doing anything else as we're in a weird state.3410draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitFramebuffer");3411}3412return;3413}34143415if (channel == RASTER_DEPTH && !draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {3416// Can't do anything :(3417return;3418}34193420// Perform a little bit of clipping first.3421// Block transfer coords are unsigned so I don't think we need to clip on the left side.. Although there are3422// other uses for BlitFramebuffer.3423if (dstX + w > dst->bufferWidth) {3424w -= dstX + w - dst->bufferWidth;3425}3426if (dstY + h > dst->bufferHeight) {3427h -= dstY + h - dst->bufferHeight;3428}3429if (srcX + w > src->bufferWidth) {3430w -= srcX + w - src->bufferWidth;3431}3432if (srcY + h > src->bufferHeight) {3433h -= srcY + h - src->bufferHeight;3434}34353436if (w <= 0 || h <= 0) {3437// The whole rectangle got clipped.3438return;3439}34403441bool useBlit = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferBlitSupported : false;3442bool useCopy = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferCopySupported : false;3443if (dst == currentRenderVfb_ || dst->fbo->MultiSampleLevel() != 0 || src->fbo->MultiSampleLevel() != 0) {3444// If already bound, using either a blit or a copy is unlikely to be an optimization.3445// So we're gonna use a raster draw instead. Also multisampling has problems with copies currently.3446useBlit = false;3447useCopy = false;3448}34493450float srcXFactor = src->renderScaleFactor;3451float srcYFactor = src->renderScaleFactor;3452const int srcBpp = BufferFormatBytesPerPixel(src->Format(channel));3453if (srcBpp != bpp && bpp != 0) {3454// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3455srcXFactor = (srcXFactor * bpp) / srcBpp;3456}3457int srcX1 = srcX * srcXFactor;3458int srcX2 = (srcX + w) * srcXFactor;3459int srcY1 = srcY * srcYFactor;3460int srcY2 = (srcY + h) * srcYFactor;34613462float dstXFactor = dst->renderScaleFactor;3463float dstYFactor = dst->renderScaleFactor;3464const int dstBpp = BufferFormatBytesPerPixel(dst->Format(channel));3465if (dstBpp != bpp && bpp != 0) {3466// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3467dstXFactor = (dstXFactor * bpp) / dstBpp;3468}3469int dstX1 = dstX * dstXFactor;3470int dstX2 = (dstX + w) * dstXFactor;3471int dstY1 = dstY * dstYFactor;3472int dstY2 = (dstY + h) * dstYFactor;34733474if (src == dst && srcX == dstX && srcY == dstY) {3475// Let's just skip a copy where the destination is equal to the source.3476WARN_LOG_REPORT_ONCE(blitSame, Log::G3D, "Skipped blit with equal dst and src");3477return;3478}34793480if (useCopy) {3481// glBlitFramebuffer can clip, but glCopyImageSubData is more restricted.3482// In case the src goes outside, we just skip the optimization in that case.3483const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1;3484const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight;3485const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight;3486const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2;3487const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2;3488if (sameSize && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) {3489draw_->CopyFramebufferImage(src->fbo, 0, srcX1, srcY1, 0, dst->fbo, 0, dstX1, dstY1, 0, dstX2 - dstX1, dstY2 - dstY1, 1,3490channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, tag);3491return;3492}3493}34943495if (useBlit) {3496draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2,3497channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag);3498} else {3499Draw2DPipeline *pipeline = Get2DPipeline(channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH);3500Draw::Framebuffer *srcFBO = src->fbo;3501if (src == dst) {3502Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight);3503BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, tag);3504srcFBO = tempFBO;3505}3506BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, tag);3507}35083509draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);35103511gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3512}35133514// The input is raw pixel coordinates, scale not taken into account.3515void FramebufferManagerCommon::BlitUsingRaster(3516Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2,3517Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2,3518bool linearFilter,3519int scaleFactor,3520Draw2DPipeline *pipeline, const char *tag) {35213522if (pipeline->info.writeChannel == RASTER_DEPTH) {3523_dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported);3524}35253526int destW, destH, srcW, srcH;3527draw_->GetFramebufferDimensions(src, &srcW, &srcH);3528draw_->GetFramebufferDimensions(dest, &destW, &destH);35293530// Unbind the texture first to avoid the D3D11 hazard check (can't set render target to things bound as textures and vice versa, not even temporarily).3531draw_->BindTexture(0, nullptr);3532// This will get optimized away in case it's already bound (in VK and GL at least..)3533draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster");3534draw_->BindFramebufferAsTexture(src, 0, pipeline->info.readChannel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, Draw::ALL_LAYERS);35353536if (destX1 == 0.0f && destY1 == 0.0f && destX2 >= destW && destY2 >= destH) {3537// We overwrite the whole channel of the framebuffer, so we can invalidate the current contents.3538draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_LOAD, pipeline->info.writeChannel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT);3539}35403541Draw::Viewport viewport{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f };3542draw_->SetViewport(viewport);3543draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height());35443545draw2D_.Blit(pipeline, srcX1, srcY1, srcX2, srcY2, destX1, destY1, destX2, destY2, (float)srcW, (float)srcH, (float)destW, (float)destH, linearFilter, scaleFactor);35463547gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3548}35493550int FramebufferManagerCommon::GetFramebufferLayers() const {3551int layers = 1;3552if (gstate_c.Use(GPU_USE_SINGLE_PASS_STEREO)) {3553layers = 2;3554}3555return layers;3556}35573558VirtualFramebuffer *FramebufferManagerCommon::ResolveFramebufferColorToFormat(VirtualFramebuffer *src, GEBufferFormat newFormat) {3559// Look for an identical framebuffer with the new format3560_dbg_assert_(src->fb_format != newFormat);35613562VirtualFramebuffer *vfb = nullptr;3563for (auto dest : vfbs_) {3564if (dest == src) {3565continue;3566}35673568// Sanity check for things that shouldn't exist.3569if (dest->fb_address == src->fb_address && dest->fb_format == src->fb_format && dest->fb_stride == src->fb_stride) {3570_dbg_assert_msg_(false, "illegal clone of src found");3571}35723573if (dest->fb_address == src->fb_address && dest->FbStrideInBytes() == src->FbStrideInBytes() && dest->fb_format == newFormat) {3574vfb = dest;3575break;3576}3577}35783579if (!vfb) {3580// Create a clone!3581vfb = new VirtualFramebuffer();3582*vfb = *src; // Copies everything, but watch out! Can't copy fbo.35833584// Adjust width by bpp.3585float widthFactor = (float)BufferFormatBytesPerPixel(vfb->fb_format) / (float)BufferFormatBytesPerPixel(newFormat);35863587vfb->width *= widthFactor;3588vfb->bufferWidth *= widthFactor;3589vfb->renderWidth *= widthFactor;3590vfb->drawnWidth *= widthFactor;3591vfb->newWidth *= widthFactor;3592vfb->safeWidth *= widthFactor;35933594vfb->fb_format = newFormat;3595// stride stays the same since it's in pixels.35963597WARN_LOG(Log::FrameBuf, "Creating %s clone of %08x/%08x/%s (%dx%d -> %dx%d)", GeBufferFormatToString(newFormat), src->fb_address, src->z_address, GeBufferFormatToString(src->fb_format), src->width, src->height, vfb->width, vfb->height);35983599char tag[128];3600FormatFramebufferName(vfb, tag, sizeof(tag));3601vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, true, tag });3602vfbs_.push_back(vfb);3603}36043605// OK, now resolve it so we can texture from it.3606// This will do any necessary reinterprets.3607CopyToColorFromOverlappingFramebuffers(vfb);3608// Now we consider the resolved one the latest at the address (though really, we could make them equivalent?).3609vfb->colorBindSeq = GetBindSeqCount();3610return vfb;3611}36123613static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width) {3614// Detect whether we're rendering to the margin.3615bool margin;3616if ((params->scissorRight - params->scissorLeft) == 32) {3617// Title screen has this easy case. It also uses non-through verts, so lucky for us that we have this.3618margin = true;3619} else if (params->scissorRight == 480) {3620margin = false;3621} else {3622// Go deep, look at the vertices. Killzone-specific, of course.3623margin = false;3624if ((gstate.vertType & 0xFFFFFF) == 0x00800102) { // through, u16, s163625u16 *vdata = (u16 *)Memory::GetPointerUnchecked(gstate_c.vertexAddr);3626int v0PosU = vdata[0];3627int v0PosX = vdata[2];3628if (v0PosX >= 480 && v0PosU < 480) {3629// Texturing from surface, writing to margin3630margin = true;3631}3632}36333634// TODO: Implement this for Burnout Dominator. It has to handle self-reads inside3635// the margin framebuffer though, so framebuffer copies are still needed, just smaller.3636// It uses 0x0080019f (through, float texcoords, ABGR 8888 colors, float positions).3637}36383639if (margin) {3640gstate_c.SetCurRTOffset(-480, 0);3641// Modify the fb_address and z_address too to avoid matching below.3642params->fb_address += 480 * 4;3643params->z_address += 480 * 2;3644*drawing_width = 32;3645} else {3646gstate_c.SetCurRTOffset(0, 0);3647*drawing_width = 480;3648}3649}365036513652