Path: blob/master/GPU/Common/FramebufferManagerCommon.cpp
5654 views
// Copyright (c) 2012- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <algorithm>18#include <sstream>19#include <cmath>2021#include "Common/GPU/thin3d.h"22#include "Common/Data/Collections/TinySet.h"23#include "Common/Data/Convert/ColorConv.h"24#include "Common/LogReporting.h"25#include "Common/System/Display.h"26#include "Common/VR/PPSSPPVR.h"27#include "Common/CommonTypes.h"28#include "Common/StringUtils.h"29#include "Core/Config.h"30#include "Core/ConfigValues.h"31#include "Core/Core.h"32#include "Core/CoreParameter.h"33#include "Core/Debugger/MemBlockInfo.h"34#include "GPU/Common/DrawEngineCommon.h"35#include "GPU/Common/FramebufferManagerCommon.h"36#include "GPU/Common/PresentationCommon.h"37#include "GPU/Common/TextureCacheCommon.h"38#include "GPU/Common/ReinterpretFramebuffer.h"39#include "GPU/GPUCommon.h"40#include "GPU/GPUState.h"4142static size_t FormatFramebufferName(const VirtualFramebuffer *vfb, char *tag, size_t len) {43return snprintf(tag, len, "FB_%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, vfb->bufferWidth, vfb->bufferHeight, GeBufferFormatToString(vfb->fb_format));44}4546FramebufferManagerCommon::FramebufferManagerCommon(Draw::DrawContext *draw)47: draw_(draw), draw2D_(draw_) {48presentation_ = new PresentationCommon(draw);49}5051FramebufferManagerCommon::~FramebufferManagerCommon() {52DeviceLost();5354DecimateFBOs();55for (auto vfb : vfbs_) {56DestroyFramebuf(vfb);57}58vfbs_.clear();5960for (auto &tempFB : tempFBOs_) {61tempFB.second.fbo->Release();62}63tempFBOs_.clear();6465// Do the same for ReadFramebuffersToMemory's VFBs66for (auto vfb : bvfbs_) {67DestroyFramebuf(vfb);68}69bvfbs_.clear();7071delete presentation_;72delete[] convBuf_;73}7475void FramebufferManagerCommon::Init(int msaaLevel) {76// We may need to override the render size if the shader is upscaling or SSAA.77NotifyDisplayResized();78NotifyRenderResized(displayLayoutConfigCopy_, msaaLevel);79}8081// Returns true if we need to stop the render thread82bool FramebufferManagerCommon::UpdateRenderSize(int msaaLevel) {83const bool newRender = renderWidth_ != (float)PSP_CoreParameter().renderWidth || renderHeight_ != (float)PSP_CoreParameter().renderHeight || msaaLevel_ != msaaLevel;8485int effectiveBloomHack = g_Config.iBloomHack;86if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {87effectiveBloomHack = 3;88} else if (PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOff) {89effectiveBloomHack = 0;90}9192bool newBuffered = !g_Config.bSkipBufferEffects;93const bool newSettings = bloomHack_ != effectiveBloomHack || useBufferedRendering_ != newBuffered;9495renderWidth_ = (float)PSP_CoreParameter().renderWidth;96renderHeight_ = (float)PSP_CoreParameter().renderHeight;97renderScaleFactor_ = (float)PSP_CoreParameter().renderScaleFactor;98msaaLevel_ = msaaLevel;99100bloomHack_ = effectiveBloomHack;101useBufferedRendering_ = newBuffered;102103presentation_->UpdateRenderSize(renderWidth_, renderHeight_);104105// If just switching TO buffered rendering, no need to pause the threads. In fact this causes problems due to the open backbuffer renderpass.106if (!useBufferedRendering_ && newBuffered) {107return false;108}109return newRender || newSettings;110}111112void FramebufferManagerCommon::CheckPostShaders(const DisplayLayoutConfig &config) {113if (updatePostShaders_) {114presentation_->UpdatePostShader(config);115updatePostShaders_ = false;116}117}118119void FramebufferManagerCommon::BeginFrame(const DisplayLayoutConfig &config) {120DecimateFBOs();121presentation_->BeginFrame(config);122currentRenderVfb_ = nullptr;123124// Hack.125displayLayoutConfigCopy_ = config;126}127128bool FramebufferManagerCommon::PresentedThisFrame() const {129return presentation_->PresentedThisFrame();130}131132void FramebufferManagerCommon::SetDisplayFramebuffer(u32 framebuf, u32 stride, GEBufferFormat format) {133displayFramebufPtr_ = framebuf & 0x3FFFFFFF;134if (Memory::IsVRAMAddress(displayFramebufPtr_))135displayFramebufPtr_ = framebuf & 0x041FFFFF;136displayStride_ = stride;137displayFormat_ = format;138}139140VirtualFramebuffer *FramebufferManagerCommon::GetVFBAt(u32 addr) const {141addr &= 0x3FFFFFFF;142if (Memory::IsVRAMAddress(addr))143addr &= 0x041FFFFF;144VirtualFramebuffer *match = nullptr;145for (auto vfb : vfbs_) {146if (vfb->fb_address == addr) {147// Could check w too but whatever (actually, might very well make sense to do so, depending on context).148if (!match || vfb->last_frame_render > match->last_frame_render) {149match = vfb;150}151}152}153return match;154}155156VirtualFramebuffer *FramebufferManagerCommon::GetExactVFB(u32 addr, int stride, GEBufferFormat format) const {157addr &= 0x3FFFFFFF;158if (Memory::IsVRAMAddress(addr))159addr &= 0x041FFFFF;160VirtualFramebuffer *newest = nullptr;161for (auto vfb : vfbs_) {162if (vfb->fb_address == addr && vfb->fb_stride == stride && vfb->fb_format == format) {163if (newest) {164if (vfb->colorBindSeq > newest->colorBindSeq) {165newest = vfb;166}167} else {168newest = vfb;169}170}171}172return newest;173}174175VirtualFramebuffer *FramebufferManagerCommon::ResolveVFB(u32 addr, int stride, GEBufferFormat format) {176addr &= 0x3FFFFFFF;177if (Memory::IsVRAMAddress(addr))178addr &= 0x041FFFFF;179// Find the newest one matching addr and stride.180VirtualFramebuffer *newest = nullptr;181for (auto vfb : vfbs_) {182if (vfb->fb_address == addr && vfb->FbStrideInBytes() == stride * BufferFormatBytesPerPixel(format)) {183if (newest) {184if (vfb->colorBindSeq > newest->colorBindSeq) {185newest = vfb;186}187} else {188newest = vfb;189}190}191}192193if (newest && newest->fb_format != format) {194WARN_LOG_ONCE(resolvevfb, Log::G3D, "ResolveVFB: Resolving from %s to %s at %08x/%d", GeBufferFormatToString(newest->fb_format), GeBufferFormatToString(format), addr, stride);195return ResolveFramebufferColorToFormat(newest, format);196}197198return newest;199}200201VirtualFramebuffer *FramebufferManagerCommon::GetDisplayVFB() {202return GetExactVFB(displayFramebufPtr_, displayStride_, displayFormat_);203}204205// Heuristics to figure out the size of FBO to create.206// TODO: Possibly differentiate on whether through mode is used (since in through mode, viewport is meaningless?)207void 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) {208static const int MAX_FRAMEBUF_HEIGHT = 512;209210// Games don't always set any of these. Take the greatest parameter that looks valid based on stride.211if (viewport_width > 4 && viewport_width <= fb_stride && viewport_height > 0) {212drawing_width = viewport_width;213drawing_height = viewport_height;214// Some games specify a viewport with 0.5, but don't have VRAM for 273. 480x272 is the buffer size.215if (viewport_width == 481 && region_width == 480 && viewport_height == 273 && region_height == 272) {216drawing_width = 480;217drawing_height = 272;218}219// Sometimes region is set larger than the VRAM for the framebuffer.220// However, in one game it's correctly set as a larger height (see #7277) with the same width.221// A bit of a hack, but we try to handle that unusual case here.222if (region_width <= fb_stride && (region_width > drawing_width || (region_width == drawing_width && region_height > drawing_height)) && region_height <= MAX_FRAMEBUF_HEIGHT) {223drawing_width = region_width;224drawing_height = std::max(drawing_height, region_height);225}226// Scissor is often set to a subsection of the framebuffer, so we pay the least attention to it.227if (scissor_width <= fb_stride && scissor_width > drawing_width && scissor_height <= MAX_FRAMEBUF_HEIGHT) {228drawing_width = scissor_width;229drawing_height = std::max(drawing_height, scissor_height);230}231} else {232// If viewport wasn't valid, let's just take the greatest anything regardless of stride.233drawing_width = std::min(std::max(region_width, scissor_width), fb_stride);234drawing_height = std::max(region_height, scissor_height);235}236237if (scissor_width == 481 && region_width == 480 && scissor_height == 273 && region_height == 272) {238drawing_width = 480;239drawing_height = 272;240}241242// Assume no buffer is > 512 tall, it couldn't be textured or displayed fully if so.243if (drawing_height >= MAX_FRAMEBUF_HEIGHT) {244if (region_height < MAX_FRAMEBUF_HEIGHT) {245drawing_height = region_height;246} else if (scissor_height < MAX_FRAMEBUF_HEIGHT) {247drawing_height = scissor_height;248}249}250251if (viewport_width != region_width) {252// The majority of the time, these are equal. If not, let's check what we know.253u32 nearest_address = 0xFFFFFFFF;254for (auto vfb : vfbs_) {255const u32 other_address = vfb->fb_address;256if (other_address > fb_address && other_address < nearest_address) {257nearest_address = other_address;258}259}260261// Unless the game is using overlapping buffers, the next buffer should be far enough away.262// This catches some cases where we can know this.263// Hmm. The problem is that we could only catch it for the first of two buffers...264const u32 bpp = BufferFormatBytesPerPixel(fb_format);265int avail_height = (nearest_address - fb_address) / (fb_stride * bpp);266if (avail_height < drawing_height && avail_height == region_height) {267drawing_width = std::min(region_width, fb_stride);268drawing_height = avail_height;269}270271// Some games draw buffers interleaved, with a high stride/region/scissor but default viewport.272if (fb_stride == 1024 && region_width == 1024 && scissor_width == 1024) {273drawing_width = 1024;274}275}276277bool margin = false;278// Let's check if we're in a stride gap of a full-size framebuffer.279for (auto vfb : vfbs_) {280if (fb_address == vfb->fb_address) {281continue;282}283if (vfb->fb_stride != 512) {284continue;285}286287int vfb_stride_in_bytes = BufferFormatBytesPerPixel(vfb->fb_format) * vfb->fb_stride;288int stride_in_bytes = BufferFormatBytesPerPixel(fb_format) * fb_stride;289if (stride_in_bytes != vfb_stride_in_bytes) {290// Mismatching stride in bytes, not interesting291continue;292}293294if (fb_address > vfb->fb_address && fb_address < vfb->fb_address + vfb_stride_in_bytes) {295// Candidate!296if (vfb->height == drawing_height) {297// Might have a margin texture! Fix the drawing width if it's too large.298int width_in_bytes = vfb->fb_address + vfb_stride_in_bytes - fb_address;299int width_in_pixels = width_in_bytes / BufferFormatBytesPerPixel(fb_format);300301// Final check302if (width_in_pixels <= 32) {303drawing_width = std::min(drawing_width, width_in_pixels);304margin = true;305// Don't really need to keep looking.306break;307}308}309}310}311312DEBUG_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!)" : "");313}314315void GetFramebufferHeuristicInputs(FramebufferHeuristicParams *params, const GPUgstate &gstate) {316// GetFramebufferHeuristicInputs is only called from rendering, and thus, it's VRAM.317params->fb_address = gstate.getFrameBufRawAddress() | 0x04000000;318params->fb_stride = gstate.FrameBufStride();319320params->z_address = gstate.getDepthBufRawAddress() | 0x04000000;321params->z_stride = gstate.DepthBufStride();322323if (params->z_address == params->fb_address) {324// Probably indicates that the game doesn't care about Z for this VFB.325// Let's avoid matching it for Z copies and other shenanigans.326params->z_address = 0;327params->z_stride = 0;328}329330params->fb_format = gstate_c.framebufFormat;331332params->isClearingDepth = gstate.isModeClear() && gstate.isClearModeDepthMask();333// Technically, it may write depth later, but we're trying to detect it only when it's really true.334if (gstate.isModeClear()) {335// Not quite seeing how this makes sense..336params->isWritingDepth = !gstate.isClearModeDepthMask() && gstate.isDepthWriteEnabled();337} else {338params->isWritingDepth = gstate.isDepthWriteEnabled();339}340params->isDrawing = !gstate.isModeClear() || !gstate.isClearModeColorMask() || !gstate.isClearModeAlphaMask();341params->isModeThrough = gstate.isModeThrough();342const bool alphaBlending = gstate.isAlphaBlendEnabled();343const bool logicOpBlending = gstate.isLogicOpEnabled() && gstate.getLogicOp() != GE_LOGIC_CLEAR && gstate.getLogicOp() != GE_LOGIC_COPY;344params->isBlending = alphaBlending || logicOpBlending;345346// Viewport-X1 and Y1 are not the upper left corner, but half the width/height. A bit confusing.347float vpx = gstate.getViewportXScale();348float vpy = gstate.getViewportYScale();349350// Work around problem in F1 Grand Prix, where it draws in through mode with a bogus viewport.351// We set bad values to 0 which causes the framebuffer size heuristic to rely on the other parameters instead.352if (std::isnan(vpx) || vpx > 10000000.0f) {353vpx = 0.f;354}355if (std::isnan(vpy) || vpy > 10000000.0f) {356vpy = 0.f;357}358params->viewportWidth = (int)(fabsf(vpx) * 2.0f);359params->viewportHeight = (int)(fabsf(vpy) * 2.0f);360params->regionWidth = gstate.getRegionX2() + 1;361params->regionHeight = gstate.getRegionY2() + 1;362363params->scissorLeft = gstate.getScissorX1();364params->scissorTop = gstate.getScissorY1();365params->scissorRight = gstate.getScissorX2() + 1;366params->scissorBottom = gstate.getScissorY2() + 1;367368if (gstate.getRegionRateX() != 0x100 || gstate.getRegionRateY() != 0x100) {369WARN_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());370}371}372373static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width);374375VirtualFramebuffer *FramebufferManagerCommon::DoSetRenderFrameBuffer(FramebufferHeuristicParams ¶ms, u32 skipDrawReason) {376gstate_c.Clean(DIRTY_FRAMEBUF);377378// Collect all parameters. This whole function has really become a cesspool of heuristics...379// but it appears that's what it takes, unless we emulate VRAM layout more accurately somehow.380381// As there are no clear "framebuffer width" and "framebuffer height" registers,382// we need to infer the size of the current framebuffer somehow.383int drawing_width, drawing_height;384EstimateDrawingSize(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);385386if (params.fb_address == params.z_address) {387// Most likely Z will not be used in this pass, as that would wreak havoc (undefined behavior for sure)388// We probably don't need to do anything about that, but let's log it.389WARN_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);390}391392// Compatibility hack for Killzone, see issue #6207.393if (PSP_CoreParameter().compat.flags().SplitFramebufferMargin && params.fb_format == GE_FORMAT_8888) {394ApplyKillzoneFramebufferSplit(¶ms, &drawing_width);395} else {396gstate_c.SetCurRTOffset(0, 0);397}398399// Find a matching framebuffer.400VirtualFramebuffer *normal_vfb = nullptr;401int y_offset;402VirtualFramebuffer *large_offset_vfb = nullptr;403404for (auto v : vfbs_) {405const u32 bpp = BufferFormatBytesPerPixel(v->fb_format);406407if (params.fb_address == v->fb_address && params.fb_format == v->fb_format && params.fb_stride == v->fb_stride) {408if (!normal_vfb) {409normal_vfb = v;410}411} else if (!PSP_CoreParameter().compat.flags().DisallowFramebufferAtOffset && !PSP_CoreParameter().compat.flags().SplitFramebufferMargin &&412v->fb_stride == params.fb_stride && v->fb_format == params.fb_format) {413u32 v_fb_first_line_end_ptr = v->fb_address + v->fb_stride * bpp;414u32 v_fb_end_ptr = v->fb_address + v->fb_stride * v->height * bpp;415416if (!normal_vfb && params.fb_address > v->fb_address && params.fb_address < v_fb_first_line_end_ptr) {417const int x_offset = (params.fb_address - v->fb_address) / bpp;418if (x_offset < params.fb_stride && v->height >= drawing_height) {419// Pretty certainly a pure render-to-X-offset.420WARN_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);421normal_vfb = v;422gstate_c.SetCurRTOffset(x_offset, 0);423normal_vfb->width = std::max((int)normal_vfb->width, x_offset + drawing_width);424// To prevent the newSize code from being confused.425drawing_width += x_offset;426break;427}428} else if (PSP_CoreParameter().compat.flags().FramebufferAllowLargeVerticalOffset &&429params.fb_address > v->fb_address && v->fb_stride > 0 && (params.fb_address - v->fb_address) % v->FbStrideInBytes() == 0 &&430params.fb_address != 0x04088000 && v->fb_address != 0x04000000) { // Heuristic to avoid merging the main framebuffers.431y_offset = (params.fb_address - v->fb_address) / v->FbStrideInBytes();432if (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.433large_offset_vfb = v;434break;435}436}437}438}439440VirtualFramebuffer *vfb = nullptr;441if (large_offset_vfb) {442// These are prioritized over normal VFBs matches, to ensure things work even if the higher-address one443// is created first. Only enabled under compat flag.444vfb = large_offset_vfb;445WARN_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);446gstate_c.SetCurRTOffset(0, y_offset);447vfb->height = std::max((int)vfb->height, y_offset + drawing_height);448drawing_height += y_offset;449// TODO: We can allow X/Y overlaps too, but haven't seen any so safer to not.450} else if (normal_vfb) {451vfb = normal_vfb;452if (vfb->z_address == 0 && vfb->z_stride == 0 && params.z_stride != 0) {453// Got one that was created by CreateRAMFramebuffer. Since it has no depth buffer,454// we just recreate it immediately.455ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);456}457458// Keep track, but this isn't really used.459vfb->z_stride = params.z_stride;460// Heuristic: In throughmode, a higher height could be used. Let's avoid shrinking the buffer.461if (params.isModeThrough && (int)vfb->width <= params.fb_stride) {462vfb->width = std::max((int)vfb->width, drawing_width);463vfb->height = std::max((int)vfb->height, drawing_height);464} else {465vfb->width = drawing_width;466vfb->height = drawing_height;467}468}469470if (vfb) {471bool resized = false;472if ((drawing_width != vfb->bufferWidth || drawing_height != vfb->bufferHeight)) {473// Even if it's not newly wrong, if this is larger we need to resize up.474if (vfb->width > vfb->bufferWidth || vfb->height > vfb->bufferHeight) {475ResizeFramebufFBO(vfb, vfb->width, vfb->height);476resized = true;477} else if (vfb->newWidth != drawing_width || vfb->newHeight != drawing_height) {478// If it's newly wrong, or changing every frame, just keep track.479vfb->newWidth = drawing_width;480vfb->newHeight = drawing_height;481vfb->lastFrameNewSize = gpuStats.numFlips;482} else if (vfb->lastFrameNewSize + FBO_OLD_AGE < gpuStats.numFlips) {483// Okay, it's changed for a while (and stayed that way.) Let's start over.484// But only if we really need to, to avoid blinking.485bool needsRecreate = vfb->bufferWidth > params.fb_stride;486needsRecreate = needsRecreate || vfb->newWidth > vfb->bufferWidth || vfb->newWidth * 2 < vfb->bufferWidth;487needsRecreate = needsRecreate || vfb->newHeight > vfb->bufferHeight || vfb->newHeight * 2 < vfb->bufferHeight;488489// Whether we resize or not, change the size parameters so we stop detecting a resize.490// It might be larger if all drawing has been in throughmode.491vfb->width = drawing_width;492vfb->height = drawing_height;493494if (needsRecreate) {495ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);496resized = true;497// Let's discard this information, might be wrong now.498vfb->safeWidth = 0;499vfb->safeHeight = 0;500}501}502} else {503// It's not different, let's keep track of that too.504vfb->lastFrameNewSize = gpuStats.numFlips;505}506507if (!resized && renderScaleFactor_ != 1 && vfb->renderScaleFactor == 1) {508// Might be time to change this framebuffer - have we used depth?509if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {510ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);511_assert_(vfb->renderScaleFactor != 1);512}513}514}515516// None found? Create one.517if (!vfb) {518gstate_c.usingDepth = false; // reset depth buffer tracking519520vfb = new VirtualFramebuffer{};521vfb->fbo = nullptr;522vfb->fb_address = params.fb_address;523vfb->fb_stride = params.fb_stride;524vfb->z_address = params.z_address;525vfb->z_stride = params.z_stride;526527// The other width/height parameters are set in ResizeFramebufFBO below.528vfb->width = drawing_width;529vfb->height = drawing_height;530vfb->newWidth = drawing_width;531vfb->newHeight = drawing_height;532vfb->lastFrameNewSize = gpuStats.numFlips;533vfb->fb_format = params.fb_format;534vfb->usageFlags = FB_USAGE_RENDER_COLOR;535536u32 colorByteSize = vfb->BufferByteSize(RASTER_COLOR);537if (Memory::IsVRAMAddress(params.fb_address) && params.fb_address + colorByteSize > framebufColorRangeEnd_) {538framebufColorRangeEnd_ = params.fb_address + colorByteSize;539}540541// This is where we actually create the framebuffer. The true is "force".542ResizeFramebufFBO(vfb, drawing_width, drawing_height, true);543NotifyRenderFramebufferCreated(vfb);544545// Note that we do not even think about depth right now. That'll be handled546// on the first depth access, which will call SetDepthFramebuffer.547548CopyToColorFromOverlappingFramebuffers(vfb);549SetColorUpdated(vfb, skipDrawReason);550551INFO_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));552553vfb->last_frame_render = gpuStats.numFlips;554frameLastFramebufUsed_ = gpuStats.numFlips;555vfbs_.push_back(vfb);556currentRenderVfb_ = vfb;557558// Assume that if we're clearing right when switching to a new framebuffer, we don't need to upload.559if (useBufferedRendering_ && params.isDrawing && vfb->fb_stride > 0) {560gpu->PerformWriteColorFromMemory(params.fb_address, colorByteSize);561// Alpha was already done by PerformWriteColorFromMemory.562PerformWriteStencilFromMemory(params.fb_address, colorByteSize, WriteStencil::STENCIL_IS_ZERO | WriteStencil::IGNORE_ALPHA);563// TODO: Is it worth trying to upload the depth buffer (only if it wasn't copied above..?)564}565566DiscardFramebufferCopy();567568// We already have it!569} else if (vfb != currentRenderVfb_) {570// Use it as a render target.571DEBUG_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);572vfb->usageFlags |= FB_USAGE_RENDER_COLOR;573vfb->last_frame_render = gpuStats.numFlips;574frameLastFramebufUsed_ = gpuStats.numFlips;575vfb->dirtyAfterDisplay = true;576if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)577vfb->reallyDirtyAfterDisplay = true;578579VirtualFramebuffer *prev = currentRenderVfb_;580currentRenderVfb_ = vfb;581NotifyRenderFramebufferSwitched(prev, vfb, params.isClearingDepth);582CopyToColorFromOverlappingFramebuffers(vfb);583gstate_c.usingDepth = false; // reset depth buffer tracking584585DiscardFramebufferCopy();586} else {587// Something changed, but we still got the same framebuffer we were already rendering to.588// Might not be a lot to do here, we check in NotifyRenderFramebufferUpdated589vfb->last_frame_render = gpuStats.numFlips;590frameLastFramebufUsed_ = gpuStats.numFlips;591vfb->dirtyAfterDisplay = true;592if ((skipDrawReason & SKIPDRAW_SKIPFRAME) == 0)593vfb->reallyDirtyAfterDisplay = true;594NotifyRenderFramebufferUpdated(vfb);595}596597vfb->colorBindSeq = GetBindSeqCount();598599gstate_c.curRTWidth = vfb->width;600gstate_c.curRTHeight = vfb->height;601gstate_c.curRTRenderWidth = vfb->renderWidth;602gstate_c.curRTRenderHeight = vfb->renderHeight;603return vfb;604}605606// Called on the first use of depth in a render pass.607void FramebufferManagerCommon::SetDepthFrameBuffer(bool isClearingDepth) {608if (!currentRenderVfb_) {609return;610}611612// First time use of this framebuffer's depth buffer.613bool newlyUsingDepth = (currentRenderVfb_->usageFlags & FB_USAGE_RENDER_DEPTH) == 0;614currentRenderVfb_->usageFlags |= FB_USAGE_RENDER_DEPTH;615616uint32_t boundDepthBuffer = gstate.getDepthBufRawAddress() | 0x04000000;617uint32_t boundDepthStride = gstate.DepthBufStride();618if (currentRenderVfb_->z_address != boundDepthBuffer || currentRenderVfb_->z_stride != boundDepthStride) {619if (currentRenderVfb_->fb_address == boundDepthBuffer) {620// Disallow setting depth buffer to the same address as the color buffer, usually means it's not used.621WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Ignoring color matching depth buffer at %08x", boundDepthBuffer);622boundDepthBuffer = 0;623boundDepthStride = 0;624}625WARN_LOG_N_TIMES(z_reassign, 5, Log::FrameBuf, "Framebuffer at %08x/%d has switched associated depth buffer from %08x to %08x, updating.",626currentRenderVfb_->fb_address, currentRenderVfb_->fb_stride, currentRenderVfb_->z_address, boundDepthBuffer);627628// Technically, here we should copy away the depth buffer to another framebuffer that uses that z_address, or maybe629// even write it back to RAM. However, this is rare. Silent Hill is one example, see #16126.630currentRenderVfb_->z_address = boundDepthBuffer;631// Update the stride in case it changed.632currentRenderVfb_->z_stride = boundDepthStride;633634if (currentRenderVfb_->fbo) {635char tag[128];636FormatFramebufferName(currentRenderVfb_, tag, sizeof(tag));637currentRenderVfb_->fbo->UpdateTag(tag);638}639}640641// If this first draw call is anything other than a clear, "resolve" the depth buffer,642// by copying from any overlapping buffers with fresher content.643if (!isClearingDepth && useBufferedRendering_) {644CopyToDepthFromOverlappingFramebuffers(currentRenderVfb_);645646// Need to upload the first line of depth buffers, for Burnout Dominator lens flares. See issue #11100 and comments to #16081.647// Might make this more generic and upload the whole depth buffer if we find it's needed for something.648if (newlyUsingDepth && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {649// Sanity check the depth buffer pointer.650if (Memory::IsValidRange(currentRenderVfb_->z_address, currentRenderVfb_->width * 2)) {651const u16 *src = (const u16 *)Memory::GetPointerUnchecked(currentRenderVfb_->z_address);652DrawPixels(currentRenderVfb_, 0, 0, (const u8 *)src, GE_FORMAT_DEPTH16, currentRenderVfb_->z_stride, currentRenderVfb_->width, currentRenderVfb_->height, RASTER_DEPTH, "Depth Upload");653}654}655}656657currentRenderVfb_->depthBindSeq = GetBindSeqCount();658}659660struct CopySource {661VirtualFramebuffer *vfb;662RasterChannel channel;663int xOffset;664int yOffset;665666int seq() const {667return channel == RASTER_DEPTH ? vfb->depthBindSeq : vfb->colorBindSeq;668}669670bool operator < (const CopySource &other) const {671return seq() < other.seq();672}673};674675// 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)676// 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 memory677// bandwidth on tilers due to the load operation, which we might otherwise be able to skip).678void FramebufferManagerCommon::CopyToDepthFromOverlappingFramebuffers(VirtualFramebuffer *dest) {679std::vector<CopySource> sources;680for (auto src : vfbs_) {681if (src == dest)682continue;683684if (src->fb_address == dest->z_address && src->fb_stride == dest->z_stride && src->fb_format == GE_FORMAT_565) {685if (src->colorBindSeq > dest->depthBindSeq) {686// Source has newer data than the current buffer, use it.687sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });688}689} else if (src->z_address == dest->z_address && src->z_stride == dest->z_stride && src->depthBindSeq > dest->depthBindSeq) {690sources.push_back(CopySource{ src, RASTER_DEPTH, 0, 0 });691} else {692// TODO: Do more detailed overlap checks here.693}694}695696std::sort(sources.begin(), sources.end());697698// TODO: A full copy will overwrite anything else. So we can eliminate699// anything that comes before such a copy.700701// For now, let's just do the last thing, if there are multiple.702703// for (auto &source : sources) {704if (!sources.empty()) {705draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);706707auto &source = sources.back();708if (source.channel == RASTER_DEPTH) {709// Good old depth->depth copy.710BlitFramebufferDepth(source.vfb, dest);711gpuStats.numDepthCopies++;712dest->last_frame_depth_updated = gpuStats.numFlips;713} else if (source.channel == RASTER_COLOR && draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {714VirtualFramebuffer *src = source.vfb;715if (src->fb_format != GE_FORMAT_565) {716WARN_LOG_ONCE(not565, Log::FrameBuf, "fb_format of buffer at %08x not 565 as expected", src->fb_address);717}718719// Really hate to do this, but tracking the depth swizzle state across multiple720// copies is not easy.721Draw2DShader shader = DRAW2D_565_TO_DEPTH;722if (PSP_CoreParameter().compat.flags().DeswizzleDepth) {723shader = DRAW2D_565_TO_DEPTH_DESWIZZLE;724}725726gpuStats.numReinterpretCopies++;727src->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;728dest->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;729730// Copying color to depth.731BlitUsingRaster(732src->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,733dest->fbo, 0.0f, 0.0f, src->renderWidth, src->renderHeight,734false, dest->renderScaleFactor, Get2DPipeline(shader), "565_to_depth");735}736}737738gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);739}740741// Can't easily dynamically create these strings, we just pass along the pointer.742static const char *reinterpretStrings[4][4] = {743{744"self_reinterpret_565",745"reinterpret_565_to_5551",746"reinterpret_565_to_4444",747"reinterpret_565_to_8888",748},749{750"reinterpret_5551_to_565",751"self_reinterpret_5551",752"reinterpret_5551_to_4444",753"reinterpret_5551_to_8888",754},755{756"reinterpret_4444_to_565",757"reinterpret_4444_to_5551",758"self_reinterpret_4444",759"reinterpret_4444_to_8888",760},761{762"reinterpret_8888_to_565",763"reinterpret_8888_to_5551",764"reinterpret_8888_to_4444",765"self_reinterpret_8888",766},767};768769// Call this after the target has been bound for rendering. For color, raster is probably always going to win over blits/copies.770void FramebufferManagerCommon::CopyToColorFromOverlappingFramebuffers(VirtualFramebuffer *dst) {771if (!useBufferedRendering_) {772return;773}774775std::vector<CopySource> sources;776for (auto src : vfbs_) {777// Discard old and equal potential inputs.778if (src == dst || src->colorBindSeq < dst->colorBindSeq) {779continue;780}781782if (src->fb_address == dst->fb_address && src->fb_stride == dst->fb_stride) {783// Another render target at the exact same location but gotta be a different format or a different stride, otherwise784// it would be the same, and should have been detected in DoSetRenderFrameBuffer.785if (src->fb_format != dst->fb_format) {786// This will result in reinterpret later, if both formats are 16-bit.787sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });788} else {789// This shouldn't happen anymore. I think when it happened last, we still had790// lax stride checking when video was incoming, and a resize happened causing a duplicate.791}792} else if (src->fb_stride == dst->fb_stride && src->fb_format == dst->fb_format) {793u32 bytesPerPixel = BufferFormatBytesPerPixel(src->fb_format);794795u32 strideInBytes = src->fb_stride * bytesPerPixel; // Same for both src and dest796797u32 srcColorStart = src->fb_address;798u32 srcFirstLineEnd = src->fb_address + strideInBytes;799u32 srcColorEnd = strideInBytes * src->height;800801u32 dstColorStart = dst->fb_address;802u32 dstFirstLineEnd = dst->fb_address + strideInBytes;803u32 dstColorEnd = strideInBytes * dst->height;804805// Initially we'll only allow pure horizontal and vertical overlap,806// to reduce the risk for false positives. We can allow diagonal overlap too if needed807// in the future.808809// Check for potential vertical overlap, like in Juiced 2.810int xOffset = 0;811int yOffset = 0;812813// TODO: Get rid of the compatibility flag check.814if ((dstColorStart - srcColorStart) % strideInBytes == 0815&& PSP_CoreParameter().compat.flags().AllowLargeFBTextureOffsets) {816// Buffers are aligned.817yOffset = ((int)dstColorStart - (int)srcColorStart) / strideInBytes;818if (yOffset <= -(int)src->height) {819// Not overlapping820continue;821} else if (yOffset >= dst->height) {822// Not overlapping823continue;824}825} else {826// Buffers not stride-aligned - ignoring for now.827// This is where we'll add the horizontal offset for GoW.828continue;829}830sources.push_back(CopySource{ src, RASTER_COLOR, xOffset, yOffset });831} else if (src->fb_address == dst->fb_address && src->FbStrideInBytes() == dst->FbStrideInBytes()) {832if (src->fb_stride == dst->fb_stride * 2) {833// Reinterpret from 16-bit to 32-bit.834sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });835} else if (src->fb_stride * 2 == dst->fb_stride) {836// Reinterpret from 32-bit to 16-bit.837sources.push_back(CopySource{ src, RASTER_COLOR, 0, 0 });838} else {839// 16-to-16 reinterpret, should have been caught above already.840_assert_msg_(false, "Reinterpret: Shouldn't get here");841}842}843}844845std::sort(sources.begin(), sources.end());846847draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);848849bool tookActions = false;850851// TODO: Only do the latest one.852for (const CopySource &source : sources) {853VirtualFramebuffer *src = source.vfb;854855// Copy a rectangle from the original to the new buffer.856// Yes, we mean to look at src->width/height for the dest rectangle.857858// TODO: Try to bound the blit using gstate_c.vertBounds like depal does.859860int srcWidth = src->width * src->renderScaleFactor;861int srcHeight = src->height * src->renderScaleFactor;862int dstWidth = src->width * dst->renderScaleFactor;863int dstHeight = src->height * dst->renderScaleFactor;864865int dstX1 = -source.xOffset * dst->renderScaleFactor;866int dstY1 = -source.yOffset * dst->renderScaleFactor;867int dstX2 = dstX1 + dstWidth;868int dstY2 = dstY1 + dstHeight;869870if (source.channel == RASTER_COLOR) {871Draw2DPipeline *pipeline = nullptr;872const char *pass_name = "N/A";873float scaleFactorX = 1.0f;874if (src->fb_format == dst->fb_format) {875gpuStats.numColorCopies++;876pipeline = Get2DPipeline(DRAW2D_COPY_COLOR);877pass_name = "copy_color";878} else {879if (PSP_CoreParameter().compat.flags().BlueToAlpha) {880WARN_LOG_ONCE(bta, Log::FrameBuf, "WARNING: Reinterpret encountered with BlueToAlpha on");881}882883// Reinterpret!884WARN_LOG_N_TIMES(reint, 5, Log::FrameBuf, "Reinterpret detected from %08x_%s to %08x_%s",885src->fb_address, GeBufferFormatToString(src->fb_format),886dst->fb_address, GeBufferFormatToString(dst->fb_format));887888pipeline = GetReinterpretPipeline(src->fb_format, dst->fb_format, &scaleFactorX);889dstX1 *= scaleFactorX;890dstX2 *= scaleFactorX;891892pass_name = reinterpretStrings[(int)src->fb_format][(int)dst->fb_format];893894gpuStats.numReinterpretCopies++;895}896897if (pipeline) {898tookActions = true;899// OK we have the pipeline, now just do the blit.900BlitUsingRaster(src->fbo, 0.0f, 0.0f, srcWidth, srcHeight,901dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, pass_name);902}903904if (scaleFactorX == 1.0f && dst->z_address == src->z_address && dst->z_stride == src->z_stride) {905// We should also copy the depth buffer in this case!906BlitFramebufferDepth(src, dst, true);907}908}909}910911if (currentRenderVfb_ && dst != currentRenderVfb_ && tookActions) {912// Will probably just change the name of the current renderpass, since one was started by the reinterpret itself.913draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "After Reinterpret");914}915916shaderManager_->DirtyLastShader();917textureCache_->ForgetLastTexture();918}919920Draw2DPipeline *FramebufferManagerCommon::GetReinterpretPipeline(GEBufferFormat from, GEBufferFormat to, float *scaleFactorX) {921if (from == to) {922*scaleFactorX = 1.0f;923return Get2DPipeline(DRAW2D_COPY_COLOR);924}925926if (IsBufferFormat16Bit(from) && !IsBufferFormat16Bit(to)) {927// We halve the X coordinates in the destination framebuffer.928// The shader will collect two pixels worth of input data and merge into one.929*scaleFactorX = 0.5f;930} else if (!IsBufferFormat16Bit(from) && IsBufferFormat16Bit(to)) {931// We double the X coordinates in the destination framebuffer.932// The shader will sample and depending on the X coordinate & 1, use the upper or lower bits.933*scaleFactorX = 2.0f;934} else {935*scaleFactorX = 1.0f;936}937938Draw2DPipeline *pipeline = reinterpretFromTo_[(int)from][(int)to];939if (!pipeline) {940pipeline = draw2D_.Create2DPipeline([=](ShaderWriter &shaderWriter) -> Draw2DPipelineInfo {941return GenerateReinterpretFragmentShader(shaderWriter, from, to);942});943reinterpretFromTo_[(int)from][(int)to] = pipeline;944}945return pipeline;946}947948void FramebufferManagerCommon::DestroyFramebuf(VirtualFramebuffer *v) {949// Notify the texture cache of both the color and depth buffers.950textureCache_->NotifyFramebuffer(v, NOTIFY_FB_DESTROYED);951if (v->fbo) {952v->fbo->Release();953v->fbo = nullptr;954}955956// Wipe some pointers957DiscardFramebufferCopy();958if (currentRenderVfb_ == v)959currentRenderVfb_ = nullptr;960if (displayFramebuf_ == v)961displayFramebuf_ = nullptr;962if (prevDisplayFramebuf_ == v)963prevDisplayFramebuf_ = nullptr;964if (prevPrevDisplayFramebuf_ == v)965prevPrevDisplayFramebuf_ = nullptr;966967delete v;968}969970void FramebufferManagerCommon::BlitFramebufferDepth(VirtualFramebuffer *src, VirtualFramebuffer *dst, bool allowSizeMismatch) {971_dbg_assert_(src && dst);972_dbg_assert_(src != dst);973974// Check that the depth address is even the same before actually blitting.975bool matchingDepthBuffer = src->z_address == dst->z_address && src->z_stride != 0 && dst->z_stride != 0;976bool matchingSize = (src->width == dst->width || (src->width == 512 && dst->width == 480) || (src->width == 480 && dst->width == 512)) && src->height == dst->height;977if (!matchingDepthBuffer || (!matchingSize && !allowSizeMismatch)) {978return;979}980981// Copy depth value from the previously bound framebuffer to the current one.982bool hasNewerDepth = src->last_frame_depth_render != 0 && src->last_frame_depth_render >= dst->last_frame_depth_updated;983if (!src->fbo || !dst->fbo || !useBufferedRendering_ || !hasNewerDepth) {984// If depth wasn't updated, then we're at least "two degrees" away from the data.985// This is an optimization: it probably doesn't need to be copied in this case.986return;987}988989bool useCopy = draw_->GetDeviceCaps().framebufferSeparateDepthCopySupported || (!draw_->GetDeviceCaps().framebufferDepthBlitSupported && draw_->GetDeviceCaps().framebufferCopySupported);990bool useBlit = draw_->GetDeviceCaps().framebufferDepthBlitSupported;991992bool useRaster = draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported && draw_->GetDeviceCaps().textureDepthSupported;993994if (src->fbo->MultiSampleLevel() > 0 && dst->fbo->MultiSampleLevel() > 0) {995// If multisampling, we want to copy depth properly so we get all the samples, to avoid aliased edges.996// Can be seen in the fire in Jeanne D'arc, for example.997if (useRaster && useCopy) {998useRaster = false;999}1000}10011002int w = std::min(src->renderWidth, dst->renderWidth);1003int h = std::min(src->renderHeight, dst->renderHeight);10041005// 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.1006if (useRaster) {1007BlitUsingRaster(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, false, dst->renderScaleFactor, Get2DPipeline(Draw2DShader::DRAW2D_COPY_DEPTH), "BlitDepthRaster");1008} else if (useCopy) {1009draw_->CopyFramebufferImage(src->fbo, 0, 0, 0, 0, dst->fbo, 0, 0, 0, 0, w, h, 1, Draw::Aspect::DEPTH_BIT, "CopyFramebufferDepth");1010RebindFramebuffer("After BlitFramebufferDepth");1011} else if (useBlit) {1012// We'll accept whether we get a separate depth blit or not...1013draw_->BlitFramebuffer(src->fbo, 0, 0, w, h, dst->fbo, 0, 0, w, h, Draw::Aspect::DEPTH_BIT, Draw::FB_BLIT_NEAREST, "BlitFramebufferDepth");1014RebindFramebuffer("After BlitFramebufferDepth");1015}10161017draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);1018}10191020void FramebufferManagerCommon::NotifyRenderFramebufferCreated(VirtualFramebuffer *vfb) {1021if (!useBufferedRendering_) {1022// Let's ignore rendering to targets that have not (yet) been displayed.1023gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1024} else if (currentRenderVfb_) {1025DownloadFramebufferOnSwitch(currentRenderVfb_);1026}10271028textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);10291030NotifyRenderFramebufferUpdated(vfb);1031}10321033void FramebufferManagerCommon::NotifyRenderFramebufferUpdated(VirtualFramebuffer *vfb) {1034if (gstate_c.curRTWidth != vfb->width || gstate_c.curRTHeight != vfb->height) {1035gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX | DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1036}1037if (gstate_c.curRTRenderWidth != vfb->renderWidth || gstate_c.curRTRenderHeight != vfb->renderHeight) {1038gstate_c.Dirty(DIRTY_PROJMATRIX);1039gstate_c.Dirty(DIRTY_PROJTHROUGHMATRIX);1040}1041}10421043void FramebufferManagerCommon::DownloadFramebufferOnSwitch(VirtualFramebuffer *vfb) {1044if (vfb && vfb->safeWidth > 0 && vfb->safeHeight > 0 && !(vfb->usageFlags & FB_USAGE_FIRST_FRAME_SAVED) && !vfb->memoryUpdated) {1045// Some games will draw to some memory once, and use it as a render-to-texture later.1046// To support this, we save the first frame to memory when we have a safe w/h.1047// Saving each frame would be slow.10481049// TODO: This type of download could be made async, for less stutter on framebuffer creation.1050if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && !PSP_CoreParameter().compat.flags().DisableFirstFrameReadback) {1051ReadFramebufferToMemory(vfb, 0, 0, vfb->safeWidth, vfb->safeHeight, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1052vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1053vfb->safeWidth = 0;1054vfb->safeHeight = 0;1055}1056}1057}10581059bool FramebufferManagerCommon::ShouldDownloadFramebufferColor(const VirtualFramebuffer *vfb) {1060// Dangan Ronpa hack1061return PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000;1062}10631064bool FramebufferManagerCommon::ShouldDownloadFramebufferDepth(const VirtualFramebuffer *vfb) {1065// Download depth buffer if compat flag set (previously used for Syphon Filter lens flares, now used for nothing)1066if (!PSP_CoreParameter().compat.flags().ReadbackDepth || GetSkipGPUReadbackMode() != SkipGPUReadbackMode::NO_SKIP) {1067return false;1068}1069return (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) != 0 && vfb->width >= 480 && vfb->height >= 272;1070}10711072void FramebufferManagerCommon::NotifyRenderFramebufferSwitched(VirtualFramebuffer *prevVfb, VirtualFramebuffer *vfb, bool isClearingDepth) {1073if (prevVfb) {1074if (ShouldDownloadFramebufferColor(prevVfb) && !prevVfb->memoryUpdated) {1075// NOTE: This path is ONLY for the Dangan Ronpa hack, see ShouldDownloadFramebufferColor1076ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RASTER_COLOR, Draw::ReadbackMode::OLD_DATA_OK);1077prevVfb->usageFlags = (prevVfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1078} else {1079DownloadFramebufferOnSwitch(prevVfb);1080}10811082if (ShouldDownloadFramebufferDepth(prevVfb)) {1083ReadFramebufferToMemory(prevVfb, 0, 0, prevVfb->width, prevVfb->height, RasterChannel::RASTER_DEPTH, Draw::ReadbackMode::BLOCK);1084}1085}10861087textureCache_->ForgetLastTexture();1088shaderManager_->DirtyLastShader();10891090if (useBufferedRendering_) {1091if (vfb->fbo) {1092shaderManager_->DirtyLastShader();1093Draw::RPAction depthAction = Draw::RPAction::KEEP;1094float clearDepth = 0.0f;1095if (vfb->usageFlags & FB_USAGE_INVALIDATE_DEPTH) {1096depthAction = Draw::RPAction::CLEAR;1097clearDepth = GetDepthScaleFactors(gstate_c.UseFlags()).Offset();1098vfb->usageFlags &= ~FB_USAGE_INVALIDATE_DEPTH;1099}1100draw_->BindFramebufferAsRenderTarget(vfb->fbo, {Draw::RPAction::KEEP, depthAction, Draw::RPAction::KEEP, 0, clearDepth}, "FBSwitch");1101} else {1102// This should only happen very briefly when toggling useBufferedRendering_.1103ResizeFramebufFBO(vfb, vfb->width, vfb->height, true);1104}1105} else {1106if (vfb->fbo) {1107// This should only happen very briefly when toggling useBufferedRendering_.1108textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_DESTROYED);1109vfb->fbo->Release();1110vfb->fbo = nullptr;1111}11121113// Let's ignore rendering to targets that have not (yet) been displayed.1114if (vfb->usageFlags & FB_USAGE_DISPLAYED_FRAMEBUFFER) {1115gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;1116} else {1117gstate_c.skipDrawReason |= SKIPDRAW_NON_DISPLAYED_FB;1118}1119}1120textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_UPDATED);11211122NotifyRenderFramebufferUpdated(vfb);1123}11241125void FramebufferManagerCommon::PerformWriteFormattedFromMemory(u32 addr, int size, int stride, GEBufferFormat fmt) {1126// Note: UpdateFromMemory() is still called later.1127// This is a special case where we have extra information prior to the invalidation,1128// because it's called from sceJpeg, sceMpeg, scePsmf etc.11291130// TODO: Could possibly be at an offset...1131// Also, stride needs better handling.1132VirtualFramebuffer *vfb = ResolveVFB(addr, stride, fmt);1133if (vfb) {1134// Let's count this as a "render". This will also force us to use the correct format.1135vfb->last_frame_render = gpuStats.numFlips;1136vfb->colorBindSeq = GetBindSeqCount();11371138if (vfb->fb_stride < stride) {1139INFO_LOG(Log::FrameBuf, "Changing stride for %08x from %d to %d", addr, vfb->fb_stride, stride);1140const int bpp = BufferFormatBytesPerPixel(fmt);1141ResizeFramebufFBO(vfb, stride, size / (bpp * stride));1142// Resizing may change the viewport/etc.1143gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);1144vfb->fb_stride = stride;1145// This might be a bit wider than necessary, but we'll redetect on next render.1146vfb->width = stride;1147}1148}1149}11501151void FramebufferManagerCommon::UpdateFromMemory(u32 addr, int size) {1152// Take off the uncached flag from the address. Not to be confused with the start of VRAM.1153addr &= 0x3FFFFFFF;1154if (Memory::IsVRAMAddress(addr))1155addr &= 0x041FFFFF;1156// TODO: Could go through all FBOs, but probably not important?1157// TODO: Could also check for inner changes, but video is most important.1158// TODO: This shouldn't care if it's a display framebuf or not, should work exactly the same.1159bool isDisplayBuf = addr == CurrentDisplayFramebufAddr() || addr == PrevDisplayFramebufAddr();1160// TODO: Deleting the FBO is a heavy hammer solution, so let's only do it if it'd help.1161if (!Memory::IsValidAddress(displayFramebufPtr_))1162return;11631164for (size_t i = 0; i < vfbs_.size(); ++i) {1165VirtualFramebuffer *vfb = vfbs_[i];1166if (vfb->fb_address == addr) {1167FlushBeforeCopy();11681169if (useBufferedRendering_ && vfb->fbo) {1170GEBufferFormat fmt = vfb->fb_format;1171if (vfb->last_frame_render + 1 < gpuStats.numFlips && isDisplayBuf) {1172// If we're not rendering to it, format may be wrong. Use displayFormat_ instead.1173// TODO: This doesn't seem quite right anymore.1174fmt = displayFormat_;1175}1176DrawPixels(vfb, 0, 0, Memory::GetPointerUnchecked(addr), fmt, vfb->fb_stride, vfb->width, vfb->height, RASTER_COLOR, "UpdateFromMemory_DrawPixels");1177SetColorUpdated(vfb, gstate_c.skipDrawReason);1178} else {1179INFO_LOG(Log::FrameBuf, "Invalidating FBO for %08x (%dx%d %s)", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format));1180DestroyFramebuf(vfb);1181vfbs_.erase(vfbs_.begin() + i--);1182}1183}1184}11851186RebindFramebuffer("RebindFramebuffer - UpdateFromMemory");11871188// TODO: Necessary?1189gstate_c.Dirty(DIRTY_FRAGMENTSHADER_STATE);1190}11911192void FramebufferManagerCommon::DrawPixels(VirtualFramebuffer *vfb, int dstX, int dstY, const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height, RasterChannel channel, const char *tag) {1193textureCache_->ForgetLastTexture();1194shaderManager_->DirtyLastShader();1195float u0 = 0.0f, u1 = 1.0f;1196float v0 = 0.0f, v1 = 1.0f;11971198DrawTextureFlags flags;1199if (useBufferedRendering_ && vfb) {1200_dbg_assert_(vfb->fbo);1201if (vfb->fbo) {1202if (channel == RASTER_DEPTH || PSP_CoreParameter().compat.flags().NearestFilteringOnFramebufferCreate) {1203flags = DRAWTEX_NEAREST;1204} else {1205flags = DRAWTEX_LINEAR;1206}1207draw_->BindFramebufferAsRenderTarget(vfb->fbo, {Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP}, tag);1208SetViewport2D(0, 0, vfb->renderWidth, vfb->renderHeight);1209draw_->SetScissorRect(0, 0, vfb->renderWidth, vfb->renderHeight);1210}1211} else {1212// The hacky way to get the display layout config (normally we pass it down, but it would require a lot of plumbing here).1213// This is only for non-buffered rendering.1214auto config = g_Config.GetDisplayLayoutConfig(g_display.GetDeviceOrientation());1215// Here config is valid.1216_dbg_assert_(channel == RASTER_COLOR);1217// We are drawing directly to the back buffer so need to flip.1218// Should more of this be handled by the presentation engine?1219if (needBackBufferYSwap_)1220std::swap(v0, v1);1221flags = config.iDisplayFilter == SCALE_LINEAR ? DRAWTEX_LINEAR : DRAWTEX_NEAREST;1222flags = flags | DRAWTEX_TO_BACKBUFFER;1223FRect frame = GetScreenFrame(config.bIgnoreScreenInsets, pixelWidth_, pixelHeight_);1224FRect rc;1225CalculateDisplayOutputRect(config, &rc, 480.0f, 272.0f, frame, ROTATION_LOCKED_HORIZONTAL);1226SetViewport2D(rc.x, rc.y, rc.w, rc.h);1227draw_->SetScissorRect(0, 0, pixelWidth_, pixelHeight_);1228}12291230if (channel == RASTER_DEPTH) {1231_dbg_assert_(srcPixelFormat == GE_FORMAT_DEPTH16);1232flags = flags | DRAWTEX_DEPTH;1233if (vfb)1234vfb->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;1235}12361237Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, width, height);1238if (pixelsTex) {1239draw_->BindTextures(0, 1, &pixelsTex, Draw::TextureBindFlags::VULKAN_BIND_ARRAY);12401241// TODO: Replace with draw2D_.Blit() directly.1242DrawActiveTexture(dstX, dstY, width, height,1243vfb ? vfb->bufferWidth : g_display.pixel_xres,1244vfb ? vfb->bufferHeight : g_display.pixel_yres,1245u0, v0, u1, v1, ROTATION_LOCKED_HORIZONTAL, flags);12461247draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);12481249gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);1250}1251}12521253bool FramebufferManagerCommon::BindFramebufferAsColorTexture(int stage, VirtualFramebuffer *framebuffer, int flags, int layer) {1254if (!framebuffer->fbo || !useBufferedRendering_) {1255draw_->BindTexture(stage, nullptr);1256gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1257return false;1258}12591260// currentRenderVfb_ will always be set when this is called, except from the GE debugger.1261// Let's just not bother with the copy in that case.1262bool skipCopy = !(flags & BINDFBCOLOR_MAY_COPY);12631264// Currently rendering to this framebuffer. Need to make a copy.1265if (!skipCopy && framebuffer == currentRenderVfb_) {1266// Self-texturing, need a copy currently (some backends can potentially support it though).1267WARN_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);1268// TODO: Maybe merge with bvfbs_? Not sure if those could be packing, and they're created at a different size.1269if (currentFramebufferCopy_ && (flags & BINDFBCOLOR_UNCACHED) == 0) {1270// We have a copy already that hasn't been invalidated, let's keep using it.1271draw_->BindFramebufferAsTexture(currentFramebufferCopy_, stage, Draw::Aspect::COLOR_BIT, layer);1272return true;1273}12741275// There's a special case we can handle here, where the game is texturing from the same pixels being read, in order to1276// implement a DST*DST blending function, which the PSP can't do. However on the PC we can absolutely do this!1277// TODO: Add more checks here.1278if (PSP_CoreParameter().compat.flags().DetectDestBlendSquared &&1279gstate.isAlphaBlendEnabled() && gstate.getBlendEq() == GE_BLENDMODE_MUL_AND_ADD && gstate.getBlendFuncA() == GE_SRCBLEND_DSTCOLOR && gstate.getBlendFuncB() == GE_DSTBLEND_FIXB && gstate.getFixB() == 0x0 &&1280gstate.getMaterialAmbientRGBA() == 0xFFFFFFFF) {1281// This is the pure DST*DST case, the SRC color is ignored.1282// Used by Brave Story - New Traveller. This assumes that texture coordinates are set to match the framebuffer pixels - and to1283// be able to make that assumption reasonably safely we use a compat flag to restrict it to that game.1284// We can just override the blend mode. Let's set a state variable.1285// We also just leave the last texture bound, ideally we should bind a placeholder here.1286gstate_c.dstSquared = true;1287return true;1288}12891290Draw::Framebuffer *renderCopy = GetTempFBO(TempFBO::COPY, framebuffer->renderWidth, framebuffer->renderHeight);1291if (renderCopy) {1292VirtualFramebuffer copyInfo = *framebuffer;1293copyInfo.fbo = renderCopy;12941295bool partial = false;1296CopyFramebufferForColorTexture(©Info, framebuffer, flags, layer, &partial);1297RebindFramebuffer("After BindFramebufferAsColorTexture");1298draw_->BindFramebufferAsTexture(renderCopy, stage, Draw::Aspect::COLOR_BIT, layer);12991300// Only cache the copy if it wasn't a partial copy.1301// TODO: Improve on this.1302if (!partial && (flags & BINDFBCOLOR_UNCACHED) == 0) {1303currentFramebufferCopy_ = renderCopy;1304}1305gpuStats.numCopiesForSelfTex++;1306} else {1307// Failed to get temp FBO? Weird.1308draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::Aspect::COLOR_BIT, layer);1309}1310return true;1311} else if (framebuffer != currentRenderVfb_ || (flags & BINDFBCOLOR_FORCE_SELF) != 0) {1312draw_->BindFramebufferAsTexture(framebuffer->fbo, stage, Draw::Aspect::COLOR_BIT, layer);1313return true;1314} else {1315// Here it's an error because for some reason skipCopy is true. That shouldn't really happen.1316ERROR_LOG_REPORT_ONCE(selfTextureFail, Log::G3D, "Attempting to texture from target (src=%08x / target=%08x / flags=%d)", framebuffer->fb_address, currentRenderVfb_->fb_address, flags);1317// To do this safely in Vulkan, we need to use input attachments.1318// Actually if the texture region and render regions don't overlap, this is safe, but we need1319// to transition to GENERAL image layout which will take some trickery.1320// Badness on D3D11 to bind the currently rendered-to framebuffer as a texture.1321draw_->BindTexture(stage, nullptr);1322gstate_c.skipDrawReason |= SKIPDRAW_BAD_FB_TEXTURE;1323return false;1324}1325}13261327void FramebufferManagerCommon::CopyFramebufferForColorTexture(VirtualFramebuffer *dst, VirtualFramebuffer *src, int flags, int layer, bool *partial) {1328int x = 0;1329int y = 0;1330int w = src->drawnWidth;1331int h = src->drawnHeight;13321333*partial = false;13341335// If max is not > min, we probably could not detect it. Skip.1336// See the vertex decoder, where this is updated.1337// TODO: We're currently not hitting this path in Dante. See #170321338if ((flags & BINDFBCOLOR_MAY_COPY_WITH_UV) == BINDFBCOLOR_MAY_COPY_WITH_UV && gstate_c.vertBounds.maxU > gstate_c.vertBounds.minU) {1339x = std::max(gstate_c.vertBounds.minU, (u16)0);1340y = std::max(gstate_c.vertBounds.minV, (u16)0);1341w = std::min(gstate_c.vertBounds.maxU, src->drawnWidth) - x;1342h = std::min(gstate_c.vertBounds.maxV, src->drawnHeight) - y;13431344// If we bound a framebuffer, apply the byte offset as pixels to the copy too.1345if (flags & BINDFBCOLOR_APPLY_TEX_OFFSET) {1346x += gstate_c.curTextureXOffset;1347y += gstate_c.curTextureYOffset;1348}13491350// We'll have to reapply these next time since we cropped to UV.1351gstate_c.Dirty(DIRTY_TEXTURE_PARAMS);1352}13531354if (x < src->drawnWidth && y < src->drawnHeight && w > 0 && h > 0) {1355if (x != 0 || y != 0 || w < src->drawnWidth || h < src->drawnHeight) {1356*partial = true;1357}1358BlitFramebuffer(dst, x, y, src, x, y, w, h, 0, RASTER_COLOR, "CopyFBForColorTexture");1359}1360}13611362Draw::Texture *FramebufferManagerCommon::MakePixelTexture(const u8 *srcPixels, GEBufferFormat srcPixelFormat, int srcStride, int width, int height) {1363Draw::DataFormat depthFormat = Draw::DataFormat::UNDEFINED;13641365int bpp = BufferFormatBytesPerPixel(srcPixelFormat);1366int srcStrideInBytes = srcStride * bpp;1367int widthInBytes = width * bpp;13681369// Compute hash of contents.1370uint64_t imageHash;1371if (widthInBytes == srcStrideInBytes) {1372imageHash = XXH3_64bits(srcPixels, widthInBytes * height);1373} else {1374XXH3_state_t *hashState = XXH3_createState();1375XXH3_64bits_reset(hashState);1376for (int y = 0; y < height; y++) {1377XXH3_64bits_update(hashState, srcPixels + srcStrideInBytes * y, widthInBytes);1378}1379imageHash = XXH3_64bits_digest(hashState);1380XXH3_freeState(hashState);1381}13821383Draw::DataFormat texFormat = preferredPixelsFormat_;13841385if (srcPixelFormat == GE_FORMAT_DEPTH16) {1386if ((draw_->GetDataFormatSupport(Draw::DataFormat::R16_UNORM) & Draw::FMT_TEXTURE) != 0) {1387texFormat = Draw::DataFormat::R16_UNORM;1388} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R8_UNORM) & Draw::FMT_TEXTURE) != 0) {1389// This could be improved by using specific draw shaders to pack full precision in two channels.1390// However, not really worth the trouble until we find a game that requires it.1391texFormat = Draw::DataFormat::R8_UNORM;1392} else {1393// No usable single channel format. Can't be bothered.1394return nullptr;1395}1396} else if (srcPixelFormat == GE_FORMAT_565) {1397// Check for supported matching formats.1398// This mainly benefits the redundant copies in God of War on low-end platforms.1399if ((draw_->GetDataFormatSupport(Draw::DataFormat::B5G6R5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1400texFormat = Draw::DataFormat::B5G6R5_UNORM_PACK16;1401} else if ((draw_->GetDataFormatSupport(Draw::DataFormat::R5G6B5_UNORM_PACK16) & Draw::FMT_TEXTURE) != 0) {1402texFormat = Draw::DataFormat::R5G6B5_UNORM_PACK16;1403}1404}14051406// TODO: We can just change the texture format and flip some bits around instead of this.1407// Could share code with the texture cache perhaps.1408auto generateTexture = [&](uint8_t *data, const uint8_t *initData, uint32_t w, uint32_t h, uint32_t d, uint32_t byteStride, uint32_t sliceByteStride) {1409for (int y = 0; y < height; y++) {1410const u16_le *src16 = (const u16_le *)srcPixels + srcStride * y;1411const u32_le *src32 = (const u32_le *)srcPixels + srcStride * y;1412u32 *dst = (u32 *)(data + byteStride * y);1413u16 *dst16 = (u16 *)(data + byteStride * y);1414u8 *dst8 = (u8 *)(data + byteStride * y);1415switch (srcPixelFormat) {1416case GE_FORMAT_565:1417if (texFormat == Draw::DataFormat::B5G6R5_UNORM_PACK16) {1418memcpy(dst16, src16, w * sizeof(uint16_t));1419} else if (texFormat == Draw::DataFormat::R5G6B5_UNORM_PACK16) {1420ConvertRGB565ToBGR565(dst16, src16, width); // Fast!1421} else if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM) {1422ConvertRGB565ToBGRA8888(dst, src16, width);1423} else {1424ConvertRGB565ToRGBA8888(dst, src16, width);1425}1426break;14271428case GE_FORMAT_5551:1429if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1430ConvertRGBA5551ToBGRA8888(dst, src16, width);1431else1432ConvertRGBA5551ToRGBA8888(dst, src16, width);1433break;14341435case GE_FORMAT_4444:1436if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1437ConvertRGBA4444ToBGRA8888(dst, src16, width);1438else1439ConvertRGBA4444ToRGBA8888(dst, src16, width);1440break;14411442case GE_FORMAT_8888:1443if (texFormat == Draw::DataFormat::B8G8R8A8_UNORM)1444ConvertRGBA8888ToBGRA8888(dst, src32, width);1445// This means use original pointer as-is. May avoid or optimize a copy.1446else if (srcStride == width)1447return false;1448else1449memcpy(dst, src32, width * 4);1450break;14511452case GE_FORMAT_DEPTH16:1453// TODO: Must take the depth range into account, unless it's already 0-1.1454// TODO: Depending on the color buffer format used with this depth buffer, we need1455// to do one of two different swizzle operations. However, for the only use of this so far,1456// the Burnout lens flare trickery, swizzle doesn't matter since it's just a 0, 7fff, 0, 7fff pattern1457// which comes out the same.1458if (texFormat == Draw::DataFormat::R16_UNORM) {1459// We just use this format straight.1460memcpy(dst16, src16, w * 2);1461} else if (texFormat == Draw::DataFormat::R8_UNORM) {1462// We fall back to R8_UNORM. Precision is enough for most cases of depth clearing and initialization we've seen,1463// but hardly ideal.1464for (int i = 0; i < width; i++) {1465dst8[i] = src16[i] >> 8;1466}1467}1468break;14691470case GE_FORMAT_INVALID:1471case GE_FORMAT_CLUT8:1472// Bad1473break;1474}1475}1476return true;1477};14781479int frameNumber = draw_->GetFrameCount();14801481// First look for an exact match (including contents hash) that we can re-use.1482for (auto &iter : drawPixelsCache_) {1483if (iter.contentsHash == imageHash && iter.tex->Width() == width && iter.tex->Height() == height && iter.tex->Format() == texFormat) {1484iter.frameNumber = frameNumber;1485gpuStats.numCachedUploads++;1486return iter.tex;1487}1488}14891490// Then, look for an alternative one that's not been used recently that we can overwrite.1491for (auto &iter : drawPixelsCache_) {1492if (iter.frameNumber >= frameNumber - 3 || iter.tex->Width() != width || iter.tex->Height() != height || iter.tex->Format() != texFormat) {1493continue;1494}14951496// OK, current one seems good, let's use it (and mark it used).1497gpuStats.numUploads++;1498draw_->UpdateTextureLevels(iter.tex, &srcPixels, generateTexture, 1);1499// NOTE: numFlips is no good - this is called every frame when paused sometimes!1500iter.frameNumber = frameNumber;1501// We need to update the hash for future matching.1502iter.contentsHash = imageHash;1503return iter.tex;1504}15051506// Note: For depth, we create an R16_UNORM texture, that'll be just fine for uploading depth through a shader,1507// and likely more efficient.1508Draw::TextureDesc desc{1509Draw::TextureType::LINEAR2D,1510texFormat,1511width,1512height,15131,15141,1515false,1516Draw::TextureSwizzle::DEFAULT,1517"DrawPixels",1518{ (uint8_t *)srcPixels },1519generateTexture,1520};15211522// Hot Shots Golf (#12355) does tons of these in a frame in some situations! So creating textures1523// better be fast. So does God of War, a lot of the time, a bit unclear what it's doing.1524Draw::Texture *tex = draw_->CreateTexture(desc);1525if (!tex) {1526ERROR_LOG(Log::G3D, "Failed to create DrawPixels texture");1527}1528// We don't need to count here, already counted by numUploads by the caller.15291530// INFO_LOG(Log::G3D, "Creating drawPixelsCache texture: %dx%d", tex->Width(), tex->Height());15311532DrawPixelsEntry entry{ tex, imageHash, frameNumber };1533drawPixelsCache_.push_back(entry);1534gpuStats.numUploads++;1535return tex;1536}15371538bool FramebufferManagerCommon::DrawFramebufferToOutput(const DisplayLayoutConfig &config, const u8 *srcPixels, int srcStride, GEBufferFormat srcPixelFormat) {1539textureCache_->ForgetLastTexture();1540shaderManager_->DirtyLastShader();15411542float u0 = 0.0f, u1 = 480.0f / 512.0f;1543float v0 = 0.0f, v1 = 1.0f;1544Draw::Texture *pixelsTex = MakePixelTexture(srcPixels, srcPixelFormat, srcStride, 512, 272);1545if (!pixelsTex)1546return false;15471548int uvRotation = useBufferedRendering_ ? config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1549OutputFlags flags = config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1550if (needBackBufferYSwap_) {1551flags |= OutputFlags::BACKBUFFER_FLIPPED;1552}1553// CopyToOutput reverses these, probably to match "up".1554if (GetGPUBackend() == GPUBackend::DIRECT3D11) {1555flags |= OutputFlags::POSITION_FLIPPED;1556}15571558presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1559presentation_->SourceTexture(pixelsTex, 512, 272);1560presentation_->CopyToOutput(config, flags, uvRotation, u0, v0, u1, v1);15611562// PresentationCommon sets all kinds of state, we can't rely on anything.1563gstate_c.Dirty(DIRTY_ALL);15641565DiscardFramebufferCopy();1566currentRenderVfb_ = nullptr;15671568return true;1569}15701571void FramebufferManagerCommon::SetViewport2D(int x, int y, int w, int h) {1572Draw::Viewport viewport{ (float)x, (float)y, (float)w, (float)h, 0.0f, 1.0f };1573draw_->SetViewport(viewport);1574}15751576void FramebufferManagerCommon::CopyDisplayToOutput(const DisplayLayoutConfig &config, bool reallyDirty) {1577DownloadFramebufferOnSwitch(currentRenderVfb_);1578shaderManager_->DirtyLastShader();15791580if (displayFramebufPtr_ == 0) {1581if (GetUIState() != UISTATE_PAUSEMENU) {1582if (Core_IsStepping())1583VERBOSE_LOG(Log::FrameBuf, "Display disabled, displaying only black");1584else1585DEBUG_LOG(Log::FrameBuf, "Display disabled, displaying only black");1586}1587// No framebuffer to display! Clear to black.1588if (useBufferedRendering_) {1589draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput");1590}1591gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1592presentation_->NotifyPresent();1593return;1594}15951596u32 offsetX = 0;1597u32 offsetY = 0;15981599// If it's not really dirty, we're probably frameskipping. Use the last working one.1600u32 fbaddr = reallyDirty ? displayFramebufPtr_ : prevDisplayFramebufPtr_;1601prevDisplayFramebufPtr_ = fbaddr;16021603VirtualFramebuffer *vfb = ResolveVFB(fbaddr, displayStride_, displayFormat_);1604if (!vfb) {1605// Let's search for a framebuf within this range. Note that we also look for1606// "framebuffers" sitting in RAM (created from block transfer or similar) so we only take off the kernel1607// and uncached bits of the address when comparing.1608const u32 addr = fbaddr;1609for (auto v : vfbs_) {1610const u32 v_addr = v->fb_address;1611const u32 v_size = v->BufferByteSize(RASTER_COLOR);16121613if (v->fb_format != displayFormat_ || v->fb_stride != displayStride_) {1614// Displaying a buffer of the wrong format or stride is nonsense, ignore it.1615continue;1616}16171618if (addr >= v_addr && addr < v_addr + v_size) {1619const u32 dstBpp = BufferFormatBytesPerPixel(v->fb_format);1620const u32 v_offsetX = ((addr - v_addr) / dstBpp) % v->fb_stride;1621const u32 v_offsetY = ((addr - v_addr) / dstBpp) / v->fb_stride;1622// We have enough space there for the display, right?1623if (v_offsetX + 480 > (u32)v->fb_stride || v->bufferHeight < v_offsetY + 272) {1624continue;1625}1626// Check for the closest one.1627if (offsetY == 0 || offsetY > v_offsetY) {1628offsetX = v_offsetX;1629offsetY = v_offsetY;1630vfb = v;1631}1632}1633}16341635if (vfb) {1636// Okay, we found one above.1637// Log should be "Displaying from framebuf" but not worth changing the report.1638DEBUG_LOG(Log::FrameBuf, "Rendering from framebuf with offset %08x -> %08x+%dx%d", addr, vfb->fb_address, offsetX, offsetY);1639}1640}16411642// Reject too-tiny framebuffers to display (Godfather, see issue #16915).1643if (vfb && vfb->height < 64) {1644vfb = nullptr;1645}16461647if (!vfb) {1648if (Memory::IsValidAddress(fbaddr)) {1649// The game is displaying something directly from RAM. In GTA, it's decoded video.1650// If successful, this effectively calls presentation_->NotifyPresent();1651if (!DrawFramebufferToOutput(config, Memory::GetPointerUnchecked(fbaddr), displayStride_, displayFormat_)) {1652if (useBufferedRendering_) {1653// Bind and clear the backbuffer. This should be the first time during the frame that it's bound.1654draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput_DrawError");1655}1656presentation_->NotifyPresent();1657}1658return;1659} else {1660DEBUG_LOG(Log::FrameBuf, "Found no FBO to display! displayFBPtr = %08x", fbaddr);1661// No framebuffer to display! Clear to black.1662if (useBufferedRendering_) {1663// Bind and clear the backbuffer. This should be the first time during the frame that it's bound.1664draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "CopyDisplayToOutput_NoFBO");1665} // For non-buffered rendering, every frame is cleared anyway.1666gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE);1667presentation_->NotifyPresent();1668return;1669}1670}16711672vfb->usageFlags |= FB_USAGE_DISPLAYED_FRAMEBUFFER;1673vfb->last_frame_displayed = gpuStats.numFlips;1674vfb->dirtyAfterDisplay = false;1675vfb->reallyDirtyAfterDisplay = false;16761677if (prevDisplayFramebuf_ != displayFramebuf_) {1678prevPrevDisplayFramebuf_ = prevDisplayFramebuf_;1679}1680if (displayFramebuf_ != vfb) {1681prevDisplayFramebuf_ = displayFramebuf_;1682}1683displayFramebuf_ = vfb;16841685if (vfb->fbo) {1686if (GetUIState() != UISTATE_PAUSEMENU) {1687if (Core_IsStepping())1688VERBOSE_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1689else1690DEBUG_LOG(Log::FrameBuf, "Displaying FBO %08x", vfb->fb_address);1691}16921693float u0 = offsetX / (float)vfb->bufferWidth;1694float v0 = offsetY / (float)vfb->bufferHeight;1695float u1 = (480.0f + offsetX) / (float)vfb->bufferWidth;1696float v1 = (272.0f + offsetY) / (float)vfb->bufferHeight;16971698//clip the VR framebuffer to keep the aspect ratio1699if (IsVREnabled() && !IsFlatVRGame() && !IsGameVRScene()) {1700float aspect = 272.0f / 480.0f * (IsImmersiveVRMode() ? 2.0f : 1.0f);1701float clipY = 272.0f * (1.0f - aspect) / 2.0f;1702v0 = (clipY + offsetY) / (float)vfb->bufferHeight;1703v1 = (272.0f - clipY + offsetY) / (float)vfb->bufferHeight;17041705//zoom inside1706float zoom = IsImmersiveVRMode() ? 0.4f : 0.1f;1707u0 += zoom / aspect;1708u1 -= zoom / aspect;1709v0 += zoom;1710v1 -= zoom;1711}17121713textureCache_->ForgetLastTexture();17141715int uvRotation = useBufferedRendering_ ? config.iInternalScreenRotation : ROTATION_LOCKED_HORIZONTAL;1716OutputFlags flags = config.iDisplayFilter == SCALE_LINEAR ? OutputFlags::LINEAR : OutputFlags::NEAREST;1717if (needBackBufferYSwap_) {1718flags |= OutputFlags::BACKBUFFER_FLIPPED;1719}1720// DrawActiveTexture reverses these, probably to match "up".1721if (GetGPUBackend() == GPUBackend::DIRECT3D11) {1722flags |= OutputFlags::POSITION_FLIPPED;1723}17241725int actualWidth = (vfb->bufferWidth * vfb->renderWidth) / vfb->width;1726int actualHeight = (vfb->bufferHeight * vfb->renderHeight) / vfb->height;1727presentation_->UpdateUniforms(textureCache_->VideoIsPlaying());1728presentation_->SourceFramebuffer(vfb->fbo, actualWidth, actualHeight);1729presentation_->CopyToOutput(config, flags, uvRotation, u0, v0, u1, v1);1730} else if (useBufferedRendering_) {1731WARN_LOG(Log::FrameBuf, "Using buffered rendering, and current VFB lacks an FBO: %08x", vfb->fb_address);1732} else {1733// This is OK because here we're in "skip buffered" mode, so even if we haven't presented1734// we will have a render target.1735presentation_->NotifyPresent();1736}17371738// This may get called mid-draw if the game uses an immediate flip.1739// PresentationCommon sets all kinds of state, we can't rely on anything.1740gstate_c.Dirty(DIRTY_ALL);1741DiscardFramebufferCopy();1742currentRenderVfb_ = nullptr;1743}17441745void FramebufferManagerCommon::DecimateFBOs() {1746DiscardFramebufferCopy();1747currentRenderVfb_ = nullptr;17481749for (auto iter : fbosToDelete_) {1750iter->Release();1751}1752fbosToDelete_.clear();17531754for (size_t i = 0; i < vfbs_.size(); ++i) {1755VirtualFramebuffer *vfb = vfbs_[i];1756int age = frameLastFramebufUsed_ - std::max(vfb->last_frame_render, vfb->last_frame_used);17571758if (ShouldDownloadFramebufferColor(vfb) && age == 0 && !vfb->memoryUpdated) {1759ReadFramebufferToMemory(vfb, 0, 0, vfb->width, vfb->height, RASTER_COLOR, Draw::ReadbackMode::BLOCK);1760vfb->usageFlags = (vfb->usageFlags | FB_USAGE_DOWNLOAD | FB_USAGE_FIRST_FRAME_SAVED) & ~FB_USAGE_DOWNLOAD_CLEAR;1761}17621763// Let's also "decimate" the usageFlags.1764UpdateFramebufUsage(vfb);17651766if (vfb != displayFramebuf_ && vfb != prevDisplayFramebuf_ && vfb != prevPrevDisplayFramebuf_) {1767if (age > FBO_OLD_AGE) {1768INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%ix%i %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1769DestroyFramebuf(vfb);1770vfbs_.erase(vfbs_.begin() + i--);1771}1772}1773}17741775for (auto it = tempFBOs_.begin(); it != tempFBOs_.end(); ) {1776int age = frameLastFramebufUsed_ - it->second.last_frame_used;1777if (age > FBO_OLD_AGE) {1778it->second.fbo->Release();1779it = tempFBOs_.erase(it);1780} else {1781++it;1782}1783}17841785// Do the same for ReadFramebuffersToMemory's VFBs1786for (size_t i = 0; i < bvfbs_.size(); ++i) {1787VirtualFramebuffer *vfb = bvfbs_[i];1788int age = frameLastFramebufUsed_ - vfb->last_frame_render;1789if (age > FBO_OLD_AGE) {1790INFO_LOG(Log::FrameBuf, "Decimating FBO for %08x (%dx%d %s), age %i", vfb->fb_address, vfb->width, vfb->height, GeBufferFormatToString(vfb->fb_format), age);1791DestroyFramebuf(vfb);1792bvfbs_.erase(bvfbs_.begin() + i--);1793}1794}17951796// And DrawPixels cached textures.17971798for (auto it = drawPixelsCache_.begin(); it != drawPixelsCache_.end(); ) {1799int age = draw_->GetFrameCount() - it->frameNumber;1800if (age > 10) {1801// INFO_LOG(Log::G3D, "Releasing drawPixelsCache texture: %dx%d", it->tex->Width(), it->tex->Height());1802it->tex->Release();1803it->tex = nullptr;1804it = drawPixelsCache_.erase(it);1805} else {1806++it;1807}1808}1809}18101811// Requires width/height to be set already.1812void FramebufferManagerCommon::ResizeFramebufFBO(VirtualFramebuffer *vfb, int w, int h, bool force, bool skipCopy) {1813_dbg_assert_(w > 0);1814_dbg_assert_(h > 0);1815VirtualFramebuffer old = *vfb;18161817int oldWidth = vfb->bufferWidth;1818int oldHeight = vfb->bufferHeight;18191820if (force) {1821vfb->bufferWidth = w;1822vfb->bufferHeight = h;1823} else {1824if (vfb->bufferWidth >= w && vfb->bufferHeight >= h) {1825return;1826}18271828// In case it gets thin and wide, don't resize down either side.1829vfb->bufferWidth = std::max((int)vfb->bufferWidth, w);1830vfb->bufferHeight = std::max((int)vfb->bufferHeight, h);1831}18321833bool force1x = false;1834switch (bloomHack_) {1835case 1:1836force1x = vfb->bufferWidth <= 128 || vfb->bufferHeight <= 64;1837break;1838case 2:1839force1x = vfb->bufferWidth <= 256 || vfb->bufferHeight <= 128;1840break;1841case 3:1842force1x = vfb->bufferWidth < 480 || vfb->bufferWidth > 800 || vfb->bufferHeight < 272; // GOW uses 864x2721843break;1844}18451846if ((vfb->usageFlags & FB_USAGE_COLOR_MIXED_DEPTH) && !PSP_CoreParameter().compat.flags().ForceLowerResolutionForEffectsOn) {1847force1x = false;1848}1849if (PSP_CoreParameter().compat.flags().Force04154000Download && vfb->fb_address == 0x04154000) {1850force1x = true;1851}18521853if (force1x && g_Config.iInternalResolution != 1) {1854vfb->renderScaleFactor = 1;1855vfb->renderWidth = vfb->bufferWidth;1856vfb->renderHeight = vfb->bufferHeight;1857} else {1858vfb->renderScaleFactor = renderScaleFactor_;1859vfb->renderWidth = (u16)(vfb->bufferWidth * renderScaleFactor_);1860vfb->renderHeight = (u16)(vfb->bufferHeight * renderScaleFactor_);1861}18621863bool creating = old.bufferWidth == 0;1864if (creating) {1865INFO_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);1866} else {1867INFO_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);1868}18691870// During hardware rendering, we always render at full color depth even if the game wouldn't on real hardware.1871// It's not worth the trouble trying to support lower bit-depth rendering, just1872// more cases to test that nobody will ever use.18731874textureCache_->ForgetLastTexture();18751876if (!useBufferedRendering_) {1877if (vfb->fbo) {1878vfb->fbo->Release();1879vfb->fbo = nullptr;1880}1881return;1882}1883if (!old.fbo && vfb->last_frame_failed != 0 && vfb->last_frame_failed - gpuStats.numFlips < 63) {1884// Don't constantly retry FBOs which failed to create.1885return;1886}18871888shaderManager_->DirtyLastShader();1889char tag[128];1890size_t len = FormatFramebufferName(vfb, tag, sizeof(tag));18911892gpuStats.numFBOsCreated++;18931894vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), msaaLevel_, true, tag });1895if (Memory::IsVRAMAddress(vfb->fb_address) && vfb->fb_stride != 0) {1896NotifyMemInfo(MemBlockFlags::ALLOC, vfb->fb_address, vfb->BufferByteSize(RASTER_COLOR), tag, len);1897}1898if (Memory::IsVRAMAddress(vfb->z_address) && vfb->z_stride != 0) {1899char buf[128];1900size_t len = snprintf(buf, sizeof(buf), "Z_%s", tag);1901NotifyMemInfo(MemBlockFlags::ALLOC, vfb->z_address, vfb->z_stride * vfb->height * sizeof(uint16_t), buf, len);1902}1903if (old.fbo) {1904INFO_LOG(Log::FrameBuf, "Resizing FBO for %08x : %dx%dx%s", vfb->fb_address, w, h, GeBufferFormatToString(vfb->fb_format));1905if (vfb->fbo) {1906draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1907if (!skipCopy) {1908BlitFramebuffer(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");1909}1910if (vfb->usageFlags & FB_USAGE_RENDER_DEPTH) {1911BlitFramebuffer(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");1912}1913}1914fbosToDelete_.push_back(old.fbo);1915draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "ResizeFramebufFBO");1916} else {1917draw_->BindFramebufferAsRenderTarget(vfb->fbo, { Draw::RPAction::CLEAR, Draw::RPAction::CLEAR, Draw::RPAction::CLEAR }, "ResizeFramebufFBO");1918}1919DiscardFramebufferCopy();1920currentRenderVfb_ = vfb;19211922if (!vfb->fbo) {1923ERROR_LOG(Log::FrameBuf, "Error creating FBO during resize! %dx%d", vfb->renderWidth, vfb->renderHeight);1924vfb->last_frame_failed = gpuStats.numFlips;1925}1926}19271928struct CopyCandidate {1929VirtualFramebuffer *vfb = nullptr;1930int y = 0;1931int h = 0;19321933std::string ToString(RasterChannel channel) const {1934return StringFromFormat("%08x %s %dx%d y=%d h=%d", vfb->Address(channel), GeBufferFormatToString(vfb->Format(channel)), vfb->width, vfb->height, y, h);1935}1936};19371938static const CopyCandidate *GetBestCopyCandidate(const TinySet<CopyCandidate, 4> &candidates, uint32_t basePtr, RasterChannel channel) {1939const CopyCandidate *best = nullptr;19401941// Pick the "best" candidate by comparing to the old best using heuristics.1942for (size_t i = 0; i < candidates.size(); i++) {1943const CopyCandidate *candidate = &candidates[i];19441945bool better = !best;1946if (!better) {1947// Heuristics determined from the old algorithm, that we might want to keep:1948// * Lower yOffsets are prioritized.1949// * Bindseq1950better = candidate->y < best->y;1951if (!better) {1952better = candidate->vfb->BindSeq(channel) > best->vfb->BindSeq(channel);1953}1954}19551956if (better) {1957best = candidate;1958}1959}1960return best;1961}19621963// This is called from detected memcopies and framebuffer initialization from VRAM. Not block transfers.1964// Also with specialized flags from some replacement functions. Only those will currently request depth copies!1965// NOTE: This is very tricky because there's no information about color depth here, so we'll have to make guesses1966// about what underlying framebuffer is the most likely to be the relevant ones. For src, we can probably prioritize recent1967// ones. For dst, less clear.1968bool FramebufferManagerCommon::NotifyFramebufferCopy(u32 src, u32 dst, int size, GPUCopyFlag flags, u32 skipDrawReason) {1969if (size == 0) {1970return false;1971}19721973dst &= 0x3FFFFFFF;1974src &= 0x3FFFFFFF;19751976if (Memory::IsVRAMAddress(dst))1977dst &= 0x041FFFFF;1978if (Memory::IsVRAMAddress(src))1979src &= 0x041FFFFF;19801981// TODO: Merge the below into FindTransferFramebuffer.1982// Or at least this should be like the other ones, gathering possible candidates1983// with the ability to list them out for debugging.19841985bool ignoreDstBuffer = flags & GPUCopyFlag::FORCE_DST_MATCH_MEM;1986bool ignoreSrcBuffer = flags & (GPUCopyFlag::FORCE_SRC_MATCH_MEM | GPUCopyFlag::MEMSET);19871988// TODO: In the future we should probably check both channels. Currently depth is only on request.1989RasterChannel channel = (flags & GPUCopyFlag::DEPTH_REQUESTED) ? RASTER_DEPTH : RASTER_COLOR;19901991TinySet<CopyCandidate, 4> srcCandidates;1992TinySet<CopyCandidate, 4> dstCandidates;19931994// TODO: These two loops should be merged into one utility function, similar to what's done with rectangle copies.19951996// First find candidates for the source.1997// We only look at the color channel for now.1998for (auto vfb : vfbs_) {1999if (vfb->fb_stride == 0 || ignoreSrcBuffer) {2000continue;2001}20022003// We only remove the kernel and uncached bits when comparing.2004const u32 vfb_address = vfb->Address(channel);2005const u32 vfb_size = vfb->BufferByteSize(channel);2006const u32 vfb_byteStride = vfb->BufferByteStride(channel);2007const int vfb_byteWidth = vfb->BufferByteWidth(channel);20082009CopyCandidate srcCandidate;2010srcCandidate.vfb = vfb;20112012// Special path for depth for now.2013if (channel == RASTER_DEPTH) {2014if (src == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {2015srcCandidate.y = 0;2016srcCandidate.h = vfb->height;2017srcCandidates.push_back(srcCandidate);2018}2019continue;2020}20212022if (src >= vfb_address && (src + size <= vfb_address + vfb_size || src == vfb_address)) {2023// Heuristic originally from dest below, but just as valid looking for the source.2024// Fixes a misdetection in Brothers in Arms: D-Day, issue #18512.2025if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {2026// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM2027// that can be displayed from, or another matching buffer with the right format if rendering is going on.2028// If we had scoring here, we should strongly penalize this target instead of ignoring it.2029WARN_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);2030continue;2031}20322033if ((u32)size > vfb_size + 0x1000 && vfb->fb_format != GE_FORMAT_8888 && vfb->last_frame_render < gpuStats.numFlips) {2034// Seems likely we are looking at a potential copy of 32-bit pixels (like video) to an old 16-bit buffer,2035// which is very likely simply the wrong target, so skip it. See issue #17740 where this happens in Naruto Ultimate Ninja Heroes 2.2036// Probably no point to give it a bad score and let it pass to sorting, as we're pretty sure here.2037WARN_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));2038continue;2039}20402041const u32 offset = src - vfb_address;2042const u32 yOffset = offset / vfb_byteStride;2043if ((offset % vfb_byteStride) == 0 && (size == vfb_byteWidth || (size % vfb_byteStride) == 0)) {2044srcCandidate.y = yOffset;2045srcCandidate.h = size == vfb_byteWidth ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2046} else if ((offset % vfb_byteStride) == 0 && size == vfb->fb_stride) {2047// Valkyrie Profile reads 512 bytes at a time, rather than 2048. So, let's whitelist fb_stride also.2048srcCandidate.y = yOffset;2049srcCandidate.h = 1;2050} else if (yOffset == 0 && (vfb->usageFlags & FB_USAGE_CLUT)) {2051// Okay, last try - it might be a clut.2052srcCandidate.y = yOffset;2053srcCandidate.h = 1;2054} else {2055continue;2056}2057srcCandidates.push_back(srcCandidate);2058}2059}20602061for (auto vfb : vfbs_) {2062if (vfb->fb_stride == 0 || ignoreDstBuffer) {2063continue;2064}20652066// We only remove the kernel and uncached bits when comparing.2067const u32 vfb_address = vfb->Address(channel);2068const u32 vfb_size = vfb->BufferByteSize(channel);2069const u32 vfb_byteStride = vfb->BufferByteStride(channel);2070const int vfb_byteWidth = vfb->BufferByteWidth(channel);20712072// Heuristic to try to prevent potential glitches with video playback.2073if (vfb_address == dst && ((size == 0x44000 && vfb_size == 0x88000) || (size == 0x88000 && vfb_size == 0x44000))) {2074// Not likely to be a correct color format copy for this buffer. Ignore it, there will either be RAM2075// that can be displayed from, or another matching buffer with the right format if rendering is going on.2076// If we had scoring here, we should strongly penalize this target instead of ignoring it.2077WARN_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);2078continue;2079}20802081CopyCandidate dstCandidate;2082dstCandidate.vfb = vfb;20832084// Special path for depth for now.2085if (channel == RASTER_DEPTH) {2086// Let's assume exact matches only for simplicity.2087if (dst == vfb->z_address && size == vfb->z_stride * 2 * vfb->height) {2088dstCandidate.y = 0;2089dstCandidate.h = vfb->height;2090dstCandidates.push_back(dstCandidate);2091}2092continue;2093}20942095if (!ignoreDstBuffer && dst >= vfb_address && (dst + size <= vfb_address + vfb_size || dst == vfb_address)) {2096const u32 offset = dst - vfb_address;2097const u32 yOffset = offset / vfb_byteStride;2098if ((offset % vfb_byteStride) == 0 && (size <= vfb_byteWidth || (size % vfb_byteStride) == 0)) {2099dstCandidate.y = yOffset;2100dstCandidate.h = (size <= vfb_byteWidth) ? 1 : std::min((u32)size / vfb_byteStride, (u32)vfb->height);2101dstCandidates.push_back(dstCandidate);2102}2103}2104}21052106// For now fill in these old variables from the candidates to reduce the initial diff.2107VirtualFramebuffer *dstBuffer = nullptr;2108VirtualFramebuffer *srcBuffer = nullptr;2109int srcY;2110int srcH;2111int dstY;2112int dstH;21132114const CopyCandidate *bestSrc = GetBestCopyCandidate(srcCandidates, src, channel);2115if (bestSrc) {2116srcBuffer = bestSrc->vfb;2117srcY = bestSrc->y;2118srcH = bestSrc->h;2119}2120const CopyCandidate *bestDst = GetBestCopyCandidate(dstCandidates, dst, channel);2121if (bestDst) {2122dstBuffer = bestDst->vfb;2123dstY = bestDst->y;2124dstH = bestDst->h;2125}21262127if (srcCandidates.size() > 1) {2128if (Reporting::ShouldLogNTimes("mulblock", 5)) {2129std::string log;2130for (size_t i = 0; i < srcCandidates.size(); i++) {2131log += " - " + srcCandidates[i].ToString(channel);2132if (bestSrc && srcCandidates[i].vfb == bestSrc->vfb) {2133log += " * \n";2134} else {2135log += "\n";2136}2137}2138WARN_LOG(Log::FrameBuf, "Copy: Multiple src vfb candidates for (src: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2139}2140}21412142if (dstCandidates.size() > 1) {2143if (Reporting::ShouldLogNTimes("mulblock", 5)) {2144std::string log;2145for (size_t i = 0; i < dstCandidates.size(); i++) {2146log += " - " + dstCandidates[i].ToString(channel);2147if (bestDst && dstCandidates[i].vfb == bestDst->vfb) {2148log += " * \n";2149} else {2150log += "\n";2151}2152}2153WARN_LOG(Log::FrameBuf, "Copy: Multiple dst vfb candidates for (dst: %08x, size: %d):\n%s (%s)", src, size, log.c_str(), RasterChannelToString(channel));2154}2155}21562157if (!useBufferedRendering_) {2158// If we're copying into a recently used display buf, it's probably destined for the screen.2159if (channel == RASTER_DEPTH || srcBuffer || (dstBuffer != displayFramebuf_ && dstBuffer != prevDisplayFramebuf_)) {2160return false;2161}2162}21632164if (!dstBuffer && srcBuffer && channel != RASTER_DEPTH) {2165// Note - if we're here, we're in a memcpy, not a block transfer. Not allowing IntraVRAMBlockTransferAllowCreateFB.2166// Technically, that makes BlockTransferAllowCreateFB a bit of a misnomer.2167bool allowCreateFB = (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB || GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE);2168if (allowCreateFB && !(flags & GPUCopyFlag::DISALLOW_CREATE_VFB)) {2169dstBuffer = CreateRAMFramebuffer(dst, srcBuffer->width, srcBuffer->height, srcBuffer->fb_stride, srcBuffer->fb_format);2170dstY = 0;2171}2172}2173if (dstBuffer) {2174dstBuffer->last_frame_used = gpuStats.numFlips;2175if (channel == RASTER_DEPTH && !srcBuffer)2176dstBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;2177}2178if (srcBuffer && channel == RASTER_DEPTH && !dstBuffer)2179srcBuffer->usageFlags |= FB_USAGE_COLOR_MIXED_DEPTH;21802181if (dstBuffer && srcBuffer) {2182if (srcBuffer == dstBuffer) {2183WARN_LOG_ONCE(dstsrccpy, Log::FrameBuf, "Intra-buffer memcpy (not supported) %08x -> %08x (size: %x)", src, dst, size);2184} else {2185WARN_LOG_ONCE(dstnotsrccpy, Log::FrameBuf, "Inter-buffer memcpy %08x -> %08x (size: %x)", src, dst, size);2186// Just do the blit!2187BlitFramebuffer(dstBuffer, 0, dstY, srcBuffer, 0, srcY, srcBuffer->width, srcH, 0, channel, "Blit_InterBufferMemcpy");2188SetColorUpdated(dstBuffer, skipDrawReason);2189RebindFramebuffer("RebindFramebuffer - Inter-buffer memcpy");2190}2191return false;2192} else if (dstBuffer) {2193if (flags & GPUCopyFlag::MEMSET) {2194gpuStats.numClears++;2195WARN_LOG_N_TIMES(btucpy, 5, Log::FrameBuf, "Memcpy fbo memset-clear %08x (size: %x)", dst, size);2196} else {2197WARN_LOG_N_TIMES(btucpy, 5, Log::FrameBuf, "Memcpy fbo upload %08x -> %08x (size: %x)", src, dst, size);2198}2199FlushBeforeCopy();22002201// 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.2202// We could collect these in a buffer and flush on the next draw, or something like that, to avoid that. The line copies cause2203// awkward visual artefacts.2204const u8 *srcBase = Memory::GetPointerUnchecked(src);2205GEBufferFormat srcFormat = channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : dstBuffer->fb_format;2206int srcStride = channel == RASTER_DEPTH ? dstBuffer->z_stride : dstBuffer->fb_stride;2207DrawPixels(dstBuffer, 0, dstY, srcBase, srcFormat, srcStride, dstBuffer->width, dstH, channel, "MemcpyFboUpload_DrawPixels");2208SetColorUpdated(dstBuffer, skipDrawReason);2209RebindFramebuffer("RebindFramebuffer - Memcpy fbo upload");2210// This is a memcpy, let's still copy just in case.2211return false;2212} else if (srcBuffer) {2213WARN_LOG_N_TIMES(btdcpy, 5, Log::FrameBuf, "Memcpy fbo download %08x -> %08x", src, dst);2214FlushBeforeCopy();2215// TODO: In Hot Shots Golf, check if we can do a readback to a framebuffer here.2216// Again we have the problem though that it's doing a lot of small copies here, one for each line.2217if (srcH == 0 || srcY + srcH > srcBuffer->bufferHeight) {2218WARN_LOG_ONCE(btdcpyheight, Log::FrameBuf, "Memcpy fbo download %08x -> %08x skipped, %d+%d is taller than %d", src, dst, srcY, srcH, srcBuffer->bufferHeight);2219} else if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && (!srcBuffer->memoryUpdated || channel == RASTER_DEPTH)) {2220ReadFramebufferToMemory(srcBuffer, 0, srcY, srcBuffer->width, srcH, channel, Draw::ReadbackMode::BLOCK);2221srcBuffer->usageFlags = (srcBuffer->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2222}2223return false;2224} else {2225return false;2226}2227}22282229std::string BlockTransferRect::ToString() const {2230int bpp = BufferFormatBytesPerPixel(channel == RASTER_DEPTH ? GE_FORMAT_DEPTH16 : vfb->fb_format);2231return 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);2232}22332234// This is used when looking for framebuffers for a block transfer.2235// The only known game to block transfer depth buffers is Iron Man, see #16530, so2236// we have a compat flag and pretty limited functionality for that.2237bool FramebufferManagerCommon::FindTransferFramebuffer(u32 basePtr, int stride_pixels, int x_pixels, int y, int w_pixels, int h, int bpp, bool destination, BlockTransferRect *rect) {2238basePtr &= 0x3FFFFFFF;2239if (Memory::IsVRAMAddress(basePtr))2240basePtr &= 0x041FFFFF;2241rect->vfb = nullptr;22422243if (!stride_pixels) {2244WARN_LOG(Log::FrameBuf, "Zero stride in FindTransferFrameBuffer, ignoring");2245return false;2246}22472248const u32 byteStride = stride_pixels * bpp;2249int x_bytes = x_pixels * bpp;2250int w_bytes = w_pixels * bpp;22512252TinySet<BlockTransferRect, 4> candidates;22532254// We work entirely in bytes when we do the matching, because games don't consistently use bpps that match2255// that of their buffers. Then after matching we try to map the copy to the simplest operation that does2256// what we need.22572258// We are only looking at color for now, have not found any block transfers of depth data (although it's plausible).22592260for (auto vfb : vfbs_) {2261BlockTransferRect candidate{ vfb, RASTER_COLOR };22622263// Two cases so far of games depending on depth copies: Iron Man in issue #16530 (buffer->buffer)2264// and also #17878 where a game does ram->buffer to an auto-swizzling (|0x600000) address,2265// to initialize Z with a pre-rendered depth buffer.2266if (vfb->z_address == basePtr && vfb->BufferByteStride(RASTER_DEPTH) == byteStride && PSP_CoreParameter().compat.flags().BlockTransferDepth) {2267WARN_LOG_N_TIMES(z_xfer, 5, Log::FrameBuf, "FindTransferFramebuffer: found matching depth buffer, %08x (dest=%d, bpp=%d)", basePtr, (int)destination, bpp);2268candidate.channel = RASTER_DEPTH;2269candidate.x_bytes = x_pixels * bpp;2270candidate.w_bytes = w_pixels * bpp;2271candidate.y = y;2272candidate.h = h;2273candidates.push_back(candidate);2274continue;2275}22762277const u32 vfb_address = vfb->fb_address;2278const u32 vfb_size = vfb->BufferByteSize(RASTER_COLOR);22792280if (basePtr < vfb_address || basePtr >= vfb_address + vfb_size) {2281continue;2282}22832284const u32 vfb_bpp = BufferFormatBytesPerPixel(vfb->fb_format);2285const u32 vfb_byteStride = vfb->FbStrideInBytes();2286const u32 vfb_byteWidth = vfb->WidthInBytes();22872288candidate.w_bytes = w_pixels * bpp;2289candidate.h = h;22902291const u32 byteOffset = basePtr - vfb_address;2292const int memXOffset = byteOffset % byteStride;2293const int memYOffset = byteOffset / byteStride;22942295// Some games use mismatching bitdepths. But make sure the stride matches.2296// If it doesn't, generally this means we detected the framebuffer with too large a height.2297// Use bufferHeight in case of buffers that resize up and down often per frame (Valkyrie Profile.)22982299// If it's outside the vfb by a single pixel, we currently disregard it.2300if (memYOffset > vfb->bufferHeight - h) {2301continue;2302}23032304if (byteOffset == vfb->WidthInBytes() && w_bytes < vfb->FbStrideInBytes()) {2305// Looks like we're in a margin texture of the vfb, which is not the vfb itself.2306// Ignore the match.2307continue;2308}23092310if (vfb_byteStride != byteStride) {2311// Grand Knights History occasionally copies with a mismatching stride but a full line at a time.2312// 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.2313// Makes it hard to detect the wrong transfers in e.g. God of War.2314if (w_pixels != stride_pixels || (byteStride * h != vfb_byteStride && byteStride * h != vfb_byteWidth)) {2315if (destination) {2316// However, some other games write cluts to framebuffers.2317// Let's catch this and upload. Otherwise reject the match.2318bool match = (vfb->usageFlags & FB_USAGE_CLUT) != 0;2319if (match) {2320candidate.w_bytes = byteStride * h;2321h = 1;2322} else {2323continue;2324}2325} else {2326continue;2327}2328} else {2329// This is the Grand Knights History case.2330candidate.w_bytes = byteStride * h;2331candidate.h = 1;2332}2333} else {2334candidate.w_bytes = w_bytes;2335candidate.h = h;2336}23372338candidate.x_bytes = x_bytes + memXOffset;2339candidate.y = y + memYOffset;2340candidate.vfb = vfb;2341candidates.push_back(candidate);2342}23432344const BlockTransferRect *best = nullptr;2345// Sort candidates by just recency for now, we might add other.2346for (size_t i = 0; i < candidates.size(); i++) {2347const BlockTransferRect *candidate = &candidates[i];23482349bool better = !best;2350if (!better) {2351if (candidate->channel == best->channel) {2352better = candidate->vfb->BindSeq(candidate->channel) > best->vfb->BindSeq(candidate->channel);2353} else {2354// Prefer depth over color if the address match is perfect.2355if (candidate->channel == RASTER_DEPTH && best->channel == RASTER_COLOR && candidate->vfb->z_address == basePtr) {2356better = true;2357}2358}2359}23602361if ((candidate->vfb->usageFlags & FB_USAGE_CLUT) && candidate->x_bytes == 0 && candidate->y == 0 && destination) {2362// Hack to prioritize copies to clut buffers.2363best = candidate;2364break;2365}2366if (better) {2367best = candidate;2368}2369}23702371if (candidates.size() > 1) {2372if (Reporting::ShouldLogNTimes("mulblock", 5)) {2373std::string log;2374for (size_t i = 0; i < candidates.size(); i++) {2375log += " - " + candidates[i].ToString() + "\n";2376}2377WARN_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());2378}2379}23802381if (best) {2382*rect = *best;2383return true;2384} else {2385if (Memory::IsVRAMAddress(basePtr) && destination && h >= 128) {2386WARN_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);2387}2388return false;2389}2390}23912392VirtualFramebuffer *FramebufferManagerCommon::CreateRAMFramebuffer(uint32_t fbAddress, int width, int height, int stride, GEBufferFormat format) {2393INFO_LOG(Log::FrameBuf, "Creating RAM framebuffer at %08x (%dx%d, stride %d, fb_format %d)", fbAddress, width, height, stride, format);23942395RasterChannel channel = format == GE_FORMAT_DEPTH16 ? RASTER_DEPTH : RASTER_COLOR;23962397// A target for the destination is missing - so just create one!2398// Make sure this one would be found by the algorithm above so we wouldn't2399// create a new one each frame.2400VirtualFramebuffer *vfb = new VirtualFramebuffer{};2401vfb->fbo = nullptr;2402uint32_t mask = Memory::IsVRAMAddress(fbAddress) ? 0x041FFFFF : 0x3FFFFFFF;2403if (format == GE_FORMAT_DEPTH16) {2404vfb->fb_address = 0xFFFFFFFF; // Invalid address2405vfb->fb_stride = 0;2406vfb->z_address = fbAddress; // marks that if anyone tries to render with depth to this framebuffer, it should be dropped and recreated.2407vfb->z_stride = stride;2408vfb->width = width;2409} else {2410vfb->fb_address = fbAddress & mask; // NOTE - not necessarily in VRAM!2411vfb->fb_stride = stride;2412vfb->z_address = 0;2413vfb->z_stride = 0;2414vfb->width = std::max(width, stride);2415}2416vfb->height = height;2417vfb->newWidth = vfb->width;2418vfb->newHeight = vfb->height;2419vfb->lastFrameNewSize = gpuStats.numFlips;2420vfb->renderScaleFactor = renderScaleFactor_;2421vfb->renderWidth = (u16)(vfb->width * renderScaleFactor_);2422vfb->renderHeight = (u16)(vfb->height * renderScaleFactor_);2423vfb->bufferWidth = vfb->width;2424vfb->bufferHeight = vfb->height;2425vfb->fb_format = format == GE_FORMAT_DEPTH16 ? GE_FORMAT_8888 : format;2426vfb->usageFlags = format == GE_FORMAT_DEPTH16 ? FB_USAGE_RENDER_DEPTH : FB_USAGE_RENDER_COLOR;2427if (format != GE_FORMAT_DEPTH16) {2428SetColorUpdated(vfb, 0);2429}2430char name[64];2431snprintf(name, sizeof(name), "%08x_%s_RAM", vfb->Address(channel), RasterChannelToString(channel));2432textureCache_->NotifyFramebuffer(vfb, NOTIFY_FB_CREATED);2433bool createDepthBuffer = format == GE_FORMAT_DEPTH16;2434vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, createDepthBuffer, name });2435vfbs_.push_back(vfb);24362437u32 byteSize = vfb->BufferByteSize(channel);2438if (fbAddress + byteSize > framebufColorRangeEnd_) {2439framebufColorRangeEnd_ = fbAddress + byteSize;2440}24412442return vfb;2443}24442445// 1:1 pixel size buffers, we resize buffers to these before we read them back.2446// TODO: We shouldn't keep whole VirtualFramebuffer structs for these - the fbo and last_frame_render is enough.2447VirtualFramebuffer *FramebufferManagerCommon::FindDownloadTempBuffer(VirtualFramebuffer *vfb, RasterChannel channel) {2448// For now we'll keep these on the same struct as the ones that can get displayed2449// (and blatantly copy work already done above while at it).2450VirtualFramebuffer *nvfb = nullptr;24512452// We maintain a separate vector of framebuffer objects for blitting.2453for (VirtualFramebuffer *v : bvfbs_) {2454if (v->Address(channel) == vfb->Address(channel) && v->Format(channel) == vfb->Format(channel)) {2455if (v->bufferWidth == vfb->bufferWidth && v->bufferHeight == vfb->bufferHeight) {2456nvfb = v;2457if (channel == RASTER_COLOR) {2458v->fb_stride = vfb->fb_stride;2459} else {2460v->z_stride = vfb->z_stride;2461}2462v->width = vfb->width;2463v->height = vfb->height;2464break;2465}2466}2467}24682469// Create a new fbo if none was found for the size2470if (!nvfb) {2471nvfb = new VirtualFramebuffer{};2472nvfb->fbo = nullptr;2473nvfb->fb_address = channel == RASTER_COLOR ? vfb->fb_address : 0;2474nvfb->fb_stride = channel == RASTER_COLOR ? vfb->fb_stride : 0;2475nvfb->z_address = channel == RASTER_DEPTH ? vfb->z_address : 0;2476nvfb->z_stride = channel == RASTER_DEPTH ? vfb->z_stride : 0;2477nvfb->width = vfb->width;2478nvfb->height = vfb->height;2479nvfb->renderWidth = vfb->bufferWidth;2480nvfb->renderHeight = vfb->bufferHeight;2481nvfb->renderScaleFactor = 1; // For readbacks we resize to the original size, of course.2482nvfb->bufferWidth = vfb->bufferWidth;2483nvfb->bufferHeight = vfb->bufferHeight;2484nvfb->fb_format = vfb->fb_format;2485nvfb->drawnWidth = vfb->drawnWidth;2486nvfb->drawnHeight = vfb->drawnHeight;24872488char name[64];2489snprintf(name, sizeof(name), "download_temp_%08x_%s", vfb->Address(channel), RasterChannelToString(channel));24902491// We always create a color-only framebuffer here - readbacks of depth convert to color while translating the values.2492nvfb->fbo = draw_->CreateFramebuffer({ nvfb->bufferWidth, nvfb->bufferHeight, 1, 1, 0, false, name });2493if (!nvfb->fbo) {2494ERROR_LOG(Log::FrameBuf, "Error creating FBO! %d x %d", nvfb->renderWidth, nvfb->renderHeight);2495delete nvfb;2496return nullptr;2497}2498bvfbs_.push_back(nvfb);2499} else {2500UpdateDownloadTempBuffer(nvfb);2501}25022503nvfb->usageFlags |= FB_USAGE_RENDER_COLOR;2504nvfb->last_frame_render = gpuStats.numFlips;2505nvfb->dirtyAfterDisplay = true;25062507return nvfb;2508}25092510void FramebufferManagerCommon::ApplyClearToMemory(int x1, int y1, int x2, int y2, u32 clearColor) {2511if (currentRenderVfb_) {2512if ((currentRenderVfb_->usageFlags & FB_USAGE_DOWNLOAD_CLEAR) != 0) {2513// Already zeroed in memory.2514return;2515}2516}25172518if (!Memory::IsValidAddress(gstate.getFrameBufAddress())) {2519return;2520}25212522u8 *addr = Memory::GetPointerWriteUnchecked(gstate.getFrameBufAddress());2523const int bpp = BufferFormatBytesPerPixel(gstate_c.framebufFormat);25242525u32 clearBits = clearColor;2526if (bpp == 2) {2527u16 clear16 = 0;2528switch (gstate_c.framebufFormat) {2529case GE_FORMAT_565: clear16 = RGBA8888toRGB565(clearColor); break;2530case GE_FORMAT_5551: clear16 = RGBA8888toRGBA5551(clearColor); break;2531case GE_FORMAT_4444: clear16 = RGBA8888toRGBA4444(clearColor); break;2532default: _dbg_assert_(0); break;2533}2534clearBits = clear16 | (clear16 << 16);2535}25362537const bool singleByteClear = (clearBits >> 16) == (clearBits & 0xFFFF) && (clearBits >> 24) == (clearBits & 0xFF);2538const int stride = gstate.FrameBufStride();2539const int width = x2 - x1;25402541const int byteStride = stride * bpp;2542const int byteWidth = width * bpp;2543for (int y = y1; y < y2; ++y) {2544NotifyMemInfo(MemBlockFlags::WRITE, gstate.getFrameBufAddress() + x1 * bpp + y * byteStride, byteWidth, "FramebufferClear");2545}25462547// Can use memset for simple cases. Often alpha is different and gums up the works.2548if (singleByteClear) {2549addr += x1 * bpp;2550for (int y = y1; y < y2; ++y) {2551memset(addr + y * byteStride, clearBits, byteWidth);2552}2553} else {2554// This will most often be true - rarely is the width not aligned.2555// TODO: We should really use non-temporal stores here to avoid the cache,2556// as it's unlikely that these bytes will be read.2557if ((width & 3) == 0 && (x1 & 3) == 0) {2558u64 val64 = clearBits | ((u64)clearBits << 32);2559int xstride = 8 / bpp;25602561u64 *addr64 = (u64 *)addr;2562const int stride64 = stride / xstride;2563const int x1_64 = x1 / xstride;2564const int x2_64 = x2 / xstride;2565for (int y = y1; y < y2; ++y) {2566for (int x = x1_64; x < x2_64; ++x) {2567addr64[y * stride64 + x] = val64;2568}2569}2570} else if (bpp == 4) {2571u32 *addr32 = (u32 *)addr;2572for (int y = y1; y < y2; ++y) {2573for (int x = x1; x < x2; ++x) {2574addr32[y * stride + x] = clearBits;2575}2576}2577} else if (bpp == 2) {2578u16 *addr16 = (u16 *)addr;2579for (int y = y1; y < y2; ++y) {2580for (int x = x1; x < x2; ++x) {2581addr16[y * stride + x] = (u16)clearBits;2582}2583}2584}2585}25862587if (currentRenderVfb_) {2588// The current content is in memory now, so update the flag.2589if (x1 == 0 && y1 == 0 && x2 >= currentRenderVfb_->width && y2 >= currentRenderVfb_->height) {2590currentRenderVfb_->usageFlags |= FB_USAGE_DOWNLOAD_CLEAR;2591currentRenderVfb_->memoryUpdated = true;2592}2593}2594}25952596bool 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) {2597if (!useBufferedRendering_) {2598return false;2599}26002601// Skip checking if there's no framebuffers in that area. Make a special exception for obvious transfers to depth buffer, see issue #178782602bool dstDepthSwizzle = Memory::IsVRAMAddress(dstBasePtr) && ((dstBasePtr & 0x600000) == 0x600000);26032604if (!dstDepthSwizzle && !MayIntersectFramebufferColor(srcBasePtr) && !MayIntersectFramebufferColor(dstBasePtr)) {2605return false;2606}26072608BlockTransferRect dstRect{};2609BlockTransferRect srcRect{};26102611// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2612bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2613bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);26142615if (srcRect.channel == RASTER_DEPTH) {2616// Ignore the found buffer if it's not 16-bit - we create a new more suitable one instead.2617if (dstRect.channel == RASTER_COLOR && dstRect.vfb->fb_format == GE_FORMAT_8888) {2618dstBuffer = false;2619}2620}26212622if (!srcBuffer && dstBuffer && dstRect.channel == RASTER_DEPTH) {2623dstBuffer = true;2624}26252626if (srcBuffer && !dstBuffer) {2627// In here, we can't read from dstRect.2628if (PSP_CoreParameter().compat.flags().BlockTransferAllowCreateFB ||2629GetSkipGPUReadbackMode() == SkipGPUReadbackMode::COPY_TO_TEXTURE ||2630(PSP_CoreParameter().compat.flags().IntraVRAMBlockTransferAllowCreateFB &&2631(srcRect.vfb && Memory::IsVRAMAddress(srcRect.vfb->fb_address)) && Memory::IsVRAMAddress(dstBasePtr))) {2632GEBufferFormat ramFormat;2633// Try to guess the appropriate format. We only know the bpp from the block transfer command (16 or 32 bit).2634if (srcRect.channel == RASTER_COLOR) {2635if (bpp == 4) {2636// Only one possibility unless it's doing split pixel tricks (which we could detect through stride maybe).2637ramFormat = GE_FORMAT_8888;2638} else if (srcRect.vfb && srcRect.vfb->fb_format != GE_FORMAT_8888) {2639// We guess that the game will interpret the data the same as it was in the source of the copy.2640// Seems like a likely good guess, and works in Test Drive Unlimited.2641ramFormat = srcRect.vfb->fb_format;2642} else {2643// No info left - just fall back to something. But this is definitely split pixel tricks.2644ramFormat = GE_FORMAT_5551;2645}2646dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, ramFormat);2647dstRect.x_bytes = bpp * dstX;2648dstRect.y = dstY;2649dstRect.w_bytes = bpp * width;2650dstRect.h = height;2651dstRect.channel = RASTER_COLOR;2652} else {2653dstRect.vfb = CreateRAMFramebuffer(dstBasePtr, width, height, dstStride, GE_FORMAT_DEPTH16);2654dstRect.x_bytes = 0;2655dstRect.w_bytes = 2 * width; // 2 = depth bpp2656dstRect.y = 0;2657dstRect.h = height;2658dstRect.channel = RASTER_DEPTH;2659}2660dstBuffer = true;2661}2662}26632664if (dstBuffer) {2665dstRect.vfb->last_frame_used = gpuStats.numFlips;2666// Mark the destination as fresh.2667if (dstRect.channel == RASTER_COLOR) {2668dstRect.vfb->colorBindSeq = GetBindSeqCount();2669} else {2670dstRect.vfb->depthBindSeq = GetBindSeqCount();2671}2672}26732674if (dstBuffer && srcBuffer) {2675if (srcRect.vfb && srcRect.vfb == dstRect.vfb && srcRect.channel == dstRect.channel) {2676// Transfer within the same buffer.2677// This is a simple case because there will be no format conversion or similar shenanigans needed.2678// However, the BPP might still mismatch, but in such a case we can convert the coordinates.2679if (srcX == dstX && srcY == dstY) {2680// Ignore, nothing to do. Tales of Phantasia X does this by accident.2681// Returning true to also skip the memory copy.2682return true;2683}26842685int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));26862687if (bpp != buffer_bpp) {2688WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in intra-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2689// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2690bpp = buffer_bpp;2691}26922693WARN_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)",2694width, height, bpp,2695srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2696dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2697FlushBeforeCopy();2698// Some backends can handle blitting within a framebuffer. Others will just have to deal with it or ignore it, apparently.2699BlitFramebuffer(dstRect.vfb, dstX, dstY, srcRect.vfb, srcX, srcY, dstRect.w_bytes / bpp, dstRect.h, bpp, dstRect.channel, "Blit_IntraBufferBlockTransfer");2700RebindFramebuffer("rebind after intra block transfer");2701SetColorUpdated(dstRect.vfb, skipDrawReason);2702return true; // Skip the memory copy.2703}27042705// Straightforward blit between two same-format framebuffers.2706if (srcRect.vfb && srcRect.channel == dstRect.channel && srcRect.vfb->Format(srcRect.channel) == dstRect.vfb->Format(dstRect.channel)) {2707WARN_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)",2708RasterChannelToString(srcRect.channel),2709width, height, bpp,2710srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride, GeBufferFormatToString(srcRect.vfb->fb_format),2711dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride, GeBufferFormatToString(dstRect.vfb->fb_format));27122713// Straight blit will do, but check the bpp, we might need to convert coordinates differently.2714int buffer_bpp = BufferFormatBytesPerPixel(srcRect.vfb->Format(srcRect.channel));2715if (bpp != buffer_bpp) {2716WARN_LOG_ONCE(intrabpp, Log::G3D, "Mismatched transfer bpp in inter-buffer block transfer. Was %d, expected %d.", bpp, buffer_bpp);2717// We just switch to using the buffer's bpp, since we've already converted the rectangle to byte offsets.2718bpp = buffer_bpp;2719}2720FlushBeforeCopy();2721BlitFramebuffer(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");2722RebindFramebuffer("RebindFramebuffer - Inter-buffer block transfer");2723SetColorUpdated(dstRect.vfb, skipDrawReason);2724return true;2725}27262727// Getting to the more complex cases. Have not actually seen much of these yet.2728if (srcRect.vfb && dstRect.vfb) {2729WARN_LOG_N_TIMES(blockformat, 5, Log::G3D, "Mismatched buffer formats in block transfer: %s->%s (%dx%d)",2730GeBufferFormatToString(srcRect.vfb->Format(srcRect.channel)), GeBufferFormatToString(dstRect.vfb->Format(dstRect.channel)),2731width, height);2732}27332734// TODO27352736// No need to actually do the memory copy behind, probably.2737return true;27382739} else if (dstBuffer) {2740// Handle depth uploads directly here, and let's not bother copying the data. This is compat-flag-gated for now,2741// may generalize it when I remove the compat flag.2742if (dstRect.channel == RASTER_DEPTH) {2743WARN_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));2744FlushBeforeCopy();2745const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;2746DrawPixels(dstRect.vfb, dstX, dstY, srcBase, dstRect.vfb->Format(dstRect.channel), srcStride * bpp / 2, (int)(dstRect.w_bytes / 2), dstRect.h, dstRect.channel, "BlockTransferCopy_DrawPixelsDepth");2747RebindFramebuffer("RebindFramebuffer - UploadDepth");2748return true;2749}27502751// Here we should just draw the pixels into the buffer. Return false to copy the memory first.2752// NotifyBlockTransferAfter will take care of the rest.2753return false;2754} else if (srcBuffer) {2755if (width == 48 && height == 48 && srcY == 224 && srcX == 432 && PSP_CoreParameter().compat.flags().TacticsOgreEliminateDebugReadback) {2756return false;2757}27582759WARN_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)",2760width, height, bpp,2761srcBasePtr, srcRect.x_bytes / bpp, srcRect.y, srcStride,2762dstBasePtr, dstRect.x_bytes / bpp, dstRect.y, dstStride);2763FlushBeforeCopy();2764if (GetSkipGPUReadbackMode() == SkipGPUReadbackMode::NO_SKIP && srcRect.vfb && !srcRect.vfb->memoryUpdated) {2765const int srcBpp = BufferFormatBytesPerPixel(srcRect.vfb->fb_format);2766const float srcXFactor = (float)bpp / srcBpp;2767const bool tooTall = srcY + srcRect.h > srcRect.vfb->bufferHeight;2768if (srcRect.h <= 0 || (tooTall && srcY != 0)) {2769WARN_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);2770} else {2771if (tooTall) {2772WARN_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);2773}2774ReadFramebufferToMemory(srcRect.vfb, static_cast<int>(srcX * srcXFactor), srcY, static_cast<int>(srcRect.w_bytes * srcXFactor), srcRect.h, RASTER_COLOR, Draw::ReadbackMode::BLOCK);2775srcRect.vfb->usageFlags = (srcRect.vfb->usageFlags | FB_USAGE_DOWNLOAD) & ~FB_USAGE_DOWNLOAD_CLEAR;2776}2777}2778return false; // Let the bit copy happen2779} else {2780return false;2781}2782}27832784SkipGPUReadbackMode FramebufferManagerCommon::GetSkipGPUReadbackMode() {2785if (PSP_CoreParameter().compat.flags().ForceEnableGPUReadback) {2786return SkipGPUReadbackMode::NO_SKIP;2787} else {2788return (SkipGPUReadbackMode)g_Config.iSkipGPUReadbackMode;2789}2790}27912792void 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) {2793// If it's a block transfer direct to the screen, and we're not using buffers, draw immediately.2794// We may still do a partial block draw below if this doesn't pass.2795if (!useBufferedRendering_ && dstStride >= 480 && width >= 480 && height == 272) {2796bool isPrevDisplayBuffer = PrevDisplayFramebufAddr() == dstBasePtr;2797bool isDisplayBuffer = CurrentDisplayFramebufAddr() == dstBasePtr;2798if (isPrevDisplayBuffer || isDisplayBuffer) {2799FlushBeforeCopy();2800// HACK2801DrawFramebufferToOutput(displayLayoutConfigCopy_, Memory::GetPointerUnchecked(dstBasePtr), dstStride, displayFormat_);2802return;2803}2804}28052806if (MayIntersectFramebufferColor(srcBasePtr) || MayIntersectFramebufferColor(dstBasePtr)) {2807// TODO: Figure out how we can avoid repeating the search here.28082809BlockTransferRect dstRect{};2810BlockTransferRect srcRect{};28112812// These modify the X/Y/W/H parameters depending on the memory offset of the base pointers from the actual buffers.2813bool srcBuffer = FindTransferFramebuffer(srcBasePtr, srcStride, srcX, srcY, width, height, bpp, false, &srcRect);2814bool dstBuffer = FindTransferFramebuffer(dstBasePtr, dstStride, dstX, dstY, width, height, bpp, true, &dstRect);28152816// A few games use this INSTEAD of actually drawing the video image to the screen, they just blast it to2817// the backbuffer. Detect this and have the framebuffermanager draw the pixels.2818if ((!useBufferedRendering_ && currentRenderVfb_ != dstRect.vfb) || dstRect.vfb == nullptr) {2819return;2820}28212822if (dstBuffer && !srcBuffer) {2823WARN_LOG_ONCE(btu, Log::G3D, "Block transfer upload %08x -> %08x (%dx%d %d,%d bpp=%d)", srcBasePtr, dstBasePtr, width, height, dstX, dstY, bpp);2824FlushBeforeCopy();2825const u8 *srcBase = Memory::GetPointerUnchecked(srcBasePtr) + (srcX + srcY * srcStride) * bpp;28262827int dstBpp = BufferFormatBytesPerPixel(dstRect.vfb->fb_format);2828float dstXFactor = (float)bpp / dstBpp;2829if (dstRect.w_bytes / bpp > dstRect.vfb->width || dstRect.h > dstRect.vfb->height) {2830// The buffer isn't big enough, and we have a clear hint of size. Resize.2831// This happens in Valkyrie Profile when uploading video at the ending.2832// Also happens to the CLUT framebuffer in the Burnout Dominator lens flare effect. See #160752833ResizeFramebufFBO(dstRect.vfb, dstRect.w_bytes / bpp, dstRect.h, false, true);2834// Make sure we don't flop back and forth.2835dstRect.vfb->newWidth = std::max(dstRect.w_bytes / bpp, (int)dstRect.vfb->width);2836dstRect.vfb->newHeight = std::max(dstRect.h, (int)dstRect.vfb->height);2837dstRect.vfb->lastFrameNewSize = gpuStats.numFlips;2838// Resizing may change the viewport/etc.2839gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_CULLRANGE);2840}2841DrawPixels(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");2842SetColorUpdated(dstRect.vfb, skipDrawReason);2843RebindFramebuffer("RebindFramebuffer - NotifyBlockTransferAfter");2844}2845}2846}28472848void FramebufferManagerCommon::SetSafeSize(u16 w, u16 h) {2849VirtualFramebuffer *vfb = currentRenderVfb_;2850if (vfb) {2851vfb->safeWidth = std::min(vfb->bufferWidth, std::max(vfb->safeWidth, w));2852vfb->safeHeight = std::min(vfb->bufferHeight, std::max(vfb->safeHeight, h));2853}2854}28552856void FramebufferManagerCommon::NotifyDisplayResized() {2857pixelWidth_ = PSP_CoreParameter().pixelWidth;2858pixelHeight_ = PSP_CoreParameter().pixelHeight;2859presentation_->UpdateDisplaySize(pixelWidth_, pixelHeight_);28602861INFO_LOG(Log::G3D, "FramebufferManagerCommon::NotifyDisplayResized: %dx%d", pixelWidth_, pixelHeight_);28622863// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2864// So we need to defer the post processing initialization.2865updatePostShaders_ = true;2866}28672868void FramebufferManagerCommon::NotifyRenderResized(const DisplayLayoutConfig &config, int msaaLevel) {2869gstate_c.skipDrawReason &= ~SKIPDRAW_NON_DISPLAYED_FB;28702871int w, h, scaleFactor;2872presentation_->CalculateRenderResolution(config, &w, &h, &scaleFactor, &postShaderIsUpscalingFilter_, &postShaderIsSupersampling_);2873PSP_CoreParameter().renderWidth = w;2874PSP_CoreParameter().renderHeight = h;2875PSP_CoreParameter().renderScaleFactor = scaleFactor;28762877if (UpdateRenderSize(msaaLevel)) {2878draw_->StopThreads();2879DestroyAllFBOs();2880draw_->StartThreads();2881}28822883// No drawing is allowed here. This includes anything that might potentially touch a command buffer, like creating images!2884// So we need to defer the post processing initialization.2885updatePostShaders_ = true;2886}28872888void FramebufferManagerCommon::NotifyConfigChanged() {2889updatePostShaders_ = true;2890}28912892void FramebufferManagerCommon::DestroyAllFBOs() {2893DiscardFramebufferCopy();2894currentRenderVfb_ = nullptr;2895displayFramebuf_ = nullptr;2896prevDisplayFramebuf_ = nullptr;2897prevPrevDisplayFramebuf_ = nullptr;28982899for (VirtualFramebuffer *vfb : vfbs_) {2900INFO_LOG(Log::FrameBuf, "Destroying FBO for %08x : %i x %i x %i", vfb->fb_address, vfb->width, vfb->height, vfb->fb_format);2901DestroyFramebuf(vfb);2902}2903vfbs_.clear();29042905for (VirtualFramebuffer *vfb : bvfbs_) {2906DestroyFramebuf(vfb);2907}2908bvfbs_.clear();29092910for (auto &tempFB : tempFBOs_) {2911tempFB.second.fbo->Release();2912}2913tempFBOs_.clear();29142915for (auto &iter : fbosToDelete_) {2916iter->Release();2917}2918fbosToDelete_.clear();29192920for (auto &iter : drawPixelsCache_) {2921iter.tex->Release();2922}2923drawPixelsCache_.clear();2924}29252926static const char *TempFBOReasonToString(TempFBO reason) {2927switch (reason) {2928case TempFBO::DEPAL: return "depal";2929case TempFBO::BLIT: return "blit";2930case TempFBO::COPY: return "copy";2931case TempFBO::STENCIL: return "stencil";2932default: break;2933}2934return "";2935}29362937Draw::Framebuffer *FramebufferManagerCommon::GetTempFBO(TempFBO reason, u16 w, u16 h) {2938u64 key = ((u64)reason << 48) | ((u32)w << 16) | h;2939auto it = tempFBOs_.find(key);2940if (it != tempFBOs_.end()) {2941it->second.last_frame_used = gpuStats.numFlips;2942return it->second.fbo;2943}29442945bool z_stencil = reason == TempFBO::STENCIL;2946char name[128];2947snprintf(name, sizeof(name), "tempfbo_%s_%dx%d", TempFBOReasonToString(reason), w / renderScaleFactor_, h / renderScaleFactor_);29482949Draw::Framebuffer *fbo = draw_->CreateFramebuffer({ w, h, 1, GetFramebufferLayers(), 0, z_stencil, name });2950if (!fbo) {2951return nullptr;2952}29532954const TempFBOInfo info = { fbo, gpuStats.numFlips };2955tempFBOs_[key] = info;2956return fbo;2957}29582959void FramebufferManagerCommon::UpdateFramebufUsage(VirtualFramebuffer *vfb) const {2960auto checkFlag = [&](u16 flag, int last_frame) {2961if (vfb->usageFlags & flag) {2962const int age = frameLastFramebufUsed_ - last_frame;2963if (age > FBO_OLD_USAGE_FLAG) {2964vfb->usageFlags &= ~flag;2965}2966}2967};29682969checkFlag(FB_USAGE_DISPLAYED_FRAMEBUFFER, vfb->last_frame_displayed);2970checkFlag(FB_USAGE_TEXTURE, vfb->last_frame_used);2971checkFlag(FB_USAGE_RENDER_COLOR, vfb->last_frame_render);2972checkFlag(FB_USAGE_CLUT, vfb->last_frame_clut);2973}29742975void FramebufferManagerCommon::ClearAllDepthBuffers() {2976for (auto vfb : vfbs_) {2977vfb->usageFlags |= FB_USAGE_INVALIDATE_DEPTH;2978}2979}29802981// We might also want to implement an asynchronous callback-style version of this. Would probably2982// only be possible to implement optimally on Vulkan, but on GL and D3D11 we could do pixel buffers2983// and read on the next frame, then call the callback.2984//2985// The main use cases for this are:2986// * GE debugging(in practice async will not matter because it will stall anyway.)2987// * Video file recording(would probably be great if it was async.)2988// * Screenshots(benefit slightly from async.)2989// * Save state screenshots(could probably be async but need to manage the stall.)2990bool FramebufferManagerCommon::GetFramebuffer(u32 fb_address, int fb_stride, GEBufferFormat format, GPUDebugBuffer &buffer, int maxScaleFactor) {2991VirtualFramebuffer *vfb = currentRenderVfb_;2992if (!vfb || vfb->fb_address != fb_address) {2993vfb = ResolveVFB(fb_address, fb_stride, format);2994}29952996if (!vfb) {2997if (!Memory::IsValidAddress(fb_address))2998return false;2999// If there's no vfb and we're drawing there, must be memory?3000buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(fb_address), fb_stride, 512, format);3001return true;3002}30033004int w = vfb->renderWidth, h = vfb->renderHeight;30053006Draw::Framebuffer *bound = nullptr;30073008if (vfb->fbo) {3009if (maxScaleFactor > 0 && vfb->renderWidth > vfb->width * maxScaleFactor) {3010w = vfb->width * maxScaleFactor;3011h = vfb->height * maxScaleFactor;30123013Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::COPY, w, h);3014VirtualFramebuffer tempVfb = *vfb;3015tempVfb.fbo = tempFBO;3016tempVfb.bufferWidth = vfb->width;3017tempVfb.bufferHeight = vfb->height;3018tempVfb.renderWidth = w;3019tempVfb.renderHeight = h;3020tempVfb.renderScaleFactor = maxScaleFactor;3021BlitFramebuffer(&tempVfb, 0, 0, vfb, 0, 0, vfb->width, vfb->height, 0, RASTER_COLOR, "Blit_GetFramebuffer");30223023bound = tempFBO;3024} else {3025bound = vfb->fbo;3026}3027}30283029if (!useBufferedRendering_) {3030// Safety check.3031w = std::min(w, PSP_CoreParameter().pixelWidth);3032h = std::min(h, PSP_CoreParameter().pixelHeight);3033}30343035// TODO: Maybe should handle flipY inside CopyFramebufferToMemorySync somehow?3036bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3037buffer.Allocate(w, h, GE_FORMAT_8888, flipY);3038bool retval = draw_->CopyFramebufferToMemory(bound, Draw::Aspect::COLOR_BIT, 0, 0, w, h, Draw::DataFormat::R8G8B8A8_UNORM, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetFramebuffer");30393040// Don't need to increment gpu stats for readback count here, this is a debugger-only function.30413042// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3043gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3044// We may have blitted to a temp FBO.3045RebindFramebuffer("RebindFramebuffer - GetFramebuffer");3046return retval;3047}30483049bool FramebufferManagerCommon::GetDepthbuffer(u32 fb_address, int fb_stride, u32 z_address, int z_stride, GPUDebugBuffer &buffer) {3050VirtualFramebuffer *vfb = currentRenderVfb_;3051if (!vfb) {3052vfb = GetVFBAt(fb_address);3053}30543055if (!vfb) {3056if (!Memory::IsValidAddress(z_address))3057return false;3058// If there's no vfb and we're drawing there, must be memory?3059buffer = GPUDebugBuffer(Memory::GetPointerWriteUnchecked(z_address), z_stride, 512, GPU_DBG_FORMAT_16BIT);3060return true;3061}30623063int w = vfb->renderWidth;3064int h = vfb->renderHeight;3065if (!useBufferedRendering_) {3066// Safety check.3067w = std::min(w, PSP_CoreParameter().pixelWidth);3068h = std::min(h, PSP_CoreParameter().pixelHeight);3069}30703071bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;30723073// Old code3074if (gstate_c.Use(GPU_SCALE_DEPTH_FROM_24BIT_TO_16BIT)) {3075buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT_DIV_256, flipY);3076} else {3077buffer.Allocate(w, h, GPU_DBG_FORMAT_FLOAT, flipY);3078}3079// No need to free on failure, that's the caller's job (it likely will reuse a buffer.)3080bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::DEPTH_BIT, 0, 0, w, h, Draw::DataFormat::D32F, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetDepthBuffer");3081if (!retval) {3082// Try ReadbackDepthbufferSync, in case GLES.3083buffer.Allocate(w, h, GPU_DBG_FORMAT_16BIT, flipY);3084retval = ReadbackDepthbuffer(vfb->fbo, 0, 0, w, h, (uint16_t *)buffer.GetData(), w, w, h, Draw::ReadbackMode::BLOCK);3085}30863087// After a readback we'll have flushed and started over, need to dirty a bunch of things to be safe.3088gstate_c.Dirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);3089// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3090RebindFramebuffer("RebindFramebuffer - GetDepthbuffer");3091return retval;3092}30933094bool FramebufferManagerCommon::GetStencilbuffer(u32 fb_address, int fb_stride, GPUDebugBuffer &buffer) {3095VirtualFramebuffer *vfb = currentRenderVfb_;3096if (!vfb) {3097vfb = GetVFBAt(fb_address);3098}30993100if (!vfb) {3101if (!Memory::IsValidAddress(fb_address))3102return false;3103// If there's no vfb and we're drawing there, must be memory?3104// TODO: Actually get the stencil.3105buffer = GPUDebugBuffer(Memory::GetPointerWrite(fb_address), fb_stride, 512, GPU_DBG_FORMAT_8888);3106return true;3107}31083109int w = vfb->renderWidth;3110int h = vfb->renderHeight;3111if (!useBufferedRendering_) {3112// Safety check.3113w = std::min(w, PSP_CoreParameter().pixelWidth);3114h = std::min(h, PSP_CoreParameter().pixelHeight);3115}31163117bool flipY = (GetGPUBackend() == GPUBackend::OPENGL && !useBufferedRendering_) ? true : false;3118// No need to free on failure, the caller/destructor will do that. Usually this is a reused buffer, anyway.3119buffer.Allocate(w, h, GPU_DBG_FORMAT_8BIT, flipY);3120bool retval = draw_->CopyFramebufferToMemory(vfb->fbo, Draw::Aspect::STENCIL_BIT, 0, 0, w,h, Draw::DataFormat::S8, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetStencilbuffer");3121if (!retval) {3122retval = ReadbackStencilbuffer(vfb->fbo, 0, 0, w, h, buffer.GetData(), w, Draw::ReadbackMode::BLOCK);3123}3124// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3125RebindFramebuffer("RebindFramebuffer - GetStencilbuffer");3126return retval;3127}31283129bool GetOutputFramebuffer(Draw::DrawContext *draw, GPUDebugBuffer &buffer) {3130int w, h;3131draw->GetFramebufferDimensions(nullptr, &w, &h);3132Draw::DataFormat fmt = draw->PreferredFramebufferReadbackFormat(nullptr);3133// Ignore preferred formats other than BGRA.3134_dbg_assert_(fmt == Draw::DataFormat::B8G8R8A8_UNORM || fmt == Draw::DataFormat::R8G8B8A8_UNORM);3135if (fmt != Draw::DataFormat::B8G8R8A8_UNORM)3136fmt = Draw::DataFormat::R8G8B8A8_UNORM;31373138bool flipped = g_Config.iGPUBackend == (int)GPUBackend::OPENGL;31393140buffer.Allocate(w, h, fmt == Draw::DataFormat::R8G8B8A8_UNORM ? GPU_DBG_FORMAT_8888 : GPU_DBG_FORMAT_8888_BGRA, flipped);3141return draw->CopyFramebufferToMemory(nullptr, Draw::Aspect::COLOR_BIT, 0, 0, w, h, fmt, buffer.GetData(), w, Draw::ReadbackMode::BLOCK, "GetOutputFramebuffer");3142}31433144bool FramebufferManagerCommon::GetOutputFramebuffer(GPUDebugBuffer &buffer) {3145bool retval = ::GetOutputFramebuffer(draw_, buffer);3146// That may have unbound the framebuffer, rebind to avoid crashes when debugging.3147RebindFramebuffer("RebindFramebuffer - GetOutputFramebuffer");3148return retval;3149}31503151// This reads a channel of a framebuffer into emulated PSP VRAM, taking care of scaling down as needed.3152//3153// Color conversion is currently done on CPU but should theoretically be done on GPU.3154// (Except using the GPU might cause problems because of various implementations'3155// dithering behavior and games that expect exact colors like Danganronpa, so we3156// can't entirely be rid of the CPU path.) -- unknown3157void FramebufferManagerCommon::ReadbackFramebuffer(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3158if (w <= 0 || h <= 0) {3159ERROR_LOG(Log::FrameBuf, "Bad inputs to ReadbackFramebufferSync: %d %d %d %d", x, y, w, h);3160return;3161}31623163// Note that ReadbackDepthBufferSync can stretch on its own while converting data format, so we don't need to downscale in that case.3164if (vfb->renderScaleFactor == 1 || channel == RASTER_DEPTH) {3165// No need to stretch-blit3166} else {3167VirtualFramebuffer *nvfb = FindDownloadTempBuffer(vfb, channel);3168if (nvfb) {3169BlitFramebuffer(nvfb, x, y, vfb, x, y, w, h, 0, channel, "Blit_ReadFramebufferToMemory");3170vfb = nvfb;3171}3172}31733174const u32 fb_address = channel == RASTER_COLOR ? vfb->fb_address : vfb->z_address;31753176Draw::DataFormat destFormat = channel == RASTER_COLOR ? GEFormatToThin3D(vfb->fb_format) : GEFormatToThin3D(GE_FORMAT_DEPTH16);3177const int dstBpp = (int)DataFormatSizeInBytes(destFormat);31783179int stride = channel == RASTER_COLOR ? vfb->fb_stride : vfb->z_stride;31803181const int dstByteOffset = (y * stride + x) * dstBpp;3182// Leave the gap between the end of the last line and the full stride.3183// This is only used for the NotifyMemInfo range.3184const int dstSize = ((h - 1) * stride + w) * dstBpp;31853186if (!Memory::IsValidRange(fb_address + dstByteOffset, dstSize)) {3187ERROR_LOG_REPORT(Log::G3D, "ReadbackFramebufferSync would write outside of memory, ignoring");3188return;3189}31903191u8 *destPtr = Memory::GetPointerWriteUnchecked(fb_address + dstByteOffset);31923193// We always need to convert from the framebuffer native format.3194// Right now that's always 8888.3195DEBUG_LOG(Log::FrameBuf, "Reading framebuffer to mem, fb_address = %08x, ptr=%p", fb_address, destPtr);31963197if (channel == RASTER_DEPTH) {3198_assert_msg_(vfb && vfb->z_address != 0 && vfb->z_stride != 0, "Depth buffer invalid");3199ReadbackDepthbuffer(vfb->fbo,3200x * vfb->renderScaleFactor, y * vfb->renderScaleFactor,3201w * vfb->renderScaleFactor, h * vfb->renderScaleFactor, (uint16_t *)destPtr, stride, w, h, mode);3202} else {3203draw_->CopyFramebufferToMemory(vfb->fbo, channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, x, y, w, h, destFormat, destPtr, stride, mode, "ReadbackFramebufferSync");3204}32053206char tag[128];3207size_t len = snprintf(tag, sizeof(tag), "FramebufferPack/%08x_%08x_%dx%d_%s", vfb->fb_address, vfb->z_address, w, h, GeBufferFormatToString(vfb->fb_format));3208NotifyMemInfo(MemBlockFlags::WRITE, fb_address + dstByteOffset, dstSize, tag, len);32093210if (mode == Draw::ReadbackMode::BLOCK) {3211gpuStats.numBlockingReadbacks++;3212} else {3213gpuStats.numReadbacks++;3214}3215}32163217bool FramebufferManagerCommon::ReadbackStencilbuffer(Draw::Framebuffer *fbo, int x, int y, int w, int h, uint8_t *pixels, int pixelsStride, Draw::ReadbackMode mode) {3218return draw_->CopyFramebufferToMemory(fbo, Draw::Aspect::DEPTH_BIT, x, y, w, h, Draw::DataFormat::S8, pixels, pixelsStride, mode, "ReadbackStencilbufferSync");3219}32203221void FramebufferManagerCommon::ReadFramebufferToMemory(VirtualFramebuffer *vfb, int x, int y, int w, int h, RasterChannel channel, Draw::ReadbackMode mode) {3222if (!vfb || !vfb->fbo) {3223return;3224}32253226// Clamp to bufferWidth. Sometimes block transfers can cause this to hit.3227if (x + w >= vfb->bufferWidth) {3228w = vfb->bufferWidth - x;3229}3230if (gameUsesSequentialCopies_) {3231// Ignore the x/y/etc., read the entire thing. See below.3232x = 0;3233y = 0;3234w = vfb->width;3235h = vfb->height;3236vfb->memoryUpdated = true;3237vfb->usageFlags |= FB_USAGE_DOWNLOAD;3238} else if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3239// Mark it as fully downloaded until next render to it.3240if (channel == RASTER_COLOR)3241vfb->memoryUpdated = true;3242vfb->usageFlags |= FB_USAGE_DOWNLOAD;3243} else {3244// Let's try to set the flag eventually, if the game copies a lot.3245// Some games (like Grand Knights History) copy subranges very frequently.3246const static int FREQUENT_SEQUENTIAL_COPIES = 3;3247static int frameLastCopy = 0;3248static u32 bufferLastCopy = 0;3249static int copiesThisFrame = 0;3250if (frameLastCopy != gpuStats.numFlips || bufferLastCopy != vfb->fb_address) {3251frameLastCopy = gpuStats.numFlips;3252bufferLastCopy = vfb->fb_address;3253copiesThisFrame = 0;3254}3255if (++copiesThisFrame > FREQUENT_SEQUENTIAL_COPIES) {3256gameUsesSequentialCopies_ = true;3257}3258}32593260// This handles any required stretching internally.3261ReadbackFramebuffer(vfb, x, y, w, h, channel, mode);32623263draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3264textureCache_->ForgetLastTexture();3265RebindFramebuffer("RebindFramebuffer - ReadFramebufferToMemory");3266}32673268void FramebufferManagerCommon::FlushBeforeCopy() {3269drawEngine_->FlushQueuedDepth();3270// Flush anything not yet drawn before blitting, downloading, or uploading.3271// This might be a stalled list, or unflushed before a block transfer, etc.3272// Only bother if any draws are pending.3273if (drawEngine_->GetNumDrawCalls() > 0) {3274// TODO: It's really bad that we are calling SetRenderFramebuffer here with3275// all the irrelevant state checking it'll use to decide what to do. Should3276// do something more focused here.3277bool changed;3278SetRenderFrameBuffer(gstate_c.IsDirty(DIRTY_FRAMEBUF), gstate_c.skipDrawReason, &changed);3279drawEngine_->Flush();3280}3281}32823283// TODO: Replace with with depal, reading the palette from the texture on the GPU directly.3284void FramebufferManagerCommon::DownloadFramebufferForClut(u32 fb_address, u32 loadBytes) {3285VirtualFramebuffer *vfb = GetVFBAt(fb_address);3286if (vfb && vfb->fb_stride != 0) {3287const u32 bpp = BufferFormatBytesPerPixel(vfb->fb_format);3288int x = 0;3289int y = 0;3290int pixels = loadBytes / bpp;3291// The height will be 1 for each stride or part thereof.3292int w = std::min(pixels % vfb->fb_stride, (int)vfb->width);3293int h = std::min((pixels + vfb->fb_stride - 1) / vfb->fb_stride, (int)vfb->height);32943295if (w == 0 || h > 1) {3296// Exactly aligned, or more than one row.3297w = std::min(vfb->fb_stride, vfb->width);3298}32993300// We might still have a pending draw to the fb in question, flush if so.3301FlushBeforeCopy();33023303// No need to download if we already have it.3304if (w > 0 && h > 0 && !vfb->memoryUpdated && vfb->clutUpdatedBytes < loadBytes) {3305// We intentionally don't try to optimize into a full download here - we don't want to over download.33063307// CLUT framebuffers are often incorrectly estimated in size.3308if (x == 0 && y == 0 && w == vfb->width && h == vfb->height) {3309vfb->memoryUpdated = true;3310}3311vfb->clutUpdatedBytes = loadBytes;33123313// This function now handles scaling down internally.3314ReadbackFramebuffer(vfb, x, y, w, h, RASTER_COLOR, Draw::ReadbackMode::BLOCK);33153316textureCache_->ForgetLastTexture();3317RebindFramebuffer("RebindFramebuffer - DownloadFramebufferForClut");3318}3319}3320}33213322void FramebufferManagerCommon::RebindFramebuffer(const char *tag) {3323draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);3324shaderManager_->DirtyLastShader();3325// Needed for D3D11 to run validation clean. I don't think it's actually an issue.3326// textureCache_->ForgetLastTexture();3327if (currentRenderVfb_ && currentRenderVfb_->fbo) {3328draw_->BindFramebufferAsRenderTarget(currentRenderVfb_->fbo, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag);3329} else {3330// This can happen (like it does in Parappa) when a frame starts with copies instead of rendering.3331// Let's do nothing and assume it'll take care of itself.3332}3333}33343335std::vector<const VirtualFramebuffer *> FramebufferManagerCommon::GetFramebufferList() const {3336std::vector<const VirtualFramebuffer *> list;3337for (auto vfb : vfbs_) {3338list.push_back(vfb);3339}3340return list;3341}33423343template <typename T>3344static void DoRelease(T *&obj) {3345if (obj)3346obj->Release();3347obj = nullptr;3348}33493350void FramebufferManagerCommon::ReleasePipelines() {3351for (int i = 0; i < ARRAY_SIZE(reinterpretFromTo_); i++) {3352for (int j = 0; j < ARRAY_SIZE(reinterpretFromTo_); j++) {3353DoRelease(reinterpretFromTo_[i][j]);3354}3355}3356DoRelease(stencilWriteSampler_);3357DoRelease(stencilWritePipeline_);3358DoRelease(stencilReadbackSampler_);3359DoRelease(stencilReadbackPipeline_);3360DoRelease(depthReadbackSampler_);3361DoRelease(depthReadbackPipeline_);3362DoRelease(draw2DPipelineCopyColor_);3363DoRelease(draw2DPipelineColorRect2Lin_);3364DoRelease(draw2DPipelineCopyDepth_);3365DoRelease(draw2DPipelineEncodeDepth_);3366DoRelease(draw2DPipeline565ToDepth_);3367DoRelease(draw2DPipeline565ToDepthDeswizzle_);3368}33693370void FramebufferManagerCommon::DeviceLost() {3371DestroyAllFBOs();33723373presentation_->DeviceLost();3374draw2D_.DeviceLost();33753376ReleasePipelines();33773378draw_ = nullptr;3379}33803381void FramebufferManagerCommon::DeviceRestore(Draw::DrawContext *draw) {3382draw_ = draw;3383draw2D_.DeviceRestore(draw_);3384presentation_->DeviceRestore(draw_);3385}33863387void 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) {3388// Will be drawn as a strip.3389Draw2DVertex coord[4] = {3390{x, y, u0, v0},3391{x + w, y, u1, v0},3392{x + w, y + h, u1, v1},3393{x, y + h, u0, v1},3394};33953396if (uvRotation != ROTATION_LOCKED_HORIZONTAL) {3397float temp[8];3398int rotation = 0;3399switch (uvRotation) {3400case ROTATION_LOCKED_HORIZONTAL180: rotation = 2; break;3401case ROTATION_LOCKED_VERTICAL: rotation = 1; break;3402case ROTATION_LOCKED_VERTICAL180: rotation = 3; break;3403}3404for (int i = 0; i < 4; i++) {3405temp[i * 2] = coord[((i + rotation) & 3)].u;3406temp[i * 2 + 1] = coord[((i + rotation) & 3)].v;3407}34083409for (int i = 0; i < 4; i++) {3410coord[i].u = temp[i * 2];3411coord[i].v = temp[i * 2 + 1];3412}3413}34143415const float invDestW = 2.0f / destW;3416const float invDestH = 2.0f / destH;3417for (int i = 0; i < 4; i++) {3418coord[i].x = coord[i].x * invDestW - 1.0f;3419coord[i].y = coord[i].y * invDestH - 1.0f;3420}34213422if ((flags & DRAWTEX_TO_BACKBUFFER) && g_display.rotation != DisplayRotation::ROTATE_0) {3423for (int i = 0; i < 4; i++) {3424// backwards notation, should fix that...3425Lin::Vec3 pos = Lin::Vec3(coord[i].x, coord[i].y, 0.0);3426pos = pos * g_display.rot_matrix;3427coord[i].x = pos.x;3428coord[i].y = pos.y;3429}3430}34313432// Rearrange to strip form.3433std::swap(coord[2], coord[3]);34343435draw2D_.DrawStrip2D(nullptr, coord, 4, (flags & DRAWTEX_LINEAR) != 0, Get2DPipeline((flags & DRAWTEX_DEPTH) ? DRAW2D_ENCODE_R16_TO_DEPTH : DRAW2D_COPY_COLOR));34363437gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3438}34393440void 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) {3441if (!dst->fbo || !src->fbo || !useBufferedRendering_) {3442// This can happen if they recently switched from non-buffered.3443if (useBufferedRendering_) {3444// Just bind the back buffer for rendering, forget about doing anything else as we're in a weird state.3445draw_->BindFramebufferAsRenderTarget(nullptr, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, "BlitFramebuffer");3446}3447return;3448}34493450if (channel == RASTER_DEPTH && !draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported) {3451// Can't do anything :(3452return;3453}34543455// Perform a little bit of clipping first.3456// Block transfer coords are unsigned so I don't think we need to clip on the left side.. Although there are3457// other uses for BlitFramebuffer.3458if (dstX + w > dst->bufferWidth) {3459w -= dstX + w - dst->bufferWidth;3460}3461if (dstY + h > dst->bufferHeight) {3462h -= dstY + h - dst->bufferHeight;3463}3464if (srcX + w > src->bufferWidth) {3465w -= srcX + w - src->bufferWidth;3466}3467if (srcY + h > src->bufferHeight) {3468h -= srcY + h - src->bufferHeight;3469}34703471if (w <= 0 || h <= 0) {3472// The whole rectangle got clipped.3473return;3474}34753476bool useBlit = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferBlitSupported : false;3477bool useCopy = channel == RASTER_COLOR ? draw_->GetDeviceCaps().framebufferCopySupported : false;3478if (src != dst && (dst == currentRenderVfb_ || dst->fbo->MultiSampleLevel() != 0 || src->fbo->MultiSampleLevel() != 0)) {3479// If already bound, using either a blit or a copy is unlikely to be an optimization.3480// So we're gonna use a raster draw instead. Also multisampling has problems with copies currently.3481useBlit = false;3482useCopy = false;3483}34843485float srcXFactor = src->renderScaleFactor;3486float srcYFactor = src->renderScaleFactor;3487const int srcBpp = BufferFormatBytesPerPixel(src->Format(channel));3488if (srcBpp != bpp && bpp != 0) {3489// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3490srcXFactor = (srcXFactor * bpp) / srcBpp;3491}3492int srcX1 = srcX * srcXFactor;3493int srcX2 = (srcX + w) * srcXFactor;3494int srcY1 = srcY * srcYFactor;3495int srcY2 = (srcY + h) * srcYFactor;34963497float dstXFactor = dst->renderScaleFactor;3498float dstYFactor = dst->renderScaleFactor;3499const int dstBpp = BufferFormatBytesPerPixel(dst->Format(channel));3500if (dstBpp != bpp && bpp != 0) {3501// If we do this, we're kinda in nonsense territory since the actual formats won't match (unless intentionally blitting black or white).3502dstXFactor = (dstXFactor * bpp) / dstBpp;3503}3504int dstX1 = dstX * dstXFactor;3505int dstX2 = (dstX + w) * dstXFactor;3506int dstY1 = dstY * dstYFactor;3507int dstY2 = (dstY + h) * dstYFactor;35083509if (src == dst && srcX == dstX && srcY == dstY) {3510// Let's just skip a copy where the destination is equal to the source.3511WARN_LOG_REPORT_ONCE(blitSame, Log::G3D, "Skipped blit with equal dst and src");3512return;3513}35143515if (useCopy) {3516// glBlitFramebuffer can clip, but glCopyImageSubData is more restricted.3517// In case the src goes outside, we just skip the optimization in that case.3518const bool sameSize = dstX2 - dstX1 == srcX2 - srcX1 && dstY2 - dstY1 == srcY2 - srcY1;3519const bool srcInsideBounds = srcX2 <= src->renderWidth && srcY2 <= src->renderHeight;3520const bool dstInsideBounds = dstX2 <= dst->renderWidth && dstY2 <= dst->renderHeight;3521const bool xOverlap = src == dst && srcX2 > dstX1 && srcX1 < dstX2;3522const bool yOverlap = src == dst && srcY2 > dstY1 && srcY1 < dstY2;3523if (sameSize && srcInsideBounds && dstInsideBounds && !(xOverlap && yOverlap)) {3524draw_->CopyFramebufferImage(src->fbo, 0, srcX1, srcY1, 0, dst->fbo, 0, dstX1, dstY1, 0, dstX2 - dstX1, dstY2 - dstY1, 1,3525channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, tag);3526return;3527}3528}35293530if (useBlit) {3531draw_->BlitFramebuffer(src->fbo, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2,3532channel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, Draw::FB_BLIT_NEAREST, tag);3533} else {3534Draw2DPipeline *pipeline = Get2DPipeline(channel == RASTER_COLOR ? DRAW2D_COPY_COLOR : DRAW2D_COPY_DEPTH);3535Draw::Framebuffer *srcFBO = src->fbo;3536if (src == dst) {3537Draw::Framebuffer *tempFBO = GetTempFBO(TempFBO::BLIT, src->renderWidth, src->renderHeight);3538// We need to copy to the temp using only the source coordinates, since those are the ones we read in the next blit.3539BlitUsingRaster(src->fbo, srcX1, srcY1, srcX2, srcY2, tempFBO, srcX1, srcY1, srcX2, srcY2, false, dst->renderScaleFactor, pipeline, tag);3540srcFBO = tempFBO;3541}3542BlitUsingRaster(srcFBO, srcX1, srcY1, srcX2, srcY2, dst->fbo, dstX1, dstY1, dstX2, dstY2, false, dst->renderScaleFactor, pipeline, tag);3543}35443545draw_->Invalidate(InvalidationFlags::CACHED_RENDER_STATE);35463547gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3548}35493550// The input is raw pixel coordinates, scale not taken into account.3551void FramebufferManagerCommon::BlitUsingRaster(3552Draw::Framebuffer *src, float srcX1, float srcY1, float srcX2, float srcY2,3553Draw::Framebuffer *dest, float destX1, float destY1, float destX2, float destY2,3554bool linearFilter,3555int scaleFactor,3556Draw2DPipeline *pipeline, const char *tag) {35573558_dbg_assert_(src);3559_dbg_assert_(dest);3560_dbg_assert_(pipeline);35613562if (!src || !dest || !pipeline) {3563// Nothing we can do, other than trying to catch it in debug with the asserts above.3564return;3565}35663567if (pipeline->info.writeChannel == RASTER_DEPTH) {3568_dbg_assert_(draw_->GetDeviceCaps().fragmentShaderDepthWriteSupported);3569}35703571int destW, destH, srcW, srcH;3572draw_->GetFramebufferDimensions(src, &srcW, &srcH);3573draw_->GetFramebufferDimensions(dest, &destW, &destH);35743575// 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).3576draw_->BindTexture(0, nullptr);3577// This will get optimized away in case it's already bound (in VK and GL at least..)3578draw_->BindFramebufferAsRenderTarget(dest, { Draw::RPAction::KEEP, Draw::RPAction::KEEP, Draw::RPAction::KEEP }, tag ? tag : "BlitUsingRaster");3579draw_->BindFramebufferAsTexture(src, 0, pipeline->info.readChannel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT, Draw::ALL_LAYERS);35803581if (destX1 == 0.0f && destY1 == 0.0f && destX2 >= destW && destY2 >= destH) {3582// We overwrite the whole channel of the framebuffer, so we can invalidate the current contents.3583draw_->InvalidateFramebuffer(Draw::FB_INVALIDATION_LOAD, pipeline->info.writeChannel == RASTER_COLOR ? Draw::Aspect::COLOR_BIT : Draw::Aspect::DEPTH_BIT);3584}35853586Draw::Viewport viewport{ 0.0f, 0.0f, (float)dest->Width(), (float)dest->Height(), 0.0f, 1.0f };3587draw_->SetViewport(viewport);3588draw_->SetScissorRect(0, 0, (int)dest->Width(), (int)dest->Height());35893590draw2D_.Blit(pipeline, srcX1, srcY1, srcX2, srcY2, destX1, destY1, destX2, destY2, (float)srcW, (float)srcH, (float)destW, (float)destH, linearFilter, scaleFactor);35913592gstate_c.Dirty(DIRTY_ALL_RENDER_STATE);3593}35943595int FramebufferManagerCommon::GetFramebufferLayers() const {3596int layers = 1;3597if (gstate_c.Use(GPU_USE_SINGLE_PASS_STEREO)) {3598layers = 2;3599}3600return layers;3601}36023603VirtualFramebuffer *FramebufferManagerCommon::ResolveFramebufferColorToFormat(VirtualFramebuffer *src, GEBufferFormat newFormat) {3604// Look for an identical framebuffer with the new format3605_dbg_assert_(src->fb_format != newFormat);36063607VirtualFramebuffer *vfb = nullptr;3608for (auto dest : vfbs_) {3609if (dest == src) {3610continue;3611}36123613// Sanity check for things that shouldn't exist.3614if (dest->fb_address == src->fb_address && dest->fb_format == src->fb_format && dest->fb_stride == src->fb_stride) {3615_dbg_assert_msg_(false, "illegal clone of src found");3616}36173618if (dest->fb_address == src->fb_address && dest->FbStrideInBytes() == src->FbStrideInBytes() && dest->fb_format == newFormat) {3619vfb = dest;3620break;3621}3622}36233624if (!vfb) {3625// Create a clone!3626vfb = new VirtualFramebuffer();3627*vfb = *src; // Copies everything, but watch out! Can't copy fbo.36283629// Adjust width by bpp.3630float widthFactor = (float)BufferFormatBytesPerPixel(vfb->fb_format) / (float)BufferFormatBytesPerPixel(newFormat);36313632vfb->width *= widthFactor;3633vfb->bufferWidth *= widthFactor;3634vfb->renderWidth *= widthFactor;3635vfb->drawnWidth *= widthFactor;3636vfb->newWidth *= widthFactor;3637vfb->safeWidth *= widthFactor;36383639vfb->fb_format = newFormat;3640// stride stays the same since it's in pixels.36413642WARN_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);36433644char tag[128];3645FormatFramebufferName(vfb, tag, sizeof(tag));3646vfb->fbo = draw_->CreateFramebuffer({ vfb->renderWidth, vfb->renderHeight, 1, GetFramebufferLayers(), 0, true, tag });3647vfbs_.push_back(vfb);3648}36493650// OK, now resolve it so we can texture from it.3651// This will do any necessary reinterprets.3652CopyToColorFromOverlappingFramebuffers(vfb);3653// Now we consider the resolved one the latest at the address (though really, we could make them equivalent?).3654vfb->colorBindSeq = GetBindSeqCount();3655return vfb;3656}36573658static void ApplyKillzoneFramebufferSplit(FramebufferHeuristicParams *params, int *drawing_width) {3659// Detect whether we're rendering to the margin.3660bool margin;3661if ((params->scissorRight - params->scissorLeft) == 32) {3662// Title screen has this easy case. It also uses non-through verts, so lucky for us that we have this.3663margin = true;3664} else if (params->scissorRight == 480) {3665margin = false;3666} else {3667// Go deep, look at the vertices. Killzone-specific, of course.3668margin = false;3669if ((gstate.vertType & 0xFFFFFF) == 0x00800102) { // through, u16, s163670u16 *vdata = (u16 *)Memory::GetPointerUnchecked(gstate_c.vertexAddr);3671int v0PosU = vdata[0];3672int v0PosX = vdata[2];3673if (v0PosX >= 480 && v0PosU < 480) {3674// Texturing from surface, writing to margin3675margin = true;3676}3677}36783679// TODO: Implement this for Burnout Dominator. It has to handle self-reads inside3680// the margin framebuffer though, so framebuffer copies are still needed, just smaller.3681// It uses 0x0080019f (through, float texcoords, ABGR 8888 colors, float positions).3682}36833684if (margin) {3685gstate_c.SetCurRTOffset(-480, 0);3686// Modify the fb_address and z_address too to avoid matching below.3687params->fb_address += 480 * 4;3688params->z_address += 480 * 2;3689*drawing_width = 32;3690} else {3691gstate_c.SetCurRTOffset(0, 0);3692*drawing_width = 480;3693}3694}369536963697