CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/GPU/Common/FramebufferManagerCommon.cpp
Views: 1401
// 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/GPU/OpenGL/GLFeatures.h"23#include "Common/Data/Collections/TinySet.h"24#include "Common/Data/Convert/ColorConv.h"25#include "Common/Data/Text/I18n.h"26#include "Common/LogReporting.h"27#include "Common/Math/lin/matrix4x4.h"28#include "Common/Math/math_util.h"29#include "Common/System/Display.h"30#include "Common/System/OSD.h"31#include "Common/VR/PPSSPPVR.h"32#include "Common/CommonTypes.h"33#include "Common/StringUtils.h"34#include "Core/Config.h"35#include "Core/ConfigValues.h"36#include "Core/Core.h"37#include "Core/CoreParameter.h"38#include "Core/Debugger/MemBlockInfo.h"39#include "Core/MIPS/MIPS.h"40#include "GPU/Common/DrawEngineCommon.h"41#include "GPU/Common/FramebufferManagerCommon.h"42#include "GPU/Common/PostShader.h"43#include "GPU/Common/PresentationCommon.h"44#include "GPU/Common/TextureCacheCommon.h"45#include "GPU/Common/ReinterpretFramebuffer.h"46#include "GPU/Debugger/Debugger.h"47#include "GPU/Debugger/Record.h"48#include "GPU/Debugger/Stepping.h"49#include "GPU/GPUInterface.h"50#include "GPU/GPUState.h"5152static size_t FormatFramebufferName(const VirtualFramebuffer *vfb, char *tag, size_t len) {53return snprintf(tag, len, "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, vfb->bufferWidth, vfb->bufferHeight, GeBufferFormatToString(vfb->fb_format));54}5556FramebufferManagerCommon::FramebufferManagerCommon(Draw::DrawContext *draw)57: draw_(draw), draw2D_(draw_) {58presentation_ = new PresentationCommon(draw);59}6061FramebufferManagerCommon::~FramebufferManagerCommon() {62DeviceLost();6364DecimateFBOs();65for (auto vfb : vfbs_) {66DestroyFramebuf(vfb);67}68vfbs_.clear();6970for (auto &tempFB : tempFBOs_) {71tempFB.second.fbo->Release();72}73tempFBOs_.clear();7475// Do the same for ReadFramebuffersToMemory's VFBs76for (auto vfb : bvfbs_) {77DestroyFramebuf(vfb);78}79bvfbs_.clear();8081delete presentation_;82delete[] convBuf_;83}8485void FramebufferManagerCommon::Init(int msaaLevel) {86// We may need to override the render size if the shader is upscaling or SSAA.87NotifyDisplayResized();88NotifyRenderResized(msaaLevel);89}9091bool FramebufferManagerCommon::UpdateRenderSize(int msaaLevel) {92const bool newRender = renderWidth_ != (float)PSP_CoreParameter().renderWidth || renderHeight_ != (float)PSP_CoreParameter().renderHeight || msaaLevel_ != msaaLevel;9394int effectiveBloomHack = g_Config.iBloomHack;95if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {96effectiveBloomHack = 3;97} else if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOff) {98effectiveBloomHack = 0;99}100101bool newBuffered = !g_Config.bSkipBufferEffects;102const bool newSettings = bloomHack_ != effectiveBloomHack || useBufferedRendering_ != newBuffered;103104renderWidth_ = (float)PSP_CoreParameter().renderWidth;105renderHeight_ = (float)PSP_CoreParameter().renderHeight;106renderScaleFactor_ = (float)PSP_CoreParameter().renderScaleFactor;107msaaLevel_ = msaaLevel;108109bloomHack_ = effectiveBloomHack;110useBufferedRendering_ = newBuffered;111112presentation_->UpdateRenderSize(renderWidth_, renderHeight_);113return newRender || newSettings;114}115116void FramebufferManagerCommon::CheckPostShaders() {117if (updatePostShaders_) {118presentation_->UpdatePostShader();119updatePostShaders_ = false;120}121}122123void FramebufferManagerCommon::BeginFrame() {124DecimateFBOs();125presentation_->BeginFrame();126currentRenderVfb_ = nullptr;127}128129bool FramebufferManagerCommon::PresentedThisFrame() const {130return presentation_->PresentedThisFrame();131}132133void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) {134displayFramebufPtr_ = framebuf & 0x3FFFFFFF;135if (Memory::IsVRAMAddress(displayFramebufPtr_))136displayFramebufPtr_ = framebuf & 0x041FFFFF;137displayStride_ = stride;138displayFormat_ = format;139GPUDebug::NotifyDisplay(framebuf, stride, format);140GPURecord::NotifyDisplay(framebuf, stride, format);141}142143VirtualFramebuffer *FramebufferManagerCommon::GetVFBAt(u32 addr) const {144addr &= 0x3FFFFFFF;145if (Memory::IsVRAMAddress(addr))146addr &= 0x041FFFFF;147VirtualFramebuffer *match = nullptr;148for (auto vfb : vfbs_) {149if (vfb->fb_address == addr) {150// Could check w too but whatever (actually, might very well make sense to do so, depending on context).151if (!match || vfb->last_frame_render > match->last_frame_render) {152match = vfb;153}154}155}156return match;157}158159VirtualFramebuffer *FramebufferManagerCommon::GetExactVFB(u32 addr, int stride, GEBufferFormat format) const {160addr &= 0x3FFFFFFF;161if (Memory::IsVRAMAddress(addr))162addr &= 0x041FFFFF;163VirtualFramebuffer *newest = nullptr;164for (auto vfb : vfbs_) {165if (vfb->fb_address == addr && vfb->fb_stride == stride && vfb->fb_format == format) {166if (newest) {167if (vfb->colorBindSeq > newest->colorBindSeq) {168newest = vfb;169}170} else {171newest = vfb;172}173}174}175return newest;176}177178VirtualFramebuffer *FramebufferManagerCommon::ResolveVFB(u32 addr, int stride, GEBufferFormat format) {179addr &= 0x3FFFFFFF;180if (Memory::IsVRAMAddress(addr))181addr &= 0x041FFFFF;182// Find the newest one matching addr and stride.183VirtualFramebuffer *newest = nullptr;184for (auto vfb : vfbs_) {185if (vfb->fb_address == addr && vfb->FbStrideInBytes() == stride * BufferFormatBytesPerPixel(format)) {186if (newest) {187if (vfb->colorBindSeq > newest->colorBindSeq) {188newest = vfb;189}190} else {191newest = vfb;192}193}194}195196if (newest && newest->fb_format != format) {197WARN_LOG_ONCE(resolvevfb, Log::G3D, "ResolveVFB: Resolving from %s to %s at %08x/%d", GeBufferFormatToString(newest->fb_format), GeBufferFormatToString(format), addr, stride);198return ResolveFramebufferColorToFormat(newest, format);199}200201return newest;202}203204VirtualFramebuffer *FramebufferManagerCommon::GetDisplayVFB() {205return GetExactVFB(displayFramebufPtr_, displayStride_, displayFormat_);206}207208// Heuristics to figure out the size of FBO to create.209// TODO: Possibly differentiate on whether through mode is used (since in through mode, viewport is meaningless?)210void 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) {211static const int MAX_FRAMEBUF_HEIGHT = 512;212213// Games don't always set any of these. Take the greatest parameter that looks valid based on stride.214if (viewport_width > 4 && viewport_width <= fb_stride && viewport_height > 0) {215drawing_width = viewport_width;216drawing_height = viewport_height;217// Some games specify a viewport with 0.5, but don't have VRAM for 273. 480x272 is the buffer size.218if (viewport_width == 481 && region_width == 480 && viewport_height == 273 && region_height == 272) {219drawing_width = 480;220drawing_height = 272;221}222// Sometimes region is set larger than the VRAM for the framebuffer.223// However, in one game it's correctly set as a larger height (see #7277) with the same width.224// A bit of a hack, but we try to handle that unusual case here.225if (region_width <= fb_stride && (region_width > drawing_width || (region_width == drawing_width && region_height > drawing_height)) && region_height <= MAX_FRAMEBUF_HEIGHT) {226drawing_width = region_width;227drawing_height = std::max(drawing_height, region_height);228}229// Scissor is often set to a subsection of the framebuffer, so we pay the least attention to it.230if (scissor_width <= fb_stride && scissor_width > drawing_width && scissor_height <= MAX_FRAMEBUF_HEIGHT) {231drawing_width = scissor_width;232drawing_height = std::max(drawing_height, scissor_height);233}234} else {235// If viewport wasn't valid, let's just take the greatest anything regardless of stride.236drawing_width = std::min(std::max(region_width, scissor_width), fb_stride);237drawing_height = std::max(region_height, scissor_height);238}239240if (scissor_width == 481 && region_width == 480 && scissor_height == 273 && region_height == 272) {241drawing_width = 480;242drawing_height = 272;243}244245// Assume no buffer is > 512 tall, it couldn't be textured or displayed fully if so.246if (drawing_height >= MAX_FRAMEBUF_HEIGHT) {247if (region_height < MAX_FRAMEBUF_HEIGHT) {248drawing_height = region_height;249} else if (scissor_height < MAX_FRAMEBUF_HEIGHT) {250drawing_height = scissor_height;251}252}253254if (viewport_width != region_width) {255// The majority of the time, these are equal. If not, let's check what we know.256u32 nearest_address = 0xFFFFFFFF;257for (auto vfb : vfbs_) {258const u32 other_address = vfb->fb_address;259if (other_address > fb_address && other_address < nearest_address) {260nearest_address = other_address;261}262}263264// Unless the game is using overlapping buffers, the next buffer should be far enough away.265// This catches some cases where we can know this.266// Hmm. The problem is that we could only catch it for the first of two buffers...267const u32 bpp = BufferFormatBytesPerPixel(fb_format);268int avail_height = (nearest_address - fb_address) / (fb_stride * bpp);269if (avail_height < drawing_height && avail_height == region_height) {270drawing_width = std::min(region_width, fb_stride);271drawing_height = avail_height;272}273274// Some games draw buffers interleaved, with a high stride/region/scissor but default viewport.275if (fb_stride == 1024 && region_width == 1024 && scissor_width == 1024) {276drawing_width = 1024;277}278}279280bool margin = false;281// Let's check if we're in a stride gap of a full-size framebuffer.282for (auto vfb : vfbs_) {283if (fb_address == vfb->fb_address) {284continue;285}286if (vfb->fb_stride != 512) {287continue;288}289290int vfb_stride_in_bytes = BufferFormatBytesPerPixel(vfb->fb_format) * vfb->fb_stride;291int stride_in_bytes = BufferFormatBytesPerPixel(fb_format) * fb_stride;292if (stride_in_bytes != vfb_stride_in_bytes) {293// Mismatching stride in bytes, not interesting294continue;295}296297if (fb_address > vfb->fb_address && fb_address < vfb->fb_address + vfb_stride_in_bytes) {298// Candidate!299if (vfb->height == drawing_height) {300// Might have a margin texture! Fix the drawing width if it's too large.301int width_in_bytes = vfb->fb_address + vfb_stride_in_bytes - fb_address;302int width_in_pixels = width_in_bytes / BufferFormatBytesPerPixel(fb_format);303304// Final check305if (width_in_pixels <= 32) {306drawing_width = std::min(drawing_width, width_in_pixels);307margin = true;308// Don't really need to keep looking.309break;310}311}312}313}314315DEBUG_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!)" : "");316}317318void GetFramebufferHeuristicInputs(FramebufferHeuristicParams *params, const GPUgstate &gstate) {319// GetFramebufferHeuristicInputs is only called from rendering, and thus, it's VRAM.320params->fb_address = gstate.getFrameBufRawAddress() | 0x04000000;321params->fb_stride = gstate.FrameBufStride();322323params->z_address = gstate.getDepthBufRawAddress() | 0x04000000;324params->z_stride = gstate.DepthBufStride();325326if (params->z_address == params->fb_address) {327// Probably indicates that the game doesn't care about Z for this VFB.328// Let's avoid matching it for Z copies and other shenanigans.329params->z_address = 0;330params->z_stride = 0;331}332333params->fb_format = gstate_c.framebufFormat;334335params->isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask();336// Technically, it may write depth later, but we're trying to detect it only when it's really true.337if (gstate.isModeClear()) {338// Not quite seeing how this makes sense..339params->isWritingDepth = !gstate.isClearModeDepthMask() && gstate.isDepthWriteEnabled();340} else {341params->isWritingDepth = gstate.isDepthWriteEnabled();342}343params->isDrawing = !gstate.isModeClear() || !gstate.isClearModeColorMask() || !gstate.isClearModeAlphaMask();344params->isModeThrough = gstate.isModeThrough();345const bool alphaBlending = gstate.isAlphaBlendEnabled();346const bool logicOpBlending = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_CLEAR && gstate.getLogicOp() != GE_LOGIC_COPY;347params->isBlending = alphaBlending || logicOpBlending;348349// Viewport-X1 and Y1 are not the upper left corner, but half the width/height. A bit confusing.350float vpx = gstate.getViewportXScale();351float vpy = gstate.getViewportYScale();352353// Work around problem in F1 Grand Prix, where it draws in through mode with a bogus viewport.354// We set bad values to 0 which causes the framebuffer size heuristic to rely on the other parameters instead.355if (std::isnan(vpx) || vpx > 10000000.0f) {356vpx = 0.f;357}358if (std::isnan(vpy) || vpy > 10000000.0f) {359vpy = 0.f;360}361params->viewportWidth = (int)(fabsf(vpx) * 2.0f);362params->viewportHeight = (int)(fabsf(vpy) * 2.0f);363params->regionWidth = gstate.getRegionX2() + 1;364params->regionHeight = gstate.getRegionY2() + 1;365366params->scissorLeft = gstate.getScissorX1();367params->scissorTop = gstate.getScissorY1();368params->scissorRight = gstate.getScissorX2() + 1;369params->scissorBottom = gstate.getScissorY2() + 1;370371if (gstate.getRegionRateX() != 0x100 || gstate.getRegionRateY() != 0x100) {372WARN_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());373}374}375376static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width);377378VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(FramebufferHeuristicParams ¶ms, u32 skipDrawReason) {379gstate_c.Clean(DIRTY_FRAMEBUF);380381// Collect all parameters. This whole function has really become a cesspool of heuristics...382// but it appears that's what it takes, unless we emulate VRAM layout more accurately somehow.383384// As there are no clear "framebuffer width" and "framebuffer height" registers,385// we need to infer the size of the current framebuffer somehow.386int drawing_width, drawing_height;387EstimateDrawingSize(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);388389if (params.fb_address == params.z_address) {390// Most likely Z will not be used in this pass, as that would wreak havoc (undefined behavior for sure)391// We probably don't need to do anything about that, but let's log it.392WARN_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);393}394395// Compatibility hack for Killzone, see issue #6207.396if (PSP_CoreParameter().compat.flags().SplitFramebufferMargin && params.fb_format == GE_FORMAT_8888) {397ApplyKillzoneFramebufferSplit(¶ms, &drawing_width);398} else {399gstate_c.SetCurRTOffset(0, 0);400}401402// Find a matching framebuffer.403VirtualFramebuffer *normal_vfb = nullptr;404int y_offset;405VirtualFramebuffer *large_offset_vfb = nullptr;406407for (auto v : vfbs_) {408const u32 bpp = BufferFormatBytesPerPixel(v->fb_format);409410if (params.fb_address == v->fb_address && params.fb_format == v->fb_format && params.fb_stride == v->fb_stride) {411if (!normal_vfb) {412normal_vfb = v;413}414} else if (!PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset && !PSP_CoreParameter().compat.flags().SplitFramebufferMargin &&415v->fb_stride == params.fb_stride && v->fb_format == params.fb_format) {416u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp;417u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp;418419if (!normal_vfb && params.fb_address > v->fb_address && params.fb_address < v_fb_first_line_end_ptr) {420const int x_offset = (params.fb_address - v->fb_address) / bpp;421if (x_offset < params.fb_stride && v->height >= drawing_height) {422// Pretty certainly a pure render-to-X-offset.423WARN_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);424normal_vfb = v;425gstate_c.SetCurRTOffset(x_offset, 0);426normal_vfb->width = std::max((int)normal_vfb->width, x_offset + drawing_width);427// To prevent the newSize code from being confused.428drawing_width += x_offset;429break;430}431} else if (PSP_CoreParameter().compat.flags().FramebufferAllowLargeVerticalOffset &&432params.fb_address > v->fb_address && v->fb_stride > 0 && (params.fb_address - v->fb_address) % v->FbStrideInBytes() == 0 &&433params.fb_address != 0x04088000 && v->fb_address != 0x04000000) { // Heuristic to avoid merging the main framebuffers.434y_offset = (params.fb_address - v->fb_address) / v->FbStrideInBytes();435if (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.436large_offset_vfb = v;437break;438}439}440}441}442443VirtualFramebuffer *vfb = nullptr;444if (large_offset_vfb) {445// These are prioritized over normal VFBs matches, to ensure things work even if the higher-address one446// is created first. Only enabled under compat flag.447vfb = large_offset_vfb;448WARN_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);449gstate_c.SetCurRTOffset(0, y_offset);450vfb->height = std::max((int)vfb->height, y_offset + drawing_height);451drawing_height += y_offset;452// TODO: We can allow X/Y overlaps too, but haven't seen any so safer to not.453} else if (normal_vfb) {454vfb = normal_vfb;455if (vfb->z_address == 0 && vfb->z_stride == 0 && params.z_stride != 0) {456// Got one that was created by CreateRAMFramebuffer. Since it has no depth buffer,457// we just recreate it immediately.458ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);459}460461// Keep track, but this isn't really used.462vfb->z_stride = params.z_stride;463// Heuristic: In throughmode, a higher height could be used. Let's avoid shrinking the buffer.464if (params.isModeThrough && (int)vfb->width <= params.fb_stride) {465vfb->width = std::max((int)vfb->width, drawing_width);466vfb->height = std::max((int)vfb->height, drawing_height);467} else {468vfb->width = drawing_width;469vfb->height = drawing_height;470}471}472473if (vfb) {474bool resized = false;475if ((drawing_width != vfb->bufferWidth || drawing_height != vfb->bufferHeight)) {476// Even if it's not newly wrong, if this is larger we need to resize up.477if (vfb->width > vfb->bufferWidth || vfb->height > vfb->bufferHeight) {478ResizeFramebufFBO(vfb, vfb->width, vfb->height);479resized = true;480} else if (vfb->newWidth != drawing_width || vfb->newHeight != drawing_height) {481// If it's newly wrong, or changing every frame, just keep track.482vfb->newWidth = drawing_width;483vfb->newHeight = drawing_height;484vfb->lastFrameNewSize = gpuStats.numFlips;485} else if (vfb->lastFrameNewSize + FBO_OLD_AGE < gpuStats.numFlips) {486// Okay, it's changed for a while (and stayed that way.) Let's start over.487// But only if we really need to, to avoid blinking.488bool needsRecreate = vfb->bufferWidth > params.fb_stride;489needsRecreate = needsRecreate || vfb->newWidth > vfb->bufferWidth || vfb->newWidth * 2 < vfb->bufferWidth;490needsRecreate = needsRecreate || vfb->newHeight > vfb->bufferHeight || vfb->newHeight * 2 < vfb->bufferHeight;491492// Whether we resize or not, change the size parameters so we stop detecting a resize.493// It might be larger if all drawing has been in throughmode.494vfb->width = drawing_width;495vfb->height = drawing_height;496497if (needsRecreate) {498ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);499resized = true;500// Let's discard this information, might be wrong now.501vfb->safeWidth = 0;502vfb->safeHeight = 0;503}504}505} else {506// It's not different, let's keep track of that too.507vfb->lastFrameNewSize = gpuStats.numFlips;508}509510if (!resized && renderScaleFactor_ != 1 && vfb->renderScaleFactor == 1) {511// Might be time to change this framebuffer - have we used depth?512if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {513ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);514_assert_(vfb->renderScaleFactor != 1);515}516}517}518519// None found? Create one.520if (!vfb) {521gstate_c.usingDepth = false; // reset depth buffer tracking522523vfb = new VirtualFramebuffer{};524vfb->fbo = nullptr;525vfb->fb_address = params.fb_address;526vfb->fb_stride = params.fb_stride;527vfb->z_address = params.z_address;528vfb->z_stride = params.z_stride;529530// The other width/height parameters are set in ResizeFramebufFBO below.531vfb->width = drawing_width;532vfb->height = drawing_height;533vfb->newWidth = drawing_width;534vfb->newHeight = drawing_height;535vfb->lastFrameNewSize = gpuStats.numFlips;536vfb->fb_format = params.fb_format;537vfb->usageFlags = FB_USAGE_RENDER_COLOR;538539u32 colorByteSize = vfb->BufferByteSize(RASTER_COLOR);540if (Memory::IsVRAMAddress(params.fb_address) && params.fb_address + colorByteSize > framebufColorRangeEnd_) {541framebufColorRangeEnd_ = params.fb_address + colorByteSize;542}543544// This is where we actually create the framebuffer. The true is "force".545ResizeFramebufFBO(vfb, drawing_width, drawing_height, true);546NotifyRenderFramebufferCreated(vfb);547548// Note that we do not even think about depth right now. That'll be handled549// on the first depth access, which will call SetDepthFramebuffer.550551CopyToColorFromOverlappingFramebuffers(vfb);552SetColorUpdated(vfb, skipDrawReason);553554INFO_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));555556vfb->last_frame_render = gpuStats.numFlips;557frameLastFramebufUsed_ = gpuStats.numFlips;558vfbs_.push_back(vfb);559currentRenderVfb_ = vfb;560561// Assume that if we're clearing right when switching to a new framebuffer, we don't need to upload.562if (useBufferedRendering_ && params.isDrawing) {563gpu->PerformWriteColorFromMemory(params.fb_address, colorByteSize);564// Alpha was already done by PerformWriteColorFromMemory.565PerformWriteStencilFromMemory(params.fb_address, colorByteSize, WriteStencil::STENCIL_IS_ZERO | WriteStencil::IGNORE_ALPHA);566// TODO: Is it worth trying to upload the depth buffer (only if it wasn't copied above..?)567}568569DiscardFramebufferCopy();570571// We already have it!572} else if (vfb != currentRenderVfb_) {573// Use it as a render target.574DEBUG_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);575vfb->usageFlags |= FB_USAGE_RENDER_COLOR;576vfb->last_frame_render = gpuStats.numFlips;577frameLastFramebufUsed_ = gpuStats.numFlips;578vfb->dirtyAfterDisplay = true;579if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)580vfb->reallyDirtyAfterDisplay = true;581582VirtualFramebuffer *prev = currentRenderVfb_;583currentRenderVfb_ = vfb;584NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth);585CopyToColorFromOverlappingFramebuffers(vfb);586gstate_c.usingDepth = false; // reset depth buffer tracking587588DiscardFramebufferCopy();589} else {590// Something changed, but we still got the same framebuffer we were already rendering to.591// Might not be a lot to do here, we check in NotifyRenderFramebufferUpdated592vfb->last_frame_render = gpuStats.numFlips;593frameLastFramebufUsed_ = gpuStats.numFlips;594vfb->dirtyAfterDisplay = true;595if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)596vfb->reallyDirtyAfterDisplay = true;597NotifyRenderFramebufferUpdated(vfb);598}599600vfb->colorBindSeq = GetBindSeqCount();601602gstate_c.curRTWidth = vfb->width;603gstate_c.curRTHeight = vfb->height;604gstate_c.curRTRenderWidth = vfb->renderWidth;605gstate_c.curRTRenderHeight = vfb->renderHeight;606return vfb;607}608609// Called on the first use of depth in a render pass.610void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) {611if (!currentRenderVfb_) {612return;613}614615// First time use of this framebuffer's depth buffer.616bool newlyUsingDepth = (currentRenderVfb_->usageFlags & FB_USAGE_RENDER_DEPTH) == 0;617currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH;618619uint32_t boundDepthBuffer = gstate.getDepthBufRawAddress() | 0x04000000;620uint32_t boundDepthStride = gstate.DepthBufStride();621if (currentRenderVfb_->z_address != boundDepthBuffer || currentRenderVfb_->z_stride != boundDepthStride) {622if (currentRenderVfb_->fb_address == boundDepthBuffer) {623// Disallow setting depth buffer to the same address as the color buffer, usually means it's not used.624WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Ignoring color matching depth buffer at %08x", boundDepthBuffer);625boundDepthBuffer = 0;626boundDepthStride = 0;627}628WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Framebuffer at %08x/%d has switched associated depth buffer from %08x to %08x, updating.",629currentRenderVfb_->fb_address, currentRenderVfb_->fb_stride, currentRenderVfb_->z_address, boundDepthBuffer);630631// Technically, here we should copy away the depth buffer to another framebuffer that uses that z_address, or maybe632// even write it back to RAM. However, this is rare. Silent Hill is one example, see #16126.633currentRenderVfb_->z_address = boundDepthBuffer;634// Update the stride in case it changed.635currentRenderVfb_->z_stride = boundDepthStride;636637if (currentRenderVfb_->fbo) {638char tag[128];639FormatFramebufferName(currentRenderVfb_, tag, sizeof(tag));640currentRenderVfb_->fbo->UpdateTag(tag);641}642}643644// If this first draw call is anything other than a clear, "resolve" the depth buffer,645// by copying from any overlapping buffers with fresher content.646if (!isClearingDepth && useBufferedRendering_) {647CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_);648649// Need to upload the first line of depth buffers, for Burnout Dominator lens flares. See issue #11100 and comments to #16081.650// Might make this more generic and upload the whole depth buffer if we find it's needed for something.651if (newlyUsingDepth && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {652// Sanity check the depth buffer pointer.653if (Memory::IsValidRange(currentRenderVfb_->z_address, currentRenderVfb_->width * 2)) {654const u16 *src = (const u16 *)Memory::GetPointerUnchecked(currentRenderVfb_->z_address);655DrawPixels(currentRenderVfb_, 0, 0, (const u8 *)src, GE_FORMAT_DEPTH16, currentRenderVfb_->z_stride, currentRenderVfb_->width, currentRenderVfb_->height, RASTER_DEPTH, "Depth Upload");656}657}658}659660currentRenderVfb_->depthBindSeq = GetBindSeqCount();661}662663struct CopySource {664VirtualFramebuffer *vfb;665RasterChannel channel;666int xOffset;667int yOffset;668669int seq() const {670return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq;671}672673bool operator < (const CopySource &other) const {674return seq() < other.seq();675}676};677678// 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)679// 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 memory680// bandwidth on tilers due to the load operation, which we might otherwise be able to skip).681void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) {682std::vector<CopySource> sources;683for (auto src : vfbs_) {684if (src == dest)685continue;686687if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->fb_format == GE_FORMAT_565) {688if (src->colorBindSeq > dest->depthBindSeq) {689// Source has newer data than the current buffer, use it.690sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });691}692} else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) {693sources.push_back(CopySource{ src, RASTER_DEPTH, 0, 0 });694} else {695// TODO: Do more detailed overlap checks here.696}697}698699std::sort(sources.begin(), sources.end());700701// TODO: A full copy will overwrite anything else. So we can eliminate702// anything that comes before such a copy.703704// For now, let's just do the last thing, if there are multiple.705706// for (auto &source : sources) {707if (!sources.empty()) {708draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);709710auto &source = sources.back();711if (source.channel == RASTER_DEPTH) {712// Good old depth->depth copy.713BlitFramebufferDepth(source.vfb, dest);714gpuStats.numDepthCopies++;715dest->last_frame_depth_updated = gpuStats.numFlips;716} else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {717VirtualFramebuffer *src = source.vfb;718if (src->fb_format != GE_FORMAT_565) {719WARN_LOG_ONCE(not565, Log::FrameBuf, "fb_format of buffer at %08x not 565 as expected", src->fb_address);720}721722// Really hate to do this, but tracking the depth swizzle state across multiple723// copies is not easy.724Draw2DShader shader = DRAW2D_565_TO_DEPTH;725if (PSP_CoreParameter().compat.flags().DeswizzleDepth) {726shader = DRAW2D_565_TO_DEPTH_DESWIZZLE;727}728729gpuStats.numReinterpretCopies++;730src->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;731dest->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;732733// Copying color to depth.734BlitUsingRaster(735src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,736dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,737false, dest->renderScaleFactor, Get2DPipeline(shader), "565_to_depth");738}739}740741gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);742}743744// Can't easily dynamically create these strings, we just pass along the pointer.745static const char *reinterpretStrings[4][4] = {746{747"self_reinterpret_565",748"reinterpret_565_to_5551",749"reinterpret_565_to_4444",750"reinterpret_565_to_8888",751},752{753"reinterpret_5551_to_565",754"self_reinterpret_5551",755"reinterpret_5551_to_4444",756"reinterpret_5551_to_8888",757},758{759"reinterpret_4444_to_565",760"reinterpret_4444_to_5551",761"self_reinterpret_4444",762"reinterpret_4444_to_8888",763},764{765"reinterpret_8888_to_565",766"reinterpret_8888_to_5551",767"reinterpret_8888_to_4444",768"self_reinterpret_8888",769},770};771772// Call this after the target has been bound for rendering. For color, raster is probably always going to win over blits/copies.773void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dst) {774if (!useBufferedRendering_) {775return;776}777778std::vector<CopySource> sources;779for (auto src : vfbs_) {780// Discard old and equal potential inputs.781if (src == dst || src->colorBindSeq < dst->colorBindSeq) {782continue;783}784785if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) {786// Another render target at the exact same location but gotta be a different format or a different stride, otherwise787// it would be the same, and should have been detected in DoSetRenderFrameBuffer.788if (src->fb_format != dst->fb_format) {789// This will result in reinterpret later, if both formats are 16-bit.790sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });791} else {792// This shouldn't happen anymore. I think when it happened last, we still had793// lax stride checking when video was incoming, and a resize happened causing a duplicate.794}795} else if (src->fb_stride == dst->fb_stride && src->fb_format == dst->fb_format) {796u32 bytesPerPixel = BufferFormatBytesPerPixel(src->fb_format);797798u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest799800u32 srcColorStart = src->fb_address;801u32 srcFirstLineEnd = src->fb_address + strideInBytes;802u32 srcColorEnd = strideInBytes * src->height;803804u32 dstColorStart = dst->fb_address;805u32 dstFirstLineEnd = dst->fb_address + strideInBytes;806u32 dstColorEnd = strideInBytes * dst->height;807808// Initially we'll only allow pure horizontal and vertical overlap,809// to reduce the risk for false positives. We can allow diagonal overlap too if needed810// in the future.811812// Check for potential vertical overlap, like in Juiced 2.813int xOffset = 0;814int yOffset = 0;815816// TODO: Get rid of the compatibility flag check.817if ((dstColorStart - srcColorStart) % strideInBytes == 0818&& PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {819// Buffers are aligned.820yOffset = ((int)dstColorStart - (int)srcColorStart) / strideInBytes;821if (yOffset <= -(int)src->height) {822// Not overlapping823continue;824} else if (yOffset >= dst->height) {825// Not overlapping826continue;827}828} else {829// Buffers not stride-aligned - ignoring for now.830// This is where we'll add the horizontal offset for GoW.831continue;832}833sources.push_back(CopySource{ src, RASTER_COLOR, xOffset, yOffset });834} else if (src->fb_address == dst->fb_address && src->FbStrideInBytes() == dst->FbStrideInBytes()) {835if (src->fb_stride == dst->fb_stride * 2) {836// Reinterpret from 16-bit to 32-bit.837sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });838} else if (src->fb_stride * 2 == dst->fb_stride) {839// Reinterpret from 32-bit to 16-bit.840sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });841} else {842// 16-to-16 reinterpret, should have been caught above already.843_assert_msg_(false, "Reinterpret: Shouldn't get here");844}845}846}847848std::sort(sources.begin(), sources.end());849850draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);851852bool tookActions = false;853854// TODO: Only do the latest one.855for (const CopySource &source : sources) {856VirtualFramebuffer *src = source.vfb;857858// Copy a rectangle from the original to the new buffer.859// Yes, we mean to look at src->width/height for the dest rectangle.860861// TODO: Try to bound the blit using gstate_c.vertBounds like depal does.862863int srcWidth = src->width * src->renderScaleFactor;864int srcHeight = src->height * src->renderScaleFactor;865int dstWidth = src->width * dst->renderScaleFactor;866int dstHeight = src->height * dst->renderScaleFactor;867868int dstX1 = -source.xOffset * dst->renderScaleFactor;869int dstY1 = -source.yOffset * dst->renderScaleFactor;870int dstX2 = dstX1 + dstWidth;871int dstY2 = dstY1 + dstHeight;872873if (source.channel == RASTER_COLOR) {874Draw2DPipeline *pipeline = nullptr;875const char *pass_name = "N/A";876float scaleFactorX = 1.0f;877if (src->fb_format == dst->fb_format) {878gpuStats.numColorCopies++;879pipeline = Get2DPipeline(DRAW2D_COPY_COLOR);880pass_name = "copy_color";881} else {882if (PSP_CoreParameter().compat.flags().BlueToAlpha) {883WARN_LOG_ONCE(bta, Log::FrameBuf, "WARNING: Reinterpret encountered with BlueToAlpha on");884}885886// Reinterpret!887WARN_LOG_N_TIMES(reint, 5, Log::FrameBuf, "Reinterpret detected from %08x_%s to %08x_%s",888src->fb_address, GeBufferFormatToString(src->fb_format),889dst->fb_address, GeBufferFormatToString(dst->fb_format));890891pipeline = GetReinterpretPipeline(src->fb_format, dst->fb_format, &scaleFactorX);892dstX1 *= scaleFactorX;893dstX2 *= scaleFactorX;894895pass_name = reinterpretStrings[(int)src->fb_format][(int)dst->fb_format];896897gpuStats.numReinterpretCopies++;898}899900if (pipeline) {901tookActions = true;902// OK we have the pipeline, now just do the blit.903BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight,904dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, pass_name);905}906907if (scaleFactorX == 1.0f && dst->z_address == src->z_address && dst->z_stride == src->z_stride) {908// We should also copy the depth buffer in this case!909BlitFramebufferDepth(src, dst, true);910}911}912}913914if (currentRenderVfb_ && dst != currentRenderVfb_ && tookActions) {915// Will probably just change the name of the current renderpass, since one was started by the reinterpret itself.916draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "After Reinterpret");917}918919shaderManager_->DirtyLastShader();920textureCache_->ForgetLastTexture();921}922923Draw2DPipeline *FramebufferManagerCommon::GetReinterpretPipeline(GEBufferFormat from, GEBufferFormat to, float *scaleFactorX) {924if (from == to) {925*scaleFactorX = 1.0f;926return Get2DPipeline(DRAW2D_COPY_COLOR);927}928929if (IsBufferFormat16Bit(from) && !IsBufferFormat16Bit(to)) {930// We halve the X coordinates in the destination framebuffer.931// The shader will collect two pixels worth of input data and merge into one.932*scaleFactorX = 0.5f;933} else if (!IsBufferFormat16Bit(from) && IsBufferFormat16Bit(to)) {934// We double the X coordinates in the destination framebuffer.935// The shader will sample and depending on the X coordinate & 1, use the upper or lower bits.936*scaleFactorX = 2.0f;937} else {938*scaleFactorX = 1.0f;939}940941Draw2DPipeline *pipeline = reinterpretFromTo_[(int)from][(int)to];942if (!pipeline) {943pipeline = draw2D_.Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo {944return GenerateReinterpretFragmentShader(shaderWriter, from, to);945});946reinterpretFromTo_[(int)from][(int)to] = pipeline;947}948return pipeline;949}950951void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) {952// Notify the texture cache of both the color and depth buffers.953textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED);954if (v->fbo) {955v->fbo->Release();956v->fbo = nullptr;957}958959// Wipe some pointers960DiscardFramebufferCopy();961if (currentRenderVfb_ == v)962currentRenderVfb_ = nullptr;963if (displayFramebuf_ == v)964displayFramebuf_ = nullptr;965if (prevDisplayFramebuf_ == v)966prevDisplayFramebuf_ = nullptr;967if (prevPrevDisplayFramebuf_ == v)968prevPrevDisplayFramebuf_ = nullptr;969970delete v;971}972973void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst, bool allowSizeMismatch) {974_dbg_assert_(src && dst);975976_dbg_assert_(src != dst);977978// Check that the depth address is even the same before actually blitting.979bool matchingDepthBuffer = src->z_address == dst->z_address && src->z_stride != 0 && dst->z_stride != 0;980bool matchingSize = (src->width == dst->width || (src->width == 512 && dst->width == 480) || (src->width == 480 && dst->width == 512)) && src->height == dst->height;981if (!matchingDepthBuffer || (!matchingSize && !allowSizeMismatch)) {982return;983}984985// Copy depth value from the previously bound framebuffer to the current one.986bool hasNewerDepth = src->last_frame_depth_render != 0 && src->last_frame_depth_render >= dst->last_frame_depth_updated;987if (!src->fbo || !dst->fbo || !useBufferedRendering_ || !hasNewerDepth) {988// If depth wasn't updated, then we're at least "two degrees" away from the data.989// This is an optimization: it probably doesn't need to be copied in this case.990return;991}992993bool useCopy = draw_->GetDeviceCaps().framebufferSeparateDepthCopySupported || (!draw_->GetDeviceCaps().framebufferDepthBlitSupported && draw_->GetDeviceCaps().framebufferCopySupported);994bool useBlit = draw_->GetDeviceCaps().framebufferDepthBlitSupported;995996bool useRaster = draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported && draw_->GetDeviceCaps().textureDepthSupported;997998if (src->fbo->MultiSampleLevel() > 0 && dst->fbo->MultiSampleLevel() > 0) {999// If multisampling, we want to copy depth properly so we get all the samples, to avoid aliased edges.1000// Can be seen in the fire in Jeanne D'arc, for example.1001if (useRaster && useCopy) {1002useRaster = false;1003}1004}10051006int w = std::min(src->renderWidth, dst->renderWidth);1007int h = std::min(src->renderHeight, dst->renderHeight);10081009// 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.1010if (useRaster) {1011BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, dst->renderScaleFactor, Get2DPipeline(Draw2DShader::DRAW2D_COPY_DEPTH), "BlitDepthRaster");1012} else if (useCopy) {1013draw_->CopyFramebufferImage(src->fbo, 0, 0, 0, 0, dst->fbo, 0, 0, 0, 0, w, h, 1, Draw::FB_DEPTH_BIT, "CopyFramebufferDepth");1014RebindFramebuffer("After BlitFramebufferDepth");1015} else if (useBlit) {1016// We'll accept whether we get a separate depth blit or not...1017draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth");1018RebindFramebuffer("After BlitFramebufferDepth");1019}10201021draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);1022}10231024void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) {1025if (!useBufferedRendering_) {1026// Let's ignore rendering to targets that have not (yet) been displayed.1027gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1028} else if (currentRenderVfb_) {1029DownloadFramebufferOnSwitch(currentRenderVfb_);1030}10311032textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);10331034NotifyRenderFramebufferUpdated(vfb);1035}10361037void FramebufferManagerCommon::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb) {1038if (gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) {1039gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1040}1041if (gstate_c.curRTRenderWidth != vfb->renderWidth || gstate_c.curRTRenderHeight != vfb->renderHeight) {1042gstate_c.Dirty(DIRTY_PROJMATRIX);1043gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX);1044}1045}10461047void FramebufferManagerCommon::DownloadFramebufferOnSwitch(VirtualFramebuffer *vfb) {1048if (vfb && vfb->safeWidth > 0 && vfb->safeHeight > 0 && !(vfb->usageFlags & FB_USAGE_FIRST_FRAME_SAVED) && !vfb->memoryUpdated) {1049// Some games will draw to some memory once, and use it as a render-to-texture later.1050// To support this, we save the first frame to memory when we have a safe w/h.1051// Saving each frame would be slow.10521053// TODO: This type of download could be made async, for less stutter on framebuffer creation.1054if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && !PSP_CoreParameter().compat.flags().DisableFirstFrameReadback) {1055ReadFramebufferToMemory(vfb, 0, 0, vfb->safeWidth, vfb->safeHeight, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1056vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1057vfb->safeWidth = 0;1058vfb->safeHeight = 0;1059}1060}1061}10621063bool FramebufferManagerCommon::ShouldDownloadFramebufferColor(const VirtualFramebuffer *vfb) {1064// Dangan Ronpa hack1065return PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000;1066}10671068bool FramebufferManagerCommon::ShouldDownloadFramebufferDepth(const VirtualFramebuffer *vfb) {1069// Download depth buffer for Syphon Filter lens flares1070if (!PSP_CoreParameter().compat.flags().ReadbackDepth || GetSkipGPUReadbackMode() != SkipGPUReadbackMode::NO_SKIP) {1071return false;1072}1073return (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) != 0 && vfb->width >= 480 && vfb->height >= 272;1074}10751076void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) {1077if (prevVfb) {1078if (ShouldDownloadFramebufferColor(prevVfb) && !prevVfb->memoryUpdated) {1079ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RASTER_COLOR, Draw::ReadbackMode::OLD_DATA_OK);1080prevVfb->usageFlags = (prevVfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1081} else {1082DownloadFramebufferOnSwitch(prevVfb);1083}10841085if (ShouldDownloadFramebufferDepth(prevVfb)) {1086ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RasterChannel::RASTER_DEPTH, Draw::ReadbackMode::BLOCK);1087}1088}10891090textureCache_->ForgetLastTexture();1091shaderManager_->DirtyLastShader();10921093if (useBufferedRendering_) {1094if (vfb->fbo) {1095shaderManager_->DirtyLastShader();1096Draw::RPAction depthAction = Draw::RPAction::KEEP;1097float clearDepth = 0.0f;1098if (vfb->usageFlags & FB_USAGE_INVALIDATE_DEPTH) {1099depthAction = Draw::RPAction::CLEAR;1100clearDepth = GetDepthScaleFactors(gstate_c.UseFlags()).Offset();1101vfb->usageFlags &= ~FB_USAGE_INVALIDATE_DEPTH;1102}1103draw_->BindFramebufferAsRenderTarget(vfb->fbo, {Draw::RPAction::KEEP, depthAction, Draw::RPAction::KEEP, 0, clearDepth}, "FBSwitch");1104} else {1105// This should only happen very briefly when toggling useBufferedRendering_.1106ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);1107}1108} else {1109if (vfb->fbo) {1110// This should only happen very briefly when toggling useBufferedRendering_.1111textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_DESTROYED);1112vfb->fbo->Release();1113vfb->fbo = nullptr;1114}11151116// Let's ignore rendering to targets that have not (yet) been displayed.1117if (vfb->usageFlags & FB_USAGE_DISPLAYED_FRAMEBUFFER) {1118gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;1119} else {1120gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1121}1122}1123textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_UPDATED);11241125NotifyRenderFramebufferUpdated(vfb);1126}11271128void FramebufferManagerCommon::PerformWriteFormattedFromMemory(u32 addr, int size, int stride, GEBufferFormat fmt) {1129// Note: UpdateFromMemory() is still called later.1130// This is a special case where we have extra information prior to the invalidation,1131// because it's called from sceJpeg, sceMpeg, scePsmf etc.11321133// TODO: Could possibly be at an offset...1134// Also, stride needs better handling.1135VirtualFramebuffer *vfb = ResolveVFB(addr, stride, fmt);1136if (vfb) {1137// Let's count this as a "render". This will also force us to use the correct format.1138vfb->last_frame_render = gpuStats.numFlips;1139vfb->colorBindSeq = GetBindSeqCount();11401141if (vfb->fb_stride < stride) {1142INFO_LOG(Log::FrameBuf, "Changing stride for %08x from %d to %d", addr, vfb->fb_stride, stride);1143const int bpp = BufferFormatBytesPerPixel(fmt);1144ResizeFramebufFBO(vfb, stride, size / (bpp * stride));1145// Resizing may change the viewport/etc.1146gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1147vfb->fb_stride = stride;1148// This might be a bit wider than necessary, but we'll redetect on next render.1149vfb->width = stride;1150}1151}1152}11531154void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size) {1155// Take off the uncached flag from the address. Not to be confused with the start of VRAM.1156addr &= 0x3FFFFFFF;1157if (Memory::IsVRAMAddress(addr))1158addr &= 0x041FFFFF;1159// TODO: Could go through all FBOs, but probably not important?1160// TODO: Could also check for inner changes, but video is most important.1161// TODO: This shouldn't care if it's a display framebuf or not, should work exactly the same.1162bool isDisplayBuf = addr == CurrentDisplayFramebufAddr() || addr == PrevDisplayFramebufAddr();1163// TODO: Deleting the FBO is a heavy hammer solution, so let's only do it if it'd help.1164if (!Memory::IsValidAddress(displayFramebufPtr_))1165return;11661167for (size_t i = 0; i < vfbs_.size(); ++i) {1168VirtualFramebuffer *vfb = vfbs_[i];1169if (vfb->fb_address == addr) {1170FlushBeforeCopy();11711172if (useBufferedRendering_ && vfb->fbo) {1173GEBufferFormat fmt = vfb->fb_format;1174if (vfb->last_frame_render + 1 < gpuStats.numFlips && isDisplayBuf) {1175// If we're not rendering to it, format may be wrong. Use displayFormat_ instead.1176// TODO: This doesn't seem quite right anymore.1177fmt = displayFormat_;1178}1179DrawPixels(vfb, 0, 0, Memory::GetPointerUnchecked(addr), fmt, vfb->fb_stride, vfb->width, vfb->height, RASTER_COLOR, "UpdateFromMemory_DrawPixels");1180SetColorUpdated(vfb, gstate_c.skipDrawReason);1181} else {1182INFO_LOG(Log::FrameBuf, "Invalidating FBO for %08x (%dx%d %s)", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format));1183DestroyFramebuf(vfb);1184vfbs_.erase(vfbs_.begin() + i--);1185}1186}1187}11881189RebindFramebuffer("RebindFramebuffer - UpdateFromMemory");11901191// TODO: Necessary?1192gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);1193}11941195void FramebufferManagerCommon::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height, RasterChannel channel, const char *tag) {1196textureCache_->ForgetLastTexture();1197shaderManager_->DirtyLastShader();1198float u0 = 0.0f, u1 = 1.0f;1199float v0 = 0.0f, v1 = 1.0f;12001201DrawTextureFlags flags;1202if (useBufferedRendering_ && vfb && vfb->fbo) {1203if (channel == RASTER_DEPTH || PSP_CoreParameter().compat.flags().NearestFilteringOnFramebufferCreate) {1204flags = DRAWTEX_NEAREST;1205} else {1206flags = DRAWTEX_LINEAR;1207}1208draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag);1209SetViewport2D(0, 0, vfb->renderWidth, vfb->renderHeight);1210draw_->SetScissorRect(0, 0, vfb->renderWidth, vfb->renderHeight);1211} else {1212_dbg_assert_(channel == RASTER_COLOR);1213// We are drawing directly to the back buffer so need to flip.1214// Should more of this be handled by the presentation engine?1215if (needBackBufferYSwap_)1216std::swap(v0, v1);1217flags = g_Config.iDisplayFilter == SCALE_LINEAR ? DRAWTEX_LINEAR : DRAWTEX_NEAREST;1218flags = flags | DRAWTEX_TO_BACKBUFFER;1219FRect frame = GetScreenFrame(pixelWidth_, pixelHeight_);1220FRect rc;1221CalculateDisplayOutputRect(&rc, 480.0f, 272.0f, frame, ROTATION_LOCKED_HORIZONTAL);1222SetViewport2D(rc.x, rc.y, rc.w, rc.h);1223draw_->SetScissorRect(0, 0, pixelWidth_, pixelHeight_);1224}12251226if (channel == RASTER_DEPTH) {1227_dbg_assert_(srcPixelFormat == GE_FORMAT_DEPTH16);1228flags = flags | DRAWTEX_DEPTH;1229if (vfb)1230vfb->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;1231}12321233Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, width, height);1234if (pixelsTex) {1235draw_->BindTextures(0, 1, &pixelsTex, Draw::TextureBindFlags::VULKAN_BIND_ARRAY);12361237// TODO: Replace with draw2D_.Blit() directly.1238DrawActiveTexture(dstX, dstY, width, height,1239vfb ? vfb->bufferWidth : g_display.pixel_xres,1240vfb ? vfb->bufferHeight : g_display.pixel_yres,1241u0, v0, u1, v1, ROTATION_LOCKED_HORIZONTAL, flags);12421243draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);12441245gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);1246}1247}12481249bool FramebufferManagerCommon::BindFramebufferAsColorTexture(int stage, VirtualFramebuffer *framebuffer, int flags, int layer) {1250if (!framebuffer->fbo || !useBufferedRendering_) {1251draw_->BindTexture(stage, nullptr);1252gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1253return false;1254}12551256// currentRenderVfb_ will always be set when this is called, except from the GE debugger.1257// Let's just not bother with the copy in that case.1258bool skipCopy = !(flags & BINDFBCOLOR_MAY_COPY);12591260// Currently rendering to this framebuffer. Need to make a copy.1261if (!skipCopy && framebuffer == currentRenderVfb_) {1262// Self-texturing, need a copy currently (some backends can potentially support it though).1263WARN_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);1264// TODO: Maybe merge with bvfbs_? Not sure if those could be packing, and they're created at a different size.1265if (currentFramebufferCopy_ && (flags & BINDFBCOLOR_UNCACHED) == 0) {1266// We have a copy already that hasn't been invalidated, let's keep using it.1267draw_->BindFramebufferAsTexture(currentFramebufferCopy_, stage, Draw::FB_COLOR_BIT, layer);1268return true;1269}12701271Draw::Framebuffer *renderCopy = GetTempFBO(TempFBO::COPY, framebuffer->renderWidth, framebuffer->renderHeight);1272if (renderCopy) {1273VirtualFramebuffer copyInfo = *framebuffer;1274copyInfo.fbo = renderCopy;12751276bool partial = false;1277CopyFramebufferForColorTexture(©Info, framebuffer, flags, layer, &partial);1278RebindFramebuffer("After BindFramebufferAsColorTexture");1279draw_->BindFramebufferAsTexture(renderCopy, stage, Draw::FB_COLOR_BIT, layer);12801281// Only cache the copy if it wasn't a partial copy.1282// TODO: Improve on this.1283if (!partial && (flags & BINDFBCOLOR_UNCACHED) == 0) {1284currentFramebufferCopy_ = renderCopy;1285}1286gpuStats.numCopiesForSelfTex++;1287} else {1288// Failed to get temp FBO? Weird.1289draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::FB_COLOR_BIT, layer);1290}1291return true;1292} else if (framebuffer != currentRenderVfb_ || (flags & BINDFBCOLOR_FORCE_SELF) != 0) {1293draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::FB_COLOR_BIT, layer);1294return true;1295} else {1296// Here it's an error because for some reason skipCopy is true. That shouldn't really happen.1297ERROR_LOG_REPORT_ONCE(selfTextureFail, Log::G3D, "Attempting to texture from target (src=%08x / target=%08x / flags=%d)", framebuffer->fb_address, currentRenderVfb_->fb_address, flags);1298// To do this safely in Vulkan, we need to use input attachments.1299// Actually if the texture region and render regions don't overlap, this is safe, but we need1300// to transition to GENERAL image layout which will take some trickery.1301// Badness on D3D11 to bind the currently rendered-to framebuffer as a texture.1302draw_->BindTexture(stage, nullptr);1303gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1304return false;1305}1306}13071308void FramebufferManagerCommon::CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags, int layer, bool *partial) {1309int x = 0;1310int y = 0;1311int w = src->drawnWidth;1312int h = src->drawnHeight;13131314*partial = false;13151316// If max is not > min, we probably could not detect it. Skip.1317// See the vertex decoder, where this is updated.1318// TODO: We're currently not hitting this path in Dante. See #170321319if ((flags & BINDFBCOLOR_MAY_COPY_WITH_UV) == BINDFBCOLOR_MAY_COPY_WITH_UV && gstate_c.vertBounds.maxU > gstate_c.vertBounds.minU) {1320x = std::max(gstate_c.vertBounds.minU, (u16)0);1321y = std::max(gstate_c.vertBounds.minV, (u16)0);1322w = std::min(gstate_c.vertBounds.maxU, src->drawnWidth) - x;1323h = std::min(gstate_c.vertBounds.maxV, src->drawnHeight) - y;13241325// If we bound a framebuffer, apply the byte offset as pixels to the copy too.1326if (flags & BINDFBCOLOR_APPLY_TEX_OFFSET) {1327x += gstate_c.curTextureXOffset;1328y += gstate_c.curTextureYOffset;1329}13301331// We'll have to reapply these next time since we cropped to UV.1332gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);1333}13341335if (x < src->drawnWidth && y < src->drawnHeight && w > 0 && h > 0) {1336if (x != 0 || y != 0 || w < src->drawnWidth || h < src->drawnHeight) {1337*partial = true;1338}1339BlitFramebuffer(dst, x, y, src, x, y, w, h, 0, RASTER_COLOR, "CopyFBForColorTexture");1340}1341}13421343Draw::Texture *FramebufferManagerCommon::MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) {1344Draw::DataFormat depthFormat = Draw::DataFormat::UNDEFINED;13451346int bpp = BufferFormatBytesPerPixel(srcPixelFormat);1347int srcStrideInBytes = srcStride * bpp;1348int widthInBytes = width * bpp;13491350// Compute hash of contents.1351uint64_t imageHash;1352if (widthInBytes == srcStrideInBytes) {1353imageHash = XXH3_64bits(srcPixels, widthInBytes * height);1354} else {1355XXH3_state_t *hashState = XXH3_createState();1356XXH3_64bits_reset(hashState);1357for (int y = 0; y < height; y++) {1358XXH3_64bits_update(hashState, srcPixels + srcStrideInBytes * y, widthInBytes);1359}1360imageHash = XXH3_64bits_digest(hashState);1361XXH3_freeState(hashState);1362}13631364Draw::DataFormat texFormat = preferredPixelsFormat_;13651366if (srcPixelFormat == GE_FORMAT_DEPTH16) {1367if ((draw_->GetDataFormatSupport(Draw::DataFormat::R16_UNORM) & Draw::FMT_TEXTURE) != 0) {1368texFormat = Draw::DataFormat::R16_UNORM;1369} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R8_UNORM) & Draw::FMT_TEXTURE) != 0) {1370// This could be improved by using specific draw shaders to pack full precision in two channels.1371// However, not really worth the trouble until we find a game that requires it.1372texFormat = Draw::DataFormat::R8_UNORM;1373} else {1374// No usable single channel format. Can't be bothered.1375return nullptr;1376}1377} else if (srcPixelFormat == GE_FORMAT_565) {1378// Check for supported matching formats.1379// This mainly benefits the redundant copies in God of War on low-end platforms.1380if ((draw_->GetDataFormatSupport(Draw::DataFormat::B5G6R5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1381texFormat = Draw::DataFormat::B5G6R5_UNORM_PACK16;1382} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R5G6B5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1383texFormat = Draw::DataFormat::R5G6B5_UNORM_PACK16;1384}1385}13861387// TODO: We can just change the texture format and flip some bits around instead of this.1388// Could share code with the texture cache perhaps.1389auto generateTexture = [&](uint8_t *data, const uint8_t *initData, uint32_t w, uint32_t h, uint32_t d, uint32_t byteStride, uint32_t sliceByteStride) {1390for (int y = 0; y < height; y++) {1391const u16_le *src16 = (const u16_le *)srcPixels + srcStride * y;1392const u32_le *src32 = (const u32_le *)srcPixels + srcStride * y;1393u32 *dst = (u32 *)(data + byteStride * y);1394u16 *dst16 = (u16 *)(data + byteStride * y);1395u8 *dst8 = (u8 *)(data + byteStride * y);1396switch (srcPixelFormat) {1397case GE_FORMAT_565:1398if (texFormat == Draw::DataFormat::B5G6R5_UNORM_PACK16) {1399memcpy(dst16, src16, w * sizeof(uint16_t));1400} else if (texFormat == Draw::DataFormat::R5G6B5_UNORM_PACK16) {1401ConvertRGB565ToBGR565(dst16, src16, width); // Fast!1402} else if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM) {1403ConvertRGB565ToBGRA8888(dst, src16, width);1404} else {1405ConvertRGB565ToRGBA8888(dst, src16, width);1406}1407break;14081409case GE_FORMAT_5551:1410if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1411ConvertRGBA5551ToBGRA8888(dst, src16, width);1412else1413ConvertRGBA5551ToRGBA8888(dst, src16, width);1414break;14151416case GE_FORMAT_4444:1417if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1418ConvertRGBA4444ToBGRA8888(dst, src16, width);1419else1420ConvertRGBA4444ToRGBA8888(dst, src16, width);1421break;14221423case GE_FORMAT_8888:1424if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1425ConvertRGBA8888ToBGRA8888(dst, src32, width);1426// This means use original pointer as-is. May avoid or optimize a copy.1427else if (srcStride == width)1428return false;1429else1430memcpy(dst, src32, width * 4);1431break;14321433case GE_FORMAT_DEPTH16:1434// TODO: Must take the depth range into account, unless it's already 0-1.1435// TODO: Depending on the color buffer format used with this depth buffer, we need1436// to do one of two different swizzle operations. However, for the only use of this so far,1437// the Burnout lens flare trickery, swizzle doesn't matter since it's just a 0, 7fff, 0, 7fff pattern1438// which comes out the same.1439if (texFormat == Draw::DataFormat::R16_UNORM) {1440// We just use this format straight.1441memcpy(dst16, src16, w * 2);1442} else if (texFormat == Draw::DataFormat::R8_UNORM) {1443// We fall back to R8_UNORM. Precision is enough for most cases of depth clearing and initialization we've seen,1444// but hardly ideal.1445for (int i = 0; i < width; i++) {1446dst8[i] = src16[i] >> 8;1447}1448}1449break;14501451case GE_FORMAT_INVALID:1452case GE_FORMAT_CLUT8:1453// Bad1454break;1455}1456}1457return true;1458};14591460int frameNumber = draw_->GetFrameCount();14611462// First look for an exact match (including contents hash) that we can re-use.1463for (auto &iter : drawPixelsCache_) {1464if (iter.contentsHash == imageHash && iter.tex->Width() == width && iter.tex->Height() == height && iter.tex->Format() == texFormat) {1465iter.frameNumber = frameNumber;1466gpuStats.numCachedUploads++;1467return iter.tex;1468}1469}14701471// Then, look for an alternative one that's not been used recently that we can overwrite.1472for (auto &iter : drawPixelsCache_) {1473if (iter.frameNumber >= frameNumber - 3 || iter.tex->Width() != width || iter.tex->Height() != height || iter.tex->Format() != texFormat) {1474continue;1475}14761477// OK, current one seems good, let's use it (and mark it used).1478gpuStats.numUploads++;1479draw_->UpdateTextureLevels(iter.tex, &srcPixels, generateTexture, 1);1480// NOTE: numFlips is no good - this is called every frame when paused sometimes!1481iter.frameNumber = frameNumber;1482// We need to update the hash for future matching.1483iter.contentsHash = imageHash;1484return iter.tex;1485}14861487// Note: For depth, we create an R16_UNORM texture, that'll be just fine for uploading depth through a shader,1488// and likely more efficient.1489Draw::TextureDesc desc{1490Draw::TextureType::LINEAR2D,1491texFormat,1492width,1493height,14941,14951,1496false,1497Draw::TextureSwizzle::DEFAULT,1498"DrawPixels",1499{ (uint8_t *)srcPixels },1500generateTexture,1501};15021503// Hot Shots Golf (#12355) does tons of these in a frame in some situations! So creating textures1504// better be fast. So does God of War, a lot of the time, a bit unclear what it's doing.1505Draw::Texture *tex = draw_->CreateTexture(desc);1506if (!tex) {1507ERROR_LOG(Log::G3D, "Failed to create DrawPixels texture");1508}1509// We don't need to count here, already counted by numUploads by the caller.15101511// INFO_LOG(Log::G3D, "Creating drawPixelsCache texture: %dx%d", tex->Width(), tex->Height());15121513DrawPixelsEntry entry{ tex, imageHash, frameNumber };1514drawPixelsCache_.push_back(entry);1515gpuStats.numUploads++;1516return tex;1517}15181519void FramebufferManagerCommon::DrawFramebufferToOutput(const u8 *srcPixels, int srcStride, GEBufferFormat srcPixelFormat) {1520textureCache_->ForgetLastTexture();1521shaderManager_->DirtyLastShader();15221523float u0 = 0.0f, u1 = 480.0f / 512.0f;1524float v0 = 0.0f, v1 = 1.0f;1525Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, 512, 272);1526if (!pixelsTex)1527return;15281529int uvRotation = useBufferedRendering_ ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1530OutputFlags flags = g_Config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1531if (needBackBufferYSwap_) {1532flags |= OutputFlags::BACKBUFFER_FLIPPED;1533}1534// CopyToOutput reverses these, probably to match "up".1535if (GetGPUBackend() == GPUBackend::DIRECT3D9 || GetGPUBackend() == GPUBackend::DIRECT3D11) {1536flags |= OutputFlags::POSITION_FLIPPED;1537}15381539presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1540presentation_->SourceTexture(pixelsTex, 512, 272);1541presentation_->CopyToOutput(flags, uvRotation, u0, v0, u1, v1);15421543// PresentationCommon sets all kinds of state, we can't rely on anything.1544gstate_c.Dirty(DIRTY_ALL);15451546DiscardFramebufferCopy();1547currentRenderVfb_ = nullptr;1548}15491550void FramebufferManagerCommon::SetViewport2D(int x, int y, int w, int h) {1551Draw::Viewport viewport{ (float)x, (float)y, (float)w, (float)h, 0.0f, 1.0f };1552draw_->SetViewport(viewport);1553}15541555void FramebufferManagerCommon::CopyDisplayToOutput(bool reallyDirty) {1556DownloadFramebufferOnSwitch(currentRenderVfb_);1557shaderManager_->DirtyLastShader();15581559if (displayFramebufPtr_ == 0) {1560if (GetUIState() != UISTATE_PAUSEMENU) {1561if (Core_IsStepping())1562VERBOSE_LOG(Log::FrameBuf, "Display disabled, displaying only black");1563else1564DEBUG_LOG(Log::FrameBuf, "Display disabled, displaying only black");1565}1566// No framebuffer to display! Clear to black.1567if (useBufferedRendering_) {1568draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput");1569presentation_->NotifyPresent();1570}1571gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1572return;1573}15741575u32 offsetX = 0;1576u32 offsetY = 0;15771578// If it's not really dirty, we're probably frameskipping. Use the last working one.1579u32 fbaddr = reallyDirty ? displayFramebufPtr_ : prevDisplayFramebufPtr_;1580prevDisplayFramebufPtr_ = fbaddr;15811582VirtualFramebuffer *vfb = ResolveVFB(fbaddr, displayStride_, displayFormat_);1583if (!vfb) {1584// Let's search for a framebuf within this range. Note that we also look for1585// "framebuffers" sitting in RAM (created from block transfer or similar) so we only take off the kernel1586// and uncached bits of the address when comparing.1587const u32 addr = fbaddr;1588for (auto v : vfbs_) {1589const u32 v_addr = v->fb_address;1590const u32 v_size = v->BufferByteSize(RASTER_COLOR);15911592if (v->fb_format != displayFormat_ || v->fb_stride != displayStride_) {1593// Displaying a buffer of the wrong format or stride is nonsense, ignore it.1594continue;1595}15961597if (addr >= v_addr && addr < v_addr + v_size) {1598const u32 dstBpp = BufferFormatBytesPerPixel(v->fb_format);1599const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride;1600const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride;1601// We have enough space there for the display, right?1602if (v_offsetX + 480 > (u32)v->fb_stride || v->bufferHeight < v_offsetY + 272) {1603continue;1604}1605// Check for the closest one.1606if (offsetY == 0 || offsetY > v_offsetY) {1607offsetX = v_offsetX;1608offsetY = v_offsetY;1609vfb = v;1610}1611}1612}16131614if (vfb) {1615// Okay, we found one above.1616// Log should be "Displaying from framebuf" but not worth changing the report.1617INFO_LOG_REPORT_ONCE(displayoffset, Log::FrameBuf, "Rendering from framebuf with offset %08x -> %08x+%dx%d", addr, vfb->fb_address, offsetX, offsetY);1618}1619}16201621// Reject too-tiny framebuffers to display (Godfather, see issue #16915).1622if (vfb && vfb->height < 64) {1623vfb = nullptr;1624}16251626if (!vfb) {1627if (Memory::IsValidAddress(fbaddr)) {1628// The game is displaying something directly from RAM. In GTA, it's decoded video.1629DrawFramebufferToOutput(Memory::GetPointerUnchecked(fbaddr), displayStride_, displayFormat_);1630return;1631} else {1632DEBUG_LOG(Log::FrameBuf, "Found no FBO to display! displayFBPtr = %08x", fbaddr);1633// No framebuffer to display! Clear to black.1634if (useBufferedRendering_) {1635// Bind and clear the backbuffer. This should be the first time during the frame that it's bound.1636draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput_NoFBO");1637}1638gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1639return;1640}1641}16421643vfb->usageFlags |= FB_USAGE_DISPLAYED_FRAMEBUFFER;1644vfb->last_frame_displayed = gpuStats.numFlips;1645vfb->dirtyAfterDisplay = false;1646vfb->reallyDirtyAfterDisplay = false;16471648if (prevDisplayFramebuf_ != displayFramebuf_) {1649prevPrevDisplayFramebuf_ = prevDisplayFramebuf_;1650}1651if (displayFramebuf_ != vfb) {1652prevDisplayFramebuf_ = displayFramebuf_;1653}1654displayFramebuf_ = vfb;16551656if (vfb->fbo) {1657if (GetUIState() != UISTATE_PAUSEMENU) {1658if (Core_IsStepping())1659VERBOSE_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1660else1661DEBUG_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1662}16631664float u0 = offsetX / (float)vfb->bufferWidth;1665float v0 = offsetY / (float)vfb->bufferHeight;1666float u1 = (480.0f + offsetX) / (float)vfb->bufferWidth;1667float v1 = (272.0f + offsetY) / (float)vfb->bufferHeight;16681669//clip the VR framebuffer to keep the aspect ratio1670if (IsVREnabled() && !IsFlatVRGame() && !IsGameVRScene()) {1671float aspect = 272.0f / 480.0f * (IsImmersiveVRMode() ? 2.0f : 1.0f);1672float clipY = 272.0f * (1.0f - aspect) / 2.0f;1673v0 = (clipY + offsetY) / (float)vfb->bufferHeight;1674v1 = (272.0f - clipY + offsetY) / (float)vfb->bufferHeight;16751676//zoom inside1677float zoom = IsImmersiveVRMode() ? 0.4f : 0.1f;1678u0 += zoom / aspect;1679u1 -= zoom / aspect;1680v0 += zoom;1681v1 -= zoom;1682}16831684textureCache_->ForgetLastTexture();16851686int uvRotation = useBufferedRendering_ ? g_Config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1687OutputFlags flags = g_Config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1688if (needBackBufferYSwap_) {1689flags |= OutputFlags::BACKBUFFER_FLIPPED;1690}1691// DrawActiveTexture reverses these, probably to match "up".1692if (GetGPUBackend() == GPUBackend::DIRECT3D9 || GetGPUBackend() == GPUBackend::DIRECT3D11) {1693flags |= OutputFlags::POSITION_FLIPPED;1694}16951696int actualWidth = (vfb->bufferWidth * vfb->renderWidth) / vfb->width;1697int actualHeight = (vfb->bufferHeight * vfb->renderHeight) / vfb->height;1698presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1699presentation_->SourceFramebuffer(vfb->fbo, actualWidth, actualHeight);1700presentation_->CopyToOutput(flags, uvRotation, u0, v0, u1, v1);1701} else if (useBufferedRendering_) {1702WARN_LOG(Log::FrameBuf, "Current VFB lacks an FBO: %08x", vfb->fb_address);1703}17041705// This may get called mid-draw if the game uses an immediate flip.1706// PresentationCommon sets all kinds of state, we can't rely on anything.1707gstate_c.Dirty(DIRTY_ALL);1708DiscardFramebufferCopy();1709currentRenderVfb_ = nullptr;1710}17111712void FramebufferManagerCommon::DecimateFBOs() {1713DiscardFramebufferCopy();1714currentRenderVfb_ = nullptr;17151716for (auto iter : fbosToDelete_) {1717iter->Release();1718}1719fbosToDelete_.clear();17201721for (size_t i = 0; i < vfbs_.size(); ++i) {1722VirtualFramebuffer *vfb = vfbs_[i];1723int age = frameLastFramebufUsed_ - std::max(vfb->last_frame_render, vfb->last_frame_used);17241725if (ShouldDownloadFramebufferColor(vfb) && age == 0 && !vfb->memoryUpdated) {1726ReadFramebufferToMemory(vfb, 0, 0, vfb->width, vfb->height, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1727vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1728}17291730// Let's also "decimate" the usageFlags.1731UpdateFramebufUsage(vfb);17321733if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) {1734if (age > FBO_OLD_AGE) {1735INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%ix%i %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1736DestroyFramebuf(vfb);1737vfbs_.erase(vfbs_.begin() + i--);1738}1739}1740}17411742for (auto it = tempFBOs_.begin(); it != tempFBOs_.end(); ) {1743int age = frameLastFramebufUsed_ - it->second.last_frame_used;1744if (age > FBO_OLD_AGE) {1745it->second.fbo->Release();1746it = tempFBOs_.erase(it);1747} else {1748++it;1749}1750}17511752// Do the same for ReadFramebuffersToMemory's VFBs1753for (size_t i = 0; i < bvfbs_.size(); ++i) {1754VirtualFramebuffer *vfb = bvfbs_[i];1755int age = frameLastFramebufUsed_ - vfb->last_frame_render;1756if (age > FBO_OLD_AGE) {1757INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%dx%d %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1758DestroyFramebuf(vfb);1759bvfbs_.erase(bvfbs_.begin() + i--);1760}1761}17621763// And DrawPixels cached textures.17641765for (auto it = drawPixelsCache_.begin(); it != drawPixelsCache_.end(); ) {1766int age = draw_->GetFrameCount() - it->frameNumber;1767if (age > 10) {1768// INFO_LOG(Log::G3D, "Releasing drawPixelsCache texture: %dx%d", it->tex->Width(), it->tex->Height());1769it->tex->Release();1770it->tex = nullptr;1771it = drawPixelsCache_.erase(it);1772} else {1773++it;1774}1775}1776}17771778// Requires width/height to be set already.1779void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, int h, bool force, bool skipCopy) {1780_dbg_assert_(w > 0);1781_dbg_assert_(h > 0);1782VirtualFramebuffer old = *vfb;17831784int oldWidth = vfb->bufferWidth;1785int oldHeight = vfb->bufferHeight;17861787if (force) {1788vfb->bufferWidth = w;1789vfb->bufferHeight = h;1790} else {1791if (vfb->bufferWidth >= w && vfb->bufferHeight >= h) {1792return;1793}17941795// In case it gets thin and wide, don't resize down either side.1796vfb->bufferWidth = std::max((int)vfb->bufferWidth, w);1797vfb->bufferHeight = std::max((int)vfb->bufferHeight, h);1798}17991800bool force1x = false;1801switch (bloomHack_) {1802case 1:1803force1x = vfb->bufferWidth <= 128 || vfb->bufferHeight <= 64;1804break;1805case 2:1806force1x = vfb->bufferWidth <= 256 || vfb->bufferHeight <= 128;1807break;1808case 3:1809force1x = vfb->bufferWidth < 480 || vfb->bufferWidth > 800 || vfb->bufferHeight < 272; // GOW uses 864x2721810break;1811}18121813if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {1814force1x = false;1815}1816if (PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000) {1817force1x = true;1818}18191820if (force1x && g_Config.iInternalResolution != 1) {1821vfb->renderScaleFactor = 1;1822vfb->renderWidth = vfb->bufferWidth;1823vfb->renderHeight = vfb->bufferHeight;1824} else {1825vfb->renderScaleFactor = renderScaleFactor_;1826vfb->renderWidth = (u16)(vfb->bufferWidth * renderScaleFactor_);1827vfb->renderHeight = (u16)(vfb->bufferHeight * renderScaleFactor_);1828}18291830bool creating = old.bufferWidth == 0;1831if (creating) {1832WARN_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);1833} else {1834WARN_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);1835}18361837// During hardware rendering, we always render at full color depth even if the game wouldn't on real hardware.1838// It's not worth the trouble trying to support lower bit-depth rendering, just1839// more cases to test that nobody will ever use.18401841textureCache_->ForgetLastTexture();18421843if (!useBufferedRendering_) {1844if (vfb->fbo) {1845vfb->fbo->Release();1846vfb->fbo = nullptr;1847}1848return;1849}1850if (!old.fbo && vfb->last_frame_failed != 0 && vfb->last_frame_failed - gpuStats.numFlips < 63) {1851// Don't constantly retry FBOs which failed to create.1852return;1853}18541855shaderManager_->DirtyLastShader();1856char tag[128];1857size_t len = FormatFramebufferName(vfb, tag, sizeof(tag));18581859vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), msaaLevel_, true, tag });1860if (Memory::IsVRAMAddress(vfb->fb_address) && vfb->fb_stride != 0) {1861NotifyMemInfo(MemBlockFlags::ALLOC, vfb->fb_address, vfb->BufferByteSize(RASTER_COLOR), tag, len);1862}1863if (Memory::IsVRAMAddress(vfb->z_address) && vfb->z_stride != 0) {1864char buf[128];1865size_t len = snprintf(buf, sizeof(buf), "Z_%s", tag);1866NotifyMemInfo(MemBlockFlags::ALLOC, vfb->z_address, vfb->z_stride * vfb->height * sizeof(uint16_t), buf, len);1867}1868if (old.fbo) {1869INFO_LOG(Log::FrameBuf, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->fb_format));1870if (vfb->fbo) {1871draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1872if (!skipCopy) {1873BlitFramebuffer(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");1874}1875if (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) {1876BlitFramebuffer(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");1877}1878}1879fbosToDelete_.push_back(old.fbo);1880draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "ResizeFramebufFBO");1881} else {1882draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1883}1884DiscardFramebufferCopy();1885currentRenderVfb_ = vfb;18861887if (!vfb->fbo) {1888ERROR_LOG(Log::FrameBuf, "Error creating FBO during resize! %dx%d", vfb->renderWidth, vfb->renderHeight);1889vfb->last_frame_failed = gpuStats.numFlips;1890}1891}18921893struct CopyCandidate {1894VirtualFramebuffer *vfb = nullptr;1895int y;1896int h;18971898std::string ToString(RasterChannel channel) const {1899return StringFromFormat("%08x %s %dx%d y=%d h=%d", vfb->Address(channel), GeBufferFormatToString(vfb->Format(channel)), vfb->width, vfb->height, y, h);1900}1901};19021903static const CopyCandidate *GetBestCopyCandidate(const TinySet<CopyCandidate, 4> &candidates, uint32_t basePtr, RasterChannel channel) {1904const CopyCandidate *best = nullptr;19051906// Pick the "best" candidate by comparing to the old best using heuristics.1907for (size_t i = 0; i < candidates.size(); i++) {1908const CopyCandidate *candidate = &candidates[i];19091910bool better = !best;1911if (!better) {1912// Heuristics determined from the old algorithm, that we might want to keep:1913// * Lower yOffsets are prioritized.1914// * Bindseq1915better = candidate->y < best->y;1916if (!better) {1917better = candidate->vfb->BindSeq(channel) > best->vfb->BindSeq(channel);1918}1919}19201921if (better) {1922best = candidate;1923}1924}1925return best;1926}19271928// This is called from detected memcopies and framebuffer initialization from VRAM. Not block transfers.1929// Also with specialized flags from some replacement functions. Only those will currently request depth copies!1930// NOTE: This is very tricky because there's no information about color depth here, so we'll have to make guesses1931// about what underlying framebuffer is the most likely to be the relevant ones. For src, we can probably prioritize recent1932// ones. For dst, less clear.1933bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, GPUCopyFlag flags, u32 skipDrawReason) {1934if (size == 0) {1935return false;1936}19371938dst &= 0x3FFFFFFF;1939src &= 0x3FFFFFFF;19401941if (Memory::IsVRAMAddress(dst))1942dst &= 0x041FFFFF;1943if (Memory::IsVRAMAddress(src))1944src &= 0x041FFFFF;19451946// TODO: Merge the below into FindTransferFramebuffer.1947// Or at least this should be like the other ones, gathering possible candidates1948// with the ability to list them out for debugging.19491950bool ignoreDstBuffer = flags & GPUCopyFlag::FORCE_DST_MATCH_MEM;1951bool ignoreSrcBuffer = flags & (GPUCopyFlag::FORCE_SRC_MATCH_MEM | GPUCopyFlag::MEMSET);19521953// TODO: In the future we should probably check both channels. Currently depth is only on request.1954RasterChannel channel = (flags & GPUCopyFlag::DEPTH_REQUESTED) ? RASTER_DEPTH : RASTER_COLOR;19551956TinySet<CopyCandidate, 4> srcCandidates;1957TinySet<CopyCandidate, 4> dstCandidates;19581959// TODO: These two loops should be merged into one utility function, similar to what's done with rectangle copies.19601961// First find candidates for the source.1962// We only look at the color channel for now.1963for (auto vfb : vfbs_) {1964if (vfb->fb_stride == 0 || ignoreSrcBuffer) {1965continue;1966}19671968// We only remove the kernel and uncached bits when comparing.1969const u32 vfb_address = vfb->Address(channel);1970const u32 vfb_size = vfb->BufferByteSize(channel);1971const u32 vfb_byteStride = vfb->BufferByteStride(channel);1972const int vfb_byteWidth = vfb->BufferByteWidth(channel);19731974CopyCandidate srcCandidate;1975srcCandidate.vfb = vfb;19761977// Special path for depth for now.1978if (channel == RASTER_DEPTH) {1979if (src == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {1980srcCandidate.y = 0;1981srcCandidate.h = vfb->height;1982srcCandidates.push_back(srcCandidate);1983}1984continue;1985}19861987if (src >= vfb_address && (src + size <= vfb_address + vfb_size || src == vfb_address)) {1988// Heuristic originally from dest below, but just as valid looking for the source.1989// Fixes a misdetection in Brothers in Arms: D-Day, issue #18512.1990if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {1991// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM1992// that can be displayed from, or another matching buffer with the right format if rendering is going on.1993// If we had scoring here, we should strongly penalize this target instead of ignoring it.1994WARN_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);1995continue;1996}19971998if ((u32)size > vfb_size + 0x1000 && vfb->fb_format != GE_FORMAT_8888 && vfb->last_frame_render < gpuStats.numFlips) {1999// Seems likely we are looking at a potential copy of 32-bit pixels (like video) to an old 16-bit buffer,2000// which is very likely simply the wrong target, so skip it. See issue #17740 where this happens in Naruto Ultimate Ninja Heroes 2.2001// Probably no point to give it a bad score and let it pass to sorting, as we're pretty sure here.2002WARN_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));2003continue;2004}20052006const u32 offset = src - vfb_address;2007const u32 yOffset = offset / vfb_byteStride;2008if ((offset % vfb_byteStride) == 0 && (size == vfb_byteWidth || (size % vfb_byteStride) == 0)) {2009srcCandidate.y = yOffset;2010srcCandidate.h = size == vfb_byteWidth ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2011} else if ((offset % vfb_byteStride) == 0 && size == vfb->fb_stride) {2012// Valkyrie Profile reads 512 bytes at a time, rather than 2048. So, let's whitelist fb_stride also.2013srcCandidate.y = yOffset;2014srcCandidate.h = 1;2015} else if (yOffset == 0 && (vfb->usageFlags & FB_USAGE_CLUT)) {2016// Okay, last try - it might be a clut.2017srcCandidate.y = yOffset;2018srcCandidate.h = 1;2019} else {2020continue;2021}2022srcCandidates.push_back(srcCandidate);2023}2024}20252026for (auto vfb : vfbs_) {2027if (vfb->fb_stride == 0 || ignoreDstBuffer) {2028continue;2029}20302031// We only remove the kernel and uncached bits when comparing.2032const u32 vfb_address = vfb->Address(channel);2033const u32 vfb_size = vfb->BufferByteSize(channel);2034const u32 vfb_byteStride = vfb->BufferByteStride(channel);2035const int vfb_byteWidth = vfb->BufferByteWidth(channel);20362037// Heuristic to try to prevent potential glitches with video playback.2038if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {2039// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM2040// that can be displayed from, or another matching buffer with the right format if rendering is going on.2041// If we had scoring here, we should strongly penalize this target instead of ignoring it.2042WARN_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);2043continue;2044}20452046CopyCandidate dstCandidate;2047dstCandidate.vfb = vfb;20482049// Special path for depth for now.2050if (channel == RASTER_DEPTH) {2051// Let's assume exact matches only for simplicity.2052if (dst == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {2053dstCandidate.y = 0;2054dstCandidate.h = vfb->height;2055dstCandidates.push_back(dstCandidate);2056}2057continue;2058}20592060if (!ignoreDstBuffer && dst >= vfb_address && (dst + size <= vfb_address + vfb_size || dst == vfb_address)) {2061const u32 offset = dst - vfb_address;2062const u32 yOffset = offset / vfb_byteStride;2063if ((offset % vfb_byteStride) == 0 && (size == vfb_byteWidth || (size % vfb_byteStride) == 0)) {2064dstCandidate.y = yOffset;2065dstCandidate.h = (size == vfb_byteWidth) ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2066dstCandidates.push_back(dstCandidate);2067}2068}2069}20702071// For now fill in these old variables from the candidates to reduce the initial diff.2072VirtualFramebuffer *dstBuffer = nullptr;2073VirtualFramebuffer *srcBuffer = nullptr;2074int srcY;2075int srcH;2076int dstY;2077int dstH;20782079const CopyCandidate *bestSrc = GetBestCopyCandidate(srcCandidates, src, channel);2080if (bestSrc) {2081srcBuffer = bestSrc->vfb;2082srcY = bestSrc->y;2083srcH = bestSrc->h;2084}2085const CopyCandidate *bestDst = GetBestCopyCandidate(dstCandidates, dst, channel);2086if (bestDst) {2087dstBuffer = bestDst->vfb;2088dstY = bestDst->y;2089dstH = bestDst->h;2090}20912092if (srcCandidates.size() > 1) {2093if (Reporting::ShouldLogNTimes("mulblock", 5)) {2094std::string log;2095for (size_t i = 0; i < srcCandidates.size(); i++) {2096log += " - " + srcCandidates[i].ToString(channel);2097if (bestSrc && srcCandidates[i].vfb == bestSrc->vfb) {2098log += " * \n";2099} else {2100log += "\n";2101}2102}2103WARN_LOG(Log::FrameBuf, "Copy: Multiple src vfb candidates for (src: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2104}2105}21062107if (dstCandidates.size() > 1) {2108if (Reporting::ShouldLogNTimes("mulblock", 5)) {2109std::string log;2110for (size_t i = 0; i < dstCandidates.size(); i++) {2111log += " - " + dstCandidates[i].ToString(channel);2112if (bestDst && dstCandidates[i].vfb == bestDst->vfb) {2113log += " * \n";2114} else {2115log += "\n";2116}2117}2118WARN_LOG(Log::FrameBuf, "Copy: Multiple dst vfb candidates for (dst: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2119}2120}21212122if (!useBufferedRendering_) {2123// If we're copying into a recently used display buf, it's probably destined for the screen.2124if (channel == RASTER_DEPTH || srcBuffer || (dstBuffer != displayFramebuf_ && dstBuffer != prevDisplayFramebuf_)) {2125return false;2126}2127}21282129if (!dstBuffer && srcBuffer && channel != RASTER_DEPTH) {2130// Note - if we're here, we're in a memcpy, not a block transfer. Not allowing IntraVRAMBlockTransferAllowCreateFB.2131// Technically, that makes BlockTransferAllowCreateFB a bit of a misnomer.2132bool allowCreateFB = (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB || GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE);2133if (allowCreateFB && !(flags & GPUCopyFlag::DISALLOW_CREATE_VFB)) {2134dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->fb_format);2135dstY = 0;2136}2137}2138if (dstBuffer) {2139dstBuffer->last_frame_used = gpuStats.numFlips;2140if (channel == RASTER_DEPTH && !srcBuffer)2141dstBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;2142}2143if (srcBuffer && channel == RASTER_DEPTH && !dstBuffer)2144srcBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;21452146if (dstBuffer && srcBuffer) {2147if (srcBuffer == dstBuffer) {2148WARN_LOG_ONCE(dstsrccpy, Log::FrameBuf, "Intra-buffer memcpy (not supported) %08x -> %08x (size: %x)", src, dst, size);2149} else {2150WARN_LOG_ONCE(dstnotsrccpy, Log::FrameBuf, "Inter-buffer memcpy %08x -> %08x (size: %x)", src, dst, size);2151// Just do the blit!2152BlitFramebuffer(dstBuffer, 0, dstY, srcBuffer, 0, srcY, srcBuffer->width, srcH, 0, channel, "Blit_InterBufferMemcpy");2153SetColorUpdated(dstBuffer, skipDrawReason);2154RebindFramebuffer("RebindFramebuffer - Inter-buffer memcpy");2155}2156return false;2157} else if (dstBuffer) {2158if (flags & GPUCopyFlag::MEMSET) {2159gpuStats.numClears++;2160}2161WARN_LOG_N_TIMES(btucpy, 5, Log::FrameBuf, "Memcpy fbo upload %08x -> %08x (size: %x)", src, dst, size);2162FlushBeforeCopy();21632164// 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.2165// We could collect these in a buffer and flush on the next draw, or something like that, to avoid that. The line copies cause2166// awkward visual artefacts.2167const u8 *srcBase = Memory::GetPointerUnchecked(src);2168GEBufferFormat srcFormat = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : dstBuffer->fb_format;2169int srcStride = channel == RASTER_DEPTH ? dstBuffer->z_stride : dstBuffer->fb_stride;2170DrawPixels(dstBuffer, 0, dstY, srcBase, srcFormat, srcStride, dstBuffer->width, dstH, channel, "MemcpyFboUpload_DrawPixels");2171SetColorUpdated(dstBuffer, skipDrawReason);2172RebindFramebuffer("RebindFramebuffer - Memcpy fbo upload");2173// This is a memcpy, let's still copy just in case.2174return false;2175} else if (srcBuffer) {2176WARN_LOG_N_TIMES(btdcpy, 5, Log::FrameBuf, "Memcpy fbo download %08x -> %08x", src, dst);2177FlushBeforeCopy();2178// TODO: In Hot Shots Golf, check if we can do a readback to a framebuffer here.2179// Again we have the problem though that it's doing a lot of small copies here, one for each line.2180if (srcH == 0 || srcY + srcH > srcBuffer->bufferHeight) {2181WARN_LOG_ONCE(btdcpyheight, Log::FrameBuf, "Memcpy fbo download %08x -> %08x skipped, %d+%d is taller than %d", src, dst, srcY, srcH, srcBuffer->bufferHeight);2182} else if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && (!srcBuffer->memoryUpdated || channel == RASTER_DEPTH)) {2183Draw::ReadbackMode readbackMode = Draw::ReadbackMode::BLOCK;2184if (PSP_CoreParameter().compat.flags().AllowDelayedReadbacks) {2185readbackMode = Draw::ReadbackMode::OLD_DATA_OK;2186}2187ReadFramebufferToMemory(srcBuffer, 0, srcY, srcBuffer->width, srcH, channel, readbackMode);2188srcBuffer->usageFlags = (srcBuffer->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2189}2190return false;2191} else {2192return false;2193}2194}21952196std::string BlockTransferRect::ToString() const {2197int bpp = BufferFormatBytesPerPixel(channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : vfb->fb_format);2198return 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);2199}22002201// This is used when looking for framebuffers for a block transfer.2202// The only known game to block transfer depth buffers is Iron Man, see #16530, so2203// we have a compat flag and pretty limited functionality for that.2204bool FramebufferManagerCommon::FindTransferFramebuffer(u32 basePtr, int stride_pixels, int x_pixels, int y, int w_pixels, int h, int bpp, bool destination, BlockTransferRect *rect) {2205basePtr &= 0x3FFFFFFF;2206if (Memory::IsVRAMAddress(basePtr))2207basePtr &= 0x041FFFFF;2208rect->vfb = nullptr;22092210if (!stride_pixels) {2211WARN_LOG(Log::FrameBuf, "Zero stride in FindTransferFrameBuffer, ignoring");2212return false;2213}22142215const u32 byteStride = stride_pixels * bpp;2216int x_bytes = x_pixels * bpp;2217int w_bytes = w_pixels * bpp;22182219TinySet<BlockTransferRect, 4> candidates;22202221// We work entirely in bytes when we do the matching, because games don't consistently use bpps that match2222// that of their buffers. Then after matching we try to map the copy to the simplest operation that does2223// what we need.22242225// We are only looking at color for now, have not found any block transfers of depth data (although it's plausible).22262227for (auto vfb : vfbs_) {2228BlockTransferRect candidate{ vfb, RASTER_COLOR };22292230// Two cases so far of games depending on depth copies: Iron Man in issue #16530 (buffer->buffer)2231// and also #17878 where a game does ram->buffer to an auto-swizzling (|0x600000) address,2232// to initialize Z with a pre-rendered depth buffer.2233if (vfb->z_address == basePtr && vfb->BufferByteStride(RASTER_DEPTH) == byteStride && PSP_CoreParameter().compat.flags().BlockTransferDepth) {2234WARN_LOG_N_TIMES(z_xfer, 5, Log::FrameBuf, "FindTransferFramebuffer: found matching depth buffer, %08x (dest=%d, bpp=%d)", basePtr, (int)destination, bpp);2235candidate.channel = RASTER_DEPTH;2236candidate.x_bytes = x_pixels * bpp;2237candidate.w_bytes = w_pixels * bpp;2238candidate.y = y;2239candidate.h = h;2240candidates.push_back(candidate);2241continue;2242}22432244const u32 vfb_address = vfb->fb_address;2245const u32 vfb_size = vfb->BufferByteSize(RASTER_COLOR);22462247if (basePtr < vfb_address || basePtr >= vfb_address + vfb_size) {2248continue;2249}22502251const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format);2252const u32 vfb_byteStride = vfb->FbStrideInBytes();2253const u32 vfb_byteWidth = vfb->WidthInBytes();22542255candidate.w_bytes = w_pixels * bpp;2256candidate.h = h;22572258const u32 byteOffset = basePtr - vfb_address;2259const int memXOffset = byteOffset % byteStride;2260const int memYOffset = byteOffset / byteStride;22612262// Some games use mismatching bitdepths. But make sure the stride matches.2263// If it doesn't, generally this means we detected the framebuffer with too large a height.2264// Use bufferHeight in case of buffers that resize up and down often per frame (Valkyrie Profile.)22652266// If it's outside the vfb by a single pixel, we currently disregard it.2267if (memYOffset > vfb->bufferHeight - h) {2268continue;2269}22702271if (byteOffset == vfb->WidthInBytes() && w_bytes < vfb->FbStrideInBytes()) {2272// Looks like we're in a margin texture of the vfb, which is not the vfb itself.2273// Ignore the match.2274continue;2275}22762277if (vfb_byteStride != byteStride) {2278// Grand Knights History occasionally copies with a mismatching stride but a full line at a time.2279// 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.2280// Makes it hard to detect the wrong transfers in e.g. God of War.2281if (w_pixels != stride_pixels || (byteStride * h != vfb_byteStride && byteStride * h != vfb_byteWidth)) {2282if (destination) {2283// However, some other games write cluts to framebuffers.2284// Let's catch this and upload. Otherwise reject the match.2285bool match = (vfb->usageFlags & FB_USAGE_CLUT) != 0;2286if (match) {2287candidate.w_bytes = byteStride * h;2288h = 1;2289} else {2290continue;2291}2292} else {2293continue;2294}2295} else {2296// This is the Grand Knights History case.2297candidate.w_bytes = byteStride * h;2298candidate.h = 1;2299}2300} else {2301candidate.w_bytes = w_bytes;2302candidate.h = h;2303}23042305candidate.x_bytes = x_bytes + memXOffset;2306candidate.y = y + memYOffset;2307candidate.vfb = vfb;2308candidates.push_back(candidate);2309}23102311const BlockTransferRect *best = nullptr;2312// Sort candidates by just recency for now, we might add other.2313for (size_t i = 0; i < candidates.size(); i++) {2314const BlockTransferRect *candidate = &candidates[i];23152316bool better = !best;2317if (!better) {2318if (candidate->channel == best->channel) {2319better = candidate->vfb->BindSeq(candidate->channel) > best->vfb->BindSeq(candidate->channel);2320} else {2321// Prefer depth over color if the address match is perfect.2322if (candidate->channel == RASTER_DEPTH && best->channel == RASTER_COLOR && candidate->vfb->z_address == basePtr) {2323better = true;2324}2325}2326}23272328if ((candidate->vfb->usageFlags & FB_USAGE_CLUT) && candidate->x_bytes == 0 && candidate->y == 0 && destination) {2329// Hack to prioritize copies to clut buffers.2330best = candidate;2331break;2332}2333if (better) {2334best = candidate;2335}2336}23372338if (candidates.size() > 1) {2339if (Reporting::ShouldLogNTimes("mulblock", 5)) {2340std::string log;2341for (size_t i = 0; i < candidates.size(); i++) {2342log += " - " + candidates[i].ToString() + "\n";2343}2344WARN_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());2345}2346}23472348if (best) {2349*rect = *best;2350return true;2351} else {2352if (Memory::IsVRAMAddress(basePtr) && destination && h >= 128) {2353WARN_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);2354}2355return false;2356}2357}23582359VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAddress, int width, int height, int stride, GEBufferFormat format) {2360INFO_LOG(Log::FrameBuf, "Creating RAM framebuffer at %08x (%dx%d, stride %d, fb_format %d)", fbAddress, width, height, stride, format);23612362RasterChannel channel = format == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR;23632364// A target for the destination is missing - so just create one!2365// Make sure this one would be found by the algorithm above so we wouldn't2366// create a new one each frame.2367VirtualFramebuffer *vfb = new VirtualFramebuffer{};2368vfb->fbo = nullptr;2369uint32_t mask = Memory::IsVRAMAddress(fbAddress) ? 0x041FFFFF : 0x3FFFFFFF;2370if (format == GE_FORMAT_DEPTH16) {2371vfb->fb_address = 0xFFFFFFFF; // Invalid address2372vfb->fb_stride = 0;2373vfb->z_address = fbAddress; // marks that if anyone tries to render with depth to this framebuffer, it should be dropped and recreated.2374vfb->z_stride = stride;2375vfb->width = width;2376} else {2377vfb->fb_address = fbAddress & mask; // NOTE - not necessarily in VRAM!2378vfb->fb_stride = stride;2379vfb->z_address = 0;2380vfb->z_stride = 0;2381vfb->width = std::max(width, stride);2382}2383vfb->height = height;2384vfb->newWidth = vfb->width;2385vfb->newHeight = vfb->height;2386vfb->lastFrameNewSize = gpuStats.numFlips;2387vfb->renderScaleFactor = renderScaleFactor_;2388vfb->renderWidth = (u16)(vfb->width * renderScaleFactor_);2389vfb->renderHeight = (u16)(vfb->height * renderScaleFactor_);2390vfb->bufferWidth = vfb->width;2391vfb->bufferHeight = vfb->height;2392vfb->fb_format = format == GE_FORMAT_DEPTH16 ? GE_FORMAT_8888 : format;2393vfb->usageFlags = format == GE_FORMAT_DEPTH16 ? FB_USAGE_RENDER_DEPTH : FB_USAGE_RENDER_COLOR;2394if (format != GE_FORMAT_DEPTH16) {2395SetColorUpdated(vfb, 0);2396}2397char name[64];2398snprintf(name, sizeof(name), "%08x_%s_RAM", vfb->Address(channel), RasterChannelToString(channel));2399textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);2400bool createDepthBuffer = format == GE_FORMAT_DEPTH16;2401vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, createDepthBuffer, name });2402vfbs_.push_back(vfb);24032404u32 byteSize = vfb->BufferByteSize(channel);2405if (fbAddress + byteSize > framebufColorRangeEnd_) {2406framebufColorRangeEnd_ = fbAddress + byteSize;2407}24082409return vfb;2410}24112412// 1:1 pixel size buffers, we resize buffers to these before we read them back.2413// TODO: We shouldn't keep whole VirtualFramebuffer structs for these - the fbo and last_frame_render is enough.2414VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFramebuffer *vfb, RasterChannel channel) {2415// For now we'll keep these on the same struct as the ones that can get displayed2416// (and blatantly copy work already done above while at it).2417VirtualFramebuffer *nvfb = nullptr;24182419// We maintain a separate vector of framebuffer objects for blitting.2420for (VirtualFramebuffer *v : bvfbs_) {2421if (v->Address(channel) == vfb->Address(channel) && v->Format(channel) == vfb->Format(channel)) {2422if (v->bufferWidth == vfb->bufferWidth && v->bufferHeight == vfb->bufferHeight) {2423nvfb = v;2424if (channel == RASTER_COLOR) {2425v->fb_stride = vfb->fb_stride;2426} else {2427v->z_stride = vfb->z_stride;2428}2429v->width = vfb->width;2430v->height = vfb->height;2431break;2432}2433}2434}24352436// Create a new fbo if none was found for the size2437if (!nvfb) {2438nvfb = new VirtualFramebuffer{};2439nvfb->fbo = nullptr;2440nvfb->fb_address = channel == RASTER_COLOR ? vfb->fb_address : 0;2441nvfb->fb_stride = channel == RASTER_COLOR ? vfb->fb_stride : 0;2442nvfb->z_address = channel == RASTER_DEPTH ? vfb->z_address : 0;2443nvfb->z_stride = channel == RASTER_DEPTH ? vfb->z_stride : 0;2444nvfb->width = vfb->width;2445nvfb->height = vfb->height;2446nvfb->renderWidth = vfb->bufferWidth;2447nvfb->renderHeight = vfb->bufferHeight;2448nvfb->renderScaleFactor = 1; // For readbacks we resize to the original size, of course.2449nvfb->bufferWidth = vfb->bufferWidth;2450nvfb->bufferHeight = vfb->bufferHeight;2451nvfb->fb_format = vfb->fb_format;2452nvfb->drawnWidth = vfb->drawnWidth;2453nvfb->drawnHeight = vfb->drawnHeight;24542455char name[64];2456snprintf(name, sizeof(name), "download_temp_%08x_%s", vfb->Address(channel), RasterChannelToString(channel));24572458// We always create a color-only framebuffer here - readbacks of depth convert to color while translating the values.2459nvfb->fbo = draw_->CreateFramebuffer({ nvfb->bufferWidth, nvfb->bufferHeight, 1, 1, 0, false, name });2460if (!nvfb->fbo) {2461ERROR_LOG(Log::FrameBuf, "Error creating FBO! %d x %d", nvfb->renderWidth, nvfb->renderHeight);2462delete nvfb;2463return nullptr;2464}2465bvfbs_.push_back(nvfb);2466} else {2467UpdateDownloadTempBuffer(nvfb);2468}24692470nvfb->usageFlags |= FB_USAGE_RENDER_COLOR;2471nvfb->last_frame_render = gpuStats.numFlips;2472nvfb->dirtyAfterDisplay = true;24732474return nvfb;2475}24762477void FramebufferManagerCommon::ApplyClearToMemory(int x1, int y1, int x2, int y2, u32 clearColor) {2478if (currentRenderVfb_) {2479if ((currentRenderVfb_->usageFlags & FB_USAGE_DOWNLOAD_CLEAR) != 0) {2480// Already zeroed in memory.2481return;2482}2483}24842485if (!Memory::IsValidAddress(gstate.getFrameBufAddress())) {2486return;2487}24882489u8 *addr = Memory::GetPointerWriteUnchecked(gstate.getFrameBufAddress());2490const int bpp = BufferFormatBytesPerPixel(gstate_c.framebufFormat);24912492u32 clearBits = clearColor;2493if (bpp == 2) {2494u16 clear16 = 0;2495switch (gstate_c.framebufFormat) {2496case GE_FORMAT_565: clear16 = RGBA8888toRGB565(clearColor); break;2497case GE_FORMAT_5551: clear16 = RGBA8888toRGBA5551(clearColor); break;2498case GE_FORMAT_4444: clear16 = RGBA8888toRGBA4444(clearColor); break;2499default: _dbg_assert_(0); break;2500}2501clearBits = clear16 | (clear16 << 16);2502}25032504const bool singleByteClear = (clearBits >> 16) == (clearBits & 0xFFFF) && (clearBits >> 24) == (clearBits & 0xFF);2505const int stride = gstate.FrameBufStride();2506const int width = x2 - x1;25072508const int byteStride = stride * bpp;2509const int byteWidth = width * bpp;2510for (int y = y1; y < y2; ++y) {2511NotifyMemInfo(MemBlockFlags::WRITE, gstate.getFrameBufAddress() + x1 * bpp + y * byteStride, byteWidth, "FramebufferClear");2512}25132514// Can use memset for simple cases. Often alpha is different and gums up the works.2515if (singleByteClear) {2516addr += x1 * bpp;2517for (int y = y1; y < y2; ++y) {2518memset(addr + y * byteStride, clearBits, byteWidth);2519}2520} else {2521// This will most often be true - rarely is the width not aligned.2522// TODO: We should really use non-temporal stores here to avoid the cache,2523// as it's unlikely that these bytes will be read.2524if ((width & 3) == 0 && (x1 & 3) == 0) {2525u64 val64 = clearBits | ((u64)clearBits << 32);2526int xstride = 8 / bpp;25272528u64 *addr64 = (u64 *)addr;2529const int stride64 = stride / xstride;2530const int x1_64 = x1 / xstride;2531const int x2_64 = x2 / xstride;2532for (int y = y1; y < y2; ++y) {2533for (int x = x1_64; x < x2_64; ++x) {2534addr64[y * stride64 + x] = val64;2535}2536}2537} else if (bpp == 4) {2538u32 *addr32 = (u32 *)addr;2539for (int y = y1; y < y2; ++y) {2540for (int x = x1; x < x2; ++x) {2541addr32[y * stride + x] = clearBits;2542}2543}2544} else if (bpp == 2) {2545u16 *addr16 = (u16 *)addr;2546for (int y = y1; y < y2; ++y) {2547for (int x = x1; x < x2; ++x) {2548addr16[y * stride + x] = (u16)clearBits;2549}2550}2551}2552}25532554if (currentRenderVfb_) {2555// The current content is in memory now, so update the flag.2556if (x1 == 0 && y1 == 0 && x2 >= currentRenderVfb_->width && y2 >= currentRenderVfb_->height) {2557currentRenderVfb_->usageFlags |= FB_USAGE_DOWNLOAD_CLEAR;2558currentRenderVfb_->memoryUpdated = true;2559}2560}2561}25622563bool 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) {2564if (!useBufferedRendering_) {2565return false;2566}25672568// Skip checking if there's no framebuffers in that area. Make a special exception for obvious transfers to depth buffer, see issue #178782569bool dstDepthSwizzle = Memory::IsVRAMAddress(dstBasePtr) && ((dstBasePtr & 0x600000) == 0x600000);25702571if (!dstDepthSwizzle && !MayIntersectFramebufferColor(srcBasePtr) && !MayIntersectFramebufferColor(dstBasePtr)) {2572return false;2573}25742575BlockTransferRect dstRect{};2576BlockTransferRect srcRect{};25772578// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2579bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2580bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);25812582if (srcRect.channel == RASTER_DEPTH) {2583// Ignore the found buffer if it's not 16-bit - we create a new more suitable one instead.2584if (dstRect.channel == RASTER_COLOR && dstRect.vfb->fb_format == GE_FORMAT_8888) {2585dstBuffer = false;2586}2587}25882589if (!srcBuffer && dstBuffer && dstRect.channel == RASTER_DEPTH) {2590dstBuffer = true;2591}25922593if (srcBuffer && !dstBuffer) {2594// In here, we can't read from dstRect.2595if (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB ||2596GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE ||2597(PSP_CoreParameter().compat.flags().IntraVRAMBlockTransferAllowCreateFB &&2598Memory::IsVRAMAddress(srcRect.vfb->fb_address) && Memory::IsVRAMAddress(dstBasePtr))) {2599GEBufferFormat ramFormat;2600// Try to guess the appropriate format. We only know the bpp from the block transfer command (16 or 32 bit).2601if (srcRect.channel == RASTER_COLOR) {2602if (bpp == 4) {2603// Only one possibility unless it's doing split pixel tricks (which we could detect through stride maybe).2604ramFormat = GE_FORMAT_8888;2605} else if (srcRect.vfb->fb_format != GE_FORMAT_8888) {2606// We guess that the game will interpret the data the same as it was in the source of the copy.2607// Seems like a likely good guess, and works in Test Drive Unlimited.2608ramFormat = srcRect.vfb->fb_format;2609} else {2610// No info left - just fall back to something. But this is definitely split pixel tricks.2611ramFormat = GE_FORMAT_5551;2612}2613dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, ramFormat);2614} else {2615dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, GE_FORMAT_DEPTH16);2616dstRect.x_bytes = 0;2617dstRect.w_bytes = 2 * width;2618dstRect.y = 0;2619dstRect.h = height;2620dstRect.channel = RASTER_DEPTH;2621}2622dstBuffer = true;2623}2624}26252626if (dstBuffer) {2627dstRect.vfb->last_frame_used = gpuStats.numFlips;2628// Mark the destination as fresh.2629if (dstRect.channel == RASTER_COLOR) {2630dstRect.vfb->colorBindSeq = GetBindSeqCount();2631} else {2632dstRect.vfb->depthBindSeq = GetBindSeqCount();2633}2634}26352636if (dstBuffer && srcBuffer) {2637if (srcRect.vfb && srcRect.vfb == dstRect.vfb && srcRect.channel == dstRect.channel) {2638// Transfer within the same buffer.2639// This is a simple case because there will be no format conversion or similar shenanigans needed.2640// However, the BPP might still mismatch, but in such a case we can convert the coordinates.2641if (srcX == dstX && srcY == dstY) {2642// Ignore, nothing to do. Tales of Phantasia X does this by accident.2643// Returning true to also skip the memory copy.2644return true;2645}26462647int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));26482649if (bpp != buffer_bpp) {2650WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in intra-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2651// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2652bpp = buffer_bpp;2653}26542655WARN_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)",2656width, height, bpp,2657srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2658dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2659FlushBeforeCopy();2660// Some backends can handle blitting within a framebuffer. Others will just have to deal with it or ignore it, apparently.2661BlitFramebuffer(dstRect.vfb, dstX, dstY, srcRect.vfb, srcX, srcY, dstRect.w_bytes / bpp, dstRect.h, bpp, dstRect.channel, "Blit_IntraBufferBlockTransfer");2662RebindFramebuffer("rebind after intra block transfer");2663SetColorUpdated(dstRect.vfb, skipDrawReason);2664return true; // Skip the memory copy.2665}26662667// Straightforward blit between two same-format framebuffers.2668if (srcRect.vfb && srcRect.channel == dstRect.channel && srcRect.vfb->Format(srcRect.channel) == dstRect.vfb->Format(dstRect.channel)) {2669WARN_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)",2670RasterChannelToString(srcRect.channel),2671width, height, bpp,2672srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride, GeBufferFormatToString(srcRect.vfb->fb_format),2673dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride, GeBufferFormatToString(dstRect.vfb->fb_format));26742675// Straight blit will do, but check the bpp, we might need to convert coordinates differently.2676int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));2677if (bpp != buffer_bpp) {2678WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in inter-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2679// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2680bpp = buffer_bpp;2681}2682FlushBeforeCopy();2683BlitFramebuffer(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");2684RebindFramebuffer("RebindFramebuffer - Inter-buffer block transfer");2685SetColorUpdated(dstRect.vfb, skipDrawReason);2686return true;2687}26882689// Getting to the more complex cases. Have not actually seen much of these yet.2690WARN_LOG_N_TIMES(blockformat, 5, Log::G3D, "Mismatched buffer formats in block transfer: %s->%s (%dx%d)",2691GeBufferFormatToString(srcRect.vfb->Format(srcRect.channel)), GeBufferFormatToString(dstRect.vfb->Format(dstRect.channel)),2692width, height);26932694// TODO26952696// No need to actually do the memory copy behind, probably.2697return true;26982699} else if (dstBuffer) {2700// Handle depth uploads directly here, and let's not bother copying the data. This is compat-flag-gated for now,2701// may generalize it when I remove the compat flag.2702if (dstRect.channel == RASTER_DEPTH) {2703WARN_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));2704FlushBeforeCopy();2705const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;2706DrawPixels(dstRect.vfb, dstX, dstY, srcBase, dstRect.vfb->Format(dstRect.channel), srcStride * bpp / 2, (int)(dstRect.w_bytes / 2), dstRect.h, dstRect.channel, "BlockTransferCopy_DrawPixelsDepth");2707RebindFramebuffer("RebindFramebuffer - UploadDepth");2708return true;2709}27102711// Here we should just draw the pixels into the buffer. Return false to copy the memory first.2712// NotifyBlockTransferAfter will take care of the rest.2713return false;2714} else if (srcBuffer) {2715if (width == 48 && height == 48 && srcY == 224 && srcX == 432 && PSP_CoreParameter().compat.flags().TacticsOgreEliminateDebugReadback) {2716return false;2717}27182719WARN_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)",2720width, height, bpp,2721srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2722dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2723FlushBeforeCopy();2724if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && !srcRect.vfb->memoryUpdated) {2725const int srcBpp = BufferFormatBytesPerPixel(srcRect.vfb->fb_format);2726const float srcXFactor = (float)bpp / srcBpp;2727const bool tooTall = srcY + srcRect.h > srcRect.vfb->bufferHeight;2728if (srcRect.h <= 0 || (tooTall && srcY != 0)) {2729WARN_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);2730} else {2731if (tooTall) {2732WARN_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);2733}2734Draw::ReadbackMode readbackMode = Draw::ReadbackMode::BLOCK;2735if (PSP_CoreParameter().compat.flags().AllowDelayedReadbacks) {2736readbackMode = Draw::ReadbackMode::OLD_DATA_OK;2737}2738ReadFramebufferToMemory(srcRect.vfb, static_cast<int>(srcX * srcXFactor), srcY, static_cast<int>(srcRect.w_bytes * srcXFactor), srcRect.h, RASTER_COLOR, readbackMode);2739srcRect.vfb->usageFlags = (srcRect.vfb->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2740}2741}2742return false; // Let the bit copy happen2743} else {2744return false;2745}2746}27472748SkipGPUReadbackMode FramebufferManagerCommon::GetSkipGPUReadbackMode() {2749if (PSP_CoreParameter().compat.flags().ForceEnableGPUReadback) {2750return SkipGPUReadbackMode::NO_SKIP;2751} else {2752return (SkipGPUReadbackMode)g_Config.iSkipGPUReadbackMode;2753}2754}27552756void 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) {2757// If it's a block transfer direct to the screen, and we're not using buffers, draw immediately.2758// We may still do a partial block draw below if this doesn't pass.2759if (!useBufferedRendering_ && dstStride >= 480 && width >= 480 && height == 272) {2760bool isPrevDisplayBuffer = PrevDisplayFramebufAddr() == dstBasePtr;2761bool isDisplayBuffer = CurrentDisplayFramebufAddr() == dstBasePtr;2762if (isPrevDisplayBuffer || isDisplayBuffer) {2763FlushBeforeCopy();2764DrawFramebufferToOutput(Memory::GetPointerUnchecked(dstBasePtr), dstStride, displayFormat_);2765return;2766}2767}27682769if (MayIntersectFramebufferColor(srcBasePtr) || MayIntersectFramebufferColor(dstBasePtr)) {2770// TODO: Figure out how we can avoid repeating the search here.27712772BlockTransferRect dstRect{};2773BlockTransferRect srcRect{};27742775// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2776bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2777bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);27782779// A few games use this INSTEAD of actually drawing the video image to the screen, they just blast it to2780// the backbuffer. Detect this and have the framebuffermanager draw the pixels.2781if (!useBufferedRendering_ && currentRenderVfb_ != dstRect.vfb) {2782return;2783}27842785if (dstBuffer && !srcBuffer) {2786WARN_LOG_ONCE(btu, Log::G3D, "Block transfer upload %08x -> %08x (%dx%d %d,%d bpp=%d)", srcBasePtr, dstBasePtr, width, height, dstX, dstY, bpp);2787FlushBeforeCopy();2788const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;27892790int dstBpp = BufferFormatBytesPerPixel(dstRect.vfb->fb_format);2791float dstXFactor = (float)bpp / dstBpp;2792if (dstRect.w_bytes / bpp > dstRect.vfb->width || dstRect.h > dstRect.vfb->height) {2793// The buffer isn't big enough, and we have a clear hint of size. Resize.2794// This happens in Valkyrie Profile when uploading video at the ending.2795// Also happens to the CLUT framebuffer in the Burnout Dominator lens flare effect. See #160752796ResizeFramebufFBO(dstRect.vfb, dstRect.w_bytes / bpp, dstRect.h, false, true);2797// Make sure we don't flop back and forth.2798dstRect.vfb->newWidth = std::max(dstRect.w_bytes / bpp, (int)dstRect.vfb->width);2799dstRect.vfb->newHeight = std::max(dstRect.h, (int)dstRect.vfb->height);2800dstRect.vfb->lastFrameNewSize = gpuStats.numFlips;2801// Resizing may change the viewport/etc.2802gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);2803}2804DrawPixels(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");2805SetColorUpdated(dstRect.vfb, skipDrawReason);2806RebindFramebuffer("RebindFramebuffer - NotifyBlockTransferAfter");2807}2808}2809}28102811void FramebufferManagerCommon::SetSafeSize(u16 w, u16 h) {2812VirtualFramebuffer *vfb = currentRenderVfb_;2813if (vfb) {2814vfb->safeWidth = std::min(vfb->bufferWidth, std::max(vfb->safeWidth, w));2815vfb->safeHeight = std::min(vfb->bufferHeight, std::max(vfb->safeHeight, h));2816}2817}28182819void FramebufferManagerCommon::NotifyDisplayResized() {2820pixelWidth_ = PSP_CoreParameter().pixelWidth;2821pixelHeight_ = PSP_CoreParameter().pixelHeight;2822presentation_->UpdateDisplaySize(pixelWidth_, pixelHeight_);28232824INFO_LOG(Log::G3D, "FramebufferManagerCommon::NotifyDisplayResized: %dx%d", pixelWidth_, pixelHeight_);28252826// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2827// So we need to defer the post processing initialization.2828updatePostShaders_ = true;2829}28302831void FramebufferManagerCommon::NotifyRenderResized(int msaaLevel) {2832gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;28332834int w, h, scaleFactor;2835presentation_->CalculateRenderResolution(&w, &h, &scaleFactor, &postShaderIsUpscalingFilter_, &postShaderIsSupersampling_);2836PSP_CoreParameter().renderWidth = w;2837PSP_CoreParameter().renderHeight = h;2838PSP_CoreParameter().renderScaleFactor = scaleFactor;28392840if (UpdateRenderSize(msaaLevel)) {2841draw_->StopThreads();2842DestroyAllFBOs();2843draw_->StartThreads();2844}28452846// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2847// So we need to defer the post processing initialization.2848updatePostShaders_ = true;2849}28502851void FramebufferManagerCommon::NotifyConfigChanged() {2852updatePostShaders_ = true;2853}28542855void FramebufferManagerCommon::DestroyAllFBOs() {2856DiscardFramebufferCopy();2857currentRenderVfb_ = nullptr;2858displayFramebuf_ = nullptr;2859prevDisplayFramebuf_ = nullptr;2860prevPrevDisplayFramebuf_ = nullptr;28612862for (VirtualFramebuffer *vfb : vfbs_) {2863INFO_LOG(Log::FrameBuf, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format);2864DestroyFramebuf(vfb);2865}2866vfbs_.clear();28672868for (VirtualFramebuffer *vfb : bvfbs_) {2869DestroyFramebuf(vfb);2870}2871bvfbs_.clear();28722873for (auto &tempFB : tempFBOs_) {2874tempFB.second.fbo->Release();2875}2876tempFBOs_.clear();28772878for (auto &iter : fbosToDelete_) {2879iter->Release();2880}2881fbosToDelete_.clear();28822883for (auto &iter : drawPixelsCache_) {2884iter.tex->Release();2885}2886drawPixelsCache_.clear();2887}28882889static const char *TempFBOReasonToString(TempFBO reason) {2890switch (reason) {2891case TempFBO::DEPAL: return "depal";2892case TempFBO::BLIT: return "blit";2893case TempFBO::COPY: return "copy";2894case TempFBO::STENCIL: return "stencil";2895default: break;2896}2897return "";2898}28992900Draw::Framebuffer *FramebufferManagerCommon::GetTempFBO(TempFBO reason, u16 w, u16 h) {2901u64 key = ((u64)reason << 48) | ((u32)w << 16) | h;2902auto it = tempFBOs_.find(key);2903if (it != tempFBOs_.end()) {2904it->second.last_frame_used = gpuStats.numFlips;2905return it->second.fbo;2906}29072908bool z_stencil = reason == TempFBO::STENCIL;2909char name[128];2910snprintf(name, sizeof(name), "tempfbo_%s_%dx%d", TempFBOReasonToString(reason), w / renderScaleFactor_, h / renderScaleFactor_);29112912Draw::Framebuffer *fbo = draw_->CreateFramebuffer({ w, h, 1, GetFramebufferLayers(), 0, z_stencil, name });2913if (!fbo) {2914return nullptr;2915}29162917const TempFBOInfo info = { fbo, gpuStats.numFlips };2918tempFBOs_[key] = info;2919return fbo;2920}29212922void FramebufferManagerCommon::UpdateFramebufUsage(VirtualFramebuffer *vfb) const {2923auto checkFlag = [&](u16 flag, int last_frame) {2924if (vfb->usageFlags & flag) {2925const int age = frameLastFramebufUsed_ - last_frame;2926if (age > FBO_OLD_USAGE_FLAG) {2927vfb->usageFlags &= ~flag;2928}2929}2930};29312932checkFlag(FB_USAGE_DISPLAYED_FRAMEBUFFER, vfb->last_frame_displayed);2933checkFlag(FB_USAGE_TEXTURE, vfb->last_frame_used);2934checkFlag(FB_USAGE_RENDER_COLOR, vfb->last_frame_render);2935checkFlag(FB_USAGE_CLUT, vfb->last_frame_clut);2936}29372938void FramebufferManagerCommon::ClearAllDepthBuffers() {2939for (auto vfb : vfbs_) {2940vfb->usageFlags |= FB_USAGE_INVALIDATE_DEPTH;2941}2942}29432944// We might also want to implement an asynchronous callback-style version of this. Would probably2945// only be possible to implement optimally on Vulkan, but on GL and D3D11 we could do pixel buffers2946// and read on the next frame, then call the callback.2947//2948// The main use cases for this are:2949// * GE debugging(in practice async will not matter because it will stall anyway.)2950// * Video file recording(would probably be great if it was async.)2951// * Screenshots(benefit slightly from async.)2952// * Save state screenshots(could probably be async but need to manage the stall.)2953bool FramebufferManagerCommon::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer, int maxScaleFactor) {2954VirtualFramebuffer *vfb = currentRenderVfb_;2955if (!vfb || vfb->fb_address != fb_address) {2956vfb = ResolveVFB(fb_address, fb_stride, format);2957}29582959if (!vfb) {2960if (!Memory::IsValidAddress(fb_address))2961return false;2962// If there's no vfb and we're drawing there, must be memory?2963buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(fb_address), fb_stride, 512, format);2964return true;2965}29662967int w = vfb->renderWidth, h = vfb->renderHeight;29682969Draw::Framebuffer *bound = nullptr;29702971if (vfb->fbo) {2972if (maxScaleFactor > 0 && vfb->renderWidth > vfb->width * maxScaleFactor) {2973w = vfb->width * maxScaleFactor;2974h = vfb->height * maxScaleFactor;29752976Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::COPY, w, h);2977VirtualFramebuffer tempVfb = *vfb;2978tempVfb.fbo = tempFBO;2979tempVfb.bufferWidth = vfb->width;2980tempVfb.bufferHeight = vfb->height;2981tempVfb.renderWidth = w;2982tempVfb.renderHeight = h;2983tempVfb.renderScaleFactor = maxScaleFactor;2984BlitFramebuffer(&tempVfb, 0, 0, vfb, 0, 0, vfb->width, vfb->height, 0, RASTER_COLOR, "Blit_GetFramebuffer");29852986bound = tempFBO;2987} else {2988bound = vfb->fbo;2989}2990}29912992if (!useBufferedRendering_) {2993// Safety check.2994w = std::min(w, PSP_CoreParameter().pixelWidth);2995h = std::min(h, PSP_CoreParameter().pixelHeight);2996}29972998// TODO: Maybe should handle flipY inside CopyFramebufferToMemorySync somehow?2999bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3000buffer.Allocate(w, h, GE_FORMAT_8888, flipY);3001bool retval = draw_->CopyFramebufferToMemory(bound, Draw::FB_COLOR_BIT, 0, 0, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetFramebuffer");30023003// Don't need to increment gpu stats for readback count here, this is a debugger-only function.30043005// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3006gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3007// We may have blitted to a temp FBO.3008RebindFramebuffer("RebindFramebuffer - GetFramebuffer");3009return retval;3010}30113012bool FramebufferManagerCommon::GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer) {3013VirtualFramebuffer *vfb = currentRenderVfb_;3014if (!vfb) {3015vfb = GetVFBAt(fb_address);3016}30173018if (!vfb) {3019if (!Memory::IsValidAddress(z_address))3020return false;3021// If there's no vfb and we're drawing there, must be memory?3022buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(z_address), z_stride, 512, GPU_DBG_FORMAT_16BIT);3023return true;3024}30253026int w = vfb->renderWidth;3027int h = vfb->renderHeight;3028if (!useBufferedRendering_) {3029// Safety check.3030w = std::min(w, PSP_CoreParameter().pixelWidth);3031h = std::min(h, PSP_CoreParameter().pixelHeight);3032}30333034bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;30353036// Old code3037if (gstate_c.Use(GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT)) {3038buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT_DIV_256, flipY);3039} else {3040buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT, flipY);3041}3042// No need to free on failure, that's the caller's job (it likely will reuse a buffer.)3043bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_DEPTH_BIT, 0, 0, w, h, Draw::DataFormat::D32F, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetDepthBuffer");3044if (!retval) {3045// Try ReadbackDepthbufferSync, in case GLES.3046buffer.Allocate(w, h, GPU_DBG_FORMAT_16BIT, flipY);3047retval = ReadbackDepthbuffer(vfb->fbo, 0, 0, w, h, (uint16_t *)buffer.GetData(), w, w, h, Draw::ReadbackMode::BLOCK);3048}30493050// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3051gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3052// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3053RebindFramebuffer("RebindFramebuffer - GetDepthbuffer");3054return retval;3055}30563057bool FramebufferManagerCommon::GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer) {3058VirtualFramebuffer *vfb = currentRenderVfb_;3059if (!vfb) {3060vfb = GetVFBAt(fb_address);3061}30623063if (!vfb) {3064if (!Memory::IsValidAddress(fb_address))3065return false;3066// If there's no vfb and we're drawing there, must be memory?3067// TODO: Actually get the stencil.3068buffer = GPUDebugBuffer(Memory::GetPointerWrite(fb_address), fb_stride, 512, GPU_DBG_FORMAT_8888);3069return true;3070}30713072int w = vfb->renderWidth;3073int h = vfb->renderHeight;3074if (!useBufferedRendering_) {3075// Safety check.3076w = std::min(w, PSP_CoreParameter().pixelWidth);3077h = std::min(h, PSP_CoreParameter().pixelHeight);3078}30793080bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3081// No need to free on failure, the caller/destructor will do that. Usually this is a reused buffer, anyway.3082buffer.Allocate(w, h, GPU_DBG_FORMAT_8BIT, flipY);3083bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::FB_STENCIL_BIT, 0, 0, w,h, Draw::DataFormat::S8, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetStencilbuffer");3084if (!retval) {3085retval = ReadbackStencilbuffer(vfb->fbo, 0, 0, w, h, buffer.GetData(), w, Draw::ReadbackMode::BLOCK);3086}3087// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3088RebindFramebuffer("RebindFramebuffer - GetStencilbuffer");3089return retval;3090}30913092bool GetOutputFramebuffer(Draw::DrawContext *draw, GPUDebugBuffer &buffer) {3093int w, h;3094draw->GetFramebufferDimensions(nullptr, &w, &h);3095Draw::DataFormat fmt = draw->PreferredFramebufferReadbackFormat(nullptr);3096// Ignore preferred formats other than BGRA.3097if (fmt != Draw::DataFormat::B8G8R8A8_UNORM)3098fmt = Draw::DataFormat::R8G8B8A8_UNORM;30993100bool flipped = g_Config.iGPUBackend == (int)GPUBackend::OPENGL;31013102buffer.Allocate(w, h, fmt == Draw::DataFormat::R8G8B8A8_UNORM ? GPU_DBG_FORMAT_8888 : GPU_DBG_FORMAT_8888_BGRA, flipped);3103return draw->CopyFramebufferToMemory(nullptr, Draw::FB_COLOR_BIT, 0, 0, w, h, fmt, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetOutputFramebuffer");3104}31053106bool FramebufferManagerCommon::GetOutputFramebuffer(GPUDebugBuffer &buffer) {3107bool retval = ::GetOutputFramebuffer(draw_, buffer);3108// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3109RebindFramebuffer("RebindFramebuffer - GetOutputFramebuffer");3110return retval;3111}31123113// This reads a channel of a framebuffer into emulated PSP VRAM, taking care of scaling down as needed.3114//3115// Color conversion is currently done on CPU but should theoretically be done on GPU.3116// (Except using the GPU might cause problems because of various implementations'3117// dithering behavior and games that expect exact colors like Danganronpa, so we3118// can't entirely be rid of the CPU path.) -- unknown3119void FramebufferManagerCommon::ReadbackFramebuffer(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3120if (w <= 0 || h <= 0) {3121ERROR_LOG(Log::FrameBuf, "Bad inputs to ReadbackFramebufferSync: %d %d %d %d", x, y, w, h);3122return;3123}31243125// Note that ReadbackDepthBufferSync can stretch on its own while converting data format, so we don't need to downscale in that case.3126if (vfb->renderScaleFactor == 1 || channel == RASTER_DEPTH) {3127// No need to stretch-blit3128} else {3129VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb, channel);3130if (nvfb) {3131BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0, channel, "Blit_ReadFramebufferToMemory");3132vfb = nvfb;3133}3134}31353136const u32 fb_address = channel == RASTER_COLOR ? vfb->fb_address : vfb->z_address;31373138Draw::DataFormat destFormat = channel == RASTER_COLOR ? GEFormatToThin3D(vfb->fb_format) : GEFormatToThin3D(GE_FORMAT_DEPTH16);3139const int dstBpp = (int)DataFormatSizeInBytes(destFormat);31403141int stride = channel == RASTER_COLOR ? vfb->fb_stride : vfb->z_stride;31423143const int dstByteOffset = (y * stride + x) * dstBpp;3144// Leave the gap between the end of the last line and the full stride.3145// This is only used for the NotifyMemInfo range.3146const int dstSize = ((h - 1) * stride + w) * dstBpp;31473148if (!Memory::IsValidRange(fb_address + dstByteOffset, dstSize)) {3149ERROR_LOG_REPORT(Log::G3D, "ReadbackFramebufferSync would write outside of memory, ignoring");3150return;3151}31523153u8 *destPtr = Memory::GetPointerWriteUnchecked(fb_address + dstByteOffset);31543155// We always need to convert from the framebuffer native format.3156// Right now that's always 8888.3157DEBUG_LOG(Log::FrameBuf, "Reading framebuffer to mem, fb_address = %08x, ptr=%p", fb_address, destPtr);31583159if (channel == RASTER_DEPTH) {3160_assert_msg_(vfb && vfb->z_address != 0 && vfb->z_stride != 0, "Depth buffer invalid");3161ReadbackDepthbuffer(vfb->fbo,3162x * vfb->renderScaleFactor, y * vfb->renderScaleFactor,3163w * vfb->renderScaleFactor, h * vfb->renderScaleFactor, (uint16_t *)destPtr, stride, w, h, mode);3164} else {3165draw_->CopyFramebufferToMemory(vfb->fbo, channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, x, y, w, h, destFormat, destPtr, stride, mode, "ReadbackFramebufferSync");3166}31673168char tag[128];3169size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format));3170NotifyMemInfo(MemBlockFlags::WRITE, fb_address + dstByteOffset, dstSize, tag, len);31713172if (mode == Draw::ReadbackMode::BLOCK) {3173gpuStats.numBlockingReadbacks++;3174} else {3175gpuStats.numReadbacks++;3176}3177}31783179bool FramebufferManagerCommon::ReadbackStencilbuffer(Draw::Framebuffer *fbo, int x, int y, int w, int h, uint8_t *pixels, int pixelsStride, Draw::ReadbackMode mode) {3180return draw_->CopyFramebufferToMemory(fbo, Draw::FB_DEPTH_BIT, x, y, w, h, Draw::DataFormat::S8, pixels, pixelsStride, mode, "ReadbackStencilbufferSync");3181}31823183void FramebufferManagerCommon::ReadFramebufferToMemory(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3184// Clamp to bufferWidth. Sometimes block transfers can cause this to hit.3185if (x + w >= vfb->bufferWidth) {3186w = vfb->bufferWidth - x;3187}3188if (vfb && vfb->fbo) {3189if (gameUsesSequentialCopies_) {3190// Ignore the x/y/etc., read the entire thing. See below.3191x = 0;3192y = 0;3193w = vfb->width;3194h = vfb->height;3195vfb->memoryUpdated = true;3196vfb->usageFlags |= FB_USAGE_DOWNLOAD;3197} else if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3198// Mark it as fully downloaded until next render to it.3199if (channel == RASTER_COLOR)3200vfb->memoryUpdated = true;3201vfb->usageFlags |= FB_USAGE_DOWNLOAD;3202} else {3203// Let's try to set the flag eventually, if the game copies a lot.3204// Some games (like Grand Knights History) copy subranges very frequently.3205const static int FREQUENT_SEQUENTIAL_COPIES = 3;3206static int frameLastCopy = 0;3207static u32 bufferLastCopy = 0;3208static int copiesThisFrame = 0;3209if (frameLastCopy != gpuStats.numFlips || bufferLastCopy != vfb->fb_address) {3210frameLastCopy = gpuStats.numFlips;3211bufferLastCopy = vfb->fb_address;3212copiesThisFrame = 0;3213}3214if (++copiesThisFrame > FREQUENT_SEQUENTIAL_COPIES) {3215gameUsesSequentialCopies_ = true;3216}3217}32183219// This handles any required stretching internally.3220ReadbackFramebuffer(vfb, x, y, w, h, channel, mode);32213222draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3223textureCache_->ForgetLastTexture();3224RebindFramebuffer("RebindFramebuffer - ReadFramebufferToMemory");3225}3226}32273228void FramebufferManagerCommon::FlushBeforeCopy() {3229// Flush anything not yet drawn before blitting, downloading, or uploading.3230// This might be a stalled list, or unflushed before a block transfer, etc.3231// Only bother if any draws are pending.3232if (drawEngine_->GetNumDrawCalls() > 0) {3233// TODO: It's really bad that we are calling SetRenderFramebuffer here with3234// all the irrelevant state checking it'll use to decide what to do. Should3235// do something more focused here.3236SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason);3237drawEngine_->DispatchFlush();3238}3239}32403241// TODO: Replace with with depal, reading the palette from the texture on the GPU directly.3242void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) {3243VirtualFramebuffer *vfb = GetVFBAt(fb_address);3244if (vfb && vfb->fb_stride != 0) {3245const u32 bpp = BufferFormatBytesPerPixel(vfb->fb_format);3246int x = 0;3247int y = 0;3248int pixels = loadBytes / bpp;3249// The height will be 1 for each stride or part thereof.3250int w = std::min(pixels % vfb->fb_stride, (int)vfb->width);3251int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height);32523253if (w == 0 || h > 1) {3254// Exactly aligned, or more than one row.3255w = std::min(vfb->fb_stride, vfb->width);3256}32573258// We might still have a pending draw to the fb in question, flush if so.3259FlushBeforeCopy();32603261// No need to download if we already have it.3262if (w > 0 && h > 0 && !vfb->memoryUpdated && vfb->clutUpdatedBytes < loadBytes) {3263// We intentionally don't try to optimize into a full download here - we don't want to over download.32643265// CLUT framebuffers are often incorrectly estimated in size.3266if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3267vfb->memoryUpdated = true;3268}3269vfb->clutUpdatedBytes = loadBytes;32703271// This function now handles scaling down internally.3272ReadbackFramebuffer(vfb, x, y, w, h, RASTER_COLOR, Draw::ReadbackMode::BLOCK);32733274textureCache_->ForgetLastTexture();3275RebindFramebuffer("RebindFramebuffer - DownloadFramebufferForClut");3276}3277}3278}32793280void FramebufferManagerCommon::RebindFramebuffer(const char *tag) {3281draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3282shaderManager_->DirtyLastShader();3283// Needed for D3D11 to run validation clean. I don't think it's actually an issue.3284// textureCache_->ForgetLastTexture();3285if (currentRenderVfb_ && currentRenderVfb_->fbo) {3286draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag);3287} else {3288// This can happen (like it does in Parappa) when a frame starts with copies instead of rendering.3289// Let's do nothing and assume it'll take care of itself.3290}3291}32923293std::vector<const VirtualFramebuffer *> FramebufferManagerCommon::GetFramebufferList() const {3294std::vector<const VirtualFramebuffer *> list;3295for (auto vfb : vfbs_) {3296list.push_back(vfb);3297}3298return list;3299}33003301template <typename T>3302static void DoRelease(T *&obj) {3303if (obj)3304obj->Release();3305obj = nullptr;3306}33073308void FramebufferManagerCommon::ReleasePipelines() {3309for (int i = 0; i < ARRAY_SIZE(reinterpretFromTo_); i++) {3310for (int j = 0; j < ARRAY_SIZE(reinterpretFromTo_); j++) {3311DoRelease(reinterpretFromTo_[i][j]);3312}3313}3314DoRelease(stencilWriteSampler_);3315DoRelease(stencilWritePipeline_);3316DoRelease(stencilReadbackSampler_);3317DoRelease(stencilReadbackPipeline_);3318DoRelease(depthReadbackSampler_);3319DoRelease(depthReadbackPipeline_);3320DoRelease(draw2DPipelineCopyColor_);3321DoRelease(draw2DPipelineColorRect2Lin_);3322DoRelease(draw2DPipelineCopyDepth_);3323DoRelease(draw2DPipelineEncodeDepth_);3324DoRelease(draw2DPipeline565ToDepth_);3325DoRelease(draw2DPipeline565ToDepthDeswizzle_);3326}33273328void FramebufferManagerCommon::DeviceLost() {3329DestroyAllFBOs();33303331presentation_->DeviceLost();3332draw2D_.DeviceLost();33333334ReleasePipelines();33353336draw_ = nullptr;3337}33383339void FramebufferManagerCommon::DeviceRestore(Draw::DrawContext *draw) {3340draw_ = draw;3341draw2D_.DeviceRestore(draw_);3342presentation_->DeviceRestore(draw_);3343}33443345void 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) {3346// Will be drawn as a strip.3347Draw2DVertex coord[4] = {3348{x, y, u0, v0},3349{x + w, y, u1, v0},3350{x + w, y + h, u1, v1},3351{x, y + h, u0, v1},3352};33533354if (uvRotation != ROTATION_LOCKED_HORIZONTAL) {3355float temp[8];3356int rotation = 0;3357switch (uvRotation) {3358case ROTATION_LOCKED_HORIZONTAL180: rotation = 2; break;3359case ROTATION_LOCKED_VERTICAL: rotation = 1; break;3360case ROTATION_LOCKED_VERTICAL180: rotation = 3; break;3361}3362for (int i = 0; i < 4; i++) {3363temp[i * 2] = coord[((i + rotation) & 3)].u;3364temp[i * 2 + 1] = coord[((i + rotation) & 3)].v;3365}33663367for (int i = 0; i < 4; i++) {3368coord[i].u = temp[i * 2];3369coord[i].v = temp[i * 2 + 1];3370}3371}33723373const float invDestW = 2.0f / destW;3374const float invDestH = 2.0f / destH;3375for (int i = 0; i < 4; i++) {3376coord[i].x = coord[i].x * invDestW - 1.0f;3377coord[i].y = coord[i].y * invDestH - 1.0f;3378}33793380if ((flags & DRAWTEX_TO_BACKBUFFER) && g_display.rotation != DisplayRotation::ROTATE_0) {3381for (int i = 0; i < 4; i++) {3382// backwards notation, should fix that...3383Lin::Vec3 pos = Lin::Vec3(coord[i].x, coord[i].y, 0.0);3384pos = pos * g_display.rot_matrix;3385coord[i].x = pos.x;3386coord[i].y = pos.y;3387}3388}33893390// Rearrange to strip form.3391std::swap(coord[2], coord[3]);33923393draw2D_.DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline((flags & DRAWTEX_DEPTH) ? DRAW2D_ENCODE_R16_TO_DEPTH : DRAW2D_COPY_COLOR));33943395gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3396}33973398void 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) {3399if (!dst->fbo || !src->fbo || !useBufferedRendering_) {3400// This can happen if they recently switched from non-buffered.3401if (useBufferedRendering_) {3402// Just bind the back buffer for rendering, forget about doing anything else as we're in a weird state.3403draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitFramebuffer");3404}3405return;3406}34073408if (channel == RASTER_DEPTH && !draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {3409// Can't do anything :(3410return;3411}34123413// Perform a little bit of clipping first.3414// Block transfer coords are unsigned so I don't think we need to clip on the left side.. Although there are3415// other uses for BlitFramebuffer.3416if (dstX + w > dst->bufferWidth) {3417w -= dstX + w - dst->bufferWidth;3418}3419if (dstY + h > dst->bufferHeight) {3420h -= dstY + h - dst->bufferHeight;3421}3422if (srcX + w > src->bufferWidth) {3423w -= srcX + w - src->bufferWidth;3424}3425if (srcY + h > src->bufferHeight) {3426h -= srcY + h - src->bufferHeight;3427}34283429if (w <= 0 || h <= 0) {3430// The whole rectangle got clipped.3431return;3432}34333434bool useBlit = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferBlitSupported : false;3435bool useCopy = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferCopySupported : false;3436if (dst == currentRenderVfb_ || dst->fbo->MultiSampleLevel() != 0 || src->fbo->MultiSampleLevel() != 0) {3437// If already bound, using either a blit or a copy is unlikely to be an optimization.3438// So we're gonna use a raster draw instead. Also multisampling has problems with copies currently.3439useBlit = false;3440useCopy = false;3441}34423443float srcXFactor = src->renderScaleFactor;3444float srcYFactor = src->renderScaleFactor;3445const int srcBpp = BufferFormatBytesPerPixel(src->Format(channel));3446if (srcBpp != bpp && bpp != 0) {3447// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3448srcXFactor = (srcXFactor * bpp) / srcBpp;3449}3450int srcX1 = srcX * srcXFactor;3451int srcX2 = (srcX + w) * srcXFactor;3452int srcY1 = srcY * srcYFactor;3453int srcY2 = (srcY + h) * srcYFactor;34543455float dstXFactor = dst->renderScaleFactor;3456float dstYFactor = dst->renderScaleFactor;3457const int dstBpp = BufferFormatBytesPerPixel(dst->Format(channel));3458if (dstBpp != bpp && bpp != 0) {3459// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3460dstXFactor = (dstXFactor * bpp) / dstBpp;3461}3462int dstX1 = dstX * dstXFactor;3463int dstX2 = (dstX + w) * dstXFactor;3464int dstY1 = dstY * dstYFactor;3465int dstY2 = (dstY + h) * dstYFactor;34663467if (src == dst && srcX == dstX && srcY == dstY) {3468// Let's just skip a copy where the destination is equal to the source.3469WARN_LOG_REPORT_ONCE(blitSame, Log::G3D, "Skipped blit with equal dst and src");3470return;3471}34723473if (useCopy) {3474// glBlitFramebuffer can clip, but glCopyImageSubData is more restricted.3475// In case the src goes outside, we just skip the optimization in that case.3476const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1;3477const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight;3478const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight;3479const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2;3480const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2;3481if (sameSize && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) {3482draw_->CopyFramebufferImage(src->fbo, 0, srcX1, srcY1, 0, dst->fbo, 0, dstX1, dstY1, 0, dstX2 - dstX1, dstY2 - dstY1, 1,3483channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, tag);3484return;3485}3486}34873488if (useBlit) {3489draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2,3490channel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag);3491} else {3492Draw2DPipeline *pipeline = Get2DPipeline(channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH);3493Draw::Framebuffer *srcFBO = src->fbo;3494if (src == dst) {3495Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight);3496BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, tag);3497srcFBO = tempFBO;3498}3499BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, tag);3500}35013502draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);35033504gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3505}35063507// The input is raw pixel coordinates, scale not taken into account.3508void FramebufferManagerCommon::BlitUsingRaster(3509Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2,3510Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2,3511bool linearFilter,3512int scaleFactor,3513Draw2DPipeline *pipeline, const char *tag) {35143515if (pipeline->info.writeChannel == RASTER_DEPTH) {3516_dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported);3517}35183519int destW, destH, srcW, srcH;3520draw_->GetFramebufferDimensions(src, &srcW, &srcH);3521draw_->GetFramebufferDimensions(dest, &destW, &destH);35223523// 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).3524draw_->BindTexture(0, nullptr);3525// This will get optimized away in case it's already bound (in VK and GL at least..)3526draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster");3527draw_->BindFramebufferAsTexture(src, 0, pipeline->info.readChannel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT, Draw::ALL_LAYERS);35283529if (destX1 == 0.0f && destY1 == 0.0f && destX2 >= destW && destY2 >= destH) {3530// We overwrite the whole channel of the framebuffer, so we can invalidate the current contents.3531draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_LOAD, pipeline->info.writeChannel == RASTER_COLOR ? Draw::FB_COLOR_BIT : Draw::FB_DEPTH_BIT);3532}35333534Draw::Viewport viewport{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f };3535draw_->SetViewport(viewport);3536draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height());35373538draw2D_.Blit(pipeline, srcX1, srcY1, srcX2, srcY2, destX1, destY1, destX2, destY2, (float)srcW, (float)srcH, (float)destW, (float)destH, linearFilter, scaleFactor);35393540gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3541}35423543int FramebufferManagerCommon::GetFramebufferLayers() const {3544int layers = 1;3545if (gstate_c.Use(GPU_USE_SINGLE_PASS_STEREO)) {3546layers = 2;3547}3548return layers;3549}35503551VirtualFramebuffer *FramebufferManagerCommon::ResolveFramebufferColorToFormat(VirtualFramebuffer *src, GEBufferFormat newFormat) {3552// Look for an identical framebuffer with the new format3553_dbg_assert_(src->fb_format != newFormat);35543555VirtualFramebuffer *vfb = nullptr;3556for (auto dest : vfbs_) {3557if (dest == src) {3558continue;3559}35603561// Sanity check for things that shouldn't exist.3562if (dest->fb_address == src->fb_address && dest->fb_format == src->fb_format && dest->fb_stride == src->fb_stride) {3563_dbg_assert_msg_(false, "illegal clone of src found");3564}35653566if (dest->fb_address == src->fb_address && dest->FbStrideInBytes() == src->FbStrideInBytes() && dest->fb_format == newFormat) {3567vfb = dest;3568break;3569}3570}35713572if (!vfb) {3573// Create a clone!3574vfb = new VirtualFramebuffer();3575*vfb = *src; // Copies everything, but watch out! Can't copy fbo.35763577// Adjust width by bpp.3578float widthFactor = (float)BufferFormatBytesPerPixel(vfb->fb_format) / (float)BufferFormatBytesPerPixel(newFormat);35793580vfb->width *= widthFactor;3581vfb->bufferWidth *= widthFactor;3582vfb->renderWidth *= widthFactor;3583vfb->drawnWidth *= widthFactor;3584vfb->newWidth *= widthFactor;3585vfb->safeWidth *= widthFactor;35863587vfb->fb_format = newFormat;3588// stride stays the same since it's in pixels.35893590WARN_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);35913592char tag[128];3593FormatFramebufferName(vfb, tag, sizeof(tag));3594vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, true, tag });3595vfbs_.push_back(vfb);3596}35973598// OK, now resolve it so we can texture from it.3599// This will do any necessary reinterprets.3600CopyToColorFromOverlappingFramebuffers(vfb);3601// Now we consider the resolved one the latest at the address (though really, we could make them equivalent?).3602vfb->colorBindSeq = GetBindSeqCount();3603return vfb;3604}36053606static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width) {3607// Detect whether we're rendering to the margin.3608bool margin;3609if ((params->scissorRight - params->scissorLeft) == 32) {3610// Title screen has this easy case. It also uses non-through verts, so lucky for us that we have this.3611margin = true;3612} else if (params->scissorRight == 480) {3613margin = false;3614} else {3615// Go deep, look at the vertices. Killzone-specific, of course.3616margin = false;3617if ((gstate.vertType & 0xFFFFFF) == 0x00800102) { // through, u16, s163618u16 *vdata = (u16 *)Memory::GetPointerUnchecked(gstate_c.vertexAddr);3619int v0PosU = vdata[0];3620int v0PosX = vdata[2];3621if (v0PosX >= 480 && v0PosU < 480) {3622// Texturing from surface, writing to margin3623margin = true;3624}3625}36263627// TODO: Implement this for Burnout Dominator. It has to handle self-reads inside3628// the margin framebuffer though, so framebuffer copies are still needed, just smaller.3629// It uses 0x0080019f (through, float texcoords, ABGR 8888 colors, float positions).3630}36313632if (margin) {3633gstate_c.SetCurRTOffset(-480, 0);3634// Modify the fb_address and z_address too to avoid matching below.3635params->fb_address += 480 * 4;3636params->z_address += 480 * 2;3637*drawing_width = 32;3638} else {3639gstate_c.SetCurRTOffset(0, 0);3640*drawing_width = 480;3641}3642}364336443645